Version: current

      1 <?php
      2 /*
      3  *  Уведомление менеджера и клиента при помощи SMS (создание заказа и изменение заказа )
      4  *  Отправляем email в нужном формате на нужный адрес, чтобы шлюз отправил смс
      5  *
      6  *  @author menedem
      7  */
      8 class SMSOrderNotification extends OrderHandlersDecorator {
      9
     10     // поле объекта Member для использования как номера телефона для отправки SMS
     11     // добавляется Member в модуле cart (ExtendMemberCart.php)
     12     protected static $memberPhoneField = 'Phone';
     13
     14     /*
     15      * Установка поля объекта Member для использования как номера телефона для отправки SMS
     16      *
     17      * @param string $field
     18      */
     19     static function setMemberPhoneField($field) {
     20         self::$memberPhoneField = $field;
     21     }
     22
     23     /**
     24      * Подстановка переменных в поля для отправки шлюзу
     25      *
     26      * @param string $field - текст в котором делаем замену
     27      * @param string $phone - замена метки {phone}
     28      * @param string $sender - замена метки {sender}
     29      * @param string $message - замена метки {message}
     30      *
     31      * @return string
     32      */
     33     static function replace_vars($field, $login, $password, $phone, $sender, $message) {
     34         $conf = SiteConfig::current_site_config();
     35         $field = str_replace('{login}', $login, $field);
     36         $field = str_replace('{password}', $password, $field);
     37         $field = str_replace('{phone}', $phone, $field);
     38         $field = str_replace('{sender}', $sender, $field);
     39         $field = str_replace('{message}', $message, $field);
     40         return $field;
     41     }
     42
     43     /**
     44      * Обработчик события "После создания заказа"
     45      *
     46      * @param Member $member
     47      *
     48      */
     49     function OnAfterCreateOrder(& $member) {
     50         $conf = SiteConfig::current_site_config();
     51
     52         $phone = $this->getClientPhone();
     53         if ($conf->ClientSMSOrderNotificationActive && $phone) {
     54             self::send(
     55                 $phone,
     56                 $this->owner->customise(array(
     57                     'Member' => $this->owner->Member(),
     58                     'Order' => $this->owner,
     59                     'SiteTitle' => $conf->Title,
     60                     'CatalogCurrency' => $conf->CatalogCurrency,
     61                 ))->owner->renderWith('SMS_ClientCreateOrderMessage')
     62             );
     63         }
     64
     65         if (($conf->ManagerSMSOrderNotificationType != 'none') && $conf->SMSManagerPhones) {
     66             self::send(
     67                 $conf->SMSManagerPhones,
     68                 $this->owner->customise(array(
     69                     'Member' => $this->owner->Member(),
     70                     'Order' => $this->owner,
     71                     'SiteTitle' => $conf->Title,
     72                     'CatalogCurrency' => $conf->CatalogCurrency,
     73                 ))->owner->renderWith('SMS_ManagerCreateOrderMessage'),
     74                 $conf->ManagerSMSOrderNotificationType
     75             );
     76         }
     77     }
     78
     79     /**
     80      * Обработчик события "Смена статуса заказа"
     81      *
     82      * @param Member $member - текущий пользователь
     83      * @param string $changedStatus - новый??? старый??? статус
     84      * @param string $note - примечание к смене статуса
     85      */
     86     function OnAfterChangeStatus($member, $changedStatus, $note) {
     87         $conf = SiteConfig::current_site_config();
     88
     89
     90         $phone = $this->getClientPhone();
     91         if ($conf->ClientSMSOrderNotificationActive && $phone) {
     92             self::send(
     93                 $phone,
     94                 $this->owner->customise(array(
     95                     'Member' => $this->owner->Member(),
     96                     'Note' => $note,
     97                     'Order' => $this->owner,
     98                 ))->owner->renderWith('SMS_ClientChangeOrderStatusMessage')
     99             );
    100         }
    101         /*
    102         // менеджер обычно сам меняет статус - зачем ему сообщать?
    103         if ($member && $member->ID != $this->owner->MemberID) return;
    104         if (($conf->ManagerSMSOrderNotificationType != 'none') && $conf->SMSManagerPhones) {
    105             self::send(
    106                 $conf->SMSManagerPhones,
    107                 $this->owner->customise(array(
    108                     'Member' => $this->owner->Member(),
    109                     'Order' => $this->owner,
    110                 ))->owner->renderWith('SMS_ManagerChangeOrderStatusMessage'),
    111                 $conf->ManagerSMSOrderNotificationType
    112             );
    113         }
    114         */
    115     }
    116
    117     /**
    118      * Ищем телефон клиента для СМС
    119      *
    120      * @return string
    121      */
    122     private function getClientPhone() {
    123         $phone = $this->owner->Phone;
    124         if (!$phone) {
    125             if ($member = $this->owner->Member()) {
    126                 $phoneField = self::$memberPhoneField;
    127                 $phone = $member->{$phoneField};
    128             }
    129         }
    130         return $phone;
    131     }
    132
    133     /**
    134      * Отправляем письмо шлюзу
    135      *
    136      * @param string $phone - телефон на который надо слать СМС
    137      * @param string $message - текст СМС
    138      * @param string $type - тип отправки(sms/voice)
    139      *
    140      * @return boolean
    141      */
    142     static function send($phone, $message, $type='sms') {
    143         if (!$phone || !$message) return false;
    144
    145         $conf = SiteConfig::current_site_config();
    146         if ($type == 'sms') {
    147             $subject = trim($conf->SMSGateSubject);
    148             $body = trim($conf->SMSGateBody);
    149         } else {
    150             $subject = trim($conf->VoiceGateSubject);
    151             $body = trim($conf->VoiceGateBody);
    152         }
    153         if ($subject || $body) {
    154             $from = ($conf->hasMethod('CartSenderEmail') ? $conf->CartSenderEmail() : ($conf->AdminEmail ? $conf->AdminEmail : Email::getAdminEmail()));
    155             $email = new Email($from);
    156             $email->setTo(self::replace_vars($conf->GateEmail, $conf->GateLogin, $conf->GatePassword, $phone, $conf->SMSSenderName, $message));
    157             $email->setSubject(self::replace_vars($subject, $conf->GateLogin, $conf->GatePassword, $phone, $conf->SMSSenderName, $message));
    158             $email->setBody(self::replace_vars($body, $conf->GateLogin, $conf->GatePassword, $phone, $conf->SMSSenderName, $message));
    159             $email->send();
    160             return true;
    161         }
    162     }
    163 }
    164
    165 // Декоратор SiteConfig для этого типа уведомлений
    166 class SMSOrderNotification_SiteConfig extends SiteConfigDecorator {
    167
    168     function extraStatics() {
    169         return array(
    170             'db' => array(
    171                 'ClientSMSOrderNotificationActive' => 'Boolean', // уведомлять клиента по СМС
    172                 'ManagerSMSOrderNotificationType' => "Enum('none,sms,voice')", // как уведомлять менеджера
    173                 'SmsGate' => 'Varchar(255)', // шлюз
    174                 'GateEmail' => 'Varchar(255)', // email шлюза
    175                 'GateLogin' => 'Varchar(255)', // логин/ключ шлюза
    176                 'GatePassword' => 'Varchar(255)', // пароль шлюза (м.б. пустым)
    177                 'SMSGateSubject' => 'Varchar(255)', // тема письма для смс
    178                 'SMSGateBody' => 'Varchar(255)', // тело письма для смс
    179                 'VoiceGateSubject' => 'Varchar(255)', // тема письма для голосовых уведомлений
    180                 'VoiceGateBody' => 'Varchar(255)', // тело письма для голосовых уведомлений
    181                 'SMSManagerPhones' => 'Varchar(255)', // номер (или список номеров через , или ;) менеджера
    182                 'SMSSenderName' => 'Varchar(255)', // имя отправителя
    183             )
    184         );
    185     }
    186
    187     static function local_notification_types() {
    188         $types = array();
    189         foreach(singleton('SiteConfig')->dbObject('ManagerSMSOrderNotificationType')->enumValues() as $value) {
    190             $types[$value] = _t("SiteConfig.ManagerSMSOrderNotificationType_{$value}");
    191         }
    192         return $types;
    193     }
    194
    195     static function sms_gate_settings($short=true) {
    196         $settings = array();
    197         $settings['smsc'] = array(
    198             'Title' => 'Шлюз SMSC',
    199             'GateEmail' => 'send@send.smsc.ru',
    200             'SMSGateSubject' => '',
    201             'SMSGateBody' => '{login}:{password}::::,,{sender}{phone}:{message}',
    202             'VoiceGateSubject' => '',
    203             'VoiceGateBody' => '{login}:{password}:::,9,{sender}:{phone}:{message}',
    204         );
    205         $settings['sms'] = array(
    206             'Title' => 'Шлюз SMS.RU',
    207             'GateEmail' => '{login}+{phone}@sms.ru',
    208             'SMSGateSubject' => 'from:{sender}',
    209             'SMSGateBody' => '{message}',
    210             'VoiceGateSubject' => '',
    211             'VoiceGateBody' => '',
    212         );
    213         if ($short) {
    214             $short = array();
    215             $short[''] = _t('SiteConfig.NotSelected', 'Не выбрано');
    216             foreach($settings as $gate=>$params) {
    217                 $short[$gate] = $params['Title'];
    218             }
    219             $settings = $short;
    220         }
    221         //[ваш ключ, виден после авторизации]+[номер получателя]@sms.ru
    222         return $settings;
    223     }
    224
    225     public function updateCMSFields(FieldSet &$fields) {
    226         $tab = self::get_config_tab($fields, 'OrderNotifications.SMSOrderNotification');
    227
    228         $tab->push(new CheckboxField('ClientSMSOrderNotificationActive', $this->owner->FieldLabel('ClientSMSOrderNotificationActive')));
    229         $tab->push(new DropdownField('ManagerSMSOrderNotificationType', $this->owner->FieldLabel('ManagerSMSOrderNotificationType'), self::local_notification_types()));
    230         $tab->push(new TextField('SMSManagerPhones', $this->owner->FieldLabel('SMSManagerPhones')));
    231
    232         $tab->push(new HeaderField('GateParams', _t('SMSOrderNotification_SiteConfig.GateParams', 'Gate Params')));
    233
    234         $tab->push(new DropdownField('SmsGate', $this->owner->FieldLabel('SmsGate'), self::sms_gate_settings()));
    235         $tab->push(new LiteralField('SmsGateSettings',  '<div id="sms_gate_settings" style="display: none;">' . json_encode(self::sms_gate_settings(false)) . '</div>'));
    236
    237         $tab->push(new TextField('SMSSenderName', $this->owner->FieldLabel('SMSSenderName')));
    238
    239         $tab->push(new LiteralField('GateInfo', _t('SMSOrderNotification_SiteConfig.GateInfo', 'You can use {login}, {password}, {phone}, {message} and {sender} placeholders in gate fileds')));
    240         $tab->push(new TextField('GateEmail', $this->owner->FieldLabel('GateEmail')));
    241         $tab->push(new TextField('GateLogin', $this->owner->FieldLabel('GateLogin')));
    242         $tab->push(new TextField('GatePassword', $this->owner->FieldLabel('GatePassword')));
    243
    244         $tab->push(new TextField('SMSGateSubject', $this->owner->FieldLabel('SMSGateSubject')));
    245         $tab->push(new TextareaField('SMSGateBody', $this->owner->FieldLabel('SMSGateBody')));
    246
    247         $tab->push(new TextField('VoiceGateSubject', $this->owner->FieldLabel('VoiceGateSubject')));
    248         $tab->push(new TextareaField('VoiceGateBody', $this->owner->FieldLabel('VoiceGateBody')));
    249
    250         Requirements::javascript('cart_notify_sms/javascript/sms_notify_cms.js');
    251     }
    252
    253     /* переделал на js
    254     function onBeforeWrite() {
    255         if ($this->owner->isChanged('SmsGate') && $this->owner->SmsGate) {
    256             $settings = self::sms_gate_settings(false);
    257             if (isset($settings[$this->owner->SmsGate]) && is_array($settings[$this->owner->SmsGate])) {
    258                 foreach($settings[$this->owner->SmsGate] as $title=>$value) {
    259                     //echo "{$title} - {$value}";
    260                     $this->owner->{$title} = $value;
    261                 }
    262             }
    263         }
    264     }
    265     */
    266 }
    267

[Raise a SilverStripe Framework issue/bug](https://github.com/silverstripe/silverstripe-framework/issues/new)
- [Raise a SilverStripe CMS issue/bug](https://github.com/silverstripe/silverstripe-cms/issues/new)
- Please use the Silverstripe Forums to ask development related questions. -