/** @inheritdoc} */
 public function getProfitResourceGroups($id = 0)
 {
     $groups = array();
     $key = $this->MlmSystem->namespace;
     $options = array('cache_key' => $key . '/profit/group/' . __CLASS__ . '/resource/' . $id, 'cacheTime' => 0);
     if ($resource = $this->modx->getObject('modResource', array('id' => $id)) and !($groups = $this->MlmSystem->getCache($options))) {
         $ids = $this->modx->getParentIds($id, 10, array('context' => $resource->get('context_key')));
         $ids[] = $id;
         $ids = array_unique($ids);
         $q = $this->modx->newQuery('modResourceGroupResource', array('document:IN' => $ids));
         $q->leftJoin('MlmSystemProfitGroup', 'MlmSystemProfitGroup', 'MlmSystemProfitGroup.group = modResourceGroupResource.document_group');
         $q->where(array('MlmSystemProfitGroup.class' => 'modResourceGroup'));
         $q->select('document_group,profit');
         $q->sortby('profit');
         $q->groupby('MlmSystemProfitGroup.group');
         $tstart = microtime(true);
         if ($q->prepare() && $q->stmt->execute()) {
             $this->modx->queryTime += microtime(true) - $tstart;
             $this->modx->executedQueries++;
             while ($row = $q->stmt->fetch(PDO::FETCH_ASSOC)) {
                 $groups[$row['document_group']] = $row['profit'];
             }
         }
         $this->MlmSystem->setCache($groups, $options);
     }
     return $groups;
 }
 /**
  * Prepare a JSON encoded object and return a valid JSON encoded Image+ object
  *
  * @param $json JSON value to prepare
  * @param array $opts
  * @param modTemplateVar $tv
  * @return string
  */
 public function prepareTvValue($json, $opts = array(), modTemplateVar $tv)
 {
     // Prepare value
     $decoded = json_decode($json);
     if (!$decoded) {
         // The variable does not contain an Image+ image object
         if ($json != '') {
             // Get Media Source
             /** @var modMediaSource $source */
             if ($tv) {
                 $source = $tv->getSource($this->modx->resource ? $this->modx->resource->get('context_key') : 'mgr');
             } else {
                 $source = $this->modx->getObject('modMediaSource', $this->modx->getOption('default_media_source'));
             }
             if (!($source && $source->getWorkingContext())) {
                 $this->modx->log(xPDO::LOG_LEVEL_ERROR, 'Invalid Media Source', '', 'Image+');
                 return '';
             }
             $source->setRequestProperties($_REQUEST);
             $source->initialize();
             // The variable contains a value and has to be converted to an Image+ image object
             $imgPath = $source->getBasePath() . $json;
             if (file_exists($imgPath)) {
                 $size = getimagesize($imgPath);
             } else {
                 $this->modx->log(xPDO::LOG_LEVEL_INFO, 'The template variabe value does not contain an existing image', '', 'Image+');
             }
             $json = json_encode(array('altTag' => '', 'crop' => array('height' => $size ? $size[1] : 0, 'width' => $size ? $size[0] : 0, 'x' => 0, 'y' => 0), 'sourceImg' => array('height' => $size ? $size[1] : 0, 'width' => $size ? $size[0] : 0, 'source' => $source->get('id'), 'src' => $json), 'targetHeight' => (int) $opts['targetHeight'], 'targetWidth' => (int) $opts['targetWidth']));
         }
     }
     return $json;
 }
Exemple #3
0
 /**
  * Loads snippet for form processing
  *
  * @param $action
  * @param array $fields
  *
  * @return array|string
  */
 public function process($action, array $fields = array())
 {
     if (!isset($_SESSION['AjaxForm'][$action])) {
         return $this->error('af_err_action_nf');
     }
     unset($fields['af_action'], $_POST['af_action']);
     $scriptProperties = $_SESSION['AjaxForm'][$action];
     $scriptProperties['fields'] = $fields;
     $scriptProperties['AjaxForm'] = $this;
     $name = $scriptProperties['snippet'];
     $set = '';
     if (strpos($name, '@') !== false) {
         list($name, $set) = explode('@', $name);
     }
     /** @var modSnippet $snippet */
     if ($snippet = $this->modx->getObject('modSnippet', array('name' => $name))) {
         $properties = $snippet->getProperties();
         $property_set = !empty($set) ? $snippet->getPropertySet($set) : array();
         $scriptProperties = array_merge($properties, $property_set, $scriptProperties);
         $snippet->_cacheable = false;
         $snippet->_processed = false;
         $response = $snippet->process($scriptProperties);
         if (strtolower($snippet->name) == 'formit') {
             $response = $this->handleFormIt($scriptProperties);
         }
         return $response;
     } else {
         return $this->error('af_err_snippet_nf', array(), array('name' => $name));
     }
 }
 /**
  * Gets a task by its ID or namespace and reference
  *
  * @param string|int $namespaceOrId
  * @param string $reference
  * @return null|sTask
  */
 public function getTask($namespaceOrId, $reference = '')
 {
     if (is_numeric($namespaceOrId) && empty($reference)) {
         $condition = $namespaceOrId;
     } else {
         $condition = array('namespace' => $namespaceOrId, 'reference' => $reference);
     }
     $task = $this->modx->getObject('sTask', $condition);
     return $task;
 }
Exemple #5
0
 /**
  * @param string $tpl
  *
  * @return int
  */
 public function getLastModified($tpl)
 {
     /** @var modChunk $chunk */
     if ($chunk = $this->modx->getObject('modTemplate', array('templatename' => $tpl))) {
         if ($chunk->isStatic() && ($file = $chunk->getSourceFile())) {
             return filemtime($file);
         }
     }
     return time();
 }
Exemple #6
0
 /**
  * @param string $tpl
  *
  * @return int
  */
 public function getLastModified($tpl)
 {
     $c = is_numeric($tpl) && $tpl > 0 ? $tpl : array('name' => $tpl);
     /** @var modChunk $chunk */
     if ($chunk = $this->modx->getObject('modChunk', $c)) {
         if ($chunk->isStatic() && ($file = $chunk->getSourceFile())) {
             return filemtime($file);
         }
     }
     return time();
 }
 /**
  * Gets an element object of the specifed type
  * 
  * @todo Keep getting "Call to a member function getObject() on a non-object" 
  * 
  * @param modX $modx
  * @param string $type
  * @param integer | string $criteria (ID or name of the element) 
  * 
  * @return Element | boolean
  */
 public static function get(modX $modx, $type, $criteria)
 {
     if (is_int($criteria)) {
         $element = $modx->getObject($type, $criteria);
     } else {
         $element = $modx->getObject($type, array(Element::get_name_field($type) => $criteria));
     }
     if (isset($element)) {
         return new Element($element);
     }
     return false;
 }
Exemple #8
0
 public function postInstall()
 {
     /* fix settings_version */
     /** @var \modSystemSetting $object */
     $object = $this->xpdo->getObject('modSystemSetting', array('key' => 'settings_version'));
     if (!$object) {
         $object = $this->xpdo->newObject('modSystemSetting');
         $object->fromArray(array('key' => 'settings_version', 'area' => 'system', 'namespace' => 'core', 'xtype' => 'textfield'), '', true);
     }
     $object->set('value', $this->xpdo->version['full_version']);
     $object->save(false);
     /* fix session_cookie_domain */
     $object = $this->xpdo->getObject('modSystemSetting', array('key' => 'session_cookie_domain'));
     if (!$object) {
         $object = $this->xpdo->newObject('modSystemSetting');
         $object->fromArray(array('key' => 'session_cookie_domain', 'area' => 'session', 'namespace' => 'core', 'xtype' => 'textfield'), '', true);
     }
     $object->set('value', '');
     $object->save(false);
     /* fix session_cookie_path */
     $object = $this->xpdo->getObject('modSystemSetting', array('key' => 'session_cookie_path'));
     if (!$object) {
         $object = $this->xpdo->newObject('modSystemSetting');
         $object->fromArray(array('key' => 'session_cookie_path', 'area' => 'session', 'namespace' => 'core', 'xtype' => 'textfield'), '', true);
     }
     $object->set('value', $this->xpdo->getOption('base_url', null, MODX_BASE_URL));
     $object->save(false);
 }
 /**
  * Handle DELETE requests
  * @return array
  */
 public function delete()
 {
     $id = $this->getProperty($this->primaryKeyField, false);
     if (empty($id)) {
         return $this->failure($this->modx->lexicon('rest.err_field_ns', array('field' => $this->primaryKeyField)));
     }
     $c = $this->getPrimaryKeyCriteria($id);
     $this->object = $this->modx->getObject($this->classKey, $c);
     if (empty($this->object)) {
         return $this->failure($this->modx->lexicon('rest.err_obj_nf', array('class_key' => $this->classKey)));
     }
     if (!empty($this->deleteRequiredFields)) {
         if (!$this->checkRequiredFields($this->deleteRequiredFields)) {
             return $this->failure();
         }
     }
     $this->object->fromArray($this->getProperties());
     $beforeDelete = $this->beforeDelete();
     if ($beforeDelete !== true) {
         return $this->failure($beforeDelete === false ? $this->errorMessage : $beforeDelete);
     }
     if (!$this->object->{$this->deleteMethod}()) {
         $this->setObjectErrors();
         return $this->failure($this->modx->lexicon('rest.err_class_remove', array('class_key' => $this->classKey)));
     }
     $objectArray = $this->object->toArray();
     $this->afterDelete($objectArray);
     return $this->success('', $objectArray);
 }
 /**
  * Return the appropriate Resource controller class based on the class_key request parameter
  * 
  * @static
  * @param modX $modx A reference to the modX instance
  * @param string $className The controller class name that is attempting to be loaded
  * @param array $config An array of configuration options for the action
  * @return modManagerController The proper controller class
  */
 public static function getInstance(modX &$modx, $className, array $config = array())
 {
     $resourceClass = 'modDocument';
     $isDerivative = false;
     if (!empty($_REQUEST['class_key'])) {
         $isDerivative = true;
         $resourceClass = in_array($_REQUEST['class_key'], array('modDocument', 'modResource')) ? 'modResource' : $_REQUEST['class_key'];
     } else {
         if (!empty($_REQUEST['id'])) {
             /** @var modResource $resource */
             $resource = $modx->getObject('modResource', $_REQUEST['id']);
             if ($resource && !in_array($resource->get('class_key'), array('modDocument', 'modResource'))) {
                 $isDerivative = true;
                 $resourceClass = $resource->get('class_key');
             }
         }
     }
     if ($isDerivative) {
         $resourceClass = str_replace(array('../', '..', '/', '\\'), '', $resourceClass);
         $delegateView = $modx->call($resourceClass, 'getControllerPath', array(&$modx));
         $action = strtolower(str_replace(array('Resource', 'ManagerController'), '', $className));
         $className = str_replace('mod', '', $resourceClass) . ucfirst($action) . 'ManagerController';
         $controllerFile = $delegateView . $action . '.class.php';
         require_once $controllerFile;
     }
     $controller = new $className($modx, $config);
     $controller->resourceClass = $resourceClass;
     return $controller;
 }
 /**
  * Validates a field based on a custom rule, if specified
  *
  * @access public
  * @param string $key The key of the field
  * @param mixed $value The value of the field
  * @param string $type Optional. The type of the validator to apply. Can
  * either be a method name of lgnValidator or a Snippet name.
  * @return boolean True if validation was successful. If not, will store
  * error messages to $this->errors.
  */
 public function validate($key, $value, $type = '')
 {
     $validated = false;
     $hasParams = strpos($type, '=');
     $param = null;
     if ($hasParams !== false) {
         $param = str_replace('`', '', substr($type, $hasParams + 1, strlen($type)));
         $type = substr($type, 0, $hasParams);
     }
     $invNames = array('validate', 'validateFields', '_addError', '__construct');
     if (method_exists($this, $type) && $type != 'validate') {
         /* built-in validator */
         $validated = $this->{$type}($key, $value, $param);
     } else {
         if ($snippet = $this->modx->getObject('modSnippet', array('name' => $type))) {
             /* custom snippet validator */
             $props = array_merge($this->login->config, array('key' => $key, 'value' => $value, 'param' => $param, 'type' => $type, 'validator' => &$this, 'errors' => &$this->errors));
             $validated = $snippet->process($props);
         } else {
             /* no validator found */
             $this->modx->log(modX::LOG_LEVEL_ERROR, '[Register] Could not find validator "' . $type . '" for field "' . $key . '".');
             $validated = true;
         }
     }
     if (is_array($validated) && !empty($validated)) {
         foreach ($validated as $key => $errMsg) {
             $this->_addError($key, $errMsg);
         }
         $validated = false;
     } elseif ($validated !== '1' && $validated !== 1 && $validated !== true) {
         $this->_addError($key, $validated);
         $validated = false;
     }
     return $validated;
 }
 public function find(array $search = array(), array $args = array())
 {
     $results = array();
     $where = array_merge(array('query' => false, 'tag' => false, 'sorter' => false, 'start' => 0, 'limit' => 10, 'dateFormat' => '%b %d, %Y', 'supportsSeparator' => ', '), $search);
     $where['page'] = !empty($where['start']) ? round($where['start'] / $where['limit']) : 0;
     /** @var modRestResponse $response */
     $response = $this->request('package', 'GET', $where);
     if ($response->isError()) {
         $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, $response->getError(), '', __METHOD__, __FILE__, __LINE__);
         return $results;
     }
     $xml = $response->toXml();
     /** @var SimpleXMLElement $package */
     foreach ($xml as $package) {
         $installed = $this->xpdo->getObject('transport.modTransportPackage', (string) $package->signature);
         $versionCompiled = rtrim((string) $package->version . '-' . (string) $package->release, '-');
         $releasedon = strftime($this->arg('dateFormat', $where), strtotime((string) $package->releasedon));
         $supports = '';
         foreach ($package->supports as $support) {
             $supports .= (string) $support . $this->arg('supportsSeparator', $where);
         }
         $results[] = array('id' => (string) $package->id, 'version' => (string) $package->version, 'release' => (string) $package->release, 'signature' => (string) $package->signature, 'author' => (string) $package->author, 'description' => (string) $package->description, 'instructions' => (string) $package->instructions, 'changelog' => (string) $package->changelog, 'createdon' => (string) $package->createdon, 'editedon' => (string) $package->editedon, 'name' => (string) $package->name, 'downloads' => number_format((int) $package->downloads, 0), 'releasedon' => $releasedon, 'screenshot' => (string) $package->screenshot, 'thumbnail' => !empty($package->thumbnail) ? (string) $package->thumbnail : (string) $package->screenshot, 'license' => (string) $package->license, 'minimum_supports' => (string) $package->minimum_supports, 'breaks_at' => (int) $package->breaks_at != 10000000 ? (string) $package->breaks_at : '', 'supports_db' => (string) $package->supports_db, 'location' => (string) $package->location, 'version-compiled' => $versionCompiled, 'downloaded' => !empty($installed) ? true : false, 'featured' => (bool) $package->featured, 'audited' => (bool) $package->audited, 'dlaction-icon' => $installed ? 'package-installed' : 'package-download', 'dlaction-text' => $installed ? $this->xpdo->lexicon('downloaded') : $this->xpdo->lexicon('download'));
     }
     return array((int) $xml['total'], $results);
 }
 /**
  * Get the statistics for the bottom area of the forums
  * @return void
  */
 protected function getStatistics()
 {
     $this->setPlaceholder('totalPosts', number_format((int) $this->getPostCount()));
     $this->setPlaceholder('totalTopics', number_format((int) $this->getThreadCount()));
     $this->setPlaceholder('totalMembers', number_format((int) $this->modx->getCount('disUser')));
     /* active in last 40 */
     if ($this->modx->getOption('discuss.show_whos_online', null, true)) {
         $this->setPlaceholder('activeUsers', $this->discuss->hooks->load('user/active_in_last'));
     } else {
         $this->setPlaceholder('activeUsers', '');
     }
     /* total active */
     $this->setPlaceholder('totalMembersActive', number_format((int) $this->modx->getCount('disSession', array('user:!=' => 0))));
     $this->setPlaceholder('totalVisitorsActive', number_format((int) $this->modx->getCount('disSession', array('user' => 0))));
     /**
      * forum activity
      * @var disForumActivity $activity
      */
     $activity = $this->modx->getObject('disForumActivity', array('day' => date('Y-m-d')));
     if (!$activity) {
         $activity = $this->modx->newObject('disForumActivity');
         $activity->set('day', date('Y-m-d'));
         $activity->save();
     }
     $this->setPlaceholders($activity->toArray('activity.'));
 }
Exemple #14
0
 /**
  * Gets a Chunk and caches it; also falls back to file-based templates
  * for easier debugging.
  *
  * Will always use the file-based chunk if $debug is set to true.
  *
  * @access public
  * @param string $name The name of the Chunk
  * @param array $properties The properties for the Chunk
  * @return string The processed content of the Chunk
  */
 public function getChunk($name, $properties = array())
 {
     $chunk = null;
     if (substr($name, 0, 6) == "@CODE:") {
         $content = substr($name, 6);
         $chunk = $this->modx->newObject('modChunk');
         $chunk->setContent($content);
     } elseif (!isset($this->chunks[$name])) {
         if (!$this->config['debug']) {
             $chunk = $this->modx->getObject('modChunk', array('name' => $name), true);
         }
         if (empty($chunk)) {
             $chunk = $this->_getTplChunk($name);
             if ($chunk == false) {
                 return false;
             }
         }
         $this->chunks[$name] = $chunk->getContent();
     } else {
         $o = $this->chunks[$name];
         $chunk = $this->modx->newObject('modChunk');
         $chunk->setContent($o);
     }
     $chunk->setCacheable(false);
     return $chunk->process($properties);
 }
Exemple #15
0
 /**
  * Move a thread to a new board
  *
  * @param int $boardId
  * @return boolean True if successful
  */
 public function move($boardId)
 {
     $oldBoard = $this->getOne('Board');
     $newBoard = is_object($boardId) && $boardId instanceof disBoard ? $boardId : $this->xpdo->getObject('disBoard', $boardId);
     if (!$oldBoard || !$newBoard) {
         return false;
     }
     $this->addOne($newBoard);
     if ($this->save()) {
         /* readjust all posts */
         $posts = $this->getMany('Posts');
         foreach ($posts as $post) {
             $post->set('board', $newBoard->get('id'));
             $post->save();
         }
         /* adjust old board topics/reply counts */
         $oldBoard->set('num_topics', $oldBoard->get('num_topics') - 1);
         $replies = $oldBoard->get('num_replies') - $this->get('replies');
         $oldBoard->set('num_replies', $replies);
         $total_posts = $oldBoard->get('total_posts') - $this->get('replies') - 1;
         $oldBoard->set('total_posts', $total_posts);
         /* recalculate latest post */
         $oldBoardLastPost = $this->xpdo->getObject('disPost', array('id' => $oldBoard->get('last_post')));
         if ($oldBoardLastPost && $oldBoardLastPost->get('id') == $this->get('post_last')) {
             $newLastPost = $oldBoard->get2ndLatestPost();
             if ($newLastPost) {
                 $oldBoard->set('last_post', $newLastPost->get('id'));
                 $oldBoard->addOne($newLastPost, 'LastPost');
             }
         }
         $oldBoard->save();
         /* adjust new board topics/reply counts */
         $newBoard->set('num_topics', $oldBoard->get('num_topics') - 1);
         $replies = $newBoard->get('num_replies') + $this->get('replies');
         $newBoard->set('num_replies', $replies);
         $total_posts = $newBoard->get('total_posts') + $this->get('replies') + 1;
         $newBoard->set('total_posts', $total_posts);
         /* recalculate latest post */
         $newBoardLastPost = $this->xpdo->getObject('disPost', array('id' => $newBoard->get('last_post')));
         $thisThreadPost = $this->getOne('LastPost');
         if ($newBoardLastPost && $thisThreadPost && $newBoardLastPost->get('createdon') < $thisThreadPost->get('createdon')) {
             $newBoard->set('last_post', $thisThreadPost->get('id'));
             $newBoard->addOne($thisThreadPost, 'LastPost');
         }
         $newBoard->save();
         /* Update ThreadRead board field */
         $this->xpdo->exec('UPDATE ' . $this->xpdo->getTableName('disThreadRead') . '
             SET ' . $this->xpdo->escape('board') . ' = ' . $newBoard->get('id') . '
             WHERE ' . $this->xpdo->escape('thread') . ' = ' . $this->get('id') . '
         ');
         /* clear caches */
         if (!defined('DISCUSS_IMPORT_MODE')) {
             $this->xpdo->getCacheManager();
             $this->xpdo->cacheManager->delete('discuss/thread/' . $this->get('id'));
             $this->xpdo->cacheManager->delete('discuss/board/' . $newBoard->get('id'));
             $this->xpdo->cacheManager->delete('discuss/board/' . $oldBoard->get('id'));
         }
     }
     return true;
 }
 /**
  * Gets an array of emails for all moderators of this thread
  * 
  * @return array
  */
 public function getModeratorEmails()
 {
     $moderatorNames = $this->get('moderators');
     $moderatorNames = explode(',', $moderatorNames);
     $moderators = array();
     foreach ($moderatorNames as $name) {
         $c = $this->xpdo->newQuery('modUser');
         $c->innerJoin('modUserProfile', 'Profile');
         $c->select(array('modUser.id', 'Profile.email'));
         $c->where(array('username' => $name));
         $user = $this->xpdo->getObject('modUser', $c);
         if ($user) {
             $moderators[] = $user->get('email');
         }
     }
     /* now get usergroup moderators */
     $moderatorGroup = $this->get('moderator_group');
     $c = $this->xpdo->newQuery('modUserProfile');
     $c->innerJoin('modUser', 'User');
     $c->innerJoin('modUserGroupMember', 'UserGroupMembers', 'User.id = UserGroupMembers.member');
     $c->innerJoin('modUserGroup', 'UserGroup', 'UserGroup.id = UserGroupMembers.user_group');
     $c->where(array('UserGroup.name' => $moderatorGroup));
     $members = $this->xpdo->getCollection('modUserProfile', $c);
     foreach ($members as $member) {
         $email = $member->get('email');
         if (!empty($email)) {
             array_push($moderators, $email);
         }
     }
     $moderators = array_unique($moderators);
     return $moderators;
 }
 /**
  * Sends notification email to moderators telling them the comment is awaiting approval.
  *
  * @return boolean True if successful
  */
 public function notifyModerators()
 {
     if (!$this->_loadLexicon()) {
         return false;
     }
     $this->xpdo->lexicon->load('quip:emails');
     /** @var quipThread $thread */
     $thread = $this->getOne('Thread');
     if (!$thread) {
         return false;
     }
     $properties = $this->toArray();
     $properties['url'] = $this->makeUrl('', array(), array('scheme' => 'full'));
     /**
      * Get the Quip mgr action
      * @var modAction $action
      */
     $action = $this->xpdo->getObject('modAction', array('controller' => 'index', 'namespace' => 'quip'));
     if ($action) {
         $managerUrl = MODX_URL_SCHEME . MODX_HTTP_HOST . MODX_MANAGER_URL;
         $properties['approveUrl'] = $managerUrl . '?a=' . $action->get('id') . '&quip_unapproved=1&quip_approve=' . $this->get('id');
         $properties['rejectUrl'] = $managerUrl . '?a=' . $action->get('id') . '&quip_unapproved=1&quip_reject=' . $this->get('id');
         $properties['unapprovedUrl'] = $managerUrl . '?a=' . $action->get('id') . '&quip_unapproved=1';
     }
     $body = $this->xpdo->lexicon('quip.email_moderate', $properties);
     $subject = $this->xpdo->lexicon('quip.email_moderate_subject');
     $success = true;
     $moderators = $thread->getModeratorEmails();
     if (!empty($moderators)) {
         $success = $this->sendEmail($subject, $body, $moderators);
     }
     return $success;
 }
Exemple #18
0
 /**
  * Redirect to a specified URL.
  *
  * Properties needed:
  * - redirectTo - the ID of the Resource to redirect to.
  *
  * @param array $fields An array of cleaned POST fields
  * @return boolean False if unsuccessful.
  */
 public function redirect(array $fields = array())
 {
     if (empty($this->formit->config['redirectTo'])) {
         return false;
     }
     $redirectParams = !empty($this->formit->config['redirectParams']) ? $this->formit->config['redirectParams'] : '';
     if (!empty($redirectParams)) {
         $prefix = $this->modx->getOption('placeholderPrefix', $this->formit->config, 'fi.');
         $this->modx->setPlaceholders($fields, $prefix);
         $this->modx->parser->processElementTags('', $redirectParams, true, true);
         $redirectParams = $this->modx->fromJSON($redirectParams);
         if (empty($redirectParams)) {
             $redirectParams = '';
         }
     }
     $contextKey = $this->modx->context->get('key');
     $resource = $this->modx->getObject('modResource', $this->formit->config['redirectTo']);
     if ($resource) {
         $contextKey = $resource->get('context_key');
     }
     if (!is_numeric($this->formit->config['redirectTo']) && isset($fields[$this->formit->config['redirectTo']]) && is_numeric($fields[$this->formit->config['redirectTo']])) {
         $url = $this->modx->makeUrl($fields[$this->formit->config['redirectTo']], $contextKey, $redirectParams, 'full');
     } elseif (!is_numeric($this->formit->config['redirectTo']) && substr($this->formit->config['redirectTo'], 0, 4) === "http") {
         $url = $this->formit->config['redirectTo'];
     } else {
         $url = $this->modx->makeUrl($this->formit->config['redirectTo'], $contextKey, $redirectParams, 'full');
     }
     $this->setRedirectUrl($url);
     return true;
 }
 /**
  * Allow user to prepare single row by custom snippet before render chunk
  * This method was developed in cooperation with Agel_Nash
  *
  * @param array $row
  *
  * @return array
  */
 public function prepareRow($row = array())
 {
     if ($this->preparing) {
         return $row;
     }
     if (!empty($this->config['prepareSnippet'])) {
         $this->preparing = true;
         $name = trim($this->config['prepareSnippet']);
         /** @var modSnippet $snippet */
         if (!($snippet = $this->getStore($name, 'snippet'))) {
             if ($snippet = $this->modx->getObject('modSnippet', array('name' => $name))) {
                 $this->setStore($name, $snippet, 'snippet');
             } else {
                 $this->addTime('Could not load snippet "' . $name . '" for preparation of row.');
                 return '';
             }
         }
         $snippet->_cacheable = false;
         $snippet->_processed = false;
         $tmp = $snippet->process(array('pdoTools' => $this, 'pdoFetch' => $this, 'row' => $row));
         $tmp = $tmp[0] == '[' || $tmp[0] == '{' ? $this->modx->fromJSON($tmp, 1) : unserialize($tmp);
         if (!is_array($tmp)) {
             $this->addTime('Preparation snippet must return an array, instead of "' . gettype($tmp) . '"');
         } else {
             $row = array_merge($row, $tmp);
         }
         $this->preparing = false;
     }
     return $row;
 }
 /**
  * Setup this resource as an archive so that FURLs can be effectively mapped
  *
  * @param integer $resourceId The ID of the resource to allow as an archive
  * @param string $prefix The filterPrefix used by that archive
  */
 public function makeArchive($resourceId, $prefix = 'arc_')
 {
     $value = $resourceId . ':' . $prefix;
     $isNew = false;
     $setting = $this->modx->getObject('modSystemSetting', array('key' => 'archivist.archive_ids'));
     if (!$setting) {
         /** @var modSystemSetting $setting */
         $setting = $this->modx->newObject('modSystemSetting');
         $setting->fromArray(array('key' => 'archivist.archive_ids', 'namespace' => 'archivist', 'area' => 'furls', 'xtype' => 'textfield'), '', true, true);
         $isNew = true;
     } else {
         $oldValue = $setting->get('value');
         if (strpos($oldValue, $resourceId . ':') !== false) {
             /* dont append if already there */
             $value = $oldValue;
         } else {
             $value = $oldValue . ',' . $value;
         }
     }
     $setting->set('value', $value);
     $saved = $setting->save();
     if ($isNew) {
         $this->_clearCache();
     }
     return $saved;
 }
 public static function getInstance(modX &$modx, $className, $properties = array())
 {
     $object = $modx->getObject('modResource', $properties['id']);
     $classKey = !empty($properties['class_key']) ? $properties['class_key'] : ($object ? $object->get('class_key') : 'modDocument');
     $className = 'msProductDisableCacheUpdateProcessor';
     $processor = new $className($modx, $properties);
     return $processor;
 }
 /**
  * Parse a chunk (with template bindings)
  * Modified parseTplElement method from getResources package (https://github.com/opengeek/getResources)
  *
  * @param $type
  * @param $source
  * @param null $properties
  * @return bool
  */
 private function parseChunk($type, $source, $properties = null)
 {
     $output = false;
     if (!is_string($type) || !in_array($type, $this->_validTypes)) {
         $type = $this->modx->getOption('tplType', $properties, '@CHUNK');
     }
     $content = false;
     switch ($type) {
         case '@FILE':
             $path = $this->modx->getOption('tplPath', $properties, $this->modx->getOption('assets_path', $properties, MODX_ASSETS_PATH) . 'elements/chunks/');
             $key = $path . $source;
             if (!isset($this->_tplCache['@FILE'])) {
                 $this->_tplCache['@FILE'] = array();
             }
             if (!array_key_exists($key, $this->_tplCache['@FILE'])) {
                 if (file_exists($key)) {
                     $content = file_get_contents($key);
                 }
                 $this->_tplCache['@FILE'][$key] = $content;
             } else {
                 $content = $this->_tplCache['@FILE'][$key];
             }
             if (!empty($content) && $content !== '0') {
                 $chunk = $this->modx->newObject('modChunk', array('name' => $key));
                 $chunk->setCacheable(false);
                 $output = $chunk->process($properties, $content);
             }
             break;
         case '@INLINE':
             $uniqid = uniqid();
             $chunk = $this->modx->newObject('modChunk', array('name' => "{$type}-{$uniqid}"));
             $chunk->setCacheable(false);
             $output = $chunk->process($properties, $source);
             break;
         case '@CHUNK':
         default:
             $chunk = null;
             if (!isset($this->_tplCache['@CHUNK'])) {
                 $this->_tplCache['@CHUNK'] = array();
             }
             if (!array_key_exists($source, $this->_tplCache['@CHUNK'])) {
                 if ($chunk = $this->modx->getObject('modChunk', array('name' => $source))) {
                     $this->_tplCache['@CHUNK'][$source] = $chunk->toArray('', true);
                 } else {
                     $this->_tplCache['@CHUNK'][$source] = false;
                 }
             } elseif (is_array($this->_tplCache['@CHUNK'][$source])) {
                 $chunk = $this->modx->newObject('modChunk');
                 $chunk->fromArray($this->_tplCache['@CHUNK'][$source], '', true, true, true);
             }
             if (is_object($chunk)) {
                 $chunk->setCacheable(false);
                 $output = $chunk->process($properties);
             }
             break;
     }
     return $output;
 }
 /**
  * Gets matching resources by tags. This is adapted function from miniShop1 for backward compatibility
  * @deprecated
  *
  * @param array $tags Tags for search
  * @param int $only_ids Return only ids of matched resources
  * @param int $strict 0 - goods must have at least one specified tag
  *					  1 - goods must have all specified tags, but can have more
  * 					  2 - goods must have exactly the same tags.
  * @return array $ids Or array with resources with data and tags
  */
 function getTagged($tags = array(), $strict = 0, $only_ids = 0)
 {
     if (!is_array($tags)) {
         $tags = explode(',', $tags);
     }
     $q = $this->modx->newQuery('msProductOption', array('key' => 'tags', 'value:IN' => $tags));
     $q->select('product_id');
     $ids = array();
     if ($q->prepare() && $q->stmt->execute()) {
         $ids = $q->stmt->fetchAll(PDO::FETCH_COLUMN);
     }
     $ids = array_unique($ids);
     // If needed only ids of not strictly mathed items - return.
     if (!$strict && $only_ids) {
         return $ids;
     }
     // Filtering ids
     $count = count($tags);
     /* @var PDOStatement $stmt*/
     if ($strict) {
         foreach ($ids as $key => $product_id) {
             if ($strict > 1) {
                 $sql = "SELECT COUNT(*) FROM {$this->modx->getTableName('msProductOption')} WHERE `product_id` = {$product_id} AND `key` = 'tags';";
                 $stmt = $this->modx->prepare($sql);
                 $stmt->execute();
                 if ($stmt->fetch(PDO::FETCH_COLUMN) != $count) {
                     unset($ids[$key]);
                     continue;
                 }
             }
             foreach ($tags as $tag) {
                 $sql = "SELECT COUNT(`product_id`) FROM {$this->modx->getTableName('msProductOption')} WHERE `product_id` = {$product_id} AND `key` = 'tags' AND `value` = '{$tag}';";
                 $stmt = $this->modx->prepare($sql);
                 $stmt->execute();
                 if (!$stmt->fetch(PDO::FETCH_COLUMN)) {
                     unset($ids[$key]);
                     break;
                 }
             }
         }
     }
     // Return strictly ids, if needed
     $ids = array_unique($ids);
     if ($only_ids) {
         return $ids;
     }
     // Process results
     $data = array();
     foreach ($ids as $id) {
         if (!$only_ids) {
             if ($res = $this->modx->getObject('msProduct', $id)) {
                 $data[$id] = $res->toArray();
             }
         }
     }
     return $data;
 }
 /**
  * Checks that an event code is valid
  */
 private function eventcode($key, $value)
 {
     if ($regType = $this->modx->getObject('RSVPMeRegType', array('code' => $value))) {
         if (strtotime($regType->end) <= time()) {
             return $this->modx->lexicon('rsvpme.event_code_expired');
         }
         return true;
     }
     return $this->modx->lexicon('rsvpme.event_code_nf');
 }
 /**
  * Get the path of the specified Namespace
  *
  * @param string $namespace The key of the Namespace
  * @return string The path for the Namespace
  */
 public function getNamespacePath($namespace = 'core') {
     $corePath = $this->modx->getOption('core_path',null,MODX_CORE_PATH);
     if ($namespace != 'core') {
         $namespaceObj = $this->modx->getObject('modNamespace',$namespace);
         if ($namespaceObj) {
             $corePath = $namespaceObj->get('path');
         }
     }
     return $corePath;
 }
 /**
  * @param string $ctx
  * @param $source
  *
  * @return bool|null|object
  */
 public function initializeMediaSource($ctx = '', $source)
 {
     if ($this->mediaSource = $this->modx->getObject('sources.modMediaSource', $source)) {
         $this->mediaSource->set('ctx', $ctx);
         $this->mediaSource->initialize();
         return $this->mediaSource;
     } else {
         return false;
     }
 }
 public function findCategory(array $path, $root)
 {
     $currentParent = $root;
     $category = null;
     foreach ($path as $name) {
         $category = $this->modx->getObject('modCategory', array('parent' => $currentParent, 'category' => $name));
         $currentParent = $category->id;
     }
     return $category->id;
 }
Exemple #28
-1
 public function init()
 {
     if (isset($this->sp['resource'])) {
         if (!$this->sp['resource']->richtext) {
             return false;
         }
     }
     $useEditor = $this->modx->getOption('use_editor', false);
     $whichEditor = $this->modx->getOption('which_editor', '');
     if ($useEditor && $whichEditor != 'MarkdownEditor') {
         $initCondition = $this->md->getOption('init.condition');
         if (empty($initCondition)) {
             $initCondition = '[]';
         }
         $initCondition = $this->modx->fromJSON($initCondition);
         if (!empty($initCondition)) {
             $c = $this->modx->newQuery('modResource');
             $c->where([['id' => $this->sp['resource']->id], $initCondition]);
             $check = $this->modx->getObject('modResource', $c);
             if ($check) {
                 $this->modx->setOption('which_editor', 'MarkdownEditor');
                 $whichEditor = 'MarkdownEditor';
             }
         }
     }
     if ($useEditor && $whichEditor == 'MarkdownEditor') {
         return true;
     }
     return false;
 }
 /**
  * Migrate ignore boards into Users
  * 
  * @return void
  */
 public function migrateIgnoreBoards()
 {
     $this->log('Migrating Ignore Boards...');
     $this->log('Collecting User cache...');
     $c = $this->modx->newQuery('disUser');
     $c->sortby('username', 'ASC');
     $c->where(array('ignore_boards:!=' => ''));
     $users = $this->modx->getCollection('disUser', $c);
     /** @var disUser $user */
     foreach ($users as $user) {
         $boards = explode(',', $user->get('ignore_boards'));
         if (!empty($boards)) {
             $this->log('Migrating ' . count($boards) . ' boards for ' . $user->get('username'));
             $newBoards = array();
             foreach ($boards as $board) {
                 /** @var disBoard $b */
                 $b = $this->modx->getObject('disBoard', array('integrated_id' => $board));
                 if ($b) {
                     $newBoards[] = $b->get('id');
                 }
             }
             if (!empty($newBoards)) {
                 $user->set('ignore_boards', implode(',', $newBoards));
                 if ($this->config['live']) {
                     $user->save();
                 }
             }
         }
     }
 }
 /**
  * Validates a field based on a custom rule, if specified
  *
  * @access public
  * @param string $key The key of the field
  * @param mixed $value The value of the field
  * @param string $type Optional. The type of the validator to apply. Can
  * either be a method name of fiValidator or a Snippet name.
  * @return boolean True if validation was successful. If not, will store
  * error messages to $this->errors.
  */
 public function validate($key, $value, $type = '')
 {
     /** @var boolean|array $validated */
     $validated = false;
     /** @var mixed $value Trim spaces from the value before validating **/
     if (!empty($this->config['trim_values_before_validation'])) {
         $value = trim($value);
     }
     /** @var boolean $hasParams */
     $hasParams = $this->config['use_multibyte'] ? mb_strpos($type, '=', 0, $this->config['encoding']) : strpos($type, '=');
     /** @var string|null $param The parameter value, if one is set */
     $param = null;
     if ($hasParams !== false) {
         $len = $this->config['use_multibyte'] ? mb_strlen($type, $this->config['encoding']) : strlen($type);
         $s = $this->config['use_multibyte'] ? mb_substr($type, $hasParams + 1, $len, $this->config['encoding']) : substr($type, $hasParams + 1, $len);
         $param = str_replace(array('`', '^'), '', $s);
         $type = $this->config['use_multibyte'] ? mb_substr($type, 0, $hasParams, $this->config['encoding']) : substr($type, 0, $hasParams);
     }
     /** @var array $invNames An array of invalid hook names to skip */
     $invNames = array('validate', 'validateFields', 'addError', '__construct');
     $customValidators = !empty($this->config['customValidators']) ? $this->config['customValidators'] : '';
     $customValidators = explode(',', $customValidators);
     if (method_exists($this, $type) && !in_array($type, $invNames)) {
         /* built-in validator */
         $validated = $this->{$type}($key, $value, $param);
         /* only allow specified validators to prevent brute force execution of unwanted snippets */
     } else {
         if (in_array($type, $customValidators)) {
             /* attempt to grab custom validator */
             /** @var modSnippet|null $snippet */
             $snippet = $this->modx->getObject('modSnippet', array('name' => $type));
             if ($snippet) {
                 /* custom snippet validator */
                 $props = array_merge($this->formit->config, array('key' => $key, 'value' => $value, 'param' => $param, 'type' => $type, 'validator' => &$this, 'errors' => &$this->errors));
                 $validated = $snippet->process($props);
             } else {
                 /* no validator found */
                 $this->modx->log(modX::LOG_LEVEL_ERROR, '[FormIt] Could not find validator "' . $type . '" for field "' . $key . '".');
                 $validated = true;
             }
         } else {
             $this->modx->log(modX::LOG_LEVEL_INFO, '[FormIt] Validator "' . $type . '" for field "' . $key . '" was not specified in the customValidators property.');
             $validated = true;
         }
     }
     /** handle return value errors */
     if (!empty($validated)) {
         if (is_array($validated)) {
             foreach ($validated as $key => $errMsg) {
                 $this->addError($key, $errMsg);
             }
             $validated = false;
         } elseif ($validated !== '1' && $validated !== 1 && $validated !== true) {
             $this->addError($key, $validated);
             $validated = false;
         }
     }
     return $validated;
 }