Exemplo n.º 1
0
 /**
  * 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);
     }
 }
Exemplo n.º 2
0
 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;
 }
Exemplo n.º 3
0
 /**
  * Fetch a list of subpages of a page.
  *
  * @param int $id The id of the item to grab the subpages for.
  * @return array
  */
 public static function getSubpages($id)
 {
     // fetch items
     $items = (array) FrontendModel::getContainer()->get('database')->getRecords('SELECT i.id, i.title, m.description, i.parent_id
          FROM pages AS i
          INNER JOIN meta AS m ON m.id = i.meta_id
          WHERE i.parent_id = ? AND i.status = ? AND i.hidden = ?
          AND i.language = ? AND i.publish_on <= ?
          ORDER BY i.sequence ASC', array((int) $id, 'active', 'N', FRONTEND_LANGUAGE, FrontendModel::getUTCDate('Y-m-d H:i') . ':00'));
     // has items
     if (!empty($items)) {
         // reset url
         foreach ($items as &$row) {
             $row['full_url'] = FrontendNavigation::getURL($row['id'], FRONTEND_LANGUAGE);
         }
     }
     // return
     return $items;
 }
Exemplo n.º 4
0
 /**
  * Saves the feedback
  *
  * @param array $feedback
  */
 public static function saveFeedback(array $feedback)
 {
     $feedback['created_on'] = FrontendModel::getUTCDate();
     unset($feedback['sentOn']);
     FrontendModel::getContainer()->get('database')->insert('faq_feedback', $feedback);
 }
Exemplo n.º 5
0
 /**
  * Unsubscribes an e-mail address from CampaignMonitor and our database
  *
  * @param string        $email   The e-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');
     $cm = self::getCM();
     // set group ID
     $groupId = !empty($groupId) ? $groupId : FrontendMailmotorModel::getDefaultGroupID();
     // get group CM ID
     $groupCMId = self::getCampaignMonitorID('list', $groupId);
     // group exists
     if (FrontendMailmotorModel::existsGroup($groupId)) {
         try {
             // unsubscribe the email from this group
             $cm->unsubscribe($email, $groupCMId);
         } catch (\Exception $e) {
             // for the unsubscribe function we ignore any errors
             // stop here if something went wrong with CM
             return false;
         }
         // 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;
 }
Exemplo n.º 6
0
    /**
     *
     * Unsubscribe the email
     *
     * @param $email
     *
     * @return bool
     */
    public static function unsubscribe($email)
    {
        $record = FrontendModel::getContainer()->get('database')->getRecord('	SELECT id
														FROM mailengine_users
														WHERE email= ?', array($email));
        //--Check if record exists
        if (is_array($record)) {
            $data = array();
            $data['active'] = 'N';
            $data['unsubscribe_on'] = FrontendModel::getUTCDate();
            //--Update record
            FrontendModel::getContainer()->get('database')->update('mailengine_users', $data, 'id=' . $record["id"]);
            //--Delete the groups for the user
            self::deleteGroupFromUser($record['id']);
            return true;
        } else {
            return false;
        }
    }
Exemplo n.º 7
0
 /**
  * Save statistics
  */
 private function saveStatistics()
 {
     // no search term = no search
     if (!$this->term) {
         return;
     }
     // previous search result
     $previousTerm = \SpoonSession::exists('searchTerm') ? \SpoonSession::get('searchTerm') : '';
     \SpoonSession::set('searchTerm', '');
     // save this term?
     if ($previousTerm != $this->term) {
         // format data
         $this->statistics = array();
         $this->statistics['term'] = $this->term;
         $this->statistics['language'] = LANGUAGE;
         $this->statistics['time'] = FrontendModel::getUTCDate();
         $this->statistics['data'] = serialize(array('server' => $_SERVER));
         $this->statistics['num_results'] = $this->pagination['num_items'];
         // save data
         FrontendSearchModel::save($this->statistics);
     }
     // save current search term in cookie
     \SpoonSession::set('searchTerm', $this->term);
 }
Exemplo n.º 8
0
 /**
  * Validate the form
  */
 private function validateForm()
 {
     // get settings
     $commentsAllowed = isset($this->settings['allow_comments']) && $this->settings['allow_comments'];
     // comments aren't allowed so we don't have to validate
     if (!$commentsAllowed) {
         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('blog_comment_' . $this->record['id'])) {
             // calculate difference
             $diff = time() - (int) \SpoonSession::get('blog_comment_' . $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('author')->isFilled(FL::err('AuthorIsRequired'));
         $this->frm->getField('email')->isEmail(FL::err('EmailIsRequired'));
         $this->frm->getField('message')->isFilled(FL::err('MessageIsRequired'));
         // validate optional fields
         if ($this->frm->getField('website')->isFilled() && $this->frm->getField('website')->getValue() != 'http://') {
             $this->frm->getField('website')->isURL(FL::err('InvalidURL'));
         }
         // no errors?
         if ($this->frm->isCorrect()) {
             // get module setting
             $spamFilterEnabled = isset($this->settings['spamfilter']) && $this->settings['spamfilter'];
             $moderationEnabled = isset($this->settings['moderation']) && $this->settings['moderation'];
             // reformat data
             $author = $this->frm->getField('author')->getValue();
             $email = $this->frm->getField('email')->getValue();
             $website = $this->frm->getField('website')->getValue();
             if (trim($website) == '' || $website == 'http://') {
                 $website = null;
             }
             $text = $this->frm->getField('message')->getValue();
             // build array
             $comment['post_id'] = $this->record['id'];
             $comment['language'] = FRONTEND_LANGUAGE;
             $comment['created_on'] = FrontendModel::getUTCDate();
             $comment['author'] = $author;
             $comment['email'] = $email;
             $comment['website'] = $website;
             $comment['text'] = $text;
             $comment['status'] = 'published';
             $comment['data'] = serialize(array('server' => $_SERVER));
             // 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
                 // comment status so it will appear in the moderation queue
                 if (!FrontendBlogModel::isModerated($author, $email)) {
                     $comment['status'] = 'moderation';
                 }
             }
             // should we check if the item is spam
             if ($spamFilterEnabled) {
                 // check for spam
                 $result = FrontendModel::isSpam($text, SITE_URL . $permaLink, $author, $email, $website);
                 // if the comment is spam alter the comment status so it will appear in the spam queue
                 if ($result) {
                     $comment['status'] = 'spam';
                 } elseif ($result == 'unknown') {
                     // if the status is unknown then we should moderate it manually
                     $comment['status'] = 'moderation';
                 }
             }
             // insert comment
             $comment['id'] = FrontendBlogModel::insertComment($comment);
             // trigger event
             FrontendModel::triggerEvent('Blog', 'after_add_comment', array('comment' => $comment));
             // append a parameter to the URL so we can show moderation
             if (strpos($redirectLink, '?') === false) {
                 if ($comment['status'] == 'moderation') {
                     $redirectLink .= '?comment=moderation#' . FL::act('Comment');
                 }
                 if ($comment['status'] == 'spam') {
                     $redirectLink .= '?comment=spam#' . FL::act('Comment');
                 }
                 if ($comment['status'] == 'published') {
                     $redirectLink .= '?comment=true#comment-' . $comment['id'];
                 }
             } else {
                 if ($comment['status'] == 'moderation') {
                     $redirectLink .= '&comment=moderation#' . FL::act('Comment');
                 }
                 if ($comment['status'] == 'spam') {
                     $redirectLink .= '&comment=spam#' . FL::act('Comment');
                 }
                 if ($comment['status'] == 'published') {
                     $redirectLink .= '&comment=true#comment-' . $comment['id'];
                 }
             }
             // set title
             $comment['post_title'] = $this->record['title'];
             $comment['post_url'] = $this->record['url'];
             // notify the admin
             FrontendBlogModel::notifyAdmin($comment);
             // store timestamp in session so we can block excessive usage
             \SpoonSession::set('blog_comment_' . $this->record['id'], time());
             // store author-data in cookies
             try {
                 CommonCookie::set('comment_author', $author);
                 CommonCookie::set('comment_email', $email);
                 CommonCookie::set('comment_website', $website);
             } catch (\Exception $e) {
                 // settings cookies isn't allowed, but because this isn't a real problem we ignore the exception
             }
             // redirect
             $this->redirect($redirectLink);
         }
     }
 }
Exemplo n.º 9
0
 /**
  * Validate the form
  */
 private function validateForm()
 {
     // is the form submitted
     if ($this->frm->isSubmitted()) {
         // get fields
         $txtDisplayName = $this->frm->getField('display_name');
         $txtEmail = $this->frm->getField('email');
         $txtPassword = $this->frm->getField('password');
         // check email
         if ($txtEmail->isFilled(FL::getError('EmailIsRequired'))) {
             // valid email?
             if ($txtEmail->isEmail(FL::getError('EmailIsInvalid'))) {
                 // email already exists?
                 if (FrontendProfilesModel::existsByEmail($txtEmail->getValue())) {
                     // set error
                     $txtEmail->setError(FL::getError('EmailExists'));
                 }
             }
         }
         // check password
         $txtPassword->isFilled(FL::getError('PasswordIsRequired'));
         // no errors
         if ($this->frm->isCorrect()) {
             // init values
             $settings = array();
             $values = array();
             // generate salt
             $settings['salt'] = FrontendProfilesModel::getRandomString();
             $settings['language'] = FRONTEND_LANGUAGE;
             // values
             $values['email'] = $txtEmail->getValue();
             $values['password'] = FrontendProfilesModel::getEncryptedString($txtPassword->getValue(), $settings['salt']);
             $values['status'] = 'inactive';
             $values['display_name'] = $txtDisplayName->getValue();
             $values['registered_on'] = FrontendModel::getUTCDate();
             $values['last_login'] = FrontendModel::getUTCDate(null, 0);
             /*
              * Add a profile.
              * We use a try-catch statement to catch errors when more users sign up simultaneously.
              */
             try {
                 // insert profile
                 $profileId = FrontendProfilesModel::insert($values);
                 // use the profile id as url until we have an actual url
                 FrontendProfilesModel::update($profileId, array('url' => FrontendProfilesModel::getUrl($values['display_name'])));
                 // trigger event
                 FrontendModel::triggerEvent('Profiles', 'after_register', array('id' => $profileId));
                 // generate activation key
                 $settings['activation_key'] = FrontendProfilesModel::getEncryptedString($profileId . microtime(), $settings['salt']);
                 // set settings
                 FrontendProfilesModel::setSettings($profileId, $settings);
                 // login
                 FrontendProfilesAuthentication::login($profileId);
                 // activation URL
                 $mailValues['activationUrl'] = SITE_URL . FrontendNavigation::getURLForBlock('Profiles', 'Activate') . '/' . $settings['activation_key'];
                 // send email
                 $from = $this->get('fork.settings')->get('Core', 'mailer_from');
                 $replyTo = $this->get('fork.settings')->get('Core', 'mailer_reply_to');
                 $message = \Common\Mailer\Message::newInstance(FL::getMessage('RegisterSubject'))->setFrom(array($from['email'] => $from['name']))->setTo(array($txtEmail->getValue() => ''))->setReplyTo(array($replyTo['email'] => $replyTo['name']))->parseHtml(FRONTEND_MODULES_PATH . '/Profiles/Layout/Templates/Mails/Register.tpl', $mailValues, true);
                 $this->get('mailer')->send($message);
                 // redirect
                 $this->redirect(SITE_URL . '/' . $this->URL->getQueryString() . '?sent=true');
             } catch (\Exception $e) {
                 // when debugging we need to see the exceptions
                 if ($this->getContainer()->getParameter('kernel.debug')) {
                     throw $e;
                 }
                 // show error
                 $this->tpl->assign('registerHasFormError', true);
             }
         } else {
             $this->tpl->assign('registerHasFormError', true);
         }
     }
 }
Exemplo n.º 10
0
 /**
  * Login a profile.
  *
  * @param  int  $profileId Login the profile with this id in.
  * @param  bool $remember  Should we set a cookie for later?
  * @return bool
  */
 public static function login($profileId, $remember = false)
 {
     // redefine vars
     $profileId = (int) $profileId;
     $remember = (bool) $remember;
     $secretKey = null;
     // cleanup old sessions
     self::cleanupOldSessions();
     // set profile_logged_in to true
     \SpoonSession::set('frontend_profile_logged_in', true);
     // should we remember the user?
     if ($remember) {
         // generate secret key
         $secretKey = FrontendProfilesModel::getEncryptedString(\SpoonSession::getSessionId(), FrontendProfilesModel::getRandomString());
         // set cookie
         CommonCookie::set('frontend_profile_secret_key', $secretKey);
     }
     // delete all records for this session to prevent duplicate keys (this should never happen)
     FrontendModel::getContainer()->get('database')->delete('profiles_sessions', 'session_id = ?', \SpoonSession::getSessionId());
     // insert new session record
     FrontendModel::getContainer()->get('database')->insert('profiles_sessions', array('profile_id' => $profileId, 'session_id' => \SpoonSession::getSessionId(), 'secret_key' => $secretKey, 'date' => FrontendModel::getUTCDate()));
     // update last login
     FrontendProfilesModel::update($profileId, array('last_login' => FrontendModel::getUTCDate()));
     // trigger event
     FrontendModel::triggerEvent('Profiles', 'after_logged_in', array('profile_id' => $profileId));
     // load the profile object
     self::$profile = new FrontendProfilesProfile($profileId);
 }
Exemplo n.º 11
0
 /**
  * Get related items based on tags
  *
  * @param int $id    The id of the item to get related items for.
  * @param int $limit The maximum number of items to retrieve.
  * @return array
  */
 public static function getRelated($id, $limit = 5)
 {
     $id = (int) $id;
     $limit = (int) $limit;
     // get the related IDs
     $relatedIDs = (array) FrontendTagsModel::getRelatedItemsByTags($id, 'Blog', 'Blog', $limit);
     // no items
     if (empty($relatedIDs)) {
         return array();
     }
     // get link
     $link = FrontendNavigation::getURLForBlock('Blog', 'Detail');
     // get items
     $items = (array) FrontendModel::getContainer()->get('database')->getRecords('SELECT i.id, i.title, m.url
          FROM blog_posts AS i
          INNER JOIN meta AS m ON i.meta_id = m.id
          WHERE i.status = ? AND i.language = ? AND i.hidden = ? AND i.publish_on <= ? AND i.id IN(' . implode(',', $relatedIDs) . ')
          ORDER BY i.publish_on DESC, i.id DESC
          LIMIT ?', array('active', FRONTEND_LANGUAGE, 'N', FrontendModel::getUTCDate('Y-m-d H:i') . ':00', $limit), 'id');
     // loop items
     foreach ($items as &$row) {
         $row['full_url'] = $link . '/' . $row['url'];
     }
     return $items;
 }
Exemplo n.º 12
0
 private static function uploadFile()
 {
     //--Check if the file is an image or file
     if (self::isImage()) {
         // the image path
         $path = FRONTEND_FILES_PATH . '/media/images';
     } else {
         // the file path
         $path = FRONTEND_FILES_PATH . '/media/files';
     }
     // create folders if needed
     if (!SpoonDirectory::exists($path . '/source')) {
         SpoonDirectory::create($path . '/source');
     }
     if (!SpoonDirectory::exists($path . '/128x128')) {
         SpoonDirectory::create($path . '/128x128');
     }
     // build the filename
     $filename = self::checkFilename();
     $item = array();
     $item["filename"] = $filename;
     $item["extension"] = self::$field->getExtension();
     $item["created_on"] = FrontendModel::getUTCDate('Y-m-d H:i:s');
     $item["filesize"] = self::$field->getFileSize("b");
     $data = array();
     //--Check if file is an image to specify data
     if (self::isImage()) {
         $item["filetype"] = self::$fieldTypeImage;
         $data["width"] = self::$field->getWidth();
         $data["height"] = self::$field->getHeight();
         // upload the image & generate thumbnails
         self::$field->generateThumbnails($path, $filename);
     } else {
         $item["filetype"] = self::$fieldTypeFile;
         // move the source file
         self::$field->moveFile($path . "/" . $filename);
     }
     //--Serialize data
     $item["data"] = serialize($data);
     // get db
     $db = FrontendModel::getDB(true);
     //--Insert into media
     return $db->insert("media", $item);
 }
Exemplo n.º 13
0
 /**
  * Update value within a order
  *
  * @param array $item
  * @param int $orderId
  * @param int $productId
  * @return int
  */
 public static function updateOrderValue($item, $orderId, $productId)
 {
     // set date
     $item['date'] = FrontendModel::getUTCDate();
     // get db
     $db = FrontendModel::getContainer()->get('database');
     // update
     $db->update('catalog_orders_values', $item, 'order_id = ? AND product_id = ?', array((int) $orderId, (int) $productId));
 }
Exemplo n.º 14
0
    /**
     * Get all items by date
     *
     * @param int $startTimestamp
     * @param int $endTimestamp
     * @return array
     *
     */
    public static function getAllByDate($startTimestamp, $endTimestamp)
    {
        // build cache info
        $cacheDirectory = FRONTEND_CACHE_PATH . '/Agenda/';
        $cacheKey = $startTimestamp . '-' . $endTimestamp . '-' . FRONTEND_LANGUAGE;
        $cacheFile = FRONTEND_CACHE_PATH . '/Agenda/' . $cacheKey . '.cache';
        $currentTime = time();
        $cacheTimeout = FrontendModel::get('fork.settings')->get('Agenda', 'cache_timeout');
        // cache file exists
        if (file_exists($cacheFile)) {
            $cacheFileLastModifiedTime = filemtime($cacheFile);
            $differenceBetweenCurrentAndModifiedTime = $currentTime - $cacheFileLastModifiedTime;
            // use cache within cache timeout
            if ($differenceBetweenCurrentAndModifiedTime < $cacheTimeout) {
                $cacheData = @unserialize(file_get_contents($cacheFile));
                // return cache data if exists
                if ($cacheData) {
                    return $cacheData;
                }
            }
        }
        $startTimestamp = FrontendModel::getUTCDate(null, $startTimestamp);
        $endTimestamp = FrontendModel::getUTCDate(null, $endTimestamp);
        $items = (array) FrontendModel::getContainer()->get('database')->getRecords('SELECT i.*, UNIX_TIMESTAMP(i.begin_date) AS begin_date, UNIX_TIMESTAMP(i.end_date) AS end_date,
					m.url, c.title AS category_title, m2.url AS category_url,
					t.agenda_id, t.frequency, t.interval, t.type, t.days, t.ends_on,
					UNIX_TIMESTAMP(t.end_date) AS ends_on_date
			 FROM agenda AS i
			 INNER JOIN meta AS m ON i.meta_id = m.id
			 INNER JOIN agenda_categories AS c ON i.category_id = c.id
			 INNER JOIN meta AS m2 ON c.meta_id = m2.id
			 LEFT OUTER JOIN agenda_recurring_options AS t ON i.id = t.agenda_id
			 WHERE i.language = ? AND DATE(i.begin_date) BETWEEN ? AND ?
			 OR i.recurring = ? AND i.language = ?
			 ORDER BY i.begin_date ASC', array(FRONTEND_LANGUAGE, $startTimestamp, $endTimestamp, 'Y', FRONTEND_LANGUAGE));
        // no results?
        if (empty($items)) {
            return array();
        }
        // get item action url
        $agendaUrl = FrontendNavigation::getURLForBlock('Agenda', 'Detail');
        // get category action url
        $categoryUrl = FrontendNavigation::getURLForBlock('Agenda', 'Category');
        // get all recurring items
        foreach ($items as $key => $item) {
            $items[$key]['full_url'] = $agendaUrl . '/' . $items[$key]['url'];
            $items[$key]['category_full_url'] = $categoryUrl . '/' . $items[$key]['category_url'];
            // get image
            $img = FrontendModel::getContainer()->get('database')->getRecord('SELECT * FROM agenda_images WHERE agenda_id = ? ORDER BY sequence', array((int) $item['id']));
            if ($img) {
                $items[$key]['image'] = FRONTEND_FILES_URL . '/Agenda/' . $item['id'] . '/400x300/' . $img['filename'];
            }
            // get recurring items
            if ($item['recurring'] == 'Y') {
                $recurringItems = FrontendAgendaRecurringAgendaItems::getItemRecurrance($item, $startTimestamp, $endTimestamp);
                // found recurring items
                if (!empty($recurringItems)) {
                    $items = array_merge($items, $recurringItems);
                }
            }
            // set dates
            $items[$key]['begin_date'] = date('Y-m-d H:i', $items[$key]['begin_date']);
            $items[$key]['end_date'] = date('Y-m-d H:i', $items[$key]['end_date']);
        }
        // unset items which are outside the view
        foreach ($items as $key => $value) {
            $beginDate = strtotime($items[$key]['begin_date']);
            $begints = strtotime($startTimestamp);
            $endts = strtotime($endTimestamp);
            // check if begin date of element fits the given timespan
            if ($beginDate < $begints || $beginDate > $endts) {
                unset($items[$key]);
            } else {
                // set timestamps for navigation detail pages
                $items[$key]['ts_begin_date'] = strtotime($value['begin_date']);
                $items[$key]['ts_end_date'] = strtotime($value['end_date']);
                // set boolean for whole day agenda
                if ($value['whole_day'] == 'Y') {
                    $items[$key]['whole_day'] = true;
                }
                if ($value['whole_day'] == 'N') {
                    $items[$key]['whole_day'] = false;
                }
                $beginAsDay = strftime('%Y%m%d', strtotime($value['begin_date']));
                $endAsDay = strftime('%Y%m%d', strtotime($value['end_date']));
                // set dif if begin and end date is different
                if ($beginAsDay != $endAsDay) {
                    $items[$key]['different_end_date'] = true;
                }
            }
        }
        // write the cache file
        $fs = new Filesystem();
        if (!empty($items)) {
            $fs->dumpFile(FRONTEND_CACHE_PATH . '/Agenda/' . $cacheKey . '.cache', serialize($items));
        }
        return $items;
    }
Exemplo n.º 15
0
 /**
  * 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);
         }
     }
 }
Exemplo n.º 16
0
 /**
  * Validate the form.
  */
 private function validateForm()
 {
     // submitted
     if ($this->frm->isSubmitted()) {
         // does the key exists?
         if (\SpoonSession::exists('formbuilder_' . $this->item['id'])) {
             // calculate difference
             $diff = time() - (int) \SpoonSession::get('formbuilder_' . $this->item['id']);
             // calculate difference, it it isn't 10 seconds the we tell the user to slow down
             if ($diff < 10 && $diff != 0) {
                 $this->frm->addError(FL::err('FormTimeout'));
             }
         }
         // validate fields
         foreach ($this->item['fields'] as $field) {
             // field name
             $fieldName = 'field' . $field['id'];
             // skip
             if ($field['type'] == 'submit' || $field['type'] == 'paragraph' || $field['type'] == 'heading') {
                 continue;
             }
             // loop other validations
             foreach ($field['validations'] as $rule => $settings) {
                 // already has an error so skip
                 if ($this->frm->getField($fieldName)->getErrors() !== null) {
                     continue;
                 }
                 // required
                 if ($rule == 'required') {
                     $this->frm->getField($fieldName)->isFilled($settings['error_message']);
                 } elseif ($rule == 'email') {
                     // only check this if the field is filled, if the field is required it will be validated before
                     if ($this->frm->getField($fieldName)->isFilled()) {
                         $this->frm->getField($fieldName)->isEmail($settings['error_message']);
                     }
                 } elseif ($rule == 'numeric') {
                     // only check this if the field is filled, if the field is required it will be validated before
                     if ($this->frm->getField($fieldName)->isFilled()) {
                         $this->frm->getField($fieldName)->isNumeric($settings['error_message']);
                     }
                 } elseif ($rule == 'time') {
                     $regexTime = '/^(([0-1][0-9]|2[0-3]|[0-9])|([0-1][0-9]|2[0-3]|[0-9])(:|h)[0-5]?[0-9]?)$/';
                     if (!\SpoonFilter::isValidAgainstRegexp($regexTime, $this->frm->getField($fieldName)->getValue())) {
                         $this->frm->getField($fieldName)->setError($settings['error_message']);
                     }
                 }
             }
         }
         // valid form
         if ($this->frm->isCorrect()) {
             // item
             $data['form_id'] = $this->item['id'];
             $data['session_id'] = \SpoonSession::getSessionId();
             $data['sent_on'] = FrontendModel::getUTCDate();
             $data['data'] = serialize(array('server' => $_SERVER));
             // insert data
             $dataId = FrontendFormBuilderModel::insertData($data);
             // init fields array
             $fields = array();
             // loop all fields
             foreach ($this->item['fields'] as $field) {
                 // skip
                 if ($field['type'] == 'submit' || $field['type'] == 'paragraph' || $field['type'] == 'heading') {
                     continue;
                 }
                 // field data
                 $fieldData['data_id'] = $dataId;
                 $fieldData['label'] = $field['settings']['label'];
                 $fieldData['value'] = $this->frm->getField('field' . $field['id'])->getValue();
                 if ($field['type'] == 'radiobutton') {
                     $values = array();
                     foreach ($field['settings']['values'] as $value) {
                         $values[$value['value']] = $value['label'];
                     }
                     $fieldData['value'] = $values[$fieldData['value']];
                 }
                 // clean up
                 if (is_array($fieldData['value']) && empty($fieldData['value'])) {
                     $fieldData['value'] = null;
                 }
                 // serialize
                 if ($fieldData['value'] !== null) {
                     $fieldData['value'] = serialize($fieldData['value']);
                 }
                 // save fields data
                 $fields[$field['id']] = $fieldData;
                 // insert
                 FrontendFormBuilderModel::insertDataField($fieldData);
             }
             $this->get('event_dispatcher')->dispatch(FormBuilderEvents::FORM_SUBMITTED, new FormBuilderSubmittedEvent($this->item, $fields, $dataId));
             // trigger event
             FrontendModel::triggerEvent('FormBuilder', 'after_submission', array('form_id' => $this->item['id'], 'data_id' => $dataId, 'data' => $data, 'fields' => $fields, 'visitorId' => FrontendModel::getVisitorId()));
             // store timestamp in session so we can block excessive usage
             \SpoonSession::set('formbuilder_' . $this->item['id'], time());
             // redirect
             $redirect = SITE_URL . $this->URL->getQueryString();
             $redirect .= stripos($redirect, '?') === false ? '?' : '&';
             $redirect .= 'identifier=' . $this->item['identifier'];
             $redirect .= '#' . $this->formName;
             throw new RedirectException('Redirect', new RedirectResponse($redirect));
         } else {
             // not correct, show errors
             // global form errors set
             if ($this->frm->getErrors() != '') {
                 $this->tpl->assign('formBuilderError', $this->frm->getErrors());
             } else {
                 // general error
                 $this->tpl->assign('formBuilderError', FL::err('FormError'));
             }
         }
     }
 }
Exemplo n.º 17
0
 /**
  * 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;
 }
 /**
  * Get a gallery by id
  *
  * @return array
  * @param  int   $galleryId The id of the gallery.
  */
 public static function getGallery($id)
 {
     return (array) FrontendModel::getContainer()->get('database')->getRecord('SELECT i.*, UNIX_TIMESTAMP(i.publish_on) AS publish_on
         FROM slideshow_galleries AS i
         INNER JOIN slideshow_images as p ON i.id = p.gallery_id
         WHERE i.id = ? AND i.language = ? AND i.hidden = ?
         AND i.publish_on <= ? AND p.hidden = ?
         ORDER BY i.sequence', array((int) $id, FRONTEND_LANGUAGE, 'N', FrontendModel::getUTCDate('Y-m-d H:i') . ':00', 'N'));
 }