Version: current

      1 <?php
      2
      3 /**
      4  * Page type for creating a page that contains a form that visitors can
      5  * use to subscript to a newsletter.
      6  *
      7  * @package newsletter
      8  */
      9 class SubscribeForm extends Page {
     10
     11     static $icon = 'newsletter/img/mail-subscribe';
     12     static $db = array(
     13         'SuccessMessage' => 'HTMLText',
     14         'AllNewsletters' => 'Boolean',
     15         'Subject' => 'Varchar(250)',
     16         'ShowFirstNameField' => 'Boolean', // показывать поле Имя в форме подписки
     17         'ShowSurnameField' => 'Boolean', // показывать поле Фамилия в форме подписки
     18     );
     19     static $defaults = array(
     20         'Content' => '<p>Подписка на новости сайта</p>',
     21         'SuccessMessage' => '<p>Спасибо вы подписаны на выбранные списки расслыки</p>',
     22         'NewletterListTitle' => 'Выберите списки рассылки',
     23     );
     24     static $many_many = array(
     25         'Newsletters' => 'NewsletterType'
     26     );
     27
     28     // флаг использования капчи в форме подписки на рассылку
     29     static $useCaptcha = true;
     30
     31     // обязательные поля формы подписки
     32     static $required_fields = array('Email', 'FirstName', 'Newsletters');
     33
     34     public function Newsletters() {
     35         return $this->getManyManyComponents('Newsletters');
     36     }
     37
     38     function getCMSFields($controller = null) {
     39         $fields = parent::getCMSFields();
     40         $fields->findOrMakeTab('Root.Content.OnSuccess', _t('SubscribeForm.ON_SUCCESS', 'On Success'));
     41         $fields->findOrMakeTab('Root.Content.Setup', _t('SubscribeForm.SETUP', 'Setup'));
     42
     43         $fields->addFieldToTab("Root.Content.OnSuccess", new HTMLEditorField('SuccessMessage', 'Сообщение о успешной подписке'));
     44         $fields->addFieldToTab("Root.Content.Setup", new TextField('Subject', 'Тема письма с уведомлением о подписке'));
     45
     46         $fields->addFieldToTab(
     47                 "Root.Content.Setup",
     48                 new OptionsetField('AllNewsletters', '',
     49                         array(
     50                             1 => 'Все рассылки сайта',
     51                             0 => 'Только указанные расслыки'
     52                         ),
     53                         $this->AllNewsletters
     54                 )
     55         );
     56
     57         $fields->addFieldToTab("Root.Content.Setup", new CheckboxSetField('Newsletters', 'Выберите рассылки', DataObject::get('NewsletterType')));
     58
     59         $fields->addFieldToTab("Root.Content.Setup", new CheckboxField('ShowFirstNameField', $this->fieldLabel('ShowFirstNameField')));
     60         $fields->addFieldToTab("Root.Content.Setup", new CheckboxField('ShowSurnameField', $this->fieldLabel('ShowSurnameField')));
     61
     62         return $fields;
     63     }
     64
     65 }
     66
     67 /**
     68  * Controller for the SubscribeForm page
     69  *
     70  * @package newsletter
     71  */
     72 class SubscribeForm_Controller extends Page_Controller {
     73
     74     function process($data, $form = null) {
     75         // Create user if not exists
     76         if (!$member = DataObject::get_one('Member', 'Email LIKE \'' . $data['Email'] . '\'')) {
     77             $member = Object::create("Member");
     78             $member->update($data);
     79             $member->write();
     80         }
     81
     82         $newsletters = new DataObjectSet();
     83
     84         // Add member to the selected newsletters
     85         if (isset($data['Newsletters'])) {
     86             if (is_array($data['Newsletters'])) {
     87                 foreach ($data['Newsletters'] as $listID) {
     88                     if ($newsletter = DataObject::get_by_id('NewsletterType', (int)$listID)) {
     89                         $newsletters->push($newsletter);
     90                         $member->Groups()->add($newsletter->GroupID);
     91                     }
     92                 }
     93             } else {
     94                 if ($newsletter = DataObject::get_by_id('NewsletterType', (int)$data['Newsletters'])) {
     95                     $newsletters->push($newsletter);
     96                     $member->Groups()->add($newsletter->GroupID);
     97                 }
     98             }
     99         }
    100
    101         // email the user with their details
    102         $templateData = array(
    103             'Content' => $this->SuccessMessage,
    104             'Email' => $member->Email,
    105             'FirstName' => $member->FirstName,
    106             'Surname' => $member->Surname,
    107             'Password' => $member->Password,
    108             'Newsletters' => $newsletters,
    109             'UnsubscribeLink' => Director::baseURL() . 'unsubscribe/index/' . $member->Email
    110         );
    111
    112         $email = new Email(Email::getAdminEmail(), $member->Email, $this->Subject);
    113         $email->setTemplate('SubscribeEmail');
    114         $email->populateTemplate($templateData);
    115         $email->send();
    116
    117         $templateData['Content'] = $this->SuccessMessage;
    118         $templateData['UnsubscribeLink'] = Director::baseURL() . 'unsubscribe/index';
    119
    120         if ($this->isAjax()) {
    121             if ($request = $this->getRequest()) {
    122                 if ($acceptType = $request->getHeader('Accept')) {
    123                     if(strpos($acceptType, 'application/json') !== FALSE) {
    124                         return json_encode(array(array(
    125                             'type' => 'good',
    126                             'message' => $this->customise($templateData)->renderWith('SubscribeSuccess')
    127                         )));
    128                     }
    129                 }
    130             }
    131             return $this->customise($templateData)->renderWith('SubscribeSuccess');
    132         }
    133
    134         $custom = $this->customise(array(
    135                     "Content" => $this->customise($templateData)->renderWith('SubscribeSuccess'),
    136                     'Form' => false,
    137                 ));
    138         return $custom->renderWith('Page');
    139     }
    140
    141     private function doSubscribe($data) {
    142
    143     }
    144
    145     function Form($data = null) {
    146         if ($this->AllNewsletters)
    147             $newsletterList = DataObject::get('NewsletterType');
    148         else
    149             $newsletterList = $this->Newsletters();
    150
    151 // !!! требуется нормальная локализация
    152         if (!$newsletterList || ($newsletterList->Count() == 0)) {
    153             $this->Title = "Нет доступных рассылок!";
    154             $this->Content = "К сожалению на данным момент нет рассылок на которые можно подписаться.";
    155             return null;
    156         }
    157
    158         $fields = new FieldSet();
    159         if ($this->ShowFirstNameField) {
    160             $fields->push(new TextField('FirstName', _t('SubscribeForm.FIRSTNAME', 'FirstName')));
    161         }
    162         if ($this->ShowSurnameField) {
    163             $fields->push(new TextField('Surname', _t('SubscribeForm.SURNAME', 'Surname')));
    164         }
    165         $fields->push(new EmailField('Email', _t('SubscribeForm.EMAIL', 'Email')));
    166
    167         if ($newsletterList->Count() == 1) {
    168             $fields->push(new HiddenField('Newsletters', 'Newsletters', $newsletterList->First()->ID));
    169         } else {
    170             $fields->push(new CheckboxSetField('Newsletters', _t('SubscribeForm.NEWSLETTERS', 'Newsletters'), $newsletterList));
    171         }
    172
    173         $this->extend('updateSubscribeFormFields', $fields);
    174
    175         $form = new Form(
    176                 $this,
    177                 'Form',
    178                 $fields,
    179                 new FieldSet(new FormAction('process', _t('SubscribeForm.PROCESS', 'Subscribe'))),
    180                 new RequiredFields(SubscribeForm::$required_fields)
    181         );
    182         if (SubscribeForm::$useCaptcha && class_exists('SpamProtectorManager')) {
    183             SpamProtectorManager::update_form($form);
    184         }
    185         $form->setTemplate('SubscribeForm');
    186         return $form;
    187     }
    188
    189 }
    190

[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. -