예제 #1
0
 /**
  * Execute the action
  *
  * @return	void
  */
 public function execute()
 {
     // call parent, this will probably add some general CSS/JS or other required files
     parent::execute();
     // user is god?
     $isGod = BackendAuthentication::getUser()->isGod();
     // get possible languages
     if ($isGod) {
         $possibleLanguages = array_unique(array_merge(BL::getWorkingLanguages(), BL::getInterfaceLanguages()));
     } else {
         $possibleLanguages = BL::getWorkingLanguages();
     }
     // get parameters
     $language = SpoonFilter::getPostValue('language', array_keys($possibleLanguages), null, 'string');
     $module = SpoonFilter::getPostValue('module', BackendModel::getModules(false), null, 'string');
     $name = SpoonFilter::getPostValue('name', null, null, 'string');
     $type = SpoonFilter::getPostValue('type', BackendModel::getDB()->getEnumValues('locale', 'type'), null, 'string');
     $application = SpoonFilter::getPostValue('application', array('backend', 'frontend'), null, 'string');
     $value = SpoonFilter::getPostValue('value', null, null, 'string');
     // validate values
     if (trim($value) == '' || $language == '' || $module == '' || $type == '' || $application == '' || $application == 'frontend' && $module != 'core') {
         $error = BL::err('InvalidValue');
     }
     // in case this is a 'act' type, there are special rules concerning possible values
     if ($type == 'act' && !isset($error)) {
         if (!SpoonFilter::isValidAgainstRegexp('|^([a-z0-9\\-\\_])+$|', $value)) {
             $error = BL::err('InvalidActionValue', $this->getModule());
         }
     }
     // no error?
     if (!isset($error)) {
         // build item
         $item['language'] = $language;
         $item['module'] = $module;
         $item['name'] = $name;
         $item['type'] = $type;
         $item['application'] = $application;
         $item['value'] = $value;
         $item['edited_on'] = BackendModel::getUTCDate();
         $item['user_id'] = BackendAuthentication::getUser()->getUserId();
         // does the translation exist?
         if (BackendLocaleModel::existsByName($name, $type, $module, $language, $application)) {
             // add the id to the item
             $item['id'] = (int) BackendLocaleModel::getByName($name, $type, $module, $language, $application);
             // update in db
             BackendLocaleModel::update($item);
         } else {
             // insert in db
             BackendLocaleModel::insert($item);
         }
         // output OK
         $this->output(self::OK);
     } else {
         $this->output(self::ERROR, null, $error);
     }
 }
예제 #2
0
    /**
     * Get the comments
     *
     * @param string[optional] $status The type of comments to get. Possible values are: published, moderation, spam.
     * @param int[optional] $limit The maximum number of items to retrieve.
     * @param int[optional] $offset The offset.
     * @return array
     */
    public static function commentsGet($status = null, $limit = 30, $offset = 0)
    {
        // authorize
        if (API::authorize() && API::isValidRequestMethod('GET')) {
            // redefine
            if ($status !== null) {
                $status = (string) $status;
            }
            $limit = (int) $limit;
            $offset = (int) $offset;
            // validate
            if ($limit > 10000) {
                API::output(API::ERROR, array('message' => 'Limit can\'t be larger than 10000.'));
            }
            // get comments
            $comments = (array) BackendModel::getDB()->getRecords('SELECT i.id, UNIX_TIMESTAMP(i.created_on) AS created_on, i.author, i.email, i.website, i.text, i.type, i.status,
				 p.id AS post_id, p.title AS post_title, m.url AS post_url, p.language AS post_language
				 FROM blog_comments AS i
				 INNER JOIN blog_posts AS p ON i.post_id = p.id AND i.language = p.language
				 INNER JOIN meta AS m ON p.meta_id = m.id
				 WHERE p.status = ?
				 GROUP BY i.id
				 LIMIT ?, ?', array('active', $offset, $limit));
            $return = array('comments' => null);
            // build return array
            foreach ($comments as $row) {
                // create array
                $item['comment'] = array();
                // article meta data
                $item['comment']['article']['@attributes']['id'] = $row['post_id'];
                $item['comment']['article']['@attributes']['lang'] = $row['post_language'];
                $item['comment']['article']['title'] = $row['post_title'];
                $item['comment']['article']['url'] = SITE_URL . BackendModel::getURLForBlock('blog', 'detail', $row['post_language']) . '/' . $row['post_url'];
                // set attributes
                $item['comment']['@attributes']['id'] = $row['id'];
                $item['comment']['@attributes']['created_on'] = date('c', $row['created_on']);
                $item['comment']['@attributes']['status'] = $row['status'];
                // set content
                $item['comment']['text'] = $row['text'];
                $item['comment']['url'] = $item['comment']['article']['url'] . '#comment-' . $row['id'];
                // author data
                $item['comment']['author']['@attributes']['email'] = $row['email'];
                $item['comment']['author']['name'] = $row['author'];
                $item['comment']['author']['website'] = $row['website'];
                // add
                $return['comments'][] = $item;
            }
            return $return;
        }
    }
예제 #3
0
 /**
  * Validate the form
  */
 private function validateForm()
 {
     // is the form submitted?
     if ($this->frm->isSubmitted()) {
         // cleanup the submitted fields, ignore fields that were added by hackers
         $this->frm->cleanupFields();
         // no errors?
         if ($this->frm->isCorrect()) {
             // the total amount of subscribers
             $subscribersTotal = 0;
             // loop all groups
             foreach ($this->externalGroups as $group) {
                 // insert them in our database
                 $groupID = BackendModel::getDB(true)->insert('mailmotor_groups', array('name' => $group['name'], 'custom_fields' => $group['custom_fields'], 'created_on' => BackendModel::getUTCDate()));
                 // insert the CM ID
                 BackendMailmotorCMHelper::insertCampaignMonitorID('list', $group['id'], $groupID);
                 // continue looping if this group has no subscribers
                 if (empty($group['subscribers'])) {
                     continue;
                 }
                 // add this groups subscribers amount to the total
                 $subscribersTotal += $group['subscribers_amount'];
                 // loop the subscribers for this group, and import them
                 foreach ($group['subscribers'] as $subscriber) {
                     // build new subscriber record
                     $item = array();
                     $item['email'] = $subscriber['email'];
                     $item['source'] = 'import';
                     $item['created_on'] = $subscriber['date'];
                     // add an additional custom field 'name', if it was set in the subscriber record
                     if (!empty($subscriber['name'])) {
                         $subscriber['custom_fields']['Name'] = $subscriber['name'];
                     }
                     // save the subscriber in our database, and subscribe it to this group
                     BackendMailmotorModel::saveAddress($item, $groupID, !empty($subscriber['custom_fields']) ? $subscriber['custom_fields'] : null);
                 }
             }
             // at this point, groups are set
             BackendModel::setModuleSetting($this->getModule(), 'cm_groups_set', true);
             // trigger event
             BackendModel::triggerEvent($this->getModule(), 'after_import_groups');
             // redirect to the index
             $this->redirect(BackendModel::createURLForAction('index', $this->getModule()) . '&report=groups-imported&var[]=' . count($this->externalGroups) . '&var[]=' . $subscribersTotal);
         }
     }
 }
예제 #4
0
파일: model.php 프로젝트: richsage/forkcms
 /**
  * Update a tag
  * Remark: $tag['id'] should be available.
  *
  * @param array $item The new data for the tag.
  */
 public static function update($item)
 {
     return BackendModel::getDB(true)->update('tags', $item, 'id = ?', $item['id']);
 }
예제 #5
0
 /**
  * Update a question item
  *
  * @return	int
  * @param	array $item		The updated item.
  */
 public static function updateQuestion(array $item)
 {
     return BackendModel::getDB(true)->update('faq_questions', $item, 'id = ?', array((int) $item['id']));
 }
예제 #6
0
    /**
     * Updates one or more comments' status
     *
     * @return	void
     * @param	array $ids			The id(s) of the comment(s) to change the status for.
     * @param	string $status		The new status.
     */
    public static function updateCommentStatuses($ids, $status)
    {
        // make sure $ids is an array
        $ids = (array) $ids;
        // loop and cast to integers
        foreach ($ids as &$id) {
            $id = (int) $id;
        }
        // create an array with an equal amount of questionmarks as ids provided
        $idPlaceHolders = array_fill(0, count($ids), '?');
        // get ids
        $itemIds = (array) BackendModel::getDB()->getColumn('SELECT i.post_id
																FROM blog_comments AS i
																WHERE i.id IN (' . implode(', ', $idPlaceHolders) . ')', $ids);
        // update record
        BackendModel::getDB(true)->execute('UPDATE blog_comments
											SET status = ?
											WHERE id IN (' . implode(', ', $idPlaceHolders) . ')', array_merge(array((string) $status), $ids));
        // recalculate the comment count
        if (!empty($itemIds)) {
            self::reCalculateCommentCount($itemIds);
        }
        // invalidate the cache for blog
        BackendModel::invalidateFrontendCache('blog', BL::getWorkingLanguage());
    }
예제 #7
0
 /**
  * Update a locale item.
  *
  * @return	void
  * @param	array $item		The new data.
  */
 public static function update(array $item)
 {
     // update category
     $updated = BackendModel::getDB(true)->update('locale', $item, 'id = ?', array($item['id']));
     // rebuild the cache
     self::buildCache($item['language'], $item['application']);
     // return
     return $updated;
 }
예제 #8
0
    /**
     * Execute the action
     *
     * @return	void
     */
    public function execute()
    {
        // call parent, this will probably add some general CSS/JS or other required files
        parent::execute();
        // get parameters
        $from = $this->getParameter('from');
        $to = $this->getParameter('to');
        // validate
        if ($from == '') {
            throw new BackendException('Specify a from-parameter.');
        }
        if ($to == '') {
            throw new BackendException('Specify a to-parameter.');
        }
        // get db
        $db = BackendModel::getDB(true);
        // get all old pages
        $ids = $db->getColumn('SELECT id
								FROM pages AS i
								WHERE i.language = ? AND i.status = ?', array($to, 'active'));
        // any old pages
        if (!empty($ids)) {
            // delete existing pages
            foreach ($ids as $id) {
                // redefine
                $id = (int) $id;
                // get revision ids
                $revisionIDs = (array) $db->getColumn('SELECT i.revision_id
														FROM pages AS i
														WHERE i.id = ? AND i.language = ?', array($id, $to));
                // get meta ids
                $metaIDs = (array) $db->getColumn('SELECT i.meta_id
													FROM pages AS i
													WHERE i.id = ? AND i.language = ?', array($id, $to));
                // delete meta records
                if (!empty($metaIDs)) {
                    $db->delete('meta', 'id IN (' . implode(',', $metaIDs) . ')');
                }
                // delete blocks and their revisions
                if (!empty($revisionIDs)) {
                    $db->delete('pages_blocks', 'revision_id IN (' . implode(',', $revisionIDs) . ')');
                }
                // delete page and the revisions
                if (!empty($revisionIDs)) {
                    $db->delete('pages', 'revision_id IN (' . implode(',', $revisionIDs) . ')');
                }
            }
        }
        // delete search indexes
        $db->delete('search_index', 'module = ? AND language = ?', array('pages', $to));
        // get all active pages
        $ids = BackendModel::getDB()->getColumn('SELECT id
													FROM pages AS i
													WHERE i.language = ? AND i.status = ?', array($from, 'active'));
        // loop
        foreach ($ids as $id) {
            // get data
            $sourceData = BackendPagesModel::get($id, $from);
            // get and build meta
            $meta = $db->getRecord('SELECT *
									FROM meta
									WHERE id = ?', $sourceData['meta_id']);
            // remove id
            unset($meta['id']);
            // build page record
            $page = array();
            $page['id'] = $sourceData['id'];
            $page['user_id'] = BackendAuthentication::getUser()->getUserId();
            $page['parent_id'] = $sourceData['parent_id'];
            $page['template_id'] = $sourceData['template_id'];
            $page['meta_id'] = (int) $db->insert('meta', $meta);
            $page['language'] = $to;
            $page['type'] = $sourceData['type'];
            $page['title'] = $sourceData['title'];
            $page['navigation_title'] = $sourceData['navigation_title'];
            $page['navigation_title_overwrite'] = $sourceData['navigation_title_overwrite'];
            $page['hidden'] = $sourceData['hidden'];
            $page['status'] = 'active';
            $page['publish_on'] = BackendModel::getUTCDate();
            $page['created_on'] = BackendModel::getUTCDate();
            $page['edited_on'] = BackendModel::getUTCDate();
            $page['allow_move'] = $sourceData['allow_move'];
            $page['allow_children'] = $sourceData['allow_children'];
            $page['allow_edit'] = $sourceData['allow_edit'];
            $page['allow_delete'] = $sourceData['allow_delete'];
            $page['sequence'] = $sourceData['sequence'];
            $page['data'] = $sourceData['data'] !== null ? serialize($sourceData['data']) : null;
            // insert page, store the id, we need it when building the blocks
            $revisionId = BackendPagesModel::insert($page);
            // init var
            $blocks = array();
            $hasBlock = $sourceData['has_extra'] == 'Y';
            // get the blocks
            $sourceBlocks = BackendPagesModel::getBlocks($id, $from);
            // loop blocks
            foreach ($sourceBlocks as $sourceBlock) {
                // build block
                $block = array();
                $block['id'] = $sourceBlock['id'];
                $block['revision_id'] = $revisionId;
                $block['extra_id'] = $sourceBlock['extra_id'];
                $block['html'] = $sourceBlock['html'];
                $block['status'] = 'active';
                $block['created_on'] = BackendModel::getUTCDate();
                $block['edited_on'] = BackendModel::getUTCDate();
                // add block
                $blocks[] = $block;
            }
            // insert the blocks
            BackendPagesModel::insertBlocks($blocks, $hasBlock);
            // check if the method exists
            if (method_exists('BackendSearchModel', 'addIndex')) {
                // init var
                $text = '';
                // build search-text
                foreach ($blocks as $block) {
                    $text .= ' ' . $block['html'];
                }
                // add
                BackendSearchModel::addIndex('pages', (int) $page['id'], array('title' => $page['title'], 'text' => $text), $to);
            }
            // get tags
            $tags = BackendTagsModel::getTags('pages', $id, 'string', $from);
            // save tags
            if ($tags != '') {
                BackendTagsModel::saveTags($page['id'], $tags, 'pages');
            }
        }
        // build cache
        BackendPagesModel::buildCache($to);
    }
예제 #9
0
 /**
  * Update a certain category
  *
  * @param array $item
  */
 public static function updateCategory(array $item)
 {
     BackendModel::getDB(true)->update('faq_categories', $item, 'id = ?', array($item['id']));
     BackendModel::invalidateFrontendCache('faq', BL::getWorkingLanguage());
 }
예제 #10
0
 /**
  * Get the referrers for certain dates
  *
  * @return	array
  */
 public static function getRecentReferrers()
 {
     // set metrics and dimensions
     $gaMetrics = 'ga:entrances';
     $gaDimensions = array('ga:source', 'ga:referralPath');
     // set parameters
     $parameters = array();
     $parameters['max-results'] = 10;
     $parameters['filters'] = 'ga:medium==referral';
     $parameters['sort'] = '-ga:entrances';
     // get results
     $results = self::getGoogleAnalyticsInstance()->getAnalyticsResults($gaMetrics, mktime(0, 0, 0), mktime(23, 59, 59), $gaDimensions, $parameters);
     // no results - try the same query but for yesterday
     if (empty($results)) {
         $results = self::getGoogleAnalyticsInstance()->getAnalyticsResults($gaMetrics, strtotime('-1day', mktime(0, 0, 0)), strtotime('-1day', mktime(23, 59, 59)), $gaDimensions, $parameters);
     }
     // init vars
     $insertArray = array();
     // loop referrers
     foreach ($results['entries'] as $entry) {
         // build insert record
         $insertRecord = array();
         $insertRecord['referrer'] = $entry['source'] . $entry['referralPath'];
         $insertRecord['entrances'] = $entry['entrances'];
         $insertRecord['date'] = $results['startDate'] . ' 00:00:00';
         // add record to insert array
         $insertArray[] = $insertRecord;
     }
     // there are some records to be inserted
     if (!empty($insertArray)) {
         // get DB
         $db = BackendModel::getDB(true);
         // remove old data and insert array into database
         $db->truncate('analytics_referrers');
         $db->insert('analytics_referrers', $insertArray);
     }
 }
예제 #11
0
    /**
     * Updates one or more comments' status
     *
     * @param array $ids The id(s) of the comment(s) to change the status for.
     * @param string $status The new status.
     */
    public static function updateCommentStatuses($ids, $status)
    {
        // make sure $ids is an array
        $ids = (array) $ids;
        // loop and cast to integers
        foreach ($ids as &$id) {
            $id = (int) $id;
        }
        // create an array with an equal amount of questionmarks as ids provided
        $idPlaceHolders = array_fill(0, count($ids), '?');
        // get the items and their languages
        $items = (array) BackendModel::getDB()->getPairs('SELECT i.post_id, i.language
			 FROM blog_comments AS i
			 WHERE i.id IN (' . implode(', ', $idPlaceHolders) . ')', $ids, 'post_id');
        // only proceed if there are items
        if (!empty($items)) {
            // get the ids
            $itemIds = array_keys($items);
            // get the unique languages
            $languages = array_unique(array_values($items));
            // update records
            BackendModel::getDB(true)->execute('UPDATE blog_comments
				 SET status = ?
				 WHERE id IN (' . implode(', ', $idPlaceHolders) . ')', array_merge(array((string) $status), $ids));
            // recalculate the comment count
            self::reCalculateCommentCount($itemIds);
            // invalidate the cache for blog
            foreach ($languages as $language) {
                BackendModel::invalidateFrontendCache('blog', $language);
            }
        }
    }
예제 #12
0
 /**
  * Update a template
  *
  * @param array $item The new data for the template.
  */
 public static function updateTemplate(array $item)
 {
     BackendModel::getDB(true)->update('themes_templates', $item, 'id = ?', array((int) $item['id']));
 }
예제 #13
0
 /**
  * Update a membership of a profile in a group.
  *
  * @return	int
  * @param 	int $id			Membership id.
  * @param 	array $values	Membership data.
  */
 public static function updateProfileGroup($id, array $values)
 {
     return (int) BackendModel::getDB(true)->update('profiles_groups_rights', $values, 'id = ?', (int) $id);
 }
    /**
     * Execute the action
     *
     * @return	void
     */
    public function execute()
    {
        // no timelimit
        set_time_limit(0);
        // get database
        $db = BackendModel::getDB(true);
        // create log
        $log = new SpoonLog('custom', BACKEND_CACHE_PATH . '/logs/events');
        // get process-id
        $pid = getmypid();
        // store PID
        SpoonFile::setContent(BACKEND_CACHE_PATH . '/hooks/pid', $pid);
        // loop forever
        while (true) {
            // get 1 item
            $item = $db->getRecord('SELECT *
									FROM hooks_queue
									WHERE status = ?
									LIMIT 1', array('queued'));
            // any item?
            if (!empty($item)) {
                // init var
                $processedSuccesfully = true;
                // set item as busy
                $db->update('hooks_queue', array('status' => 'busy'), 'id = ?', array($item['id']));
                // unserialize data
                $item['callback'] = unserialize($item['callback']);
                $item['data'] = unserialize($item['data']);
                // check if the item is callable
                if (!is_callable($item['callback'])) {
                    // in debug mode we want to know if there are errors
                    if (SPOON_DEBUG) {
                        throw new BackendException('Invalid callback.');
                    }
                    // set to error state
                    $db->update('hooks_queue', array('status' => 'error'), 'id = ?', $item['id']);
                    // reset state
                    $processedSuccesfully = false;
                    // logging when we are in debugmode
                    if (SPOON_DEBUG) {
                        $log->write('Callback (' . serialize($item['callback']) . ') failed.');
                    }
                }
                try {
                    // logging when we are in debugmode
                    if (SPOON_DEBUG) {
                        $log->write('Callback (' . serialize($item['callback']) . ') called.');
                    }
                    // call the callback
                    $return = call_user_func($item['callback'], $item['data']);
                    // failed?
                    if ($return === false) {
                        // set to error state
                        $db->update('hooks_queue', array('status' => 'error'), 'id = ?', $item['id']);
                        // reset state
                        $processedSuccesfully = false;
                        // logging when we are in debugmode
                        if (SPOON_DEBUG) {
                            $log->write('Callback (' . serialize($item['callback']) . ') failed.');
                        }
                    }
                } catch (Exception $e) {
                    // set to error state
                    $db->update('hooks_queue', array('status' => 'error'), 'id = ?', $item['id']);
                    // reset state
                    $processedSuccesfully = false;
                    // logging when we are in debugmode
                    if (SPOON_DEBUG) {
                        $log->write('Callback (' . serialize($item['callback']) . ') failed.');
                    }
                }
                // everything went fine so delete the item
                if ($processedSuccesfully) {
                    $db->delete('hooks_queue', 'id = ?', $item['id']);
                }
                // logging when we are in debugmode
                if (SPOON_DEBUG) {
                    $log->write('Callback (' . serialize($item['callback']) . ') finished.');
                }
            } else {
                // remove the file
                SpoonFile::delete(BACKEND_CACHE_PATH . '/hooks/pid');
                // stop the script
                exit;
            }
        }
    }
예제 #15
0
    /**
     * Send an email
     *
     * @param int $id The id of the mail to send.
     */
    public static function send($id)
    {
        $id = (int) $id;
        $db = BackendModel::getDB(true);
        // get record
        $emailRecord = (array) $db->getRecord('SELECT *
			 FROM emails AS e
			 WHERE e.id = ?', array($id));
        // mailer type
        $mailerType = BackendModel::getModuleSetting('core', 'mailer_type', 'mail');
        // create new SpoonEmail-instance
        $email = new SpoonEmail();
        $email->setTemplateCompileDirectory(BACKEND_CACHE_PATH . '/compiled_templates');
        // send via SMTP
        if ($mailerType == 'smtp') {
            // get settings
            $SMTPServer = BackendModel::getModuleSetting('core', 'smtp_server');
            $SMTPPort = BackendModel::getModuleSetting('core', 'smtp_port', 25);
            $SMTPUsername = BackendModel::getModuleSetting('core', 'smtp_username');
            $SMTPPassword = BackendModel::getModuleSetting('core', 'smtp_password');
            // set server and connect with SMTP
            $email->setSMTPConnection($SMTPServer, $SMTPPort, 10);
            // set authentication if needed
            if ($SMTPUsername !== null && $SMTPPassword !== null) {
                $email->setSMTPAuth($SMTPUsername, $SMTPPassword);
            }
        }
        // set some properties
        $email->setFrom($emailRecord['from_email'], $emailRecord['from_name']);
        $email->addRecipient($emailRecord['to_email'], $emailRecord['to_name']);
        $email->setReplyTo($emailRecord['reply_to_email']);
        $email->setSubject($emailRecord['subject']);
        $email->setHTMLContent($emailRecord['html']);
        $email->setCharset(SPOON_CHARSET);
        $email->setContentTransferEncoding('base64');
        if ($emailRecord['plain_text'] != '') {
            $email->setPlainContent($emailRecord['plain_text']);
        }
        // attachments added
        if (isset($emailRecord['attachments']) && $emailRecord['attachments'] !== null) {
            // unserialize
            $attachments = (array) unserialize($emailRecord['attachments']);
            // add attachments to email
            foreach ($attachments as $attachment) {
                $email->addAttachment($attachment);
            }
        }
        // send the email
        if ($email->send()) {
            // remove the email
            $db->delete('emails', 'id = ?', array($id));
            // trigger event
            BackendModel::triggerEvent('core', 'after_email_sent', array('id' => $id));
        }
    }
예제 #16
0
 /**
  * @param string $query The query to retrieve the data.
  * @param array[optional] $parameters The parameters to be used inside the query.
  * @param string[optional] $resultsQuery The optional count query, used to calculate the number of results.
  * @param array[optional] $resultsParameters  Theh parameters to be used inside the results query.
  */
 public function __construct($query, $parameters = array(), $resultsQuery = null, $resultsParameters = array())
 {
     // results query?
     $results = $resultsQuery !== null ? array($resultsQuery, $resultsParameters) : null;
     // create a new source-object
     $source = new SpoonDataGridSourceDB(BackendModel::getDB(), array($query, (array) $parameters), $results);
     parent::__construct($source);
 }
예제 #17
0
    /**
     * Parse the authentication settings for the authenticated user
     */
    private function parseAuthentication()
    {
        // init var
        $db = BackendModel::getDB();
        // get allowed actions
        $allowedActions = (array) $db->getRecords('SELECT gra.module, gra.action, MAX(gra.level) AS level
			 FROM users_sessions AS us
			 INNER JOIN users AS u ON us.user_id = u.id
			 INNER JOIN users_groups AS ug ON u.id = ug.user_id
			 INNER JOIN groups_rights_actions AS gra ON ug.group_id = gra.group_id
			 WHERE us.session_id = ? AND us.secret_key = ?
			 GROUP BY gra.module, gra.action', array(SpoonSession::getSessionId(), SpoonSession::get('backend_secret_key')));
        // loop actions and assign to template
        foreach ($allowedActions as $action) {
            if ($action['level'] == '7') {
                $this->assign('show' . SpoonFilter::toCamelCase($action['module'], '_') . SpoonFilter::toCamelCase($action['action'], '_'), true);
            }
        }
    }
예제 #18
0
 /**
  * Saves the meta object
  *
  * @param bool[optional] $update Should we update the record or insert a new one.
  * @return int
  */
 public function save($update = false)
 {
     $update = (bool) $update;
     // get meta keywords
     if ($this->frm->getField('meta_keywords_overwrite')->isChecked()) {
         $keywords = $this->frm->getField('meta_keywords')->getValue();
     } else {
         $keywords = $this->frm->getField($this->baseFieldName)->getValue();
     }
     // get meta description
     if ($this->frm->getField('meta_description_overwrite')->isChecked()) {
         $description = $this->frm->getField('meta_description')->getValue();
     } else {
         $description = $this->frm->getField($this->baseFieldName)->getValue();
     }
     // get page title
     if ($this->frm->getField('page_title_overwrite')->isChecked()) {
         $title = $this->frm->getField('page_title')->getValue();
     } else {
         $title = $this->frm->getField($this->baseFieldName)->getValue();
     }
     // get URL
     if ($this->frm->getField('url_overwrite')->isChecked()) {
         $URL = SpoonFilter::htmlspecialcharsDecode($this->frm->getField('url')->getValue());
     } else {
         $URL = SpoonFilter::htmlspecialcharsDecode($this->frm->getField($this->baseFieldName)->getValue());
     }
     // get the real URL
     $URL = $this->generateURL($URL);
     // get meta custom
     if ($this->custom && $this->frm->getField('meta_custom')->isFilled()) {
         $custom = $this->frm->getField('meta_custom')->getValue(true);
     } else {
         $custom = null;
     }
     // build meta
     $meta['keywords'] = $keywords;
     $meta['keywords_overwrite'] = $this->frm->getField('meta_keywords_overwrite')->isChecked() ? 'Y' : 'N';
     $meta['description'] = $description;
     $meta['description_overwrite'] = $this->frm->getField('meta_description_overwrite')->isChecked() ? 'Y' : 'N';
     $meta['title'] = $title;
     $meta['title_overwrite'] = $this->frm->getField('page_title_overwrite')->isChecked() ? 'Y' : 'N';
     $meta['url'] = $URL;
     $meta['url_overwrite'] = $this->frm->getField('url_overwrite')->isChecked() ? 'Y' : 'N';
     $meta['custom'] = $custom;
     $meta['data'] = null;
     if ($this->frm->getField('seo_index')->getValue() != 'none') {
         $meta['data']['seo_index'] = $this->frm->getField('seo_index')->getValue();
     }
     if ($this->frm->getField('seo_follow')->getValue() != 'none') {
         $meta['data']['seo_follow'] = $this->frm->getField('seo_follow')->getValue();
     }
     if (isset($meta['data'])) {
         $meta['data'] = serialize($meta['data']);
     }
     // get db
     $db = BackendModel::getDB(true);
     // should we update the record
     if ($update) {
         // validate
         if ($this->id === null) {
             throw new BackendException('No metaID specified.');
         }
         // update the existing record
         $db->update('meta', $meta, 'id = ?', array($this->id));
         // return the id
         return $this->id;
     } else {
         // insert
         $id = (int) $db->insert('meta', $meta);
         // return the id
         return $id;
     }
 }
예제 #19
0
 /**
  * Update an item
  *
  * @return	int
  * @param	array $item					The data of the record to update.
  */
 public static function update($item)
 {
     // get db
     $db = BackendModel::getDB(true);
     // build extra
     $extra = array('id' => $item['extra_id'], 'module' => 'location', 'type' => 'widget', 'label' => 'Location', 'action' => 'location', 'data' => serialize(array('id' => $item['id'], 'extra_label' => ucfirst(BL::lbl('Location', 'core')) . ': ' . $item['title'], 'language' => $item['language'], 'edit_url' => BackendModel::createURLForAction('edit') . '&id=' . $item['id'])), 'hidden' => 'N');
     // update extra
     $db->update('pages_extras', $extra, 'id = ? AND module = ? AND type = ? AND action = ?', array($extra['id'], $extra['module'], $extra['type'], $extra['action']));
     // update item
     return $db->update('location', $item, 'id = ? AND language = ?', array($item['id'], $item['language']));
 }
예제 #20
0
 /**
  * Update a locale item.
  *
  * @param array $item The new data.
  */
 public static function update(array $item)
 {
     // actions should be urlized
     if ($item['type'] == 'act' && urldecode($item['value']) != $item['value']) {
         $item['value'] = SpoonFilter::urlise($item['value']);
     }
     // update category
     $updated = BackendModel::getDB(true)->update('locale', $item, 'id = ?', array($item['id']));
     // rebuild the cache
     self::buildCache($item['language'], $item['application']);
     return $updated;
 }
예제 #21
0
 /**
  * Fetch data for this form from the database and reformat to csv rows.
  */
 private function setItems()
 {
     // init header labels
     $lblSessionId = SpoonFilter::ucfirst(BL::lbl('SessionId'));
     $lblSentOn = SpoonFilter::ucfirst(BL::lbl('SentOn'));
     $this->columnHeaders = array($lblSessionId, $lblSentOn);
     // fetch query and parameters
     list($query, $parameters) = $this->buildQuery();
     // get the data
     $records = (array) BackendModel::getDB()->getRecords($query, $parameters);
     $data = array();
     // reformat data
     foreach ($records as $row) {
         // first row of a submission
         if (!isset($data[$row['data_id']])) {
             $data[$row['data_id']][$lblSessionId] = $row['session_id'];
             $data[$row['data_id']][$lblSentOn] = SpoonDate::getDate('Y-m-d H:i:s', $row['sent_on'], BackendLanguage::getWorkingLanguage());
         }
         // value is serialized
         $value = unserialize($row['value']);
         // flatten arrays
         if (is_array($value)) {
             $value = implode(', ', $value);
         }
         // group submissions
         $data[$row['data_id']][$row['label']] = SpoonFilter::htmlentitiesDecode($value, null, ENT_QUOTES);
         // add into headers if not yet added
         if (!in_array($row['label'], $this->columnHeaders)) {
             $this->columnHeaders[] = $row['label'];
         }
     }
     // reorder data so they are in the correct column
     foreach ($data as $id => $row) {
         foreach ($this->columnHeaders as $header) {
             // submission has this field so add it
             if (isset($row[$header])) {
                 $this->rows[$id][] = $row[$header];
             } else {
                 $this->rows[$id][] = '';
             }
         }
     }
     // remove the keys
     $this->rows = array_values($this->rows);
 }
예제 #22
0
    /**
     * Set a setting
     *
     * @return	void
     * @param	string $key		The key of the setting.
     * @param	mixed $value	The value to store.
     */
    public function setSetting($key, $value)
    {
        // redefine
        $key = (string) $key;
        $valueToStore = serialize($value);
        // get db
        $db = BackendModel::getDB(true);
        // store
        $db->execute('INSERT INTO users_settings(user_id, name, value)
						VALUES(?, ?, ?)
						ON DUPLICATE KEY UPDATE value = ?', array($this->getUserId(), $key, $valueToStore, $valueToStore));
        // cache it
        $this->settings[(string) $key] = $value;
    }
예제 #23
0
 /**
  * Build items array and group all items by application, module, type and name.
  *
  * @return	void
  */
 private function setItems()
 {
     // build our query
     list($query, $parameters) = $this->buildQuery();
     // get locale from the database
     $items = (array) BackendModel::getDB()->getRecords($query, $parameters);
     // init
     $this->locale = array();
     // group by application, module, type and name
     foreach ($items as $item) {
         $this->locale[$item['application']][$item['module']][$item['type']][$item['name']][] = $item;
     }
     // no need to keep this around
     unset($items);
 }
예제 #24
0
 /**
  * Update a field.
  *
  * @return	int
  * @param	int $id				The id for the item to update.
  * @param	array $values		The new data.
  */
 public static function updateField($id, array $values)
 {
     // update item
     BackendModel::getDB(true)->update('forms_fields', $values, 'id = ?', (int) $id);
     // return id
     return $id;
 }
예제 #25
0
 /**
  * Updates the date viewed for a certain page.
  *
  * @return	void
  * @param	int $pageId		The id of the page to update.
  */
 public static function updatePageDateViewed($pageId)
 {
     // update the page
     BackendModel::getDB(true)->update('analytics_pages', array('date_viewed' => SpoonDate::getDate('Y-m-d H:i:s')), 'id = ?', array((int) $pageId));
 }
예제 #26
0
    /**
     * Switch templates for all existing pages
     *
     * @param int $oldTemplateId The id of the new template to replace.
     * @param int $newTemplateId The id of the new template to use.
     * @param bool[optional] $overwrite Overwrite all pages with default blocks.
     */
    public static function updatePagesTemplates($oldTemplateId, $newTemplateId, $overwrite = false)
    {
        $newTemplateId = (int) $newTemplateId;
        $oldTemplateId = (int) $oldTemplateId;
        $overwrite = (bool) $overwrite;
        // fetch new template data
        $newTemplate = BackendExtensionsModel::getTemplate($newTemplateId);
        $newTemplate['data'] = @unserialize($newTemplate['data']);
        // fetch all pages
        $pages = (array) BackendModel::getDB()->getRecords('SELECT *
			 FROM pages
			 WHERE template_id = ? AND status IN (?, ?)', array($oldTemplateId, 'active', 'draft'));
        // there is no active/draft page with the old template id
        if (empty($pages)) {
            return;
        }
        // loop pages
        foreach ($pages as $page) {
            // fetch blocks
            $blocksContent = BackendPagesModel::getBlocks($page['id'], $page['revision_id'], $page['language']);
            // unset revision id
            unset($page['revision_id']);
            // change template
            $page['template_id'] = $newTemplateId;
            // save new page revision
            $page['revision_id'] = BackendPagesModel::update($page);
            // overwrite all blocks with current defaults
            if ($overwrite) {
                // init var
                $blocksContent = array();
                // fetch default blocks for this page
                $defaultBlocks = array();
                if (isset($newTemplate['data']['default_extras_' . $page['language']])) {
                    $defaultBlocks = $newTemplate['data']['default_extras_' . $page['language']];
                } elseif (isset($newTemplate['data']['default_extras'])) {
                    $defaultBlocks = $newTemplate['data']['default_extras'];
                }
                // loop positions
                foreach ($defaultBlocks as $position => $blocks) {
                    // loop blocks
                    foreach ($blocks as $extraId) {
                        // build block
                        $block = array();
                        $block['revision_id'] = $page['revision_id'];
                        $block['position'] = $position;
                        $block['extra_id'] = $extraId;
                        $block['html'] = '';
                        $block['created_on'] = BackendModel::getUTCDate();
                        $block['edited_on'] = $block['created_on'];
                        $block['visible'] = 'Y';
                        $block['sequence'] = count($defaultBlocks[$position]) - 1;
                        // add to the list
                        $blocksContent[] = $block;
                    }
                }
            } else {
                // set new page revision id
                foreach ($blocksContent as &$block) {
                    $block['revision_id'] = $page['revision_id'];
                }
            }
            // insert the blocks
            BackendPagesModel::insertBlocks($blocksContent);
        }
    }
예제 #27
0
 /**
  * Logsout the current user
  *
  * @return	void
  */
 public static function logout()
 {
     // remove all rows owned by the current user
     BackendModel::getDB(true)->delete('users_sessions', 'session_id = ?', SpoonSession::getSessionId());
     // reset values. We can't destroy the session because session-data can be used on the site.
     SpoonSession::set('backend_logged_in', false);
     SpoonSession::set('backend_secret_key', '');
 }
예제 #28
0
 /**
  * Process the XML and treat it as a blogpost
  *
  * @param SimpleXMLElement $xml The XML to process.
  * @return bool
  */
 private function processXMLAsPost(SimpleXMLElement $xml)
 {
     // init var
     $postID = substr((string) $xml->id, mb_strpos((string) $xml->id, 'post-') + 5);
     // validate
     if ($postID == '') {
         return false;
     }
     if ((string) $xml->title == '') {
         return false;
     }
     // build item
     $item['id'] = (int) BackendBlogModel::getMaximumId() + 1;
     $item['user_id'] = BackendAuthentication::getUser()->getUserId();
     $item['hidden'] = 'N';
     $item['allow_comments'] = 'Y';
     $item['num_comments'] = 0;
     $item['status'] = 'active';
     $item['language'] = BL::getWorkingLanguage();
     $item['publish_on'] = BackendModel::getUTCDate(null, strtotime((string) $xml->published));
     $item['created_on'] = BackendModel::getUTCDate(null, strtotime((string) $xml->published));
     $item['edited_on'] = BackendModel::getUTCDate(null, strtotime((string) $xml->updated));
     $item['category_id'] = 1;
     $item['title'] = (string) $xml->title;
     $item['text'] = (string) $xml->content;
     // set drafts hidden
     if (strtotime((string) $xml->published) > time()) {
         $item['hidden'] = 'Y';
         $item['status'] = 'draft';
     }
     // build meta
     $meta = array();
     $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::getURL($item['title']);
     $meta['url_overwrite'] = 'N';
     // replace f****d up links
     $item['text'] = preg_replace('|<a(.*)onblur="(.*)"(.*)>|Ui', '<a$1$3>', $item['text']);
     // fix images
     $item['text'] = preg_replace('|<img(.*)border="(.*)"(.*)>|Ui', '<img$1$3>', $item['text']);
     // remove inline styles
     $item['text'] = preg_replace('|<(.*)style="(.*)"(.*)>|Ui', '<$1$3>', $item['text']);
     // whitespace
     $item['text'] = preg_replace('|\\s{2,}|', ' ', $item['text']);
     // cleanup
     $search = array('<br /><br />', '<div><br /></div>', '<div>', '</div>', '<i>', '</i>', '<b>', '</b>', '<p><object', '</object></p>', '<p><p>', '</p></p>', '...');
     $replace = array('</p><p>', '</p><p>', '', '', '<em>', '</em>', '<strong>', '</strong>', '<object', '</object>', '<p>', '</p>', '…');
     // cleanup
     $item['text'] = '<p>' . str_replace($search, $replace, SpoonFilter::htmlentitiesDecode($item['text'])) . '</p>';
     // get images
     $matches = array();
     preg_match_all('/<img.*src="(.*)".*\\/>/Ui', $item['text'], $matches);
     // any images?
     if (isset($matches[1]) && !empty($matches[1])) {
         // init var
         $imagesPath = FRONTEND_FILES_PATH . '/userfiles/images/blog';
         $imagesURL = FRONTEND_FILES_URL . '/userfiles/images/blog';
         // create dir if needed
         if (!SpoonDirectory::exists($imagesPath)) {
             SpoonDirectory::create($imagesPath);
         }
         // loop matches
         foreach ($matches[1] as $key => $file) {
             // get file info
             $fileInfo = SpoonFile::getInfo($file);
             // init var
             $destinationFile = $item['id'] . '_' . $fileInfo['basename'];
             try {
                 // download
                 SpoonFile::download($file, $imagesPath . '/' . $destinationFile);
                 // replace the old URL with the new one
                 $item['text'] = str_replace($file, $imagesURL . '/' . $destinationFile, $item['text']);
             } catch (Exception $e) {
                 // ignore
             }
         }
     }
     // get links
     $matches = array();
     preg_match_all('/<a.*href="(.*)".*\\/>/Ui', $item['text'], $matches);
     // any images?
     if (isset($matches[1]) && !empty($matches[1])) {
         // loop matches
         foreach ($matches[1] as $key => $file) {
             // get new link
             $replaceWith = self::download($file, $item['id']);
             // should we replace?
             if ($replaceWith !== false) {
                 // replace the old URL with the new one
                 $item['text'] = str_replace($file, $replaceWith, $item['text']);
             }
         }
     }
     // insert meta
     $item['meta_id'] = BackendModel::getDB(true)->insert('meta', $meta);
     // insert
     BackendBlogModel::insert($item);
     // store the post
     $this->newIds[$postID] = $item['id'];
     // get tags
     $tags = array();
     // loop categories
     foreach ($xml->category as $category) {
         // is this a tag? if so add it
         if ((string) $category['scheme'] == 'http://www.blogger.com/atom/ns#') {
             $tags[] = (string) $category['term'];
         }
     }
     // any tags?
     if (!empty($tags)) {
         BackendTagsModel::saveTags($item['id'], implode(',', $tags), $this->getModule());
     }
     // return
     return true;
 }
예제 #29
0
    /**
     * Update an existing item.
     *
     * @param array $item The new data.
     * @return int
     */
    public static function update(array $item)
    {
        $db = BackendModel::getDB(true);
        // build extra
        $extra = array('id' => $item['extra_id'], 'module' => 'content_blocks', 'type' => 'widget', 'label' => 'ContentBlocks', 'action' => 'detail', 'data' => serialize(array('id' => $item['id'], 'extra_label' => $item['title'], 'language' => $item['language'], 'edit_url' => BackendModel::createURLForAction('edit') . '&id=' . $item['id'])), 'hidden' => 'N');
        // update extra
        $db->update('modules_extras', $extra, 'id = ? AND module = ? AND type = ? AND action = ?', array($extra['id'], $extra['module'], $extra['type'], $extra['action']));
        // archive all older versions
        $db->update('content_blocks', array('status' => 'archived'), 'id = ? AND language = ?', array($item['id'], BL::getWorkingLanguage()));
        // insert new version
        $item['revision_id'] = $db->insert('content_blocks', $item);
        // how many revisions should we keep
        $rowsToKeep = (int) BackendModel::getModuleSetting('content_blocks', 'max_num_revisions', 20);
        // get revision-ids for items to keep
        $revisionIdsToKeep = (array) $db->getColumn('SELECT i.revision_id
			 FROM content_blocks AS i
			 WHERE i.id = ? AND i.language = ? AND i.status = ?
			 ORDER BY i.edited_on DESC
			 LIMIT ?', array($item['id'], BL::getWorkingLanguage(), 'archived', $rowsToKeep));
        // delete other revisions
        if (!empty($revisionIdsToKeep)) {
            $db->delete('content_blocks', 'id = ? AND language = ? AND status = ? AND revision_id NOT IN (' . implode(', ', $revisionIdsToKeep) . ')', array($item['id'], BL::getWorkingLanguage(), 'archived'));
        }
        // return the new revision_id
        return $item['revision_id'];
    }
예제 #30
0
 /**
  * Updates the queued mailings with 'sent' status if they were sent
  *
  * @return mixed
  */
 public static function updateQueuedMailings()
 {
     $db = BackendModel::getDB(true);
     // fetch all mailings that aren't sent
     $records = $db->getRecords(self::QRY_DATAGRID_BROWSE_SENT, array('queued'));
     // no records found, so stop here
     if (empty($records)) {
         return false;
     }
     // reserve update stack
     $updateIds = array();
     // loop the records
     foreach ($records as $record) {
         // if the sent date is smaller than the current date, update status to 'sent'
         if (date('Y-m-d H:i:s', $record['sent']) < date('Y-m-d H:i:s')) {
             $updateIds[] = $record['id'];
         }
     }
     // if don't need to update any record, stop here
     if (empty($updateIds)) {
         return false;
     }
     // update all mailings that are queued and were sent
     return (int) $db->update('mailmotor_mailings', array('status' => 'sent'), 'id IN (' . implode(',', $updateIds) . ')');
 }