protected function _prepareCustomField($fieldName, array $field) { $userFieldInfo = $this->_getCustomFieldInfo(); if (isset($userFieldInfo[$fieldName])) { $fieldInfo = $userFieldInfo[$fieldName]; if ($fieldInfo['field_type'] == 'checkbox' || $fieldInfo['field_type'] == 'multiselect') { $fieldChoices = XenForo_Helper_Php::safeUnserialize($fieldInfo['field_choices']); $field['old_value'] = $this->_prepareCustomFieldArrayValue($fieldChoices, XenForo_Helper_Php::safeUnserialize($field['old_value'])); $field['new_value'] = $this->_prepareCustomFieldArrayValue($fieldChoices, XenForo_Helper_Php::safeUnserialize($field['new_value'])); } else { if ($fieldInfo['field_type'] == 'radio' || $fieldInfo['field_type'] == 'select') { $fieldChoices = XenForo_Helper_Php::safeUnserialize($fieldInfo['field_choices']); if (empty($field['old_value'])) { $field['old_value'] = ''; } else { if (isset($fieldChoices[$field['old_value']])) { $field['old_value'] = $fieldChoices[$field['old_value']]; } } if (empty($field['new_value'])) { $field['new_value'] = ''; } else { if (isset($fieldChoices[$field['new_value']])) { $field['new_value'] = $fieldChoices[$field['new_value']]; } } } } $field['name'] = new XenForo_Phrase('user_field_' . $fieldName); } else { $field['name'] = $fieldName; } return $field; }
/** * Creates the 'answers_array' entry from the existing 'answers' * entry in the given QA CAPTCHA record * * @param array $captchaQuestion * * @return array */ protected function _prepareCaptchaQuestionAnswersArray(array $captchaQuestion) { $answersArray = XenForo_Helper_Php::safeUnserialize($captchaQuestion['answers']); if (empty($answersArray)) { $answersArray = array(''); } $captchaQuestion['answersArray'] = $answersArray; return $captchaQuestion; }
/** * Unserialize permissions from their format in the database to the array format * that the other helper functions expect. * * @param string $permissionString * * @return array */ public static function unserializePermissions($permissionString) { if ($permissionString && !is_array($permissionString)) { $permissions = XenForo_Helper_Php::safeUnserialize($permissionString); if (is_array($permissions)) { return $permissions; } } return array(); }
/** * Removes any empty answers, and ensures that at least one answer remains * * @param string Serialized $answers * * @return boolean */ protected function _verifyAnswers(&$answers) { $answers = XenForo_Helper_Php::safeUnserialize($answers); foreach ($answers as $i => &$answer) { $answer = trim($answer); if ($answer === '') { unset($answers[$i]); } } if (empty($answers)) { $this->error(new XenForo_Phrase('please_provide_at_least_one_answer'), 'answers'); return false; } $answers = XenForo_Helper_Php::safeSerialize(array_values($answers)); return true; }
public function execute(array $deferred, array $data, $targetRunTime, &$status) { $data = array_merge(array('reparseTemplateIds' => array(), 'recompileMapIds' => array(), 'position' => 0), $data); /* @var $templateModel XenForo_Model_Template */ $templateModel = XenForo_Model::create('XenForo_Model_Template'); $s = microtime(true); $outOfTime = false; $actionPhrase = new XenForo_Phrase('rebuilding'); $typePhrase = new XenForo_Phrase('templates'); $status = sprintf('%s... %s %s', $actionPhrase, $typePhrase, str_repeat(' . ', $data['position'])); if ($data['reparseTemplateIds']) { foreach ($data['reparseTemplateIds'] as $k => $templateId) { $templateModel->reparseTemplate($templateId, false); unset($data['reparseTemplateIds'][$k]); $runTime = microtime(true) - $s; if ($targetRunTime && $runTime > $targetRunTime) { $outOfTime = true; break; } } } if ($data['recompileMapIds'] && !$outOfTime) { foreach ($data['recompileMapIds'] as $k => $templateMapId) { $templateMap = $templateModel->getEffectiveTemplateByMapId($templateMapId); if (!$templateMap) { unset($data['recompileMapIds'][$k]); continue; } $parsedTemplate = XenForo_Helper_Php::safeUnserialize($templateMap['template_parsed']); $templateModel->compileAndInsertParsedTemplate($templateMap['template_map_id'], $parsedTemplate, $templateMap['title'], $templateMap['map_style_id']); unset($data['recompileMapIds'][$k]); $runTime = microtime(true) - $s; if ($targetRunTime && $runTime > $targetRunTime) { break; } } } if (!$data['reparseTemplateIds'] && !$data['recompileMapIds']) { XenForo_Model::create('XenForo_Model_Style')->updateAllStylesLastModifiedDate(); XenForo_Model::create('XenForo_Model_AdminTemplate')->updateAdminStyleLastModifiedDate(); return true; } else { $data['position']++; return $data; } }
/** * Gets the moderator add/edit controller response. This handles both super * and content moderators. * * @param array $moderator Info about the moderator; a content or super mod record * @param boolean $allowDelete If true, shows the necessary delete button * * @return XenForo_ControllerResponse_Abstract */ protected function _moderatorAddEditResponse(array $moderator, $allowDelete = true) { $moderatorModel = $this->_getModeratorModel(); $isContentModerator = !empty($moderator['content_type']); $isSuperModerator = !empty($moderator['is_super_moderator']); $existingPermissions = XenForo_Helper_Php::safeUnserialize($moderator['moderator_permissions']); if ($isContentModerator) { $generalModerator = $moderatorModel->getGeneralModeratorByUserId($moderator['user_id']); if ($generalModerator) { $moderator['extra_user_group_ids'] = $generalModerator['extra_user_group_ids']; $moderator['is_super_moderator'] = $generalModerator['is_super_moderator']; $moderator['exists'] = true; $existingPermissions = $moderatorModel->mergeGeneralModeratorPermissions($existingPermissions, XenForo_Helper_Php::safeUnserialize($generalModerator['moderator_permissions'])); } else { $moderator['extra_user_group_ids'] = ''; $moderator['is_super_moderator'] = 0; } } $generalInterfaceGroupIds = $moderatorModel->getGeneralModeratorInterfaceGroupIds(); $moderatorInterfaceGroupIds = $moderatorModel->getModeratorInterfaceGroupIds($moderator); $interfaceGroups = $moderatorModel->getModeratorPermissionsForInterface($moderatorInterfaceGroupIds, $existingPermissions); $generalInterfaceGroups = array(); foreach ($generalInterfaceGroupIds as $generalInterfaceGroupId) { $generalInterfaceGroups[$generalInterfaceGroupId] = $interfaceGroups[$generalInterfaceGroupId]; unset($interfaceGroups[$generalInterfaceGroupId]); } $userGroups = $moderatorModel->getExtraUserGroupOptions($moderator['extra_user_group_ids']); if ($isContentModerator) { $handler = $moderatorModel->getContentModeratorHandlers($moderator['content_type']); $contentTitle = $handler->getContentTitle($moderator['content_id']); } else { $contentTitle = ''; } $user = $this->_getUserModel()->getUserById($moderator['user_id']); if (empty($moderator['username'])) { $moderator['username'] = $user['username']; } $exists = isset($moderator['exists']) ? $moderator['exists'] : true; $isStaff = $exists ? $user['is_staff'] : true; $viewParams = array('user' => $user, 'moderator' => $moderator, 'contentTitle' => $contentTitle, 'allowDelete' => $allowDelete, 'isStaff' => $isStaff, 'interfaceGroups' => $interfaceGroups, 'generalInterfaceGroups' => $generalInterfaceGroups, 'userGroups' => $userGroups); return $this->responseView('XenForo_ViewAdmin_Moderator_Edit', 'moderator_edit', $viewParams); }
public function actionSpamTrigger() { /** @var XenForo_Model_SpamPrevention $spamPreventionModel */ $spamPreventionModel = $this->getModelFromCache('XenForo_Model_SpamPrevention'); $id = $this->_input->filterSingle('id', XenForo_Input::UINT); if ($id) { $entry = $spamPreventionModel->getSpamTriggerLogById($id); if (!$entry) { return $this->responseError(new XenForo_Phrase('requested_log_entry_not_found'), 404); } $entry['requestState'] = XenForo_Helper_Php::safeUnserialize($entry['request_state']); $viewParams = array('entry' => $spamPreventionModel->prepareSpamTriggerLog($entry)); return $this->responseView('XenForo_ViewAdmin_Log_SpamTriggerView', 'log_spam_trigger_view', $viewParams); } $page = $this->_input->filterSingle('page', XenForo_Input::UINT); $perPage = 20; $entries = $spamPreventionModel->getSpamTriggerLogs(array(), array('page' => $page, 'perPage' => $perPage)); $viewParams = array('entries' => $spamPreventionModel->prepareSpamTriggerLogs($entries), 'page' => $page, 'perPage' => $perPage, 'total' => $spamPreventionModel->countSpamTriggerLogs()); return $this->responseView('XenForo_ViewAdmin_Log_SpamTrigger', 'log_spam_trigger', $viewParams); }
/** * Sets the general permissions for a moderator. This does not manipulate * non-general permissions that are already set. * * @param array $generalPermissions New set of general permissions. Overwrites old permissions. */ public function setGeneralPermissions(array $generalPermissions) { $validGeneralPermissions = $this->_getModeratorModel()->getGeneralModeratorPermissions(); if ($this->isUpdate()) { $outputPermissions = XenForo_Helper_Php::safeUnserialize($this->getExisting('moderator_permissions')); foreach ($validGeneralPermissions as $generalGroupId => $generalGroup) { foreach ($generalGroup as $generalPermissionId => $general) { unset($outputPermissions[$generalGroupId][$generalPermissionId]); } } } else { $outputPermissions = array(); } foreach ($generalPermissions as $generalGroupId => $generalGroup) { foreach ($generalGroup as $generalPermissionId => $general) { if (isset($validGeneralPermissions[$generalGroupId][$generalPermissionId])) { $outputPermissions[$generalGroupId][$generalPermissionId] = $general; } } } $this->set('moderator_permissions', $outputPermissions); }
/** * Gets the admin permission cache for the specified user. * * @param integer $userId * * @return array */ public function getAdminPermissionCacheForUser($userId) { $cache = $this->_getDb()->fetchOne(' SELECT permission_cache FROM xf_admin WHERE user_id = ? ', $userId); if (!$cache) { return array(); } else { return XenForo_Helper_Php::safeUnserialize($cache); } }
/** * Gets the user field values for the given user. * * @param integer $userId * * @return array [field id] => value (may be string or array) */ public function getUserFieldValues($userId) { $fields = $this->_getDb()->fetchAll(' SELECT value.*, field.field_type FROM xf_user_field_value AS value INNER JOIN xf_user_field AS field ON (field.field_id = value.field_id) WHERE value.user_id = ? ', $userId); $values = array(); foreach ($fields as $field) { if ($field['field_type'] == 'checkbox' || $field['field_type'] == 'multiselect') { $values[$field['field_id']] = XenForo_Helper_Php::safeUnserialize($field['field_value']); } else { $values[$field['field_id']] = $field['field_value']; } } return $values; }
/** * Fetches a user's cached news feed * * @param integer $userId * * @return array */ public function getNewsFeedCache($userId) { $options = XenForo_Application::get('options'); if ($options->newsFeedCache) { $newsFeed = $this->_getDb()->fetchOne(' SELECT news_feed_cache FROM xf_user_news_feed_cache WHERE user_id = ? ', $userId); if ($newsFeed = XenForo_Helper_Php::safeUnserialize($newsFeed)) { if (sizeof($newsFeed) > $options->newsFeedMaxItems) { return array_slice($newsFeed, 0, $options->newsFeedMaxItems, true); } return $newsFeed; } } return array(); }
/** * Validates an option value for pre-save. * * @param mixed $optionValue Unvalidated option * * @return string Validated option. Options are serialized; all other types a strval'd */ protected function _validateOptionValuePreSave($optionValue) { switch ($this->get('data_type')) { case 'string': $optionValue = strval($optionValue); break; case 'integer': $optionValue = intval($optionValue); break; case 'numeric': $optionValue = strval($optionValue) + 0; break; case 'boolean': $optionValue = $optionValue ? 1 : 0; break; case 'array': if (!is_array($optionValue)) { $unserialized = XenForo_Helper_Php::safeUnserialize($optionValue); if (is_array($unserialized)) { $optionValue = $unserialized; } else { $optionValue = array(); } } break; case 'unsigned_integer': $optionValue = max(0, intval($optionValue)); break; case 'unsigned_numeric': $optionValue = max(0, strval($optionValue) + 0); break; case 'positive_integer': $optionValue = max(1, intval($optionValue)); break; } $validationClass = $this->get('validation_class'); $validationMethod = $this->get('validation_method'); if ($validationClass && $validationMethod && $this->_validateValidationClassAndMethod($validationClass, $validationMethod)) { $success = (bool) call_user_func_array(array($validationClass, $validationMethod), array(&$optionValue, $this, $this->get('option_id'))); if (!$success) { return false; } } if (is_array($optionValue)) { if ($this->get('data_type') != 'array') { $this->error(new XenForo_Phrase('only_array_data_types_may_be_represented_as_array_values'), 'data_type'); } else { $subOptions = preg_split('/(\\r\\n|\\n|\\r)+/', trim($this->get('sub_options')), -1, PREG_SPLIT_NO_EMPTY); $newOptionValue = array(); $allowAny = false; foreach ($subOptions as $subOption) { if ($subOption == '*') { $allowAny = true; } else { if (!isset($optionValue[$subOption])) { $newOptionValue[$subOption] = false; } else { $newOptionValue[$subOption] = $optionValue[$subOption]; unset($optionValue[$subOption]); } } } if ($allowAny) { // allow any keys, so bring all the remaining ones over $newOptionValue += $optionValue; } else { if (count($optionValue) > 0) { $this->error(new XenForo_Phrase('following_sub_options_unknown_x', array('subOptions' => implode(', ', array_keys($optionValue)))), 'sub_options'); } } $optionValue = $newOptionValue; } $optionValue = XenForo_Helper_Php::safeSerialize($optionValue); } return strval($optionValue); }
/** * Logs changes made to the given user * * @param integer $userId * @param array $changedFields * @param integer $editUserId */ public function logChanges($userId, array $changedFields, $editUserId = null) { $db = $this->_getDb(); if (!$userId) { return false; } if (!$editUserId) { $editUserId = XenForo_Visitor::getUserId(); } if (!$editUserId) { // there's a rare case where guests can appear to edit a user, such as a lost password // request or with system actions; some of these auth the user in a different manner // and some are not really being edited by a particular user, so treat that as a self edit // for logging purposes $editUserId = $userId; } XenForo_Db::beginTransaction(); foreach ($changedFields as $field => $values) { if ($field == 'custom_fields') { $oldValues = XenForo_Helper_Php::safeUnserialize($values[0]); if (!is_array($oldValues)) { $oldValues = array(); } $newValues = XenForo_Helper_Php::safeUnserialize($values[1]); if (!is_array($newValues)) { $newValues = array(); } $changes = array(); foreach ($oldValues as $customField => $oldValue) { if (!isset($newValues[$customField])) { continue; } $newValue = $newValues[$customField]; if ($oldValue !== $newValue) { if (is_array($oldValue) && is_array($newValue)) { $changes["{$field}:{$customField}"] = array(serialize($oldValue), serialize($newValue)); } else { if (is_array($newValue)) { // old value is not an array but new one is, drop it $changes["{$field}:{$customField}"] = array(serialize(array()), serialize($newValue)); } else { if (is_array($oldValue)) { // old value is an array but new one is not, need to drop it $changes["{$field}:{$customField}"] = array('', $newValue); } else { $changes["{$field}:{$customField}"] = array($oldValue, $newValue); } } } } } // catch places where a new field value was added foreach ($newValues as $customField => $newValue) { if (isset($oldValues[$customField])) { // already tested continue; } if (is_array($newValue)) { $oldValue = serialize(array()); $newValue = serialize($newValue); } else { $oldValue = ''; } if ($oldValue !== $newValue) { $changes["{$field}:{$customField}"] = array($oldValue, $newValue); } } } else { $changes = array($field => array($values[0], $values[1])); } foreach ($changes as $fieldName => $change) { $change[0] = strval($change[0]); $change[1] = strval($change[1]); if ($change[0] === $change[1]) { // extra check in case we went null <-> empty string - we want to ignore that case continue; } $db->insert('xf_user_change_log', array('user_id' => $userId, 'edit_user_id' => $editUserId, 'edit_date' => XenForo_Application::$time, 'field' => $fieldName, 'old_value' => $change[0], 'new_value' => $change[1])); } } XenForo_Db::commit(); return true; }
/** * Prepares the poll responses for viewing from the poll record's response cache. * * @param array|string $responses Serialized array or array itself * @param array|null $viewingUser * * @return array|false Responses prepared; false if responses can't be prepared */ public function preparePollResponsesFromCache($responses, array $viewingUser = null) { $this->standardizeViewingUserReference($viewingUser); if (!is_array($responses)) { $responses = XenForo_Helper_Php::safeUnserialize($responses); } if (!is_array($responses)) { return false; } foreach ($responses as &$response) { $response['response'] = XenForo_Helper_String::censorString($response['response']); $response['hasVoted'] = isset($response['voters'][$viewingUser['user_id']]); } return $responses; }
/** * Performs any pre-view rendering setup, such as getting style information and * ensuring the correct data is registered. * * @param XenForo_ControllerResponse_Abstract|null $controllerResponse */ public function preRenderView(XenForo_ControllerResponse_Abstract $controllerResponse = null) { parent::preRenderView($controllerResponse); if (!empty($this->_viewStateChanges['styleId'])) { $styleId = $this->_viewStateChanges['styleId']; $forceStyleId = true; } else { $user = XenForo_Visitor::getInstance(); $styleId = !empty($user['style_id']) ? $user['style_id'] : 0; $forceStyleId = $user['is_admin'] ? true : false; } XenForo_Template_Abstract::setLanguageId(XenForo_Phrase::getLanguageId()); $styles = XenForo_Application::isRegistered('styles') ? XenForo_Application::get('styles') : XenForo_Model::create('XenForo_Model_Style')->getAllStyles(); if ($styleId && isset($styles[$styleId]) && ($styles[$styleId]['user_selectable'] || $forceStyleId)) { $style = $styles[$styleId]; } else { $defaultStyleId = XenForo_Application::get('options')->defaultStyleId; $style = isset($styles[$defaultStyleId]) ? $styles[$defaultStyleId] : reset($styles); } $defaultProperties = XenForo_Application::get('defaultStyleProperties'); if ($style) { $properties = XenForo_Helper_Php::safeUnserialize($style['properties']); XenForo_Template_Helper_Core::setStyleProperties(XenForo_Application::mapMerge($defaultProperties, $properties)); XenForo_Template_Public::setStyleId($style['style_id']); } else { XenForo_Template_Helper_Core::setStyleProperties($defaultProperties); } // setup the default template params if ($style) { $this->_defaultTemplateParams['visitorStyle'] = $style; } // expose the user fields info array $this->_defaultTemplateParams['userFieldsInfo'] = XenForo_Application::get('userFieldsInfo'); }
/** * Displays a form to add a reply to a thread. * * @return XenForo_ControllerResponse_Abstract */ public function actionReply() { $threadId = $this->_input->filterSingle('thread_id', XenForo_Input::UINT); $visitor = XenForo_Visitor::getInstance(); $threadFetchOptions = array('draftUserId' => $visitor['user_id']); $ftpHelper = $this->getHelper('ForumThreadPost'); list($thread, $forum) = $ftpHelper->assertThreadValidAndViewable($threadId, $threadFetchOptions); $this->_assertCanReplyToThread($thread, $forum); $defaultMessage = ''; $quotePost = null; $useDraft = false; if ($quoteId = $this->_input->filterSingle('quote', XenForo_Input::UINT)) { $postModel = $this->_getPostModel(); $quotePost = $postModel->getPostById($quoteId, array('join' => XenForo_Model_Post::FETCH_USER)); if ($quotePost && $quotePost['thread_id'] == $threadId && $postModel->canViewPost($quotePost, $thread, $forum)) { $defaultMessage = $postModel->getQuoteTextForPost($quotePost); } } else { if ($this->_input->inRequest('more_options')) { $defaultMessage = $this->getHelper('Editor')->getMessageText('message', $this->_input); } else { if (!empty($thread['draft_message'])) { $defaultMessage = $thread['draft_message']; $useDraft = true; } } } $attachmentHash = $this->_input->filterSingle('attachment_hash', XenForo_Input::STRING); if ($useDraft && !empty($thread['draft_extra'])) { $draftExtra = XenForo_Helper_Php::safeUnserialize($thread['draft_extra']); if (!empty($draftExtra['attachment_hash'])) { $attachmentHash = $draftExtra['attachment_hash']; } } $attachmentParams = $this->_getForumModel()->getAttachmentParams($forum, array('thread_id' => $thread['thread_id']), null, null, $attachmentHash); $attachments = !empty($attachmentParams['attachments']) ? $attachmentParams['attachments'] : array(); $viewParams = array('post' => $quotePost, 'thread' => $thread, 'forum' => $forum, 'nodeBreadCrumbs' => $ftpHelper->getNodeBreadCrumbs($forum), 'attachmentParams' => $attachmentParams, 'attachments' => $attachments, 'attachmentConstraints' => $this->_getAttachmentModel()->getAttachmentConstraints(), 'defaultMessage' => $defaultMessage, 'watchState' => $this->_getThreadWatchModel()->getThreadWatchStateForVisitor($threadId), 'captcha' => XenForo_Captcha_Abstract::createDefault(), 'canLockUnlockThread' => $this->_getThreadModel()->canLockUnlockThread($thread, $forum), 'canStickUnstickThread' => $this->_getThreadModel()->canStickUnstickThread($thread, $forum)); return $this->responseView('XenForo_ViewPublic_Thread_Reply', 'thread_reply', $viewParams); }
/** * Pre-save handling. */ protected function _preSave() { if ($this->isUpdate() && $this->isChanged('definition_style_id')) { throw new XenForo_Exception('Cannot update the style of existing style property definitions.'); } if ($this->get('property_type') == 'css') { $components = $this->get('css_components'); if (is_string($components) && substr($components, 0, 2) == 'a:') { $components = XenForo_Helper_Php::safeUnserialize($components); } if (!$components) { $this->error(new XenForo_Phrase('css_style_property_must_have_at_least_one_css_component'), 'css_components'); } if ($this->get('group_name') == 'color') { $this->error(new XenForo_Phrase('color_palette_style_properties_must_be_scalar'), 'property_type'); } } if ($this->isChanged('property_name') && $this->getOption(self::OPTION_CHECK_DUPLICATE)) { $newName = $this->get('property_name'); $definitions = $this->_getStylePropertyModel()->getEffectiveStylePropertiesInStyle($this->get('definition_style_id')); foreach ($definitions as $definition) { if ($definition['property_name'] == $newName) { $this->error(new XenForo_Phrase('style_property_definitions_must_be_unique_per_style'), 'property_name'); break; } } } }
/** * Gets the count of unread threads in the given forum. This only applies to registered * users. If no user ID is given, false is returned. * * @param integer $forumId * @param integer $userId * @param integer $forumReadDate Time when the whole forum is read from * @param string|array $ignored List of ignored user IDs; if string, unserialized and keys used * * @return integer|false */ public function getUnreadThreadCountInForum($forumId, $userId, $forumReadDate = 0, $ignored = false) { if (!$userId) { return false; } if ($ignored && is_string($ignored)) { $ignored = XenForo_Helper_Php::safeUnserialize($ignored); $ignored = array_keys($ignored); } $db = $this->_getDb(); return $db->fetchOne(' SELECT COUNT(*) FROM xf_thread AS thread LEFT JOIN xf_thread_read AS thread_read ON (thread_read.thread_id = thread.thread_id AND thread_read.user_id = ?) WHERE thread.node_id = ? AND thread.last_post_date > ? AND (thread_read.thread_id IS NULL OR thread.last_post_date > thread_read.thread_read_date) ' . ($ignored ? 'AND thread.user_id NOT IN (' . $db->quote($ignored) . ')' : '') . ' AND thread.discussion_state = \'visible\' AND thread.discussion_type <> \'redirect\' ', array($userId, $forumId, $forumReadDate)); }
/** * Returns true if the specified user ID or user name is in the ignored (cache) of the given user. * * @param array $user * @param integer|string User ID or user name * * @return array|boolean */ public function isUserIgnored(array $user, $ignoredUser) { if (isset($user['ignored']) && !$user['ignored'] || !$ignoredUser) { return false; } $userId = $user['user_id']; if (!isset($this->_ignoreCache[$userId])) { if (!isset($user['ignored'])) { $user['ignored'] = $this->_getDb()->fetchOne(' SELECT ignored FROM xf_user_profile WHERE user_id = ? ', $userId); } $this->_ignoreCache[$userId] = XenForo_Helper_Php::safeUnserialize($user['ignored']); } if (is_int($ignoredUser) && isset($this->_ignoreCache[$userId][$ignoredUser])) { return array($ignoredUser, $this->_ignoreCache[$userId][$ignoredUser]); } if (is_string($ignoredUser)) { $ignoredUserId = array_search($ignoredUser, $this->_ignoreCache[$userId]); if ($ignoredUserId !== false) { return array($ignoredUserId, $this->_ignoreCache[$userId][$ignoredUserId]); } } return false; }
/** * Prepare a conversation for display or further processing. * * @param array $conversation * * @return array */ public function prepareConversation(array $conversation) { $conversation['isNew'] = $conversation['last_message_date'] > $conversation['last_read_date']; $conversation['title'] = XenForo_Helper_String::censorString($conversation['title']); $conversation['lastPageNumbers'] = $this->getLastPageNumbers($conversation['reply_count']); $conversation['last_message'] = array('message_id' => $conversation['last_message_id'], 'message_date' => $conversation['last_message_date'], 'user_id' => $conversation['last_message_user_id'], 'username' => $conversation['last_message_username']); if (isset($conversation['last_message_avatar_date'])) { $conversation['last_message']['avatar_date'] = $conversation['last_message_avatar_date']; } if (isset($conversation['last_message_gender'])) { $conversation['last_message']['gender'] = $conversation['last_message_gender']; } if (isset($conversation['last_message_gravatar'])) { $conversation['last_message']['gravatar'] = $conversation['last_message_gravatar']; } if (array_key_exists('user_group_id', $conversation)) { $conversation = $this->_getUserModel()->prepareUser($conversation); $conversation['isIgnored'] = false; // don't ignore conversations - the user can leave the conversation instead } $conversation['recipientNames'] = $conversation['recipients'] ? XenForo_Helper_Php::safeUnserialize($conversation['recipients']) : array(); return $conversation; }
/** * Pre-save handling. */ protected function _preSave() { if ($this->_newRecipients) { $creatorUserId = $this->get('user_id'); foreach ($this->_newRecipients as $key => $recipientUserId) { if ($recipientUserId == $creatorUserId) { unset($this->_newRecipients[$key]); } } } if ($this->_newRecipients) { $recipients = XenForo_Helper_Php::safeUnserialize($this->get('recipients')); if (!$recipients) { $recipients = array(); } $recipients += $this->_getUserModel()->getUsersByIds($this->_newRecipients); $this->_updateRecipients($recipients); } if ($this->isInsert() && !$this->_newRecipients) { $this->error(new XenForo_Phrase('please_enter_at_least_one_valid_recipient'), 'recipients', false); } if ($this->isInsert() && !$this->_firstMessageDw) { throw new XenForo_Exception('Must create a first message DW on insert.'); } if ($this->isInsert()) { if (!$this->isChanged('start_date')) { $this->set('start_date', XenForo_Application::$time); } $fieldMap = array('last_message_date' => 'start_date', 'last_message_user_id' => 'user_id', 'last_message_username' => 'username'); foreach ($fieldMap as $childField => $parentField) { if (!$this->isChanged($childField)) { $this->set($childField, $this->get($parentField)); } } } if ($this->_firstMessageDw) { $messageDw = $this->_firstMessageDw; $messageDw->set('conversation_id', 0); foreach ($this->_newData as $table => $newData) { foreach ($newData as $field => $value) { $messageDw->set($field, $value, '', array('ignoreInvalidFields' => true)); } } $messageDw->preSave(); $firstMessageErrors = $messageDw->getErrors(); if ($firstMessageErrors) { $this->_errors = array_merge($this->_errors, $firstMessageErrors); } } }
/** * Pre-save handler. */ protected function _preSave() { if ($this->isInsert() && !$this->isChanged('active')) { $this->set('active', 1); } $titlePhrase = $this->getExtraData(self::DATA_TITLE); if ($titlePhrase !== null && strlen($titlePhrase) == 0) { $this->error(new XenForo_Phrase('please_enter_valid_title'), 'title'); } if ($this->isChanged('cron_class') || $this->isChanged('cron_method')) { $class = $this->get('cron_class'); $method = $this->get('cron_method'); if (!XenForo_Helper_Php::validateCallbackPhrased($class, $method, $errorPhrase)) { $this->error($errorPhrase, 'cron_method'); } } if ($this->get('active')) { $runRules = XenForo_Helper_Php::safeUnserialize($this->get('run_rules')); if (!is_array($runRules)) { $runRules = array(); } $this->set('next_run', $this->_getCronModel()->calculateNextRunTime($runRules)); } else { $this->set('next_run', 0x7fffffff); // waay in future } }
/** * Displays a form to create a conversation. * * @return XenForo_ControllerResponse_Abstract */ public function actionAdd() { if (!$this->_getConversationModel()->canStartConversations($errorPhraseKey)) { throw $this->getErrorOrNoPermissionResponseException($errorPhraseKey); } $to = $this->_input->filterSingle('to', XenForo_Input::STRING); $title = $this->_input->filterSingle('title', XenForo_Input::STRING); if ($to !== '' && strpos($to, ',') === false) { $toUser = $this->getModelFromCache('XenForo_Model_User')->getUserByName($to, array('join' => XenForo_Model_User::FETCH_USER_FULL)); if (!$toUser) { return $this->responseError(new XenForo_Phrase('requested_user_not_found'), 404); } if (!$this->_getConversationModel()->canStartConversationWithUser($toUser, $errorPhraseKey)) { if ($errorPhraseKey) { $error = new XenForo_Phrase($errorPhraseKey); } else { $error = new XenForo_Phrase('you_may_not_start_conversation_with_x_privacy_settings', array('name' => $toUser['username'])); } return $this->responseError($error, 403); } $to = $toUser['username']; } $draft = $this->_getDraftModel()->getDraftByUserKey("conversation", XenForo_Visitor::getUserId()); $attachmentHash = null; if ($draft) { $extra = XenForo_Helper_Php::safeUnserialize($draft['extra_data']); if ($to && !empty($extra['recipients']) && $to != $extra['recipients']) { // our draft is to someone else $draft = false; } else { if (!empty($extra['recipients']) && !$to) { $to = $extra['recipients']; } if (!empty($extra['title']) && !$title) { $title = $extra['title']; } if (!empty($extra['attachment_hash'])) { $attachmentHash = $extra['attachment_hash']; } } } $attachmentParams = $this->_getConversationModel()->getAttachmentParams(array(), array(), null, $attachmentHash); $viewParams = array('to' => $to, 'title' => $title, 'remaining' => $this->_getConversationModel()->allowedAdditionalConversationRecipients(array()), 'draft' => $draft, 'attachmentParams' => $attachmentParams, 'attachmentConstraints' => $this->getModelFromCache('XenForo_Model_Attachment')->getAttachmentConstraints()); return $this->responseView('XenForo_ViewPublic_Conversation_Add', 'conversation_add', $viewParams); }
/** * Prepares XML to export the specified smilies and their containing categories * * @param array $smilieIds * * @return DOMDocument */ public function getSmiliesXml(array $smilieIds) { if ($smilieIds) { $smilies = $this->fetchAllKeyed(' SELECT xf_smilie.*, xf_smilie_category.display_order AS smilie_category_order FROM xf_smilie LEFT JOIN xf_smilie_category ON (xf_smilie_category.smilie_category_id = xf_smilie.smilie_category_id) WHERE xf_smilie.smilie_id IN (' . $this->_getDb()->quote($smilieIds) . ') ORDER BY xf_smilie_category.display_order, xf_smilie.display_order, xf_smilie.title ', 'smilie_id'); } else { $smilies = array(); } $document = new DOMDocument('1.0', 'utf-8'); $document->formatOutput = true; $rootNode = $document->createElement('smilies_export'); $document->appendChild($rootNode); $smiliesNode = $document->createElement('smilies'); $smilieCategories = array(); foreach ($smilies as $smilie) { $smilieNode = $document->createElement('smilie'); if ($smilie['smilie_category_id']) { $smilieCategories[$smilie['smilie_category_id']] = $smilie['smilie_category_order']; $smilieNode->setAttribute('smilie_category_id', $smilie['smilie_category_id']); } $smilieNode->setAttribute('title', $smilie['title']); $smilieNode->appendChild($document->createElement('image_url', $smilie['image_url'])); if ($smilie['sprite_mode']) { $spriteParamsNode = $document->createElement('sprite_params'); foreach (XenForo_Helper_Php::safeUnserialize($smilie['sprite_params']) as $param => $value) { $spriteParamsNode->setAttribute($param, $value); } $smilieNode->appendChild($spriteParamsNode); } foreach (preg_split('/\\r?\\n/', $smilie['smilie_text'], -1, PREG_SPLIT_NO_EMPTY) as $smilieText) { $smilieNode->appendChild($document->createElement('smilie_text', $smilieText)); } $smilieNode->setAttribute('display_order', $smilie['display_order']); $smilieNode->setAttribute('display_in_editor', $smilie['display_in_editor']); $smiliesNode->appendChild($smilieNode); } $categoriesNode = $document->createElement('smilie_categories'); foreach ($smilieCategories as $smilieCategoryId => $displayOrder) { if ($smilieCategoryId) { $categoryNode = $document->createElement('smilie_category'); $categoryNode->setAttribute('id', $smilieCategoryId); $categoryNode->setAttribute('title', $this->getSmilieCategoryMasterTitlePhraseValue($smilieCategoryId)); $categoryNode->setAttribute('display_order', $displayOrder); $categoriesNode->appendChild($categoryNode); } } $rootNode->appendChild($categoriesNode); $rootNode->appendChild($smiliesNode); return $document; }
/** * Compiles and inserts the specified effective templates. * * @param array $templates Array of effective template info */ public function compileAndInsertEffectiveTemplates(array $templates) { foreach ($templates as $template) { $this->compileAndInsertParsedTemplate($template['template_map_id'], XenForo_Helper_Php::safeUnserialize($template['template_parsed']), $template['title'], isset($template['map_style_id']) ? $template['map_style_id'] : $template['style_id']); } }
public static function unserializeCriteria($criteria) { if (!is_array($criteria)) { $criteria = XenForo_Helper_Php::safeUnserialize($criteria); if (!is_array($criteria)) { return array(); } } return $criteria; }
/** * Deletes all phrases for existing choices. */ protected function _deleteExistingChoicePhrases() { $fieldId = $this->get('field_id'); $existingChoices = $this->getExisting('field_choices'); if ($existingChoices && ($existingChoices = XenForo_Helper_Php::safeUnserialize($existingChoices))) { foreach ($existingChoices as $choice => $text) { $this->_deleteMasterPhrase($this->_getChoicePhraseName($fieldId, $choice)); } } }
/** * Builds an array of all options, in the format used by the cache and * the {@link XenForo_Options} class. * * @return array */ public function buildOptionArray() { $options = $this->getAllOptions(); $optionArray = array(); foreach ($options as $option) { if ($option['data_type'] == 'array') { $optionArray[$option['option_id']] = XenForo_Helper_Php::safeUnserialize($option['option_value']); if (!is_array($optionArray[$option['option_id']])) { $optionArray[$option['option_id']] = array(); } } else { $optionArray[$option['option_id']] = $option['option_value']; } } return $optionArray; }
/** * Setup the visitor singleton. * * @param integer $userId User ID to setup as * @param array $options * * @return XenForo_Visitor */ public static function setup($userId, array $options = array()) { $userId = intval($userId); $options = array_merge(array('languageId' => 0, 'permissionUserId' => 0), $options); /* @var $userModel XenForo_Model_User */ $userModel = XenForo_Model::create('XenForo_Model_User'); $class = XenForo_Application::resolveDynamicClass('XenForo_Visitor'); $object = new $class(); if ($userId && ($user = $userModel->getVisitingUserById($userId))) { if ($user['is_admin']) { if ($options['permissionUserId']) { // force permissions for testing $user = $userModel->setPermissionsFromUserId($user, $options['permissionUserId']); } if ($options['languageId']) { $user['admin_language_id'] = $user['language_id'] = $options['languageId']; } } $object->_user = $user; } else { $object->_user = $userModel->getVisitingGuestUser(); if ($options['languageId']) { $object->_user['language_id'] = $options['languageId']; } } $object->_user = $userModel->prepareUser($object->_user); $object->_user['referer'] = !empty($options['referer']) ? $options['referer'] : null; $object->_user['from_search'] = !empty($options['fromSearch']); if (!empty($object->_user['ignored'])) { $ignored = XenForo_Helper_Php::safeUnserialize($object->_user['ignored']); $object->_user['ignoredUsers'] = $ignored; } else { $object->_user['ignoredUsers'] = array(); } if (!$object->_user['global_permission_cache']) { // force a rebuild if we don't have the perm cache $perms = XenForo_Model::create('XenForo_Model_Permission')->rebuildPermissionCombinationById($object->_user['permission_combination_id']); $object->_user['permissions'] = $perms ? $perms : array(); } else { $object->_user['permissions'] = XenForo_Permission::unserializePermissions($object->_user['global_permission_cache']); } $object->setVisitorLanguage($object->_user['language_id']); XenForo_Locale::setDefaultTimeZone($object->_user['timezone']); self::$_instance = $object; self::$_setupOptions = $options; XenForo_CodeEvent::fire('visitor_setup', array(&self::$_instance)); return self::$_instance; }
protected function _getBbCodeXmlNode(DOMDocument $document, array $bbCode) { $attributes = array('bb_code_id', 'bb_code_mode', 'has_option', 'callback_class', 'callback_method', 'option_regex', 'trim_lines_after', 'plain_children', 'disable_smilies', 'disable_nl2br', 'disable_autolink', 'allow_empty', 'allow_signature', 'editor_icon_url', 'sprite_mode', 'active'); $children = array('replace_html', 'replace_html_email', 'replace_text', 'example'); $bbCodeNode = $document->createElement('bb_code'); foreach ($attributes as $attribute) { $bbCodeNode->setAttribute($attribute, $bbCode[$attribute]); } foreach ($children as $child) { $fieldNode = $document->createElement($child); $fieldNode->appendChild(XenForo_Helper_DevelopmentXml::createDomCdataSection($document, $bbCode[$child])); $bbCodeNode->appendChild($fieldNode); } if ($bbCode['sprite_mode']) { $params = XenForo_Helper_Php::safeUnserialize($bbCode['sprite_params']); if ($params && isset($params['x']) && isset($params['y'])) { $bbCodeNode->setAttribute('sprite_params_x', $params['x']); $bbCodeNode->setAttribute('sprite_params_y', $params['y']); } else { $bbCodeNode->setAttribute('sprite_params_x', 0); $bbCodeNode->setAttribute('sprite_params_y', 0); } } return $bbCodeNode; }