/** * Save the subscription * * @return void */ public function save() { JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); $appl = JFactory::getApplication(); $db = JFactory::getDBO(); $query = $db->getQuery(true); $chimp = new cmcHelperChimp(); $input = JFactory::getApplication()->input; $form = $input->get('jform', '', 'array'); $isAjax = $input->get('ajax'); $mergeVars = CmcHelperList::mergeVars($form); $listId = $form['cmc']['listid']; $email = $mergeVars['EMAIL']; $chimp->listSubscribe($listId, $email, $mergeVars, 'html', true, true, true, false); if ($chimp->errorCode) { $response['html'] = $chimp->errorMessage; $response['error'] = true; } else { // Get the member info from mailchimp $memberInfo = $chimp->listMemberInfo($listId, $email); $status = 'applied'; // User was found on list if ($memberInfo['success']) { $status = $memberInfo['data'][0]['status']; } // Check if the subscription is already present in the db if (CmcHelperUsers::getSubscription($email, $listId)) { $query->update('#__cmc_users')->set(array('list_id = ' . $db->quote($listId), 'email = ' . $db->quote($email), 'merges = ' . $db->quote(json_encode($mergeVars)), 'status = ' . $db->q($status)))->where('list_id = ' . $db->quote($listId))->where('email = ' . $db->quote($email)); $html = 'updated'; } else { $query->insert('#__cmc_users')->columns('list_id,email,merges,status')->values($db->quote($listId) . ',' . $db->quote($email) . ',' . $db->quote(json_encode($mergeVars)) . ',' . $db->q($status)); $html = 'saved'; } $db->setQuery($query); $db->execute(); $response['html'] = $html; $response['error'] = false; } if ($isAjax) { echo json_encode($response); jexit(); } $appl->enqueueMessage($response['html']); $appl->redirect($_SERVER['HTTP_REFERER']); }
/** * Method to get the record form. * * @param array $data An optional array of data for the form to interogate. * @param boolean $loadData True if the form is to load its own data (default case), false if not. * * @return JForm A JForm object on success, false on failure */ public function getForm($data = array(), $loadData = true) { // Get the form. $form = $this->loadForm('com_cmc.user', 'user', array('control' => 'jform', 'load_data' => $loadData)); $userData = $this->getItem(); // If the user data is stored in the session we are dealing with arrays, if we are loading from DB with object if (is_array($userData)) { $old = $userData; $userData = new JRegistry(); $userData->set('list_id', $old['list_id']); $userData->set('email', $old['cmc_groups']['email']); } elseif (is_object($userData) && !$userData->get('id')) { $userData = new JRegistry(); $userData->set('list_id', isset($data['list_id']) ? $data['list_id'] : ''); $userData->set('email', isset($data['cmc_groups']['EMAIL']) ? $data['cmc_groups']['EMAIL'] : ''); } $listId = $userData->get('list_id', JFactory::getApplication()->input->get('filter_list')); // Get the merge fields and create a new form if ($listId) { $params = new JRegistry(); $params->set('listid', $listId); $fields = array_map(function ($value) { return $value['tag']; }, CmcHelperList::getMergeFields($listId)); $interests = array_map(function ($value) { return $value['id']; }, CmcHelperList::getInterestsFields($listId)); $params->set('fields', $fields); $params->set('interests', $interests); $renderer = CmcHelperXmlbuilder::getInstance($params); // Generate the xml for the form $xml = $renderer->build(); $form->load($xml, true); $subscriptionData = CmcHelperUsers::getSubscription($userData->get('email'), $userData->get('list_id')); // Bind the data to the form if ($subscriptionData) { $form->bind(CmcHelperSubscription::convertMergesToFormData($subscriptionData->merges)); } } if (empty($form)) { return false; } return $form; }
/** * Creates a JForm * * @param int $id - the module id. We use it to create unique jform instance * @param object $params - the module params * * @return object */ public static function getForm($id, $params) { $renderer = CmcHelperXmlbuilder::getInstance($params); $user = JFactory::getUser(); // Generate the xml for the form $xml = $renderer->build(); $mapping = self::getMapping($params->get('mapfields')); try { JForm::addFieldPath(JPATH_ADMINISTRATOR . '/components/com_cmc/models/fields'); $form = JForm::getInstance('mod_cmc_' . $id, $xml, array('control' => 'jform')); $form->bind($mapping); // If we are not dealing with a guest, try to load the already existing profile merges and add them to the form if (!$user->guest) { $subscriptionData = CmcHelperUsers::getSubscription($user->email, $params->get('listid')); if ($subscriptionData) { $form->bind(CmcHelperSubscription::convertMergesToFormData($subscriptionData->merges)); } } } catch (Exception $e) { return false; } return $form; }
/** * Syncs the users of the list * * @return void */ public function batch() { // Check for a valid token. If invalid, send a 403 with the error message. JSession::checkToken('request') or $this->sendResponse(new Exception(JText::_('JINVALID_TOKEN'), 403)); // Put in a buffer to silence noise. ob_start(); // Remove the script time limit. @set_time_limit(0); $state = CmcSyncerState::getState(); $chimp = new CmcHelperChimp(); $members = $chimp->listMembers($state->lists[0]['mc_id'], 'subscribed', null, $state->offset, $state->batchSize); // Split the array of emails to 50 items - the max number possible for the listMemberInfo function $emails = array_chunk(array_map(function ($ar) { return $ar['email']; }, $members['data']), 50); $info = array(); // Let's fetch all the info about our members foreach ($emails as $chunks) { $memberInfo = $chimp->listMemberInfo($state->lists[0]['mc_id'], $chunks); if (!$memberInfo['errors']) { $info = array_merge($info, $memberInfo['data']); } } // Save the users in our database CmcHelperUsers::save($info, $state->lists[0]['id'], $state->lists[0]['mc_id']); $pages = $state->lists[0]['toSync'] / $state->batchSize; if ($state->offset < $pages) { $state->offset = $state->offset + 1; $state->header = JText::sprintf('COM_CMC_BATCH_SYNC_IN_LIST', $state->lists[0]['name']); $state->message = JText::sprintf('COM_CMC_BATCH_SYNC_PROGRESS', $state->offset * $state->batchSize, $state->batchSize); } if ($state->offset >= $pages) { // First list in the array was synced, lets remove it $oldList = array_shift($state->lists); // If we still have lists, then let us reset the offset if (count($state->lists)) { $state->header = JText::sprintf('COM_CMC_BATCH_SYNC_IN_OLD_LIST_COMPLETE', $oldList['name']); $state->message = JText::sprintf('COM_CMC_BATCH_SYNC_IN_OLD_LIST_COMPLETE_DESC', $oldList['toSync'], $oldList['name'], $state->lists[0]['name']); $state->offset = 0; } else { $state->header = JText::_('COM_CMC_SYNC_COMPLETE'); $state->message = '<div class="alert alert-info">' . JText::_('COM_CMC_SYNC_COMPLETE_DESC') . '</div>'; } } CmcSyncerState::setState($state); $this->sendResponse($state); }
/** * Prepares the form * * @param array $data - the users data * @param boolean $isNew - is the user new * @param object $result - the db result * @param string $error - the error message * * @return boolean */ public function onUserAfterSave($data, $isNew, $result, $error) { $userId = ArrayHelper::getValue($data, 'id', 0, 'int'); $input = JFactory::getApplication()->input; $task = $input->get('task'); if (in_array($task, array('register', 'activate'))) { if ($userId && $result && isset($data['cmc']) && count($data['cmc'])) { if ($data["cmc"]["newsletter"] != "1" && $isNew != false) { // Abort if Newsletter is not checked return true; } $mappedData = $this->getMapping($this->params->get('mapfields'), $data); if (count($mappedData)) { $mergedGroups = array_merge($mappedData, $data['cmc_groups']); $data = array_merge($data, array('cmc_groups' => $mergedGroups)); } $user = JFactory::getUser($data["id"]); if ($data["block"] == 1) { // Temporary save user CmcHelperRegistration::saveTempUser($user, $data, _CPLG_JOOMLA); } else { if (!$isNew) { // Activate User to Mailchimp CmcHelperRegistration::activateTempUser($user); } else { // Directly activate user $activated = CmcHelperRegistration::activateDirectUser($user, $data["cmc"], _CPLG_JOOMLA); if ($activated) { JFactory::getApplication()->enqueueMessage(JText::_('COM_CMC_YOU_VE_BEEN_SUBSCRIBED_BUT_CONFIRMATION_IS_NEEDED')); } } } } else { // We only do something if the user is unblocked if ($data["block"] == 0) { // Checking if user exists etc. is taken place in activate function CmcHelperRegistration::activateTempUser(JFactory::getUser($data["id"])); } } } if (in_array($task, array('apply', 'save'))) { if ($userId && $result && isset($data['cmc']) && count($data['cmc'])) { if ($data["cmc"]["newsletter"] != "1") { // Abort if Newsletter is not checked return true; } $mappedData = $this->getMapping($this->params->get('mapfields'), $data); if (count($mappedData)) { $mergedGroups = array_merge($mappedData, $data['cmc_groups']); $data = array_merge($data, array('cmc_groups' => $mergedGroups)); } } $subscription = CmcHelperUsers::getSubscription($data['email'], $data['cmc']['listid']); // Updating it to mailchimp $update = $subscription ? true : false; CmcHelperList::subscribe($data['cmc']['listid'], $data['email'], $data['cmc_groups']['FNAME'], $data['cmc_groups']['LNAME'], CmcHelperList::mergeVars($data), 'html', $update, true); } return true; }
/** * Subscribe a user to mailchimp and if set create an entry for this user in our database * * @param string $listId - the list id * @param string $email - the email of the user * @param string $firstname - the first name of the user * @param string $lastname - the last name of the user * @param array $groupings - any groupings (merge fields + interest fields) * @param string $email_type - the type of email the user wants to receive * @param bool $update - are we updating an existing user * @param bool $updateLocal - shall we create an entry for this user in our DB? * * @return bool * * @throws Exception */ public static function subscribe($listId, $email, $firstname, $lastname, $groupings = array(), $email_type = "html", $update = false, $updateLocal = false) { $api = new CmcHelperChimp(); $merge_vars = array_merge(array('FNAME' => $firstname, 'LNAME' => $lastname), $groupings); // By default this sends a confirmation email - you will not see new members // until the link contained in it is clicked! $api->listSubscribe($listId, $email, $merge_vars, $email_type, false, $update); if ($api->errorCode) { JFactory::getApplication()->enqueueMessage(JTEXT::_("COM_CMC_SUBSCRIBE_FAILED") . " " . $api->errorCode . " / " . $api->errorMessage, 'error'); return false; } if ($updateLocal) { JLoader::discover('cmcModel', JPATH_ADMINISTRATOR . '/components/com_cmc/models/'); $subscription = CmcHelperUsers::getSubscription($email, $listId); $memberInfo = $api->listMemberInfo($listId, $email); if ($memberInfo['success']) { $memberInfo = $memberInfo['data'][0]; } $model = JModelLegacy::getInstance('User', 'CmcModel'); $user = CmcHelperUsers::getJoomlaUsers(array($email)); $saveData = CmcHelperUsers::bind($memberInfo, $user); if ($subscription) { $saveData['id'] = $subscription->id; } // Update in the local db $model->save($saveData); } return true; }