/** * Execute the extra. */ public function execute() { // get activation key $key = $this->URL->getParameter(0); // load template $this->loadTemplate(); // do we have an activation key? if (isset($key)) { // get profile id $profileId = FrontendProfilesModel::getIdBySetting('activation_key', $key); // have id? if ($profileId != null) { // update status FrontendProfilesModel::update($profileId, array('status' => 'active')); // delete activation key FrontendProfilesModel::deleteSetting($profileId, 'activation_key'); // login profile FrontendProfilesAuthentication::login($profileId); // trigger event FrontendModel::triggerEvent('Profiles', 'after_activate', array('id' => $profileId)); // show success message $this->tpl->assign('activationSuccess', true); } else { // failure $this->redirect(FrontendNavigation::getURL(404)); } } else { $this->redirect(FrontendNavigation::getURL(404)); } }
/** * Load the data, don't forget to validate the incoming data */ private function getData() { // requested page $requestedPage = $this->URL->getParameter('page', 'int', 1); // set URL and limit $this->pagination['url'] = FrontendNavigation::getURLForBlock('catalog'); $this->pagination['limit'] = FrontendModel::getModuleSetting('catalog', 'overview_num_items', 10); // populate count fields in pagination $this->pagination['num_items'] = FrontendCatalogModel::getAllCount(); $this->pagination['num_pages'] = (int) ceil($this->pagination['num_items'] / $this->pagination['limit']); // num pages is always equal to at least 1 if ($this->pagination['num_pages'] == 0) { $this->pagination['num_pages'] = 1; } // redirect if the request page doesn't exist if ($requestedPage > $this->pagination['num_pages'] || $requestedPage < 1) { $this->redirect(FrontendNavigation::getURL(404)); } // populate calculated fields in pagination $this->pagination['requested_page'] = $requestedPage; $this->pagination['offset'] = $this->pagination['requested_page'] * $this->pagination['limit'] - $this->pagination['limit']; // get all categories $this->categories = FrontendCatalogModel::getAllCategories(); // get tree of all categories $this->categoriesTree = FrontendCatalogModel::getCategoriesTree(); // get all products $this->products = FrontendCatalogModel::getAll($this->pagination['limit'], $this->pagination['offset']); }
/** * Process links, will prepend SITE_URL if needed and append UTM-parameters * * @param string $content The content to process. * * @return string */ public function processLinks($content) { // redefine $content = (string) $content; // replace URLs and images $search = array('href="/', 'src="/'); $replace = array('href="' . SITE_URL . '/', 'src="' . SITE_URL . '/'); // replace links to files $content = str_replace($search, $replace, $content); // init var $matches = array(); // match links preg_match_all('/href="(http:\\/\\/(.*))"/iU', $content, $matches); // any links? if (isset($matches[1]) && !empty($matches[1])) { // init vars $searchLinks = array(); $replaceLinks = array(); // loop old links foreach ($matches[1] as $i => $link) { $searchLinks[] = $matches[0][$i]; $replaceLinks[] = 'href="' . Model::addURLParameters($link, $this->utm) . '"'; } // replace $content = str_replace($searchLinks, $replaceLinks, $content); } return $content; }
/** * Parse */ private function parse() { // get list of recent products $numItems = FrontendModel::getModuleSetting('Catalog', 'recent_products_full_num_items', 3); $recentProducts = FrontendCatalogModel::getAll($numItems); $this->tpl->assign('widgetCatalogRecentProducts', $recentProducts); }
/** * Execute the action */ public function execute() { parent::execute(); // get parameters $charset = $this->getContainer()->getParameter('kernel.charset'); $searchTerm = \SpoonFilter::getPostValue('term', null, ''); $term = $charset == 'utf-8' ? \SpoonFilter::htmlspecialchars($searchTerm) : \SpoonFilter::htmlentities($searchTerm); // validate search term if ($term == '') { $this->output(self::BAD_REQUEST, null, 'term-parameter is missing.'); } else { // previous search result $previousTerm = \SpoonSession::exists('searchTerm') ? \SpoonSession::get('searchTerm') : ''; \SpoonSession::set('searchTerm', ''); // save this term? if ($previousTerm != $term) { // format data $this->statistics = array(); $this->statistics['term'] = $term; $this->statistics['language'] = LANGUAGE; $this->statistics['time'] = FrontendModel::getUTCDate(); $this->statistics['data'] = serialize(array('server' => $_SERVER)); $this->statistics['num_results'] = FrontendSearchModel::getTotal($term); // save data FrontendSearchModel::save($this->statistics); } // save current search term in cookie \SpoonSession::set('searchTerm', $term); // output $this->output(self::OK); } }
/** * Validate the form */ protected function validateForm() { if ($this->frm->isSubmitted()) { $fields = $this->frm->getFields(); if ($fields['email']->isEmail(FL::err('EmailIsInvalid'))) { } if (FrontendMailengineModel::isSubscribed($fields['email']->getValue())) { $fields['email']->addError(FL::err('AlreadySubscribed')); } if ($this->frm->isCorrect()) { //--Subscribe $id = FrontendMailengineModel::subscribe($fields['email']->getValue()); //--Get the default group $defaultGroup = FrontendModel::getModuleSetting($this->module, 'default_group'); if ($defaultGroup > 0) { $data = array(); $data['user_id'] = $id; $data['group_id'] = $defaultGroup; //--Add user to group FrontendMailengineModel::insertUserToGroup($data); } // redirect $this->redirect(FrontendNavigation::getURLForBlock('Mailengine', 'MailengineSubscribe') . '?sent=true#subscribe'); } } $this->frm->parse($this->tpl); }
/** * Set the image for the feed. * * @param string $url URL of the image. * @param string $title Title of the image. * @param string $link Link of the image. * @param int $width Width of the image. * @param int $height Height of the image. * @param string $description Description of the image. */ public function setImage($url, $title, $link, $width = null, $height = null, $description = null) { // add UTM-parameters $link = Model::addURLParameters($link, array('utm_source' => 'feed', 'utm_medium' => 'rss', 'utm_campaign' => CommonUri::getUrl($this->getTitle()))); // call the parent parent::setImage($url, $title, $link, $width, $height, $description); }
/** * Stores a value in a cookie, by default the cookie will expire in one day. * * @param string $key A name for the cookie. * @param mixed $value The value to be stored. Keep in mind that they will be serialized. * @param int $time The number of seconds that this cookie will be available, 30 days is the default. * @param string $path The path on the server in which the cookie will * be available. Use / for the entire domain, /foo * if you just want it to be available in /foo. * @param string $domain The domain that the cookie is available on. Use * .example.com to make it available on all * subdomains of example.com. * @param bool $secure Should the cookie be transmitted over a * HTTPS-connection? If true, make sure you use * a secure connection, otherwise the cookie won't be set. * @param bool $httpOnly Should the cookie only be available through * HTTP-protocol? If true, the cookie can't be * accessed by Javascript, ... * @return bool If set with success, returns true otherwise false. */ public static function set($key, $value, $time = 2592000, $path = '/', $domain = null, $secure = null, $httpOnly = true) { // redefine $key = (string) $key; $value = serialize($value); $time = time() + (int) $time; $path = (string) $path; $httpOnly = (bool) $httpOnly; // when the domain isn't passed and the url-object is available we can set the cookies for all subdomains if ($domain === null && FrontendModel::getContainer()->has('request')) { $domain = '.' . FrontendModel::getContainer()->get('request')->getHost(); } // when the secure-parameter isn't set if ($secure === null) { /* detect if we are using HTTPS, this wil only work in Apache, if you are using nginx you should add the code below into your config: ssl on; fastcgi_param HTTPS on; for lighttpd you should add: setenv.add-environment = ("HTTPS" => "on") */ $secure = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on'; } // set cookie $cookie = setcookie($key, $value, $time, $path, $domain, $secure, $httpOnly); // problem occurred return $cookie === false ? false : true; }
/** * Get an item. * * @param string $id The id of the item to fetch. * * @return array * * @deprecated use doctrine instead */ public static function get($id) { trigger_error('Frontend\\Modules\\ContentBlocks\\Engine is deprecated. Switch to doctrine instead.', E_USER_DEPRECATED); return (array) FrontendModel::getContainer()->get('database')->getRecord('SELECT i.title, i.text, i.template FROM content_blocks AS i WHERE i.id = ? AND i.status = ? AND i.hidden = ? AND i.language = ?', array((int) $id, 'active', 'N', LANGUAGE)); }
public static function getRoom($room_id) { $room = (array) FrontendModel::getContainer()->get('database')->getRecord('SELECT hr.id, hr.title, hr.price, hr.image, hr.count FROM hotels_rooms AS hr WHERE hr.id = ?', array($room_id)); if ($room) { $room['image'] = HOTELS_API_URL . FRONTEND_FILES_URL . '/rooms/images/source/' . $room['image']; } return $room; }
/** * Fetches a certain item * * @param string $id * @return array */ public static function get($id) { $item = (array) FrontendModel::get('database')->getRecord('SELECT i.* FROM instagram_users AS i WHERE i.id = ? AND i.hidden = ?', array((int) $id, 'N')); // no results? if (empty($item)) { return array(); } return $item; }
/** * Execute the extra. */ public function execute() { // logout if (FrontendProfilesAuthentication::isLoggedIn()) { FrontendProfilesAuthentication::logout(); } // trigger event FrontendModel::triggerEvent('Profiles', 'after_logout'); // redirect $this->redirect(SITE_URL); }
/** * Execute the action */ public function execute() { parent::execute(); // Get POST parameters $userId = \SpoonFilter::getPostValue('userId', null, ''); // Get count settings $this->recentCount = FrontendModel::get('fork.settings')->get('Instagram', 'num_recent_items', 10); // Get the images from the Instagram API $this->images = FrontendInstagramModel::getRecentMedia($userId, $this->recentCount); // Output the result $this->output(self::OK, $this->images); }
public function testTruncate() { $containerMock = $this->getMockBuilder('Symfony\\Component\\DependencyInjection\\ContainerInterface')->disableOriginalConstructor()->getMock(); $containerMock->expects(self::any())->method('getParameter')->with('kernel.charset')->will(self::returnValue('UTF-8')); FrontendModel::setContainer($containerMock); self::assertEquals(TemplateModifiers::truncate('foo bar baz qux', 3, false, true), 'foo'); self::assertEquals(TemplateModifiers::truncate('foo bar baz qux', 4, false, true), 'foo'); self::assertEquals(TemplateModifiers::truncate('foo bar baz qux', 8, false, true), 'foo bar'); self::assertEquals(TemplateModifiers::truncate('foo bar baz qux', 100, false, true), 'foo bar baz qux'); // Hellip self::assertEquals(TemplateModifiers::truncate('foo bar baz qux', 5, true, true), 'foo…'); self::assertEquals(TemplateModifiers::truncate('foo bar baz qux', 14, true, true), 'foo bar baz…'); self::assertEquals(TemplateModifiers::truncate('foo bar baz qux', 15, true, true), 'foo bar baz qux'); }
private function saveData() { $booking['id'] = 0; $booking['room_id'] = \SpoonFilter::getPostValue('room_id', null, null); $booking['start'] = \SpoonFilter::getPostValue('arrival', null, null); $booking['end'] = \SpoonFilter::getPostValue('departure', null, null); $booking['client_name'] = \SpoonFilter::getPostValue('client_name', null, null); $booking['client_email'] = \SpoonFilter::getPostValue('client_email', null, null); $booking['date'] = FrontendModel::getUTCDate(); if ($booking['room_id'] && $booking['start'] && $booking['end'] && $booking['client_name']) { $booking['id'] = $this->addReservation($booking); } echo json_encode($booking['id']); die; }
/** * Deletes one or more cookies. * * This overwrites the spoon cookie method and adds the same functionality * as in the set method to automatically set the domain. */ public static function delete() { $domain = null; if (FrontendModel::getContainer()->has('request')) { $domain = '.' . FrontendModel::getContainer()->get('request')->getHost(); } foreach (func_get_args() as $argument) { // multiple arguments are given if (is_array($argument)) { foreach ($argument as $key) { self::delete($key); } } else { // delete the given cookie unset($_COOKIE[(string) $argument]); setcookie((string) $argument, null, 1, '/', $domain); } } }
/** * Load the data, don't forget to validate the incoming data */ private function getData() { $parameter_count = count($this->URL->getParameters(false)); if ($parameter_count <= 0) { $this->redirect(FrontendNavigation::getURL(404)); } // get category $this->category = FrontendAgendaModel::getCategory($this->URL->getParameter($parameter_count - 1)); if (empty($this->category)) { $this->redirect(FrontendNavigation::getURL(404)); } // requested page $requestedPage = $this->URL->getParameter('page', 'int', 1); // set URL and limit $this->pagination['url'] = FrontendNavigation::getURLForBlock('Agenda', 'Category') . '/' . $this->category['url']; $this->pagination['limit'] = FrontendModel::getModuleSetting('Agenda', 'overview_num_items', 10); // populate count fields in pagination $this->pagination['num_items'] = FrontendAgendaModel::getCategoryCount($this->category['id']); $this->pagination['num_pages'] = (int) ceil($this->pagination['num_items'] / $this->pagination['limit']); // num pages is always equal to at least 1 if ($this->pagination['num_pages'] == 0) { $this->pagination['num_pages'] = 1; } // redirect if the request page doesn't exist if ($requestedPage > $this->pagination['num_pages'] || $requestedPage < 1) { $this->redirect(FrontendNavigation::getURL(404)); } // populate calculated fields in pagination $this->pagination['requested_page'] = $requestedPage; $this->pagination['offset'] = $this->pagination['requested_page'] * $this->pagination['limit'] - $this->pagination['limit']; // timestamps // @todo SET CORRECT TIMES $startTimestamp = strtotime('last Monday 00:59', time()); // first day of the week $endTimestamp = strtotime("next Monday 0:59", time()); // last day of the week // get items $this->items = FrontendAgendaModel::getAllByCategory($this->category['id'], $this->pagination['limit'], $this->pagination['offset'], $startTimestamp, $endTimestamp); // sort dates usort($this->items, "self::cmpValues"); }
/** * Validate the form */ private function validateForm() { // is the form submitted if ($this->frm->isSubmitted()) { // validate required fields $email = $this->frm->getField('email'); // validate required fields if ($email->isEmail(FL::err('EmailIsInvalid'))) { if (FrontendMailmotorModel::isSubscribed($email->getValue())) { $email->addError(FL::err('AlreadySubscribed')); } } // no errors if ($this->frm->isCorrect()) { try { // subscribe the user to our default group if (!FrontendMailmotorCMHelper::subscribe($email->getValue())) { throw new FrontendException('Could not subscribe'); } // trigger event FrontendModel::triggerEvent('Mailmotor', 'after_subscribe', array('email' => $email->getValue())); // redirect $this->redirect(FrontendNavigation::getURLForBlock('Mailmotor', 'Subscribe') . '?sent=true#subscribeForm'); } catch (\Exception $e) { // make sure RedirectExceptions get thrown if ($e instanceof RedirectException) { throw $e; } // when debugging we need to see the exceptions if ($this->getContainer()->getParameter('kernel.debug')) { throw $e; } // show error $this->tpl->assign('subscribeHasError', true); } } else { $this->tpl->assign('subscribeHasFormError', true); } } }
/** * @param FormBuilderSubmittedEvent $event */ public function onFormSubmitted(FormBuilderSubmittedEvent $event) { $form = $event->getForm(); // need to send mail if ($form['method'] == 'database_email') { // build our message $from = FrontendModel::get('fork.settings')->get('Core', 'mailer_from'); $fieldData = $this->getEmailFields($event->getData()); $message = \Common\Mailer\Message::newInstance(sprintf(FL::getMessage('FormBuilderSubject'), $form['name']))->parseHtml(FRONTEND_MODULES_PATH . '/FormBuilder/Layout/Templates/Mails/Form.tpl', array('sentOn' => time(), 'name' => $form['name'], 'fields' => $fieldData), true)->setTo($form['email'])->setFrom(array($from['email'] => $from['name'])); // check if we have a replyTo email set foreach ($form['fields'] as $field) { if (array_key_exists('reply_to', $field['settings']) && $field['settings']['reply_to'] === true) { $email = $fieldData[$field['id']]['value']; $message->setReplyTo(array($email => $email)); } } if ($message->getReplyTo() === null) { $replyTo = FrontendModel::get('fork.settings')->get('Core', 'mailer_reply_to'); $message->setReplyTo(array($replyTo['email'] => $replyTo['name'])); } $this->mailer->send($message); } }
/** * The constructor will store the instance in the reference, preset some settings and map the custom modifiers. */ public function __construct() { parent::__construct(func_get_arg(0), func_get_arg(1), func_get_arg(2)); $this->debugMode = Model::getContainer()->getParameter('kernel.debug'); $this->forkSettings = Model::get('fork.settings'); // fork has been installed if ($this->forkSettings) { $this->themePath = FRONTEND_PATH . '/Themes/' . $this->forkSettings->get('Core', 'theme', 'default'); $loader = $this->environment->getLoader(); $loader = new \Twig_Loader_Chain(array($loader, new \Twig_Loader_Filesystem($this->getLoadingFolders()))); $this->environment->setLoader($loader); // connect symphony forms $formEngine = new TwigRendererEngine($this->getFormTemplates('FormLayout.html.twig')); $formEngine->setEnvironment($this->environment); $this->environment->addExtension(new SymfonyFormExtension(new TwigRenderer($formEngine, Model::get('security.csrf.token_manager')))); } $this->environment->disableStrictVariables(); // init Form extension new FormExtension($this->environment); // start the filters / globals TwigFilters::getFilters($this->environment, 'Frontend'); $this->startGlobals($this->environment); }
/** * Generate thumbnails based on the folders in the path * Use * - 128x128 as folder name to generate an image that where the width will be 128px and the height will be 128px * - 128x as folder name to generate an image that where the width will be 128px, * the height will be calculated based on the aspect ratio. * - x128 as folder name to generate an image that where the width will be 128px, * the height will be calculated based on the aspect ratio. * * @param string $path * @param string $filename */ public function generateThumbnails($path, $filename) { // create folder if needed $fs = new Filesystem(); if (!$fs->exists($path . '/source')) { $fs->mkdir($path . '/source'); } // move the source file $this->moveFile($path . '/source/' . $filename); // generate the thumbnails Model::generateThumbnails($path, $path . '/source/' . $filename); }
/** * Validate the form. */ private function validateForm() { // is the form submitted if ($this->frm->isSubmitted()) { // get fields $txtDisplayName = $this->frm->getField('display_name'); $txtFirstName = $this->frm->getField('first_name'); $txtLastName = $this->frm->getField('last_name'); $txtCity = $this->frm->getField('city'); $ddmCountry = $this->frm->getField('country'); $ddmGender = $this->frm->getField('gender'); $ddmDay = $this->frm->getField('day'); $ddmMonth = $this->frm->getField('month'); $ddmYear = $this->frm->getField('year'); // get number of display name changes $nameChanges = (int) FrontendProfilesModel::getSetting($this->profile->getId(), 'display_name_changes'); // has there been a valid display name change request? if ($this->profile->getDisplayName() !== $txtDisplayName->getValue() && $nameChanges <= FrontendProfilesModel::MAX_DISPLAY_NAME_CHANGES) { // display name filled in? if ($txtDisplayName->isFilled(FL::getError('FieldIsRequired'))) { // display name exists? if (FrontendProfilesModel::existsDisplayName($txtDisplayName->getValue(), $this->profile->getId())) { // set error $txtDisplayName->addError(FL::getError('DisplayNameExists')); } } } // birthdate is not required but if one is filled we need all if ($ddmMonth->isFilled() || $ddmDay->isFilled() || $ddmYear->isFilled()) { // valid birth date? if (!checkdate($ddmMonth->getValue(), $ddmDay->getValue(), $ddmYear->getValue())) { // set error $ddmYear->addError(FL::getError('DateIsInvalid')); } } // validate avatar when given $this->frm->getField('avatar')->isFilled(); // no errors if ($this->frm->isCorrect()) { // init $values = array(); $settings = array(); // has there been a valid display name change request? if ($this->profile->getDisplayName() !== $txtDisplayName->getValue() && $nameChanges <= FrontendProfilesModel::MAX_DISPLAY_NAME_CHANGES) { // get display name value $values['display_name'] = $txtDisplayName->getValue(); // update url based on the new display name $values['url'] = FrontendProfilesModel::getUrl($txtDisplayName->getValue(), $this->profile->getId()); // update display name count $settings['display_name_changes'] = $nameChanges + 1; } // update values if (!empty($values)) { FrontendProfilesModel::update($this->profile->getId(), $values); } // build settings $settings['first_name'] = $txtFirstName->getValue(); $settings['last_name'] = $txtLastName->getValue(); $settings['city'] = $txtCity->getValue(); $settings['country'] = $ddmCountry->getValue(); $settings['gender'] = $ddmGender->getValue(); // birthday is filled in if ($ddmYear->isFilled()) { // mysql format $settings['birth_date'] = $ddmYear->getValue() . '-'; $settings['birth_date'] .= str_pad($ddmMonth->getValue(), 2, '0', STR_PAD_LEFT) . '-'; $settings['birth_date'] .= str_pad($ddmDay->getValue(), 2, '0', STR_PAD_LEFT); } else { // not filled in $settings['birth_date'] = null; } // avatar $settings['avatar'] = $this->profile->getSetting('avatar'); // create new filename if ($this->frm->getField('avatar')->isFilled()) { // field value $settings['avatar'] = \SpoonFilter::urlise($this->profile->getDisplayName()) . '.' . $this->frm->getField('avatar')->getExtension(); // move the file $this->frm->getField('avatar')->generateThumbnails(FRONTEND_FILES_PATH . '/Profiles/Avatars/', $settings['avatar']); } // save settings $this->profile->setSettings($settings); // trigger event FrontendModel::triggerEvent('Profiles', 'after_saved_settings', array('id' => $this->profile->getId())); // redirect $this->redirect(SITE_URL . FrontendNavigation::getURLForBlock('Profiles', 'Settings') . '?sent=true'); } else { $this->tpl->assign('updateSettingsHasFormError', true); } } }
/** * Validate searches: check everything that has been marked as 'inactive', if should still be inactive */ public static function validateSearch() { // we'll iterate through the inactive search indices in little batches $offset = 0; $limit = 50; while (1) { // get the inactive indices $searchResults = (array) FrontendModel::getContainer()->get('database')->getRecords('SELECT module, other_id FROM search_index WHERE language = ? AND active = ? GROUP BY module, other_id LIMIT ?, ?', array(FRONTEND_LANGUAGE, 'N', $offset, $limit)); // none found? good news! if (!$searchResults) { return; } // prepare to send to modules $moduleResults = array(); // loop the result set foreach ($searchResults as $searchResult) { $moduleResults[$searchResult['module']][] = $searchResult['other_id']; } // pass the results to the modules foreach ($moduleResults as $module => $otherIds) { // check if this module actually is prepared to handle searches $class = 'Frontend\\Modules\\' . $module . '\\Engine\\Model'; if (is_callable(array($class, 'search'))) { $moduleResults[$module] = call_user_func(array($class, 'search'), $otherIds); // update the ones that are allowed to be searched through self::statusIndex($module, array_keys($moduleResults[$module]), true); } } // didn't even get the amount of result we asked for? no need to ask again! if (count($searchResults) < $offset) { return; } $offset += $limit; } }
/** * Subscribes email adres to list. * * @return bool * @param string $email email. * @param string[optional] $listId list id. */ public static function unsubscribe($email, $listId = null) { // get mailchimp reference $mc = self::getMC(); // if list_id = null get the setting for it if (!$listId) { $listId = FrontendModel::getModuleSetting('MailMotor', 'list'); } // return list unsubcribe return (bool) $mc->listUnsubscribe($listId, $email, FrontendModel::getModuleSetting('MailMotor', 'delete_member'), FrontendModel::getModuleSetting('MailMotor', 'send_goodbye_email'), FrontendModel::getModuleSetting('MailMotor', 'send_notify_email')); }
/** * Validate the form */ private function validateForm() { // is the form submitted if ($this->frm->isSubmitted()) { // get fields $txtOldPassword = $this->frm->getField('old_password'); $txtNewPassword = $this->frm->getField('new_password'); // old password filled in? if ($txtOldPassword->isFilled(FL::getError('PasswordIsRequired'))) { // old password correct? if (FrontendProfilesAuthentication::getLoginStatus($this->profile->getEmail(), $txtOldPassword->getValue()) !== FrontendProfilesAuthentication::LOGIN_ACTIVE) { // set error $txtOldPassword->addError(FL::getError('InvalidPassword')); } // new password filled in? $txtNewPassword->isFilled(FL::getError('PasswordIsRequired')); // passwords match? if ($this->frm->getField('new_password')->getValue() !== $this->frm->getField('verify_new_password')->getValue()) { $this->frm->getField('verify_new_password')->addError(FL::err('PasswordsDontMatch')); } } // no errors if ($this->frm->isCorrect()) { // update password FrontendProfilesAuthentication::updatePassword($this->profile->getId(), $txtNewPassword->getValue()); // trigger event FrontendModel::triggerEvent('Profiles', 'after_change_password', array('id' => $this->profile->getId())); // redirect $this->redirect(SITE_URL . FrontendNavigation::getURLForBlock('Profiles', 'ChangePassword') . '?sent=true'); } else { $this->tpl->assign('updatePasswordHasFormError', true); } } }
/** * Unsubscribes an e-mail address * * @param string $email The mail address to unsubscribe. * @param string $groupId The id of the group to unsubscribe from. * @return bool */ public static function unsubscribe($email, $groupId = null) { // get objects $db = FrontendModel::getContainer()->get('database'); // set groupID $groupId = !empty($groupId) ? $groupId : self::getDefaultGroupID(); // unsubscribe the user in CM if (self::existsGroup($groupId)) { // set variables $subscriber['status'] = 'unsubscribed'; $subscriber['unsubscribed_on'] = FrontendModel::getUTCDate('Y-m-d H:i:s'); // unsubscribe the user $db->update('mailmotor_addresses_groups', $subscriber, 'email = ? AND group_id = ?', array($email, $groupId)); // user unsubscribed return true; } // user not unsubscribed return false; }
/** * Load the data, don't forget to validate the incoming data */ private function getData() { $this->parameters = $this->URL->getParameters(); $url = end($this->parameters); if ($url === null) { $this->redirect(FrontendNavigation::getURL(404)); } // get by URL $this->record = FrontendCatalogModel::getBrandFromUrl($url); if (empty($this->record)) { $this->redirect(FrontendNavigation::getURL(404)); } // get products $this->products = FrontendCatalogModel::getAllByBrand($this->record['id']); // requested page $requestedPage = $this->URL->getParameter('page', 'int', 1); // set URL and limit $this->pagination['url'] = FrontendNavigation::getURLForBlock('catalog', 'category') . '/' . $this->record['url']; $this->pagination['limit'] = FrontendModel::getModuleSetting('catalog', 'overview_num_items', 10); // populate count fields in pagination $this->pagination['num_items'] = FrontendCatalogModel::getCategoryCount($this->record['id']); $this->pagination['num_pages'] = (int) ceil($this->pagination['num_items'] / $this->pagination['limit']); // num pages is always equal to at least 1 if ($this->pagination['num_pages'] == 0) { $this->pagination['num_pages'] = 1; } // redirect if the request page doesn't exist if ($requestedPage > $this->pagination['num_pages'] || $requestedPage < 1) { $this->redirect(FrontendNavigation::getURL(404)); } // populate calculated fields in pagination $this->pagination['requested_page'] = $requestedPage; $this->pagination['offset'] = $this->pagination['requested_page'] * $this->pagination['limit'] - $this->pagination['limit']; }
/** * Update a profile. * * @param int $id The profile id. * @param array $values The values to update. * @return int */ public static function update($id, array $values) { return (int) FrontendModel::getContainer()->get('database')->update('profiles', $values, 'id = ?', (int) $id); }
/** * Validate the form */ private function validateForm() { // get settings $subscriptionsAllowed = isset($this->settings['allow_subscriptions']) && $this->settings['allow_subscriptions']; // subscriptions aren't allowed so we don't have to validate if (!$subscriptionsAllowed) { return false; } // is the form submitted if ($this->frm->isSubmitted()) { // cleanup the submitted fields, ignore fields that were added by hackers $this->frm->cleanupFields(); // does the key exists? if (\SpoonSession::exists('agenda_subscription_' . $this->record['id'])) { // calculate difference $diff = time() - (int) \SpoonSession::get('agenda_subscription_' . $this->record['id']); // calculate difference, it it isn't 10 seconds the we tell the user to slow down if ($diff < 10 && $diff != 0) { $this->frm->getField('message')->addError(FL::err('CommentTimeout')); } } // validate required fields $this->frm->getField('name')->isFilled(FL::err('NameIsRequired')); $this->frm->getField('email')->isEmail(FL::err('EmailIsRequired')); // no errors? if ($this->frm->isCorrect()) { // get module setting $moderationEnabled = isset($this->settings['moderation']) && $this->settings['moderation']; // reformat data $name = $this->frm->getField('name')->getValue(); $email = $this->frm->getField('email')->getValue(); // build array $subscription['agenda_id'] = $this->record['id']; $subscription['language'] = FRONTEND_LANGUAGE; $subscription['created_on'] = FrontendModel::getUTCDate(); $subscription['name'] = $name; $subscription['email'] = $email; $subscription['status'] = 'subscribed'; // get URL for article $permaLink = $this->record['full_url']; $redirectLink = $permaLink; // is moderation enabled if ($moderationEnabled) { // if the commenter isn't moderated before alter the subscription status so it will appear in the moderation queue if (!FrontendAgendaModel::isModerated($name, $email)) { $subscription['status'] = 'moderation'; } } // insert comment $subscription['id'] = FrontendAgendaModel::insertSubscription($subscription); // trigger event FrontendModel::triggerEvent('agenda', 'after_add_subscription', array('subscription' => $subscription)); // append a parameter to the URL so we can show moderation if (strpos($redirectLink, '?') === false) { if ($subscription['status'] == 'moderation') { $redirectLink .= '?subscription=moderation#' . FL::act('Subscribe'); } if ($subscription['status'] == 'subscribed') { $redirectLink .= '?subscription=true#subscription-' . $subscription['id']; } } else { if ($subscription['status'] == 'moderation') { $redirectLink .= '&subscription=moderation#' . FL::act('Subscribe'); } if ($subscription['status'] == 'subscribed') { $redirectLink .= '&subscription=true#comment-' . $subscription['id']; } } // set title $subscription['agenda_title'] = $this->record['title']; $subscription['agenda_url'] = $this->record['url']; // notify the admin FrontendAgendaModel::notifyAdmin($subscription); // store timestamp in session so we can block excessive usage \SpoonSession::set('agenda_subscription_' . $this->record['id'], time()); // store author-data in cookies try { Cookie::set('subscription_author', $name); Cookie::set('subscription_email', $email); } catch (Exception $e) { // settings cookies isn't allowed, but because this isn't a real problem we ignore the exception } // redirect $this->redirect($redirectLink); } } }
/** * Set the url * * @param string $url The url to associate the item with. */ public function setUrl($url) { // redefine var $url = (string) $url; // if link doesn't start with http, we prepend the URL of the site if (substr($url, 0, 7) != 'http://') { $url = SITE_URL . $url; } $url = FrontendModel::addURLParameters($url, $this->utm); $url = htmlspecialchars_decode($url); // call parent parent::setUrl($url); }