Source of file FlexiFormMailChimpHandler.php
Size: 12,764 Bytes - Last Modified: 2021-12-24T06:34:17+00:00
/var/www/docs.ssmods.com/process/src/code/model/flexiformhandlers/FlexiFormMailChimpHandler.php
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318 | <?php class FlexiFormMailChimpHandler extends FlexiFormEmailHandler { private static $handler_label = 'Mailchimp Handler'; private static $handler_description = 'A basic handler with Mail Chimp List Integration'; private static $handler_settings = array( 'MailChimpApiKey' => 'FlexiFormHandlerSetting', 'MailChimpListID' => 'FlexiFormHandlerSetting', 'MailChimpEmailField' => 'MailChimpEmailHandlerSetting', 'MailChimpSendWelcome' => 'FlexiFormBooleanHandlerSetting', 'MailChimpDoubleOptIn' => 'FlexiFormBooleanHandlerSetting', 'MailChimpEmailType' => 'FlexiFormEnumHandlerSetting' ); private static $db = array( 'MailChimpApiKey' => 'Varchar', 'MailChimpListID' => 'Varchar', 'MailChimpSendWelcome' => 'Boolean', 'MailChimpDoubleOptIn' => 'Boolean', 'MailChimpEmailType' => "Enum(array('html', 'text'))", 'MailChimpEmailField' => 'Int' ); public function populateDefaults() { $this->MailChimpDoubleOptIn = true; $this->MailChimpSendWelcome = false; $this->MailChimpEmailType = 'html'; return parent::populateDefaults(); } public function getCMSFields() { $fields = parent::getCMSFields(); $remove_fields = array( 'MailChimpEmailField' ); $client = new FlexiFormMailChimpClient($this->MailChimpApiKey); foreach ($this->stat('handler_settings') as $component => $class) { if (in_array($component, $remove_fields)) { $fields->removeByName($component); continue; } $field = $this->augmentMailChimpField($fields->dataFieldByName($component), $component, $client); $fields->addFieldToTab('Root.MailChimp', $field); } return $fields; } // @TODO management of list subscribers from Mailchimp tab? public function updateCMSFlexiTabs(TabSet $fields, TabSet $settings_tab, $flexi) { parent::updateCMSFlexiTabs($fields, $settings_tab, $flexi); $mailchimp_tab = new Tab('MailChimp', 'MailChimp'); $fields->insertBefore($mailchimp_tab, 'Settings'); $client = new FlexiFormMailChimpClient($flexi->FlexiFormSetting('MailChimpApiKey')->getValue()); foreach ($this->stat('handler_settings') as $component => $class) { $field_name = $this->getSettingFieldName($component); $field = $this->augmentMailChimpField($settings_tab->fieldByName($field_name), $component, $client); // Move Settings to designated MailChimp Tab $settings_tab->removeByName($field_name); $mailchimp_tab->push($field); } // integrate list groups if ($list_id = $flexi->FlexiFormSetting('MailChimpListID')->getValue()) { $field = new CheckboxSetField('FlexiFormMailChimpGroups', 'List Groups'); if ($list_groups = $this->getInterestGroups($list_id, $client)) { $field->setSource($list_groups->map('id', 'name')); $field->setValue( $flexi->FlexiFormFields() ->filter('ClassName', 'FlexiMailChimpInterestGroupField') ->column('InterestGroupID')); $field->description = 'Checked groups are added to your form Fields. Groups are refreshed every 10 minutes.'; } else { $field = $field->performReadonlyTransformation(); $field->setValue('This list has no Interest Groups'); } $mailchimp_tab->push($field); } $mailchimp_tab->push( new LiteralField('MailChimpRefresh', '<br /><hr />NOTE: list and group selections are cached from mailchimp for up to 10 minutes. changing the API Key or list will cause a refresh.')); } public function onConfigUpdate(FlexiFormConfig $config, DataObject $flexi) { $fields = $flexi->FlexiFormFields(); $requested_groups = (array) Controller::curr()->getRequest()->requestVar('FlexiFormMailChimpGroups'); $current_groups = array(); // remove non requested groups from field list foreach ($fields as $field) { if ($field->is_a('FlexiMailChimpInterestGroupField')) { if (in_array($field->InterestGroupID, $requested_groups)) { $current_groups[] = $field->InterestGroupID; } else { $fields->remove($field); $field->delete(); } } } // calculate groups that need to be added to field list $new_groups = array_diff($requested_groups, $current_groups); if (! empty($new_groups)) { $client = new FlexiFormMailChimpClient($flexi->FlexiFormSetting('MailChimpApiKey')->getValue()); $list_id = $flexi->FlexiFormSetting('MailChimpListID')->getValue(); $groups = $this->getInterestGroups($list_id, $client); foreach ($new_groups as $group_id) { if ($group = $groups->find('id', $group_id)) { $options = array(); foreach ($group['groups'] as $option) { // mailchimp subscribe API uses names vs. IDs... //$options[$option['id']] = $option['name']; $options[$option['name']] = $option['name']; } $field = FlexiFormUtil::CreateFlexiField('FlexiMailChimpInterestGroupField', array( 'Name' => $group['name'], 'InterestGroupID' => $group['id'], 'InterestGroupFormField' => $group['form_field'], 'Readonly' => true, 'Options' => $options )); $fields->add($field, array( 'Prompt' => $group['name'] )); } } } return parent::onConfigUpdate($config, $flexi); } protected function augmentMailChimpField(FormField $field, String $component, FlexiFormMailChimpClient $client) { switch ($component) { case 'MailChimpSendWelcome': $field->setTitle('Send Welcome Email'); $field->description = 'flag to control whether the Welcome Email is sent. Has no effect if double opt-in is enabled.'; break; case 'MailChimpDoubleOptIn': $field->setTitle('Require Double Opt-In'); $field->description = 'flag to control whether a double opt-in confirmation message is sent, defaults to true. Abusing this may cause your account to be suspended.'; break; case 'MailChimpEmailField': $field->setTitle('Subscription Field'); $field->description = 'Used as the subscriber email. Must be an Email Field or subclass.'; break; case 'MailChimpEmailType': // @TODO ought to let user select preference through a form field [ similar to interest groups? ] $field->setTitle('Email Preference'); $field->description = 'email type preference for subscribers (html or text - defaults to html)'; break; case 'MailChimpApiKey': if ($client->isApiKeyValid()) { $field->description = 'This API Key is Valid.'; } else { if ($client->getApiKey() == '') { $field->description = 'Your MailChimp API Key. Found under Account Extras > Your API Keys'; } else { $field->description = 'This API Key is not Valid.'; } } $field->setTitle('MailChimp API Key'); break; case 'MailChimpListID': if ($lists = $client->getLists( array( 'limit' => 100, 'sort_field' => 'web' ))) { $value = $field->Value(); $source = array( '' => 'Please Select a List' ); $field = new DropdownField($field->getName()); $field->description = 'Subscribers will be added to this list. Lists are refreshed every 10 minutes.'; if ($lists['total'] > 0) { foreach ($lists['data'] as $list) { $source[$list['id']] = $list['name']; } } $field->setValue($value); $field->setSource($source); } else { $field = $field->performReadonlyTransformation(); if (! $client->isApiKeyValid()) { $field->setValue('Invalid API Key'); } else { $field->setValue('Error loading Lists from your Account'); } } $field->setTitle('MailChimp List ID'); break; } return $field; } protected function getInterestGroups(Integer $list_id, FlexiFormMailChimpClient $client) { if ($groups = $client->getInterestGroupings(array( 'id' => $list_id ))) { return new ArrayList($groups); } } // Submission Handling ////////////////////// public function onSubmit(Array $data, FlexiForm $form, SS_HTTPRequest $request, DataObject $flexi) { if ($return = parent::onSubmit($data, $form, $request, $flexi)) { $message = 'Skipped MailChimp Syncing'; // @TODO asynchronous api calls $client = new FlexiFormMailChimpClient( $flexi->FlexiFormSetting('MailChimpApiKey')->getValue()); $client->setAutoCache(false); if ($list_id = $flexi->FlexiFormSetting('MailChimpListID')->getValue()) { if ($email_field = $flexi->getFlexiFormFrontEndFieldByID( $flexi->FlexiFormSetting('MailChimpEmailField') ->getValue())) { if (isset($data[$email_field->SafeName()])) { $params = array( 'id' => $list_id, 'email' => array( 'email' => $data[$email_field->SafeName()] ), 'email_type' => $flexi->FlexiFormSetting('MailChimpEmailType')->getValue(), 'double_optin' => $flexi->FlexiFormSetting('MailChimpDoubleOptIn')->getValue(), 'send_welcome ' => $flexi->FlexiFormSetting('MailChimpSendWelcome')->getValue() ); $groupings = array(); foreach ($flexi->FlexiFormFields()->filter('ClassName', 'FlexiMailChimpInterestGroupField') as $group_field) { if (isset($data[$group_field->SafeName()])) { $groupings[] = array( 'id' => $group_field->InterestGroupID, 'groups' => (array) $data[$group_field->SafeName()] ); } } $merge_vars = array(); if (! empty($groupings)) { $merge_vars['groupings'] = $groupings; } if (! $params['double_optin']) { $merge_vars['optin_ip'] = Controller::curr()->getRequest()->getIP(); } if (! empty($merge_vars)) { $params['merge_vars'] = $merge_vars; } if ($success = $client->subscribe($params)) { $message = 'Synced ' . $email_field->Name . ' with MailChimp'; } else { $message = 'Failed Syncing ' . $email_field->Name . ' with MailChimp'; } } } } } $this->submission->addStatusMessage($message); $this->submission->write(); return $return; } } |