/** * Execute the action */ public function execute() { parent::execute(); // get parameters $categoryTitle = trim(\SpoonFilter::getPostValue('value', null, '', 'string')); // validate if ($categoryTitle === '') { $this->output(self::BAD_REQUEST, null, BL::err('TitleIsRequired')); } else { // get the data // build array $item['title'] = \SpoonFilter::htmlspecialchars($categoryTitle); $item['language'] = BL::getWorkingLanguage(); $meta['keywords'] = $item['title']; $meta['keywords_overwrite'] = 'N'; $meta['description'] = $item['title']; $meta['description_overwrite'] = 'N'; $meta['title'] = $item['title']; $meta['title_overwrite'] = 'N'; $meta['url'] = BackendBlogModel::getURLForCategory(\SpoonFilter::urlise($item['title'])); // update $item['id'] = BackendBlogModel::insertCategory($item, $meta); // output $this->output(self::OK, $item, vsprintf(BL::msg('AddedCategory'), array($item['title']))); } }
/** * Loads the dataGrids */ private function loadDatagrids() { // load all categories $categories = BackendFaqModel::getCategories(true); // loop categories and create a dataGrid for each one foreach ($categories as $categoryId => $categoryTitle) { $dataGrid = new BackendDataGridDB(BackendFaqModel::QRY_DATAGRID_BROWSE, array(BL::getWorkingLanguage(), $categoryId)); $dataGrid->setAttributes(array('class' => 'dataGrid sequenceByDragAndDrop')); $dataGrid->setColumnsHidden(array('category_id', 'sequence')); $dataGrid->addColumn('dragAndDropHandle', null, '<span>' . BL::lbl('Move') . '</span>'); $dataGrid->setColumnsSequence('dragAndDropHandle'); $dataGrid->setColumnAttributes('question', array('class' => 'title')); $dataGrid->setColumnAttributes('dragAndDropHandle', array('class' => 'dragAndDropHandle')); $dataGrid->setRowAttributes(array('id' => '[id]')); // check if this action is allowed if (BackendAuthentication::isAllowedAction('Edit')) { $dataGrid->setColumnURL('question', BackendModel::createURLForAction('Edit') . '&id=[id]'); $dataGrid->addColumn('edit', null, BL::lbl('Edit'), BackendModel::createURLForAction('Edit') . '&id=[id]', BL::lbl('Edit')); } // add dataGrid to list $this->dataGrids[] = array('id' => $categoryId, 'title' => $categoryTitle, 'content' => $dataGrid->getContent()); } // set empty datagrid $this->emptyDatagrid = new BackendDataGridArray(array(array('dragAndDropHandle' => '', 'question' => BL::msg('NoQuestionInCategory'), 'edit' => ''))); $this->emptyDatagrid->setAttributes(array('class' => 'dataGrid sequenceByDragAndDrop emptyGrid')); $this->emptyDatagrid->setHeaderLabels(array('edit' => null, 'dragAndDropHandle' => null)); }
/** * Add productdata into the comment * * @param string $text The comment. * @param string $title The title for the product. * @param string $URL The URL for the product. * @param int $id The id of the comment. * @return string */ public static function addProductData($text, $title, $URL, $id) { // reset URL $URL = BackendModel::getURLForBlock('Catalog', 'Detail') . '/' . $URL . '#comment-' . $id; // build HTML return '<p><em>' . sprintf(BL::msg('CommentOnWithURL'), $URL, $title) . '</em></p>' . "\n" . (string) $text; }
/** * Execute the action */ public function execute() { parent::execute(); // get parameters $id = \SpoonFilter::getPostValue('id', null, 0, 'int'); $tag = trim(\SpoonFilter::getPostValue('value', null, '', 'string')); // validate id if ($id === 0) { $this->output(self::BAD_REQUEST, null, 'no id provided'); } else { // validate tag name if ($tag === '') { $this->output(self::BAD_REQUEST, null, BL::err('NameIsRequired')); } else { // check if tag exists if (BackendTagsModel::existsTag($tag)) { $this->output(self::BAD_REQUEST, null, BL::err('TagAlreadyExists')); } else { $item['id'] = $id; $item['tag'] = \SpoonFilter::htmlspecialchars($tag); $item['url'] = BackendTagsModel::getURL(CommonUri::getUrl(\SpoonFilter::htmlspecialcharsDecode($item['tag'])), $id); BackendTagsModel::update($item); $this->output(self::OK, $item, vsprintf(BL::msg('Edited'), array($item['tag']))); } } } }
/** * Execute the action */ public function execute() { parent::execute(); // get parameters $id = \SpoonFilter::getPostValue('id', null, '', 'int'); $name = trim(\SpoonFilter::getPostValue('value', null, '', 'string')); // validate if ($name == '') { $this->output(self::BAD_REQUEST, null, 'no name provided'); } else { // get existing id $existingId = BackendMailmotorModel::getCampaignId($name); // validate if ($existingId !== 0 && $id !== $existingId) { $this->output(self::ERROR, array('id' => $existingId, 'error' => true), BL::err('CampaignExists', $this->getModule())); } else { // build array $item = array(); $item['id'] = $id; $item['name'] = $name; $item['created_on'] = BackendModel::getUTCDate('Y-m-d H:i:s'); // get page $rows = BackendMailmotorModel::updateCampaign($item); // trigger event BackendModel::triggerEvent($this->getModule(), 'edited_campaign', array('item' => $item)); // output if ($rows !== 0) { $this->output(self::OK, array('id' => $id), BL::msg('CampaignEdited', $this->getModule())); } else { $this->output(self::ERROR, null, BL::err('CampaignNotEdited', $this->getModule())); } } } }
/** * Execute the action */ public function execute() { parent::execute(); // get parameters $url = \SpoonFilter::getPostValue('url', null, ''); $username = \SpoonFilter::getPostValue('username', null, ''); $password = \SpoonFilter::getPostValue('password', null, ''); // filter out the 'http://' from the URL if (strpos($url, 'http://') !== false) { $url = str_replace('http://', '', $url); } if (strpos($url, 'https://') !== false) { $url = str_replace('https://', '', $url); } // init validation $errors = array(); // validate input if (empty($url)) { $errors['url'] = BL::err('NoCMAccountCredentials'); } if (empty($username)) { $errors['username'] = BL::err('NoCMAccountCredentials'); } if (empty($password)) { $errors['password'] = BL::err('NoCMAccountCredentials'); } // got errors if (!empty($errors)) { $this->output(self::OK, array('errors' => $errors), 'form contains errors'); } else { try { // check if the CampaignMonitor class exists if (!is_file(PATH_LIBRARY . '/external/campaignmonitor.php')) { throw new \Exception(BL::err('ClassDoesNotExist')); } // require CampaignMonitor class require_once PATH_LIBRARY . '/external/campaignmonitor.php'; // init CampaignMonitor object new \CampaignMonitor($url, $username, $password, 10); // save the new data $this->get('fork.settings')->set($this->getModule(), 'cm_url', $url); $this->get('fork.settings')->set($this->getModule(), 'cm_username', $username); $this->get('fork.settings')->set($this->getModule(), 'cm_password', $password); // account was linked $this->get('fork.settings')->set($this->getModule(), 'cm_account', true); // trigger event BackendModel::triggerEvent($this->getModule(), 'after_account_linked'); // CM was successfully initialized $this->output(self::OK, array('message' => 'account-linked'), BL::msg('AccountLinked', $this->getModule())); } catch (\Exception $e) { // timeout occurred if ($e->getMessage() == 'Error Fetching http headers') { $this->output(self::BAD_REQUEST, null, BL::err('CmTimeout', $this->getModule())); } // other error $this->output(self::ERROR, array('field' => 'url'), sprintf(BL::err('CampaignMonitorError', $this->getModule()), $e->getMessage())); } } }
/** * Execute the action */ public function execute() { parent::execute(); // get parameters $newSequence = \SpoonFilter::getPostValue('new_sequence', null, ''); // validate if ($newSequence == '') { $this->output(self::BAD_REQUEST, null, 'no new_sequence provided'); } else { // convert into array $json = @json_decode($newSequence, true); // validate if ($json === false) { $this->output(self::BAD_REQUEST, null, 'invalid new_sequence provided'); } else { // initialize $userSequence = array(); $hiddenItems = array(); // loop columns foreach ($json as $column => $widgets) { $columnValue = 'left'; if ($column == 1) { $columnValue = 'middle'; } elseif ($column == 2) { $columnValue = 'right'; } // loop widgets foreach ($widgets as $sequence => $widget) { // store position $userSequence[$widget['module']][$widget['widget']] = array('column' => $columnValue, 'position' => $sequence, 'hidden' => $widget['hidden'], 'present' => $widget['present']); // add to array if ($widget['hidden']) { $hiddenItems[] = $widget['module'] . '_' . $widget['widget']; } } } // get previous setting $currentSetting = BackendAuthentication::getUser()->getSetting('dashboard_sequence'); $data['reload'] = false; // any settings? if ($currentSetting !== null) { // loop modules foreach ($currentSetting as $module => $widgets) { foreach ($widgets as $widget => $values) { if ($values['hidden'] && isset($userSequence[$module][$widget]['hidden']) && !$userSequence[$module][$widget]['hidden']) { $data['reload'] = true; } } } } // store BackendAuthentication::getUser()->setSetting('dashboard_sequence', $userSequence); // output $this->output(self::OK, $data, BL::msg('Saved')); } } }
/** * Load the form */ private function loadForm() { // create form $this->frm = new BackendForm('edit'); // add "no default group" option for radiobuttons $chkDefaultForLanguageValues[] = array('label' => BL::msg('NoDefault'), 'value' => '0'); // set default for language radiobutton values foreach (BL::getWorkingLanguages() as $key => $value) { $chkDefaultForLanguageValues[] = array('label' => $value, 'value' => $key); } // create elements $this->frm->addText('name', $this->record['name']); $this->frm->addRadiobutton('default', $chkDefaultForLanguageValues, $this->record['language']); }
/** * Execute the action */ public function execute() { parent::execute(); //--Set post var to check submit $_POST["form"] = "add_image"; // get parameters $this->id = \SpoonFilter::getPostValue('id', null, '', 'int'); //--Load form $this->loadForm(); //--Validate form $this->validateForm(); // output $this->output(self::OK, null, BL::msg('Success')); }
/** * Validates the form */ private function validateForm() { // is the form submitted? if ($this->frm->isSubmitted()) { // no errors ? if ($this->frm->isCorrect()) { // smtp settings $this->get('fork.settings')->set('Core', 'seo_noodp', $this->frm->getField('seo_noodp')->getValue()); $this->get('fork.settings')->set('Core', 'seo_noydir', $this->frm->getField('seo_noydir')->getValue()); $this->get('fork.settings')->set('Core', 'seo_nofollow_in_comments', $this->frm->getField('seo_nofollow_in_comments')->getValue()); // assign report $this->tpl->assign('report', true); $this->tpl->assign('reportMessage', BL::msg('Saved')); } } }
/** * Execute the action */ public function execute() { parent::execute(); // get parameters $id = \SpoonFilter::getPostValue('id', null, '', 'int'); // validate if ($id == '' || !BackendMailmotorModel::existsMailing($id)) { $this->output(self::BAD_REQUEST, null, 'No mailing found.'); } else { // get mailing record $mailing = BackendMailmotorModel::getMailing($id); /* mailing was already sent We use a custom status code 900 because we want to do more with JS than triggering an error */ if ($mailing['status'] == 'sent') { $this->output(500, null, BL::err('MailingAlreadySent', $this->getModule())); } else { // make a regular date out of the send_on timestamp $mailing['delivery_date'] = date('Y-m-d H:i:s', $mailing['send_on']); // send the mailing try { // only update the mailing if it was queued if ($mailing['status'] == 'queued') { BackendMailmotorCMHelper::updateMailing($mailing); } else { // send the mailing if it wasn't queued BackendMailmotorCMHelper::sendMailing($mailing); } } catch (\Exception $e) { // stop the script and show our error $this->output(500, null, $e->getMessage()); return; } // set status to 'sent' $item['id'] = $id; $item['status'] = $mailing['send_on'] > time() ? 'queued' : 'sent'; // update the mailing record BackendMailmotorModel::updateMailing($item); // trigger event BackendModel::triggerEvent($this->getModule(), 'after_mailing_status_' . $item['status'], array('item' => $item)); // we made it \o/ $this->output(self::OK, array('mailing_id' => $item['id']), BL::msg('MailingSent', $this->getModule())); } } }
/** * Execute the action */ public function execute() { parent::execute(); $generalSettings = $this->get('fork.settings')->getForModule('Location'); // get parameters $itemId = \SpoonFilter::getPostValue('id', null, null, 'int'); $zoomLevel = trim(\SpoonFilter::getPostValue('zoom', null, 'auto')); $mapType = strtoupper(trim(\SpoonFilter::getPostValue('type', array('roadmap', 'satelitte', 'hybrid', 'terrain'), 'roadmap'))); $centerLat = \SpoonFilter::getPostValue('centerLat', null, 1, 'float'); $centerlng = \SpoonFilter::getPostValue('centerLng', null, 1, 'float'); $height = \SpoonFilter::getPostValue('height', null, $generalSettings['height'], 'int'); $width = \SpoonFilter::getPostValue('width', null, $generalSettings['width'], 'int'); $showLink = \SpoonFilter::getPostValue('link', array('true', 'false'), 'false', 'string'); $showDirections = \SpoonFilter::getPostValue('directions', array('true', 'false'), 'false', 'string'); $showOverview = \SpoonFilter::getPostValue('showOverview', array('true', 'false'), 'true', 'string'); // reformat $center = array('lat' => $centerLat, 'lng' => $centerlng); $showLink = $showLink == 'true'; $showDirections = $showDirections == 'true'; $showOverview = $showOverview == 'true'; // standard dimensions if ($width > 800) { $width = 800; } if ($width < 300) { $width = $generalSettings['width']; } if ($height < 150) { $height = $generalSettings['height']; } // no id given, this means we should update the main map BackendLocationModel::setMapSetting($itemId, 'zoom_level', (string) $zoomLevel); BackendLocationModel::setMapSetting($itemId, 'map_type', (string) $mapType); BackendLocationModel::setMapSetting($itemId, 'center', (array) $center); BackendLocationModel::setMapSetting($itemId, 'height', (int) $height); BackendLocationModel::setMapSetting($itemId, 'width', (int) $width); BackendLocationModel::setMapSetting($itemId, 'directions', $showDirections); BackendLocationModel::setMapSetting($itemId, 'full_url', $showLink); $item = array('id' => $itemId, 'language' => BL::getWorkingLanguage(), 'show_overview' => $showOverview ? 'Y' : 'N'); BackendLocationModel::update($item); // output $this->output(self::OK, null, BL::msg('Success')); }
/** * Load the data grid for installable modules. */ private function loadDataGridInstallable() { // create datagrid $this->dataGridInstallableModules = new BackendDataGridArray($this->installableModules); $this->dataGridInstallableModules->setSortingColumns(array('raw_name')); $this->dataGridInstallableModules->setHeaderLabels(array('raw_name' => \SpoonFilter::ucfirst(BL::getLabel('Name')))); $this->dataGridInstallableModules->setColumnsHidden(array('installed', 'name', 'cronjobs_active')); // check if this action is allowed if (BackendAuthentication::isAllowedAction('DetailModule')) { $this->dataGridInstallableModules->setColumnURL('raw_name', BackendModel::createURLForAction('DetailModule') . '&module=[raw_name]'); $this->dataGridInstallableModules->addColumn('details', null, BL::lbl('Details'), BackendModel::createURLForAction('DetailModule') . '&module=[raw_name]', BL::lbl('Details')); } // check if this action is allowed if (BackendAuthentication::isAllowedAction('InstallModule')) { // add install column $this->dataGridInstallableModules->addColumn('install', null, BL::lbl('Install'), BackendModel::createURLForAction('InstallModule') . '&module=[raw_name]', BL::lbl('Install')); $this->dataGridInstallableModules->setColumnConfirm('install', sprintf(BL::msg('ConfirmModuleInstall'), '[raw_name]'), null, \SpoonFilter::ucfirst(BL::lbl('Install')) . '?'); } }
/** * Execute the action */ public function execute() { parent::execute(); // get parameters $mailingId = \SpoonFilter::getPostValue('mailing_id', null, '', 'int'); $sendOnDate = \SpoonFilter::getPostValue('send_on_date', null, BackendModel::getUTCDate('d/m/Y')); $sendOnTime = \SpoonFilter::getPostValue('send_on_time', null, BackendModel::getUTCDate('H:i')); $messageDate = $sendOnDate; // validate mailing ID if ($mailingId == '') { $this->output(self::BAD_REQUEST, null, 'Provide a valid mailing ID'); } else { // validate date & time if ($sendOnDate == '' || $sendOnTime == '') { $this->output(self::BAD_REQUEST, null, 'Provide a valid send date date provided'); } else { // record is empty if (!BackendMailmotorModel::existsMailing($mailingId)) { $this->output(self::BAD_REQUEST, null, BL::err('MailingDoesNotExist', $this->getModule())); } else { // reverse the date and make it a proper $explodedDate = explode('/', $sendOnDate); $sendOnDate = $explodedDate[2] . '-' . $explodedDate[1] . '-' . $explodedDate[0]; // calc full send timestamp $sendTimestamp = strtotime($sendOnDate . ' ' . $sendOnTime); // build data $item['id'] = $mailingId; $item['send_on'] = BackendModel::getUTCDate('Y-m-d H:i:s', $sendTimestamp); $item['edited_on'] = BackendModel::getUTCDate('Y-m-d H:i:s'); // update mailing BackendMailmotorModel::updateMailing($item); // trigger event BackendModel::triggerEvent($this->getModule(), 'after_edit_mailing_step4', array('item' => $item)); // output $this->output(self::OK, array('mailing_id' => $mailingId, 'timestamp' => $sendTimestamp), sprintf(BL::msg('SendOn', $this->getModule()), $messageDate, $sendOnTime)); } } } }
/** * Execute the action */ public function execute() { parent::execute(); $fromEmail = \SpoonFilter::getPostValue('mailer_from_email', null, ''); $fromName = \SpoonFilter::getPostValue('mailer_from_name', null, ''); $toEmail = \SpoonFilter::getPostValue('mailer_to_email', null, ''); $toName = \SpoonFilter::getPostValue('mailer_to_name', null, ''); $replyToEmail = \SpoonFilter::getPostValue('mailer_reply_to_email', null, ''); $replyToName = \SpoonFilter::getPostValue('mailer_reply_to_name', null, ''); // init validation $errors = array(); // validate if ($fromEmail == '' || !\SpoonFilter::isEmail($fromEmail)) { $errors['from'] = BL::err('EmailIsInvalid'); } if ($toEmail == '' || !\SpoonFilter::isEmail($toEmail)) { $errors['to'] = BL::err('EmailIsInvalid'); } if ($replyToEmail == '' || !\SpoonFilter::isEmail($replyToEmail)) { $errors['reply'] = BL::err('EmailIsInvalid'); } // got errors? if (!empty($errors)) { $this->output(self::BAD_REQUEST, array('errors' => $errors), 'invalid fields'); } else { $message = \Swift_Message::newInstance('Test')->setFrom(array($fromEmail => $fromName))->setTo(array($toEmail => $toName))->setReplyTo(array($replyToEmail => $replyToName))->setBody(BL::msg('TestMessage'), 'text/plain'); $transport = \Common\Mailer\TransportFactory::create(\SpoonFilter::getPostValue('mailer_type', array('smtp', 'mail'), 'mail'), \SpoonFilter::getPostValue('smtp_server', null, ''), \SpoonFilter::getPostValue('smtp_port', null, ''), \SpoonFilter::getPostValue('smtp_username', null, ''), \SpoonFilter::getPostValue('smtp_password', null, ''), \SpoonFilter::getPostValue('smtp_secure_layer', null, '')); $mailer = \Swift_Mailer::newInstance($transport); try { if ($mailer->send($message)) { $this->output(self::OK, null, ''); } else { $this->output(self::ERROR, null, 'unknown'); } } catch (\Exception $e) { $this->output(self::ERROR, null, $e->getMessage()); } } }
/** * Validates the form */ private function validateForm() { // is the form submitted? if ($this->frm->isSubmitted()) { // validate required fields $this->frm->getField('site_title')->isFilled(BL::err('FieldIsRequired')); // date & time $this->frm->getField('time_format')->isFilled(BL::err('FieldIsRequired')); $this->frm->getField('date_format_short')->isFilled(BL::err('FieldIsRequired')); $this->frm->getField('date_format_long')->isFilled(BL::err('FieldIsRequired')); // number $this->frm->getField('number_format')->isFilled(BL::err('FieldIsRequired')); // akismet key may be filled in if ($this->needsAkismet && $this->frm->getField('akismet_key')->isFilled()) { // key has changed if ($this->frm->getField('akismet_key')->getValue() != $this->get('fork.settings')->get('Core', 'akismet_key', null)) { // create instance $akismet = new Akismet($this->frm->getField('akismet_key')->getValue(), SITE_URL); // invalid key if (!$akismet->verifyKey()) { $this->frm->getField('akismet_key')->setError(BL::err('InvalidAPIKey')); } } } // domains filled in if ($this->frm->getField('site_domains')->isFilled()) { // split on newlines $domains = explode("\n", trim($this->frm->getField('site_domains')->getValue())); // loop domains foreach ($domains as $domain) { // strip funky stuff $domain = trim(str_replace(array('www.', 'http://', 'https://'), '', $domain)); // invalid URL if (!\SpoonFilter::isURL('http://' . $domain)) { // set error $this->frm->getField('site_domains')->setError(BL::err('InvalidDomain')); // stop looping domains break; } } } if ($this->frm->getField('ckfinder_image_max_width')->isFilled()) { $this->frm->getField('ckfinder_image_max_width')->isInteger(BL::err('InvalidInteger')); } if ($this->frm->getField('ckfinder_image_max_height')->isFilled()) { $this->frm->getField('ckfinder_image_max_height')->isInteger(BL::err('InvalidInteger')); } // no errors ? if ($this->frm->isCorrect()) { // general settings $this->get('fork.settings')->set('Core', 'site_title_' . BL::getWorkingLanguage(), $this->frm->getField('site_title')->getValue()); $this->get('fork.settings')->set('Core', 'site_html_header', $this->frm->getField('site_html_header')->getValue()); $this->get('fork.settings')->set('Core', 'site_start_of_body_scripts', $this->frm->getField('site_start_of_body_scripts')->getValue()); $this->get('fork.settings')->set('Core', 'site_html_footer', $this->frm->getField('site_html_footer')->getValue()); // facebook settings $this->get('fork.settings')->set('Core', 'facebook_admin_ids', $this->frm->getField('facebook_admin_ids')->isFilled() ? $this->frm->getField('facebook_admin_ids')->getValue() : null); $this->get('fork.settings')->set('Core', 'facebook_app_id', $this->frm->getField('facebook_application_id')->isFilled() ? $this->frm->getField('facebook_application_id')->getValue() : null); $this->get('fork.settings')->set('Core', 'facebook_app_secret', $this->frm->getField('facebook_application_secret')->isFilled() ? $this->frm->getField('facebook_application_secret')->getValue() : null); // twitter settings /** @var \SpoonFormText $txtTwitterSiteName */ $txtTwitterSiteName = $this->frm->getField('twitter_site_name'); if ($txtTwitterSiteName->isFilled()) { $this->get('fork.settings')->set('Core', 'twitter_site_name', '@' . ltrim($txtTwitterSiteName->getValue(), '@')); } // ckfinder settings $this->get('fork.settings')->set('Core', 'ckfinder_license_name', $this->frm->getField('ckfinder_license_name')->isFilled() ? $this->frm->getField('ckfinder_license_name')->getValue() : null); $this->get('fork.settings')->set('Core', 'ckfinder_license_key', $this->frm->getField('ckfinder_license_key')->isFilled() ? $this->frm->getField('ckfinder_license_key')->getValue() : null); $this->get('fork.settings')->set('Core', 'ckfinder_image_max_width', $this->frm->getField('ckfinder_image_max_width')->isFilled() ? $this->frm->getField('ckfinder_image_max_width')->getValue() : 1600); $this->get('fork.settings')->set('Core', 'ckfinder_image_max_height', $this->frm->getField('ckfinder_image_max_height')->isFilled() ? $this->frm->getField('ckfinder_image_max_height')->getValue() : 1200); // api keys $this->get('fork.settings')->set('Core', 'fork_api_public_key', $this->frm->getField('fork_api_public_key')->getValue()); $this->get('fork.settings')->set('Core', 'fork_api_private_key', $this->frm->getField('fork_api_private_key')->getValue()); if ($this->needsAkismet) { $this->get('fork.settings')->set('Core', 'akismet_key', $this->frm->getField('akismet_key')->getValue()); } if ($this->needsGoogleMaps) { $this->get('fork.settings')->set('Core', 'google_maps_key', $this->frm->getField('google_maps_key')->getValue()); } // date & time formats $this->get('fork.settings')->set('Core', 'time_format', $this->frm->getField('time_format')->getValue()); $this->get('fork.settings')->set('Core', 'date_format_short', $this->frm->getField('date_format_short')->getValue()); $this->get('fork.settings')->set('Core', 'date_format_long', $this->frm->getField('date_format_long')->getValue()); // date & time formats $this->get('fork.settings')->set('Core', 'number_format', $this->frm->getField('number_format')->getValue()); // before we save the languages, we need to ensure that each language actually exists and may be chosen. $languages = array(SITE_DEFAULT_LANGUAGE); $activeLanguages = array_unique(array_merge($languages, $this->frm->getField('active_languages')->getValue())); $redirectLanguages = array_unique(array_merge($languages, $this->frm->getField('redirect_languages')->getValue())); // cleanup redirect-languages, by removing the values that aren't present in the active languages $redirectLanguages = array_intersect($redirectLanguages, $activeLanguages); // save active languages $this->get('fork.settings')->set('Core', 'active_languages', $activeLanguages); $this->get('fork.settings')->set('Core', 'redirect_languages', $redirectLanguages); // domains may not contain www, http or https. Therefor we must loop and create the list of domains. $siteDomains = array(); // domains filled in if ($this->frm->getField('site_domains')->isFilled()) { // split on newlines $domains = explode("\n", trim($this->frm->getField('site_domains')->getValue())); // loop domains foreach ($domains as $domain) { // strip funky stuff $siteDomains[] = trim(str_replace(array('www.', 'http://', 'https://'), '', $domain)); } } // save domains $this->get('fork.settings')->set('Core', 'site_domains', $siteDomains); $this->get('fork.settings')->set('Core', 'show_cookie_bar', $this->frm->getField('show_cookie_bar')->getChecked()); // assign report $this->tpl->assign('report', true); $this->tpl->assign('reportMessage', BL::msg('Saved')); } } }
/** * Exports the statistics of all mailings for a given campaign ID in CSV format. This function * will send headers to download the CSV and exit your script after use. * * @param int $id The ID of the campaign. */ public static function exportStatisticsByCampaignID($id) { // set the filename and path $filename = 'statistics-' . \SpoonDate::getDate('YmdHi') . '.csv'; // fetch the addresses by group $records = array(); $records[] = BackendMailmotorCMHelper::getStatisticsByCampaignID($id); // unset some records unset($records[0]['opens'], $records[0]['clicks'], $records[0]['clicks_percentage'], $records[0]['recipients_total'], $records[0]['recipients_percentage']); // set columns $columns = array(); $columns[] = BL::msg('MailingCSVRecipients'); $columns[] = BL::msg('MailingCSVUniqueOpens'); $columns[] = BL::msg('MailingCSVUnsubscribes'); $columns[] = BL::msg('MailingCSVBounces'); $columns[] = BL::msg('MailingCSVUnopens'); $columns[] = BL::msg('MailingCSVBouncesPercentage'); $columns[] = BL::msg('MailingCSVUniqueOpensPercentage'); $columns[] = BL::msg('MailingCSVUnopensPercentage'); // set start of the CSV $csv = BackendCSV::arrayToString($records, $columns); // fetch all mailings in this campaign $mailings = BackendModel::getContainer()->get('database')->getRecords(self::QRY_DATAGRID_BROWSE_SENT_FOR_CAMPAIGN, array('sent', $id)); // mailings set if (!empty($mailings)) { // set mailings columns $mailingColumns = array(); $mailingColumns['name'] = BL::lbl('Name'); $mailingColumns['language'] = BL::lbl('Language'); // add the records to the csv string $csv .= PHP_EOL . 'Mailings:' . PHP_EOL . BackendCSV::arrayToString($mailings, $mailingColumns, array('id', 'campaign_id', 'campaign_name', 'send_on', 'status')); } // set headers for download header('Content-type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . $filename . '"'); echo $csv; exit; }
/** * Parse the page with its widgets. */ protected function parse() { parent::parse(); // show report if ($this->getParameter('password_reset') == 'success') { $this->tpl->assign('reportMessage', BL::msg('PasswordResetSuccess', 'core')); $this->tpl->assign('report', true); } // assign $this->tpl->assign('leftColumn', $this->widgets['left']); $this->tpl->assign('middleColumn', $this->widgets['middle']); $this->tpl->assign('rightColumn', $this->widgets['right']); }
/** * Validates the form */ private function validateForm() { // is the form submitted? if ($this->frm->isSubmitted()) { // validate required fields $this->frm->getField('mailer_from_name')->isFilled(BL::err('FieldIsRequired')); $this->frm->getField('mailer_from_email')->isEmail(BL::err('EmailIsInvalid')); $this->frm->getField('mailer_to_name')->isFilled(BL::err('FieldIsRequired')); $this->frm->getField('mailer_to_email')->isEmail(BL::err('EmailIsInvalid')); $this->frm->getField('mailer_reply_to_name')->isFilled(BL::err('FieldIsRequired')); $this->frm->getField('mailer_reply_to_email')->isEmail(BL::err('EmailIsInvalid')); if ($this->isGod) { // SMTP type was chosen if ($this->frm->getField('mailer_type')->getValue() == 'smtp') { // server & port are required $this->frm->getField('smtp_server')->isFilled(BL::err('FieldIsRequired')); $this->frm->getField('smtp_port')->isFilled(BL::err('FieldIsRequired')); } } // no errors ? if ($this->frm->isCorrect()) { // e-mail settings $this->get('fork.settings')->set('Core', 'mailer_from', array('name' => $this->frm->getField('mailer_from_name')->getValue(), 'email' => $this->frm->getField('mailer_from_email')->getValue())); $this->get('fork.settings')->set('Core', 'mailer_to', array('name' => $this->frm->getField('mailer_to_name')->getValue(), 'email' => $this->frm->getField('mailer_to_email')->getValue())); $this->get('fork.settings')->set('Core', 'mailer_reply_to', array('name' => $this->frm->getField('mailer_reply_to_name')->getValue(), 'email' => $this->frm->getField('mailer_reply_to_email')->getValue())); if ($this->isGod) { $this->get('fork.settings')->set('Core', 'mailer_type', $this->frm->getField('mailer_type')->getValue()); // smtp settings $this->get('fork.settings')->set('Core', 'smtp_server', $this->frm->getField('smtp_server')->getValue()); $this->get('fork.settings')->set('Core', 'smtp_port', $this->frm->getField('smtp_port')->getValue()); $this->get('fork.settings')->set('Core', 'smtp_username', $this->frm->getField('smtp_username')->getValue()); $this->get('fork.settings')->set('Core', 'smtp_password', $this->frm->getField('smtp_password')->getValue()); $this->get('fork.settings')->set('Core', 'smtp_secure_layer', $this->frm->getField('smtp_secure_layer')->getValue()); } // assign report $this->tpl->assign('report', true); $this->tpl->assign('reportMessage', BL::msg('Saved')); } } }
/** * Execute the action */ public function execute() { parent::execute(); // get parameters $mailingId = \SpoonFilter::getPostValue('mailing_id', null, '', 'int'); $subject = \SpoonFilter::getPostValue('subject', null, ''); $contentHTML = urldecode(\SpoonFilter::getPostValue('content_html', null, '')); $contentPlain = \SpoonFilter::getPostValue('content_plain', null, ''); // validate mailing ID if ($mailingId == '') { $this->output(self::BAD_REQUEST, null, 'No mailing ID provided'); } else { // get mailing record $this->mailing = BackendMailmotorModel::getMailing($mailingId); // check if record is empty if (empty($this->mailing)) { $this->output(self::BAD_REQUEST, null, BL::err('MailingDoesNotExist', $this->getModule())); } else { // validate subject if ($subject == '') { $this->output(500, array('element' => 'subject', 'element_error' => BL::err('NoSubject', $this->getModule())), BL::err('FormError')); } else { // set plain content $contentPlain = empty($contentPlain) ? \SpoonFilter::stripHTML($contentHTML) : $contentPlain; // add unsubscribe link if (mb_strpos($contentPlain, '[unsubscribe]') === false) { $contentPlain .= PHP_EOL . '[unsubscribe]'; } // build data $item['id'] = $this->mailing['id']; $item['subject'] = $subject; $item['content_plain'] = $contentPlain; $item['content_html'] = $contentHTML; $item['edited_on'] = date('Y-m-d H:i:s'); // update mailing in our database BackendMailmotorModel::updateMailing($item); /* we should insert the draft into campaignmonitor here, so we can use sendCampaignPreview in step 4. */ $item['groups'] = $this->mailing['groups']; $item['name'] = $this->mailing['name']; $item['from_name'] = $this->mailing['from_name']; $item['from_email'] = $this->mailing['from_email']; $item['reply_to_email'] = $this->mailing['reply_to_email']; try { BackendMailmotorCMHelper::saveMailingDraft($item); } catch (Exception $e) { // CM did not receive a valid URL if (strpos($e->getMessage(), 'HTML Content URL Required')) { $message = BL::err('HTMLContentURLRequired', $this->getModule()); } elseif (strpos($e->getMessage(), 'Payment details required')) { // no payment details were set for the CM client yet $error = BL::err('PaymentDetailsRequired', $this->getModule()); $cmUsername = $this->get('fork.settings')->get($this->getModule(), 'cm_username'); $message = sprintf($error, $cmUsername); } elseif (strpos($e->getMessage(), 'Duplicate Campaign Name')) { // the campaign name already exists in CM $message = BL::err('DuplicateCampaignName', $this->getModule()); } else { // we received an unknown error $message = $e->getMessage(); } // stop the script and show our error $this->output(500, null, $message); return; } // trigger event BackendModel::triggerEvent($this->getModule(), 'after_edit_mailing_step3', array('item' => $item)); // output $this->output(self::OK, array('mailing_id' => $mailingId), BL::msg('MailingEdited', $this->getModule())); return; } } // error $this->output(500, null, $message); return; } }
/** * Loads the datagrid with the clicked link */ private function loadDataGrid() { // no statistics found if (empty($this->statistics['clicked_links'])) { return false; } // map urlencode to clicked links stack $this->statistics['clicked_links'] = \SpoonFilter::arrayMapRecursive('urlencode', $this->statistics['clicked_links']); // create a new source-object $source = new \SpoonDatagridSourceArray($this->statistics['clicked_links']); // call the parent, as in create a new datagrid with the created source $this->dataGrid = new BackendDataGrid($source); $this->dataGrid->setURL(BackendModel::createURLForAction() . '&offset=[offset]&order=[order]&sort=[sort]&id=' . $this->id); // set headers values $headers['link'] = strtoupper(BL::lbl('URL')); $headers['clicks'] = \SpoonFilter::ucfirst(BL::msg('ClicksAmount')); // set headers $this->dataGrid->setHeaderLabels($headers); // sorting columns $this->dataGrid->setSortingColumns(array('link', 'clicks'), 'link'); // set column functions $this->dataGrid->setColumnFunction('urldecode', array('[link]'), 'link', true); $this->dataGrid->setColumnFunction('urldecode', array('[link]'), 'link', true); // set paging limit $this->dataGrid->setPagingLimit(self::PAGING_LIMIT); // check if this action is allowed if (BackendAuthentication::isAllowedAction('StatisticsLink')) { // add edit column $this->dataGrid->addColumnAction('users', null, BL::lbl('Who'), BackendModel::createURLForAction('StatisticsLink') . '&url=[link]&mailing_id=' . $this->id, BL::lbl('Who')); } }
/** * Load the form */ private function loadForm() { // get default template id $defaultTemplateId = $this->get('fork.settings')->get('Pages', 'default_template', 1); // create form $this->frm = new BackendForm('edit'); // assign in template $this->tpl->assign('defaultTemplateId', $defaultTemplateId); // create elements $this->frm->addText('title', $this->record['title'], null, 'inputText title', 'inputTextError title'); $this->frm->addEditor('html'); $this->frm->addHidden('template_id', $this->record['template_id']); $this->frm->addRadiobutton('hidden', array(array('label' => BL::lbl('Hidden'), 'value' => 'Y'), array('label' => BL::lbl('Published'), 'value' => 'N')), $this->record['hidden']); // a god user should be able to adjust the detailed settings for a page easily if ($this->isGod) { // init some vars $items = array('move', 'children', 'edit', 'delete'); $checked = array(); $values = array(); foreach ($items as $value) { $values[] = array('label' => BL::msg(\SpoonFilter::toCamelCase('allow_' . $value)), 'value' => $value); if (isset($this->record['allow_' . $value]) && $this->record['allow_' . $value] == 'Y') { $checked[] = $value; } } $this->frm->addMultiCheckbox('allow', $values, $checked); } // build prototype block $block['index'] = 0; $block['formElements']['chkVisible'] = $this->frm->addCheckbox('block_visible_' . $block['index'], true); $block['formElements']['hidExtraId'] = $this->frm->addHidden('block_extra_id_' . $block['index'], 0); $block['formElements']['hidPosition'] = $this->frm->addHidden('block_position_' . $block['index'], 'fallback'); $block['formElements']['txtHTML'] = $this->frm->addTextArea('block_html_' . $block['index'], ''); // this is no editor; we'll add the editor in JS // add default block to "fallback" position, the only one which we can rest assured to exist $this->positions['fallback']['blocks'][] = $block; // content has been submitted: re-create submitted content rather than the db-fetched content if (isset($_POST['block_html_0'])) { // init vars $this->blocksContent = array(); $hasBlock = false; $i = 1; // loop submitted blocks while (isset($_POST['block_position_' . $i])) { // init var $block = array(); // save block position $block['position'] = $_POST['block_position_' . $i]; $positions[$block['position']][] = $block; // set linked extra $block['extra_id'] = $_POST['block_extra_id_' . $i]; // reset some stuff if ($block['extra_id'] <= 0) { $block['extra_id'] = null; } // init html $block['html'] = null; // extra-type is HTML if ($block['extra_id'] === null) { // reset vars $block['extra_id'] = null; $block['html'] = $_POST['block_html_' . $i]; } else { // type of block if (isset($this->extras[$block['extra_id']]['type']) && $this->extras[$block['extra_id']]['type'] == 'block') { // set error if ($hasBlock) { $this->frm->addError(BL::err('CantAdd2Blocks')); } // home can't have blocks if ($this->record['id'] == 1) { $this->frm->addError(BL::err('HomeCantHaveBlocks')); } // reset var $hasBlock = true; } } // set data $block['created_on'] = BackendModel::getUTCDate(); $block['edited_on'] = $block['created_on']; $block['visible'] = isset($_POST['block_visible_' . $i]) && $_POST['block_visible_' . $i] == 'Y' ? 'Y' : 'N'; $block['sequence'] = count($positions[$block['position']]) - 1; // add to blocks $this->blocksContent[] = $block; // increment counter; go fetch next block $i++; } } // build blocks array foreach ($this->blocksContent as $i => $block) { $block['index'] = $i + 1; $block['formElements']['chkVisible'] = $this->frm->addCheckbox('block_visible_' . $block['index'], $block['visible'] == 'Y'); $block['formElements']['hidExtraId'] = $this->frm->addHidden('block_extra_id_' . $block['index'], (int) $block['extra_id']); $block['formElements']['hidPosition'] = $this->frm->addHidden('block_position_' . $block['index'], $block['position']); $block['formElements']['txtHTML'] = $this->frm->addTextArea('block_html_' . $block['index'], $block['html']); // this is no editor; we'll add the editor in JS $this->positions[$block['position']]['blocks'][] = $block; } // redirect $redirectValue = 'none'; if (isset($this->record['data']['internal_redirect']['page_id'])) { $redirectValue = 'internal'; } if (isset($this->record['data']['external_redirect']['url'])) { $redirectValue = 'external'; } $redirectValues = array(array('value' => 'none', 'label' => \SpoonFilter::ucfirst(BL::lbl('None'))), array('value' => 'internal', 'label' => \SpoonFilter::ucfirst(BL::lbl('InternalLink')), 'variables' => array('isInternal' => true)), array('value' => 'external', 'label' => \SpoonFilter::ucfirst(BL::lbl('ExternalLink')), 'variables' => array('isExternal' => true))); $this->frm->addRadiobutton('redirect', $redirectValues, $redirectValue); $this->frm->addDropdown('internal_redirect', BackendPagesModel::getPagesForDropdown(), $redirectValue == 'internal' ? $this->record['data']['internal_redirect']['page_id'] : null); $this->frm->addText('external_redirect', $redirectValue == 'external' ? urldecode($this->record['data']['external_redirect']['url']) : null, null, null, null, true); // page info $this->frm->addCheckbox('navigation_title_overwrite', $this->record['navigation_title_overwrite'] == 'Y'); $this->frm->addText('navigation_title', $this->record['navigation_title']); // tags $this->frm->addText('tags', BackendTagsModel::getTags($this->URL->getModule(), $this->id), null, 'inputText tagBox', 'inputTextError tagBox'); // a specific action $isAction = isset($this->record['data']['is_action']) && $this->record['data']['is_action'] == true ? true : false; $this->frm->addCheckbox('is_action', $isAction); // extra $this->frm->addDropdown('extra_type', BackendPagesModel::getTypes()); // meta $this->meta = new BackendMeta($this->frm, $this->record['meta_id'], 'title', true); // set callback for generating an unique URL $this->meta->setURLCallback('Backend\\Modules\\Pages\\Engine\\Model', 'getURL', array($this->record['id'], $this->record['parent_id'], $isAction)); }
/** * Load the data grid which contains the events. */ private function loadDataGridTemplates() { // no hooks so don't bother if (!isset($this->information['templates'])) { return; } // build data for display in datagrid $templates = array(); foreach ($this->information['templates'] as $template) { // set template name & path $record['name'] = $template['label']; $record['path'] = $template['path']; // set positions $record['positions'] = array(); foreach ($template['positions'] as $position) { $record['positions'][] = $position['name']; } $record['positions'] = implode(', ', $record['positions']); // add template to list $templates[] = $record; } // create data grid $this->dataGridTemplates = new BackendDataGridArray($templates); // add label for path $this->dataGridTemplates->setHeaderLabels(array('path' => BL::msg('PathToTemplate'))); // no paging $this->dataGridTemplates->setPaging(false); }
/** * Set a tooltip * * @param string $column The name of the column to set the tooltop for. * @param string $message The key for the message (will be parsed through Language::msg). */ public function setTooltip($column, $message) { // get the column $instance = $this->getColumn($column); // build the value for the tooltip $value = Language::msg($message); // reset the label $instance->setLabel($instance->getLabel() . '<abbr class="help">?</abbr><span class="tooltip hidden" style="display: none;">' . $value . '</span>'); }
/** * Validate the form add image * * @return void */ private function validateForm() { //--Check if the add-image form is submitted if ($this->frm->isSubmitted()) { //--Clean up fields in the form (NOT ALLOWED: fields from plupload like name are deleted) //$this->frm->cleanupFields(); //--Get image field $filImage = $this->frm->getField('images'); //--Check if the field is filled in if ($filImage->isFilled()) { //--Image extension and mime type $filImage->isAllowedExtension(array('jpg', 'png', 'gif', 'jpeg'), BL::err('JPGGIFAndPNGOnly')); $filImage->isAllowedMimeType(array('image/jpg', 'image/png', 'image/gif', 'image/jpeg'), BL::err('JPGGIFAndPNGOnly')); //--Check if there are no errors. $strError = $filImage->getErrors(); if ($strError === null) { //--Get the filename $strFilename = BackendGalleryModel::checkFilename(substr($_REQUEST["name"], 0, 0 - (strlen($filImage->getExtension()) + 1)), $filImage->getExtension()); //--Fill in the item $item = array(); $item["album_id"] = (int) $this->id; $item["user_id"] = BackendAuthentication::getUser()->getUserId(); $item["language"] = BL::getWorkingLanguage(); $item["filename"] = $strFilename; $item["description"] = ""; $item["publish_on"] = BackendModel::getUTCDate(); $item["hidden"] = "N"; $item["sequence"] = BackendGalleryModel::getMaximumImageSequence($this->id) + 1; //--the image path $imagePath = FRONTEND_FILES_PATH . '/Gallery/Images'; //--create folders if needed $resolutions = $this->get('fork.settings')->get("Gallery", 'resolutions', false); foreach ($resolutions as $res) { if (!\SpoonDirectory::exists($imagePath . '/' . $res)) { \SpoonDirectory::create($imagePath . '/' . $res); // Create filesystem object $filesystem = new Filesystem(); // Create var dir for ease of use $dir = $imagePath; // Check if dir exists if ($filesystem->exists($dir . '/Source/')) { // Create Finder object for the files $finderFiles = new Finder(); // Get all the files in the source-dir $files = $finderFiles->files()->in($dir . '/Source/'); // Check if $files is not empty if (!empty($files)) { // Explode the dir-name $chunks = explode("x", $res, 2); // Create folder array $folder = array(); $folder['width'] = $chunks[0] != '' ? (int) $chunks[0] : null; $folder['height'] = $chunks[1] != '' ? (int) $chunks[1] : null; // Loop all the files foreach ($files as $file) { set_time_limit(150); // Check if the file exists if (!$filesystem->exists($imagePath . '/' . $res . '/' . $file->getBasename())) { // generate the thumbnail $thumbnail = new \SpoonThumbnail($dir . '/Source/' . $file->getBasename(), $folder['width'], $folder['height']); $thumbnail->setAllowEnlargement(true); // if the width & height are specified we should ignore the aspect ratio if ($folder['width'] !== null && $folder['height'] !== null) { $thumbnail->setForceOriginalAspectRatio(false); } $thumbnail->parseToFile($imagePath . '/' . $res . '/' . $file->getBasename()); } } } } } } if (!\SpoonDirectory::exists($imagePath . '/Source')) { \SpoonDirectory::create($imagePath . '/Source'); } if (!\SpoonDirectory::exists($imagePath . '/128x128')) { \SpoonDirectory::create($imagePath . '/128x128'); } if (!\SpoonDirectory::exists($imagePath . '/800x')) { \SpoonDirectory::create($imagePath . '/800x'); } if (!\SpoonDirectory::exists($imagePath . '/200x')) { \SpoonDirectory::create($imagePath . '/200x'); } if (!\SpoonDirectory::exists($imagePath . '/400x300')) { \SpoonDirectory::create($imagePath . '/400x300'); } //--image provided? if ($filImage->isFilled()) { //--upload the image & generate thumbnails $filImage->generateThumbnails($imagePath, $item["filename"]); } //--Add item to the database $idInsert = BackendGalleryModel::insert($item); $item['id'] = $idInsert; //--Create html for ajax $tpl = new Template(); $txtDescription = $this->frm->addTextarea("description_" . $idInsert, $item['description']); $item['field_description'] = $txtDescription->setAttribute('style', 'resize: none;')->parse(); //--Parse filename to get name $path_parts = pathinfo(FRONTEND_FILES_PATH . '/Gallery/Images/Source/' . $item['filename']); $item['name'] = $path_parts['filename']; $folders = BackendModel::getThumbnailFolders(FRONTEND_FILES_PATH . '/Gallery/Images', true); foreach ($folders as $folder) { $item['image_' . $folder['dirname']] = $folder['url'] . '/' . $folder['dirname'] . '/' . $item['filename']; } $tpl->assign('images', array($item)); $html = $tpl->getContent(BACKEND_MODULES_PATH . '/Gallery/Layout/Templates/Ajax/Image.tpl'); //Send html (ajax response) $this->output(self::OK, $html, BL::msg('Success')); } } } }
/** * Get all locale types for a multicheckbox. * * @return array */ public static function getTypesForMultiCheckbox() { // fetch types $aTypes = BackendModel::getContainer()->get('database')->getEnumValues('locale', 'type'); // init $labels = $aTypes; // loop and build labels foreach ($labels as &$row) { $row = \SpoonFilter::ucfirst(BL::msg(mb_strtoupper($row), 'Core')); } // build array $aTypes = array_combine($aTypes, $labels); // create a new array to redefine the types for the multicheckbox $types = array(); // loop the languages foreach ($aTypes as $key => $type) { // add to array $types[$key]['value'] = $key; $types[$key]['label'] = $type; } // return the redefined array return $types; }
/** * Execute the action */ public function execute() { // add jquery, we will need this in every action, so add it globally $this->header->addJS('jquery/jquery.js', 'Core', false); $this->header->addJS('jquery/jquery.ui.js', 'Core', false); $this->header->addJS('jquery/jquery.ui.dialog.patch.js', 'Core'); $this->header->addJS('jquery/jquery.tools.js', 'Core', false); $this->header->addJS('jquery/jquery.backend.js', 'Core'); // add items that always need to be loaded $this->header->addJS('utils.js', 'Core'); $this->header->addJS('backend.js', 'Core'); // add module js if (is_file($this->getBackendModulePath() . '/Js/' . $this->getModule() . '.js')) { $this->header->addJS($this->getModule() . '.js'); } // add action js if (is_file($this->getBackendModulePath() . '/Js/' . $this->getAction() . '.js')) { $this->header->addJS($this->getAction() . '.js'); } // add core css files $this->header->addCSS('reset.css', 'Core'); $this->header->addCSS('jquery_ui/fork/jquery_ui.css', 'Core', false, false); $this->header->addCSS('screen.css', 'Core'); $this->header->addCSS('debug.css', 'Core'); // add module specific css if (is_file($this->getBackendModulePath() . '/Layout/Css/' . $this->getModule() . '.css')) { $this->header->addCSS($this->getModule() . '.css'); } // store var so we don't have to call this function twice $var = array_map('strip_tags', $this->getParameter('var', 'array', array())); // is there a report to show? if ($this->getParameter('report') !== null) { // show the report $this->tpl->assign('report', true); // camelcase the string $messageName = strip_tags(\SpoonFilter::toCamelCase($this->getParameter('report'), '-')); // if we have data to use it will be passed as the var parameter if (!empty($var)) { $this->tpl->assign('reportMessage', vsprintf(BL::msg($messageName), $var)); } else { $this->tpl->assign('reportMessage', BL::msg($messageName)); } // highlight an element with the given id if needed if ($this->getParameter('highlight')) { $this->tpl->assign('highlight', strip_tags($this->getParameter('highlight'))); } } // is there an error to show? if ($this->getParameter('error') !== null) { // camelcase the string $errorName = strip_tags(\SpoonFilter::toCamelCase($this->getParameter('error'), '-')); // if we have data to use it will be passed as the var parameter if (!empty($var)) { $this->tpl->assign('errorMessage', vsprintf(BL::err($errorName), $var)); } else { $this->tpl->assign('errorMessage', BL::err($errorName)); } } }
/** * Validate the forms */ private function validateForm() { if ($this->frm->isSubmitted()) { $txtEmail = $this->frm->getField('backend_email'); $txtPassword = $this->frm->getField('backend_password'); // required fields if (!$txtEmail->isFilled() || !$txtPassword->isFilled()) { // add error $this->frm->addError('fields required'); // show error $this->tpl->assign('hasError', true); } $this->getContainer()->get('logger')->info("Trying to authenticate user '{$txtEmail->getValue()}'."); // invalid form-token? if ($this->frm->getToken() != $this->frm->getField('form_token')->getValue()) { // set a correct header, so bots understand they can't mess with us. if (!headers_sent()) { header('400 Bad Request', true, 400); } } // get the user's id $userId = BackendUsersModel::getIdByEmail($txtEmail->getValue()); // all fields are ok? if ($txtEmail->isFilled() && $txtPassword->isFilled() && $this->frm->getToken() == $this->frm->getField('form_token')->getValue()) { // try to login the user if (!BackendAuthentication::loginUser($txtEmail->getValue(), $txtPassword->getValue())) { $this->getContainer()->get('logger')->info("Failed authenticating user '{$txtEmail->getValue()}'."); // add error $this->frm->addError('invalid login'); // store attempt in session $current = \SpoonSession::exists('backend_login_attempts') ? (int) \SpoonSession::get('backend_login_attempts') : 0; // increment and store \SpoonSession::set('backend_login_attempts', ++$current); // save the failed login attempt in the user's settings if ($userId !== false) { BackendUsersModel::setSetting($userId, 'last_failed_login_attempt', time()); } // show error $this->tpl->assign('hasError', true); } } // check sessions if (\SpoonSession::exists('backend_login_attempts') && (int) \SpoonSession::get('backend_login_attempts') >= 5) { // get previous attempt $previousAttempt = \SpoonSession::exists('backend_last_attempt') ? \SpoonSession::get('backend_last_attempt') : time(); // calculate timeout $timeout = 5 * (\SpoonSession::get('backend_login_attempts') - 4); // too soon! if (time() < $previousAttempt + $timeout) { // sleep until the user can login again sleep($timeout); // set a correct header, so bots understand they can't mess with us. if (!headers_sent()) { header('503 Service Unavailable', true, 503); } } else { // increment and store \SpoonSession::set('backend_last_attempt', time()); } // too many attempts $this->frm->addEditor('too many attempts'); $this->getContainer()->get('logger')->info("Too many login attempts for user '{$txtEmail->getValue()}'."); // show error $this->tpl->assign('hasTooManyAttemps', true); $this->tpl->assign('hasError', false); } // no errors in the form? if ($this->frm->isCorrect()) { // cleanup sessions \SpoonSession::delete('backend_login_attempts'); \SpoonSession::delete('backend_last_attempt'); // save the login timestamp in the user's settings $lastLogin = BackendUsersModel::getSetting($userId, 'current_login'); BackendUsersModel::setSetting($userId, 'current_login', time()); if ($lastLogin) { BackendUsersModel::setSetting($userId, 'last_login', $lastLogin); } $this->getContainer()->get('logger')->info("Successfully authenticated user '{$txtEmail->getValue()}'."); // redirect to the correct URL (URL the user was looking for or fallback) $this->redirectToAllowedModuleAndAction(); } } // is the form submitted if ($this->frmForgotPassword->isSubmitted()) { // backend email $email = $this->frmForgotPassword->getField('backend_email_forgot')->getValue(); // required fields if ($this->frmForgotPassword->getField('backend_email_forgot')->isEmail(BL::err('EmailIsInvalid'))) { // check if there is a user with the given emailaddress if (!BackendUsersModel::existsEmail($email)) { $this->frmForgotPassword->getField('backend_email_forgot')->addError(BL::err('EmailIsUnknown')); } } // no errors in the form? if ($this->frmForgotPassword->isCorrect()) { // generate the key for the reset link and fetch the user ID for this email $key = BackendAuthentication::getEncryptedString($email, uniqid()); // insert the key and the timestamp into the user settings $userId = BackendUsersModel::getIdByEmail($email); $user = new User($userId); $user->setSetting('reset_password_key', $key); $user->setSetting('reset_password_timestamp', time()); // variables to parse in the e-mail $variables['resetLink'] = SITE_URL . BackendModel::createURLForAction('ResetPassword') . '&email=' . $email . '&key=' . $key; // send e-mail to user $from = $this->get('fork.settings')->get('Core', 'mailer_from'); $replyTo = $this->get('fork.settings')->get('Core', 'mailer_reply_to'); $message = \Common\Mailer\Message::newInstance(\SpoonFilter::ucfirst(BL::msg('ResetYourPasswordMailSubject')))->setFrom(array($from['email'] => $from['name']))->setTo(array($email))->setReplyTo(array($replyTo['email'] => $replyTo['name']))->parseHtml(BACKEND_MODULES_PATH . '/Authentication/Layout/Templates/Mails/ResetPassword.tpl', $variables); $this->get('mailer')->send($message); // clear post-values $_POST['backend_email_forgot'] = ''; // show success message $this->tpl->assign('isForgotPasswordSuccess', true); // show form $this->tpl->assign('showForm', true); } else { // errors? $this->tpl->assign('showForm', true); } } }
/** * Load the confirmation dialog */ private function loadConfirmationDialog() { // load statistics $groups = BackendMailmotorModel::getGroupsByIds($this->record['groups']); // fetch the campaign $campaign = BackendMailmotorModel::getCampaign($this->record['campaign_id']); // fetch the template $template = BackendMailmotorModel::getTemplate($this->record['language'], $this->record['template']); // declare stats array $stats['recipients'] = count($this->record['recipients']); $stats['mailing'] = $this->record['name']; $stats['label_persons'] = $stats['recipients'] > 1 ? BL::lbl('Persons', 'core') : BL::lbl('Person', 'core'); // campaign was set if (!empty($campaign)) { // set data $stats['message'] = BL::msg('RecipientStatisticsCampaign', $this->getModule()); $stats['campaign'] = $campaign['name']; // assign the recipient statistics variable $this->tpl->assign('recipientStatistics', sprintf($stats['message'], $stats['mailing'], $stats['campaign'], $stats['recipients'], $stats['label_persons'])); } else { // set data $stats['message'] = BL::msg('RecipientStatisticsNoCampaign', $this->getModule()); // assign the recipient statistics variable $this->tpl->assign('recipientStatistics', sprintf($stats['message'], $stats['mailing'], $stats['recipients'], $stats['label_persons'])); } // add comma separator to groups if (!empty($groups)) { // fetch the last key in this array $lastRecord = end($groups); // loop the groups foreach ($groups as $key => &$group) { // add comma field to the groups if this is not the last item if ($lastRecord['id'] != $key) { $group['comma'] = true; } } } // assign the groups to the template $this->tpl->assign('groups', $groups); // assign the template language $this->tpl->assign('templateLanguage', \SpoonFilter::ucfirst(BL::lbl(strtoupper($template['language'])))); // get the price settings $pricePerEmail = $this->get('fork.settings')->get($this->getModule(), 'price_per_email'); $pricePerCampaign = $this->get('fork.settings')->get($this->getModule(), 'price_per_campaign'); // parse the price total $this->tpl->assign('price', $stats['recipients'] * $pricePerEmail + $pricePerCampaign); }
/** * Validates the form. */ private function validateForm() { // is the form submitted? if ($this->frm->isSubmitted()) { // no errors? if ($this->frm->isCorrect()) { // determine themes $newTheme = $this->frm->getField('installedThemes')->getValue(); $oldTheme = $this->get('fork.settings')->get('Core', 'theme', 'core'); // check if we actually switched themes if ($newTheme != $oldTheme) { // fetch templates $oldTemplates = BackendExtensionsModel::getTemplates($oldTheme); $newTemplates = BackendExtensionsModel::getTemplates($newTheme); // check if templates already exist if (empty($newTemplates)) { // templates do not yet exist; don't switch $this->redirect(BackendModel::createURLForAction('Themes') . '&error=no-templates-available'); exit; } // fetch current default template $oldDefaultTemplatePath = $oldTemplates[$this->get('fork.settings')->get('Pages', 'default_template')]['path']; // loop new templates foreach ($newTemplates as $newTemplateId => $newTemplate) { // check if a a similar default template exists if ($newTemplate['path'] == $oldDefaultTemplatePath) { // set new default id $newDefaultTemplateId = (int) $newTemplateId; break; } } // no default template was found, set first template as default if (!isset($newDefaultTemplateId)) { $newDefaultTemplateId = array_keys($newTemplates); $newDefaultTemplateId = $newDefaultTemplateId[0]; } // update theme $this->get('fork.settings')->set('Core', 'theme', $newTheme); // save new default template $this->get('fork.settings')->set('Pages', 'default_template', $newDefaultTemplateId); // loop old templates foreach ($oldTemplates as $oldTemplateId => $oldTemplate) { // loop new templates foreach ($newTemplates as $newTemplateId => $newTemplate) { // if the templates don't match we can skip this one if ($oldTemplate['path'] != $newTemplate['path']) { continue; } // switch template BackendPagesModel::updatePagesTemplates($oldTemplateId, $newTemplateId); // break loop continue 2; } // getting here meant we found no matching template for the new theme; pick first theme's template as default BackendPagesModel::updatePagesTemplates($oldTemplateId, $newDefaultTemplateId); } // trigger event BackendModel::triggerEvent($this->getModule(), 'after_changed_theme'); } // assign report $this->tpl->assign('report', true); $this->tpl->assign('reportMessage', BL::msg('Saved')); } } }