Webylon 3.2 API Docs
  • Package
  • Class
  • Tree
  • Deprecated
  • Download
Version: current
  • 3.2
  • 3.1

Packages

  • 1c
    • exchange
      • catalog
  • auth
  • Booking
  • building
    • company
  • cart
    • shipping
    • steppedcheckout
  • Catalog
    • monument
  • cms
    • assets
    • batchaction
    • batchactions
    • bulkloading
    • comments
    • content
    • core
    • export
    • newsletter
    • publishers
    • reports
    • security
    • tasks
  • Dashboard
  • DataObjectManager
  • event
  • faq
  • forms
    • actions
    • core
    • fields-basic
    • fields-dataless
    • fields-datetime
    • fields-files
    • fields-formatted
    • fields-formattedinput
    • fields-relational
    • fields-structural
    • transformations
    • validators
  • googlesitemaps
  • guestbook
  • installer
  • newsletter
  • None
  • photo
    • gallery
  • PHP
  • polls
  • recaptcha
  • sapphire
    • api
    • bulkloading
    • control
    • core
    • cron
    • dev
    • email
    • fields-formattedinput
    • filesystem
    • formatters
    • forms
    • i18n
    • integration
    • misc
    • model
    • parsers
    • search
    • security
    • tasks
    • testing
    • tools
    • validation
    • view
    • widgets
  • seo
    • open
      • graph
  • sfDateTimePlugin
  • spamprotection
  • stealth
    • captha
  • subsites
  • userform
    • pagetypes
  • userforms
  • webylon
  • widgets

Classes

  • Address
  • AddSubsiteTask
  • Announcement
  • AnnouncementDecorator
  • AnnouncementHolder
  • AssociatedFolderDecorator
  • AttachedFiles
  • AudioPhpCaptcha
  • AutoCompleteField
  • Base1CExchanger
  • BookingOrder_StatusLog
  • CalendarUtil
  • CalendarWidgetExtention
  • CatalogCatalogLinkedDecorator
  • CatalogOldFieldsDecorator
  • CatalogProductLinkedDecorator
  • CheckoutStep_ShippingMethod
  • ChequePayment
  • ClearHistoryTask
  • ClientEmailOrderNotification_SiteConfig
  • ClientVKOrderNotification_SiteConfig
  • CommentsSiteConfig
  • ContactsPage
  • CookieExtention
  • CostTableShippingRate
  • CustomMenu
  • CustomMenuAdmin
  • CustomMenuDecorator
  • CustomMenuHolder
  • CustomMenuItem
  • CustomPayment
  • DataObjectLoggerExtension
  • DataObjectSubsites
  • DefaultCMSActionDecorator
  • DocPage
  • DocumentDirection
  • DocumentHaving
  • DocumentSearchForm
  • DocumentSiteConfig
  • DocumentsPage
  • DocumentType
  • DOMUtil
  • ExtendPageAnnouncement
  • ExtendPagePoll
  • FavoriteExtention
  • FavoritePage
  • FavoriteProductMemberExtention
  • FavoriteProducts
  • FileOversizeDecorator
  • FindCyrillicSiteConfig
  • FolderRenameTask
  • GDMergeAlpha
  • HomePage
  • ImageAutoResize
  • ImageResizeTask
  • ImportCatalog1C_Importer
  • ImportCatalogSiteConfig
  • ImportSiteConfig
  • LoggerAdmin
  • LogItem
  • ManagerEmailOrderNotification_SiteConfig
  • MapObject
  • MapObjectGroup
  • MapPage
  • MediawebForm
  • MemberLoggerExtension
  • MonumentsSiteConfig
  • MultiUploadConfig
  • NearestEventExtention
  • NewDocumentsAdmin
  • NewsArchive
  • NewsEntry
  • NewsHolder
  • NewsSiteConfig
  • Order_StatusLog
  • Orders1CExchange_Exporter
  • PageHideFieldsExtension
  • PageInformerRates
  • PageInformerWeather
  • Payment_Failure
  • Payment_Processing
  • Payment_Result
  • Payment_Success
  • PaymentMethod
  • PaymentSiteConfig
  • PayPalPayment
  • PayPalPayment_Handler
  • PhoneField
  • PhotoAlbumExtentions
  • PhpCaptcha
  • PhpCaptchaColour
  • PhpCaptchaField
  • phpMorphy
  • phpMorphy_AncodesResolver_AsIs
  • phpMorphy_AncodesResolver_Proxy
  • phpMorphy_AncodesResolver_ToDialingAncodes
  • phpMorphy_AncodesResolver_ToText
  • phpMorphy_AnnotDecoder_Base
  • phpMorphy_AnnotDecoder_Common
  • phpMorphy_AnnotDecoder_Factory
  • phpMorphy_AnnotDecoder_Predict
  • phpMorphy_FilesBundle
  • phpMorphy_Fsa
  • phpMorphy_Fsa_Decorator
  • phpMorphy_Fsa_Proxy
  • phpMorphy_Fsa_Sparse_File
  • phpMorphy_Fsa_Sparse_Mem
  • phpMorphy_Fsa_Sparse_Shm
  • phpMorphy_Fsa_Tree_File
  • phpMorphy_Fsa_Tree_Mem
  • phpMorphy_Fsa_Tree_Shm
  • phpMorphy_Fsa_WordsCollector
  • phpMorphy_GramInfo
  • phpMorphy_GramInfo_AncodeCache
  • phpMorphy_GramInfo_Decorator
  • phpMorphy_Graminfo_File
  • phpMorphy_Graminfo_Mem
  • phpMorphy_GramInfo_Proxy
  • phpMorphy_GramInfo_Proxy_WithHeader
  • phpMorphy_GramInfo_RuntimeCaching
  • phpMorphy_Graminfo_Shm
  • phpMorphy_GrammemsProvider_Base
  • phpMorphy_GrammemsProvider_Decorator
  • phpMorphy_GrammemsProvider_Empty
  • phpMorphy_GrammemsProvider_Factory
  • phpMorphy_GrammemsProvider_ForFactory
  • phpMorphy_GrammemsProvider_ru_RU
  • phpMorphy_GramTab
  • phpMorphy_GramTab_Empty
  • phpMorphy_GramTab_Proxy
  • phpMorphy_Link
  • phpMorphy_Link_Annot
  • phpMorphy_Link_Base
  • phpMorphy_Morphier_Base
  • phpMorphy_Morphier_Bulk
  • phpMorphy_Morphier_Common
  • phpMorphy_Morphier_Empty
  • phpMorphy_Morphier_Finder_Base
  • phpMorphy_Morphier_Finder_Common
  • phpMorphy_Morphier_Finder_Predict_Databse
  • phpMorphy_Morphier_Finder_Predict_Suffix
  • phpMorphy_Morphier_Helper
  • phpMorphy_Morphier_Predict_Database
  • phpMorphy_Morphier_Predict_Suffix
  • phpMorphy_Morphier_PredictCollector
  • phpMorphy_Semaphore
  • phpMorphy_Semaphore_Empty
  • phpMorphy_Semaphore_Nix
  • phpMorphy_Semaphore_Win
  • phpMorphy_Shm_Cache
  • phpMorphy_Shm_Cache_FileDescriptor
  • phpMorphy_Shm_Header
  • phpMorphy_Source_Dba
  • phpMorphy_Source_Fsa
  • phpMorphy_State
  • phpMorphy_Storage
  • phpMorphy_Storage_Factory
  • phpMorphy_Storage_File
  • phpMorphy_Storage_Mem
  • phpMorphy_Storage_Proxy
  • phpMorphy_Storage_Shm
  • phpMorphy_UnicodeHelper
  • phpMorphy_UnicodeHelper_Base
  • phpMorphy_UnicodeHelper_MultiByteFixed
  • phpMorphy_UnicodeHelper_singlebyte
  • phpMorphy_UnicodeHelper_ucs_2be
  • phpMorphy_UnicodeHelper_ucs_2le
  • phpMorphy_UnicodeHelper_ucs_4be
  • phpMorphy_UnicodeHelper_ucs_4le
  • phpMorphy_UnicodeHelper_utf_16_Base
  • phpMorphy_UnicodeHelper_utf_16be
  • phpMorphy_UnicodeHelper_utf_16le
  • phpMorphy_UnicodeHelper_utf_32_Base
  • phpMorphy_UnicodeHelper_utf_32be
  • phpMorphy_UnicodeHelper_utf_32le
  • phpMorphy_UnicodeHelper_utf_8
  • phpMorphy_WordDescriptor
  • phpMorphy_WordDescriptor_Collection
  • phpMorphy_WordDescriptor_Collection_Serializer
  • phpMorphy_WordForm
  • ProductCatalogImportTask
  • ProductOldFieldsDecorator
  • ProductParamValue_BoolValueField
  • ProductParamValue_MultiValueField
  • ProductParamValue_MultiValueSetField
  • ProductParamValue_ValueField
  • ProductProductLinkedDecorator
  • PublHolder
  • Publication
  • PublicationSiteTree
  • RatingDataObject
  • RatingExtension
  • RealtySiteConfigDecorator
  • RecentComments
  • RecentFiles
  • RecentPages
  • RelatedPageLink
  • RoomRate_PriceField
  • RussianUpLower
  • SberbankPayment
  • SberbankPayment_Handler
  • SetMainSiteHomePageTypeTask
  • ShippingEstimator
  • ShippingPackage
  • ShowUserFromExtension
  • ShowViewedProductExtention
  • SiteConfigDecorator
  • SiteConfigSubsites
  • SiteTreeSubsites
  • SMSCOrderNotification_SiteConfig
  • SMSOrderNotification_SiteConfig
  • Socle
  • SocleSize
  • SortCMSActionDecorator
  • SS_Report_FakeQuery
  • SSMorphy
  • SSNController
  • SteppedCheckout_PageMessages
  • SubpageListField
  • SubscribeFormAllPagesExtension
  • SubsiteDropdownField
  • SubsiteReportWrapper
  • TableShippingRate
  • UnitellerPayment
  • UnitellerPayment_Handler
  • UnmoderatedComments
  • VAT
  • VideoManager
  • VideoSiteConfig
  • ViewedProductExtention
  • WatermarkImage
  • WatermarkSiteConfig
  • WeightTableShippingRate
  • XMLValidate
  • YaMoneyPayment
  • YaMoneyPayment_Handler
  • YMLExporter
  • YMLSiteConfig

Interfaces

  • PaymentObjectInterface
  • phpMorphy_AncodesResolver_Interface
  • phpMorphy_AnnotDecoder_Interface
  • phpMorphy_Fsa_Interface
  • phpMorphy_GramInfo_Interace
  • phpMorphy_GrammemsProvider_Interface
  • phpMorphy_GramTab_Interface
  • phpMorphy_Morphier_Finder_Interface
  • phpMorphy_Morphier_Interface
  • phpMorphy_Shm_Cache_Interface
  • phpMorphy_Source_Interface

Exceptions

  • phpMorphy_Exception

Functions

  • column_sort
  • column_sort_callback_basic
  • encodeFileForEmail
  • encodeMultipart
  • getMimeType
  • htmlEmail
  • loadMimeTypes
  • phpmorphy_overload_mb_funcs
  • plaintextEmail
  • processHeaders
  • QuotedPrintable_encode
  • supressOutput
  • validEmailAddr
  • wrapImagesInline
  • wrapImagesInline_rewriter
  1 <?php
  2 /*
  3  *  Уведомление менеджера и клиента при помощи SMS (создание заказа и изменение заказа ) 
  4  *  Используем шлюз smsc.ru 
  5  *  
  6  *  @author menedem
  7  */
  8 class SMSCOrderNotification extends OrderHandlersDecorator {
  9     
 10     // URL для отправки сообщений через smsc
 11     protected static $smscSendURL = 'https://smsc.ru/sys/send.php';
 12     
 13     // поле объекта Member для использования как номера телефона для отправки SMS
 14     // добавляется Member в модуле cart (ExtendMemberCart.php)
 15     protected static $memberPhoneField = 'Phone';
 16     
 17     static $smscErrors = array(
 18         '1' => 'Ошибка в параметрах.',
 19         '2' => 'Неверный логин или пароль.',
 20         '3' => 'Недостаточно средств на счете Клиента.',
 21         '4' => 'IP-адрес временно заблокирован из-за частых ошибок в запросах. Подробнее',
 22         '5' => 'Неверный формат даты.',
 23         '6' => 'Сообщение запрещено (по тексту или по имени отправителя).',
 24         '7' => 'Неверный формат номера телефона.',
 25         '8' => 'Сообщение на указанный номер не может быть доставлено.',
 26         '9' => 'Отправка более одного одинакового запроса на передачу SMS-сообщения либо более пяти одинаковых запросов на получение стоимости сообщения в течение минуты.',
 27     );
 28     
 29     /*
 30      * Установка поля объекта Member для использования как номера телефона для отправки SMS
 31      *
 32      * @param string $field
 33      */
 34     static function setMemberPhoneField($field) {
 35         self::$memberPhoneField = $field;
 36     }
 37     
 38     /**
 39      * 
 40      * 
 41      * @return string
 42      */
 43     static function getSMSCURL() {
 44         $conf = SiteConfig::current_site_config();
 45         if ($conf->SMSCLogin && $conf->SMSCPassword) {
 46             $url = self::$smscSendURL . '?login='.$conf->SMSCLogin.'&psw='.$conf->SMSCPassword.'&charset=utf-8';
 47             return $url;
 48         }       
 49     }
 50     
 51     /**
 52      * Обработчик события "После создания заказа"
 53      * 
 54      * @param Member $member - текущий пользователь
 55      * 
 56      */
 57     function OnAfterCreateOrder(& $member) {
 58         $conf = SiteConfig::current_site_config();
 59         
 60         $phone = $this->getClientPhone();
 61         if ($conf->ClientSMSCOrderNotificationActive && $phone) {
 62             $this->send(
 63                 $phone,
 64                 $this->owner->customise(array(
 65                     'Member' => $this->owner->Member(),
 66                     'Order' => $this->owner,
 67                     'SiteTitle' => $conf->Title,
 68                     'CatalogCurrency' => $conf->CatalogCurrency,
 69                 ))->owner->renderWith('SMSC_ClientCreateOrderMessage'),
 70                 $conf->ClientNotificationType
 71             );
 72         }
 73 
 74         if ($conf->ManagerSMSCOrderNotificationActive && $conf->ManagerPhones) {                                
 75             $this->send(
 76                 $conf->ManagerPhones,
 77                 $this->owner->customise(array(
 78                     'Member' => $this->owner->Member(),
 79                     'Order' => $this->owner,
 80                     'SiteTitle' => $conf->Title,
 81                     'CatalogCurrency' => $conf->CatalogCurrency,
 82                 ))->owner->renderWith('SMSC_ManagerCreateOrderMessage'),
 83                 $conf->ManagerNotificationType
 84             );
 85         }       
 86     }
 87     
 88     /**
 89      * Обработчик события "Смена статуса заказа"
 90      * 
 91      * @param Member $member - текущий пользователь
 92      * @param string $changedStatus - новый??? старый??? статус
 93      * @param string $note - примечание к смене статуса
 94      */
 95     function OnAfterChangeStatus($member, $changedStatus, $note) {
 96         $conf = SiteConfig::current_site_config();      
 97         
 98         $phone = $this->getClientPhone();
 99         if ($conf->ClientSMSCOrderNotificationActive && $phone) {
100             $this->send(
101                 $phone,
102                 $this->owner->customise(array(
103                     'Member' => $this->owner->Member(),
104                     'Note' => $note,
105                     'Order' => $this->owner,
106                 ))->owner->renderWith('SMSC_ClientChangeOrderStatusMessage'),
107                 $conf->ClientNotificationType
108             );
109         }       
110         
111         /*
112         // менеджер обычно сам меняет статус - зачем ему сообщать?
113         if ($member && $member->ID != $this->owner->MemberID) return;
114         if ($conf->ManagerSMSCOrderNotificationActive && $conf->ManagerPhones) {        
115             $this->send(
116                 $conf->ManagerPhones,
117                 $this->owner->customise(array(
118                     'Member' => $member,
119                     'Order' => $this->owner,                
120                 ))->owner->renderWith('SMSC_ManagerChangeOrderStatusMessage'),
121                 $conf->ManagerNotificationType
122             );
123         }
124         */
125     }
126     
127     /**
128      * Ищем телефон клиента для СМС
129      * 
130      * @return string
131      */
132     private function getClientPhone() {
133         $phone = $this->owner->Phone;
134         if (!$phone) {
135             if ($member = $this->owner->Member()) {
136                 $phoneField = self::$memberPhoneField;
137                 $phone = $member->{$phoneField};
138             }
139         }
140         return $phone;
141     }
142     
143     /**
144      * Отправляем СМС через шлюз
145      * 
146      * @param string $phone - телефон на который надо слать СМС
147      * @param string $message - текст СМС
148      * @param <type> $type - тип уведомления СМС/голосовой звонок
149      * 
150      * @return boolean - отправили или нет
151      */
152     private function send($phones, $message, $type = 'sms') {
153         $baseURL = self::getSMSCURL();
154         if (!$baseURL) return false;
155         if (!$phones) return false;
156         if (!$message) return false;
157         
158         $url = $baseURL . '&phones=' . urlencode($phones) . '&mes=' . urlencode($message);
159         if ($type == 'voice') {
160             $url .= '&call=1';
161         }               
162         //$rs = file_get_contents($url);            
163         $request = new RestfulService($url, 0);
164         
165         // Выставляем "Максимально позволенное количество секунд для выполнения cURL-функций."
166         $rs = $request->request('', "GET", null, null, array(CURLOPT_TIMEOUT => 5));        
167         
168         // диагностика ошибок отправки     
169         $error = '';
170         if ($rs->isError()) {           
171             $error = sprintf(_t('SMSCOrderNotification.ErrorMesssage', 'Error Messsage'), $phones, ($rs->getStatusCode() . ' - ' . $rs->getStatusDescription()));
172         } elseif (substr($rs->getBody(), 0, 5) == 'ERROR') {                
173             $errorNo = (int)substr($rs->getBody(), 8, 1);
174             $error = sprintf(_t('SMSCOrderNotification.ErrorMesssage', 'Error Messsage'), $phones, ((isset(self::$smscErrors[$errorNo])) ? self::$smscErrors[$errorNo] : $rs));
175         }       
176         if ($error) {   
177             $conf = SiteConfig::current_site_config();                      
178             $em = new Email(Email::getAdminEmail(), $conf->CartAdminEmail(), _t('SMSCOrderNotification.SendError','Send Error'),  $error);
179             $em->send();            
180         }   
181         return true;
182     }
183 }
184 
185 // Декоратор SiteConfig для этого типа уведомлений
186 class SMSCOrderNotification_SiteConfig extends SiteConfigDecorator {
187     
188     static function smsNotificationTypes() {
189         $types = array();
190         $types['sms'] = _t('SMSCOrderNotification_SiteConfig.SMS', 'SMS');
191         $types['voice'] = _t('SMSCOrderNotification_SiteConfig.Voice', 'Voice');
192         return $types;
193     }
194     
195     function extraStatics() {
196         return array(
197             'db' => array(                
198                 'ClientSMSCOrderNotificationActive' => 'Boolean', // уведомлять клиента по СМС
199                 'ManagerSMSCOrderNotificationActive' => 'Boolean', // уведомлять менеджера по СМС
200                 'SMSCLogin' => 'Varchar(255)', // логин для smsc
201                 'SMSCPassword' => 'Varchar(255)', // пароль для smsc
202                 'SenderName' => 'Varchar(255)', // имя отправителя
203                 'ManagerPhones' => 'Varchar(255)', // номер (или список номеров через , или ;) менеджера
204                 'ManagerNotificationType' => "Enum('sms,voice')", // выбор варианта уведомления для менеджера: смс или голосовой звонок
205                 'ClientNotificationType' => "Enum('sms,voice')", // выбор варианта уведомления для пользователя: смс или голосовой звонок
206             )
207         );
208     }
209     
210     public function updateCMSFields(FieldSet &$fields) {    
211         $tab = self::get_config_tab($fields, 'OrderNotifications.SMSCOrderNotification');
212 
213         $tab->push(new CheckboxField('ClientSMSCOrderNotificationActive', $this->owner->FieldLabel('ClientSMSCOrderNotificationActive')));
214         $tab->push(new DropdownField('ClientNotificationType', $this->owner->FieldLabel('ClientNotificationType'), self::smsNotificationTypes()));
215         $tab->push(new CheckboxField('ManagerSMSCOrderNotificationActive', $this->owner->FieldLabel('ManagerSMSCOrderNotificationActive')));
216         $tab->push(new DropdownField('ManagerNotificationType', $this->owner->FieldLabel('ManagerNotificationType'), self::smsNotificationTypes()));
217         $tab->push(new TextField('ManagerPhones', $this->owner->FieldLabel('ManagerPhones')));
218 
219         $tab->push(new HeaderField('SMSCParams', _t('SMSCOrderNotification_SiteConfig.SMSC_Params', 'SMSC Params')));
220         $tab->push(new TextField('SMSCLogin', $this->owner->FieldLabel('SMSCLogin')));
221         $tab->push(new PasswordField('SMSCPassword', $this->owner->FieldLabel('SMSCPassword')));
222         $tab->push(new TextField('SenderName', $this->owner->FieldLabel('SenderName')));
223     }
224 }
225 
[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. -
Webylon 3.2 API Docs API documentation generated by ApiGen 2.8.0