/**
  * Abstract method for routing GET requests without a primary key passed. Must be defined in your derivative
  * controller. Handles fetching of collections of objects.
  *
  * @abstract
  * @return array
  */
 public function getList()
 {
     $this->getProperties();
     $c = $this->modx->newQuery($this->classKey);
     $c = $this->addSearchQuery($c);
     $c = $this->prepareListQueryBeforeCount($c);
     $total = $this->modx->getCount($this->classKey, $c);
     $alias = !empty($this->classAlias) ? $this->classAlias : $this->classKey;
     $c->select($this->modx->getSelectColumns($this->classKey, $alias));
     $c = $this->prepareListQueryAfterCount($c);
     $c->sortby($this->getProperty($this->getOption('propertySort', 'sort'), $this->defaultSortField), $this->getProperty($this->getOption('propertySortDir', 'dir'), $this->defaultSortDirection));
     $limit = $this->getProperty($this->getOption('propertyLimit', 'limit'), $this->defaultLimit);
     if (empty($limit)) {
         $limit = $this->defaultLimit;
     }
     $c->limit($limit, $this->getProperty($this->getOption('propertyOffset', 'start'), $this->defaultOffset));
     $objects = $this->modx->getCollection($this->classKey, $c);
     if (empty($objects)) {
         $objects = array();
     }
     $list = array();
     /** @var xPDOObject $object */
     foreach ($objects as $object) {
         $list[] = $this->prepareListObject($object);
     }
     return $this->collection($list, $total);
 }
Ejemplo n.º 2
3
 /**
  * Loads all system settings that start with the configured namespace.
  *
  * @return array
  */
 public function loadSettingsFromNamespace()
 {
     $ns = $this->namespace;
     $config = array();
     $corePath = $this->modx->getOption($ns . '.core_path', null, MODX_CORE_PATH . 'components/' . $ns . '/');
     $config['core_path'] = $corePath;
     $config['templates_path'] = $corePath . 'templates/';
     $config['controllers_path'] = $corePath . 'controllers/';
     $config['model_path'] = $corePath . 'model/';
     $config['processors_path'] = $corePath . 'processors/';
     $config['elements_path'] = $corePath . 'elements/';
     $assetsUrl = $this->modx->getOption($ns . '.assets_url', null, MODX_ASSETS_URL . 'components/' . $ns . '/');
     $config['assets_url'] = $assetsUrl;
     $config['connector_url'] = $assetsUrl . ' connector.php';
     $c = $this->modx->newQuery('modSystemSetting');
     $c->where(array('key:LIKE' => $ns . '.%'));
     $c->limit(0);
     /** @var \modSystemSetting[] $iterator */
     $iterator = $this->modx->getIterator('modSystemSetting', $c);
     foreach ($iterator as $setting) {
         $key = $setting->get('key');
         $key = substr($key, strlen($ns) + 1);
         $config[$key] = $setting->get('value');
     }
     return $config;
 }
Ejemplo n.º 3
2
 /**
  * Get all names of template from provider
  * @return array|\Iterator
  */
 public function getList()
 {
     $c = $this->modx->newQuery('modTemplate');
     $c->select('templatename');
     if ($c->prepare() && $c->stmt->execute()) {
         return $c->stmt->fetchAll(PDO::FETCH_COLUMN);
     }
     return array();
 }
Ejemplo n.º 4
1
 /** @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;
 }
Ejemplo n.º 5
0
 function getStats()
 {
     $output = '';
     $q_status = $this->modx->newQuery('msOrderStatus', array('active' => 1));
     $q_status->select('id,name,color');
     if ($q_status->prepare() && $q_status->stmt->execute()) {
         while ($row = $q_status->stmt->fetch(PDO::FETCH_ASSOC)) {
             //$output[$row['id']] = $row;
             $output['total_counts'][$row['id']] = array('name' => $row['name'], 'color' => $row['color'], 'count_orders' => $this->modx->getCount('msOrder', array('status' => $row['id'])));
         }
     }
     $q_stats_month = $this->modx->newQuery('msOrder');
     $q_stats_month->select('status,`createdon`, month(`createdon`) AS `order_month`, count(*) AS `order_count`, SUM(cart_cost) AS order_cost');
     $q_stats_month->groupby('month(`createdon`), status');
     $q_stats_month->sortby('createdon', ASC);
     if ($q_stats_month->prepare() && $q_stats_month->stmt->execute()) {
         $output['cart_cost'] = 0;
         $output['cart_count'] = 0;
         while ($row = $q_stats_month->stmt->fetch(PDO::FETCH_ASSOC)) {
             $date = date_parse($row['createdon']);
             $output['stats_month'][$date['year'] . '-' . $date['month']][$row['status']] = array('total_cost' => $row['order_cost'], 'count_orders' => $row['order_count'], 'status' => $row['status']);
             $output['cart_cost'] += $row['order_cost'];
             $output['cart_count'] += $row['order_count'];
         }
         $output['cart_cost'] = number_format($output['cart_cost'], 2, ',', ' ');
         $output['users_count'] = $this->modx->getCount('modUser', array('active' => 1, 'primary_group' => 0));
     }
     return $output;
 }
Ejemplo n.º 6
0
 /**
  * Create conversations map
  *
  * @return array|false False if cache is off
  */
 public function conversationsMap()
 {
     /**
      * If disabled caching return False
      */
     if (!$this->modx->getCacheManager()) {
         return false;
     }
     /**
      * If a map is present in the cache, then just return it
      */
     $map = $this->modx->cacheManager->get('conversations_map', array(xPDO::OPT_CACHE_KEY => 'modxtalks'));
     if ($map) {
         return $map;
     }
     /**
      * If the map is not in the cache, we all topics from the database and build the map
      */
     $map = array();
     $c = $this->modx->newQuery('modxTalksConversation');
     $c->select(array('id', 'rid', 'conversation'));
     if ($c->prepare() && $c->stmt->execute()) {
         $conversations = $c->stmt->fetchAll(PDO::FETCH_ASSOC);
         foreach ($conversations as $c) {
             $map[$c['rid']][$c['id']] = $c['conversation'];
         }
         $this->modx->cacheManager->set('conversations_map', $map, 0, array(xPDO::OPT_CACHE_KEY => 'modxtalks'));
     }
     return $map;
 }
Ejemplo n.º 7
0
 /**
  * Fetch all posts for this thread
  *
  * @param mixed $post A reference to a disPost or ID of disPost to start the posts from
  * @param array $options An array of options for sorting, limiting and display
  * @return array
  */
 public function fetchPosts($post = false, array $options = array())
 {
     $response = array();
     $c = $this->xpdo->newQuery('disPost');
     $c->innerJoin('disThread', 'Thread');
     $c->where(array('thread' => $this->get('id')));
     $response['total'] = $this->xpdo->discuss->controller->getPostCount('disThread', $this->get('id'));
     $flat = $this->xpdo->getOption('flat', $options, true);
     $limit = $this->xpdo->getOption('limit', $options, (int) $this->xpdo->getOption('discuss.post_per_page', $options, 10));
     $start = $this->xpdo->getOption('start', $options, 0);
     if ($flat) {
         $sortBy = $this->xpdo->getOption('sortBy', $options, 'createdon');
         $sortDir = $this->xpdo->getOption('sortDir', $options, 'ASC');
         $c->sortby($this->xpdo->getSelectColumns('disPost', 'disPost', '', array($sortBy)), $sortDir);
         if (empty($_REQUEST['print'])) {
             $c->limit($limit, $start);
         }
     } else {
         $c->sortby($this->xpdo->getSelectColumns('disPost', 'disPost', '', array('rank')), 'ASC');
     }
     if (!empty($post)) {
         if (!is_object($post)) {
             $post = $this->xpdo->getObject('disPost', $post);
         }
         if ($post) {
             $c->where(array('disPost.createdon:>=' => $post->get('createdon')));
         }
     }
     $c->bindGraph('{"Author":{"PrimaryDiscussGroup":{},"PrimaryGroup":{}},"EditedBy":{}}');
     //$c->prepare();
     //$cacheKey = 'discuss/thread/'.$thread->get('id').'/'.md5($c->toSql());
     $response['results'] = $this->xpdo->getCollectionGraph('disPost', '{"Author":{"PrimaryDiscussGroup":{},"PrimaryGroup":{}},"EditedBy":{}}', $c);
     return $response;
 }
Ejemplo n.º 8
0
 /**
  * @param $string
  *
  * @return mixed
  */
 public function addAliases($string)
 {
     $string = mb_strtoupper(str_ireplace('ё', 'е', $this->modx->stripTags($string)), 'UTF-8');
     $string = preg_replace('#\\[.*\\]#isU', '', $string);
     $pcre = $this->config['split_words'];
     $words = preg_split($pcre, $string, -1, PREG_SPLIT_NO_EMPTY);
     $words = array_unique($words);
     $forms = $this->getBaseForms($words, false);
     $q = $this->modx->newQuery('mseAlias', array('word:IN' => array_merge($words, array_keys($forms))));
     $q->select('word,alias,replace');
     $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)) {
             if ($row['replace']) {
                 $all = current($this->getAllForms($row['word']));
                 $all[] = $row['word'];
                 foreach ($all as $word) {
                     $key = array_search(mb_strtolower($word), $words);
                     if ($key !== false) {
                         $words[$key] = $row['alias'];
                     }
                 }
             } else {
                 $words[] = $row['alias'];
             }
         }
     }
     $words = array_unique($words);
     return implode(' ', $words);
 }
Ejemplo n.º 9
0
 /**
  * Get total post count
  * @param string $class
  * @param int $id
  * return int
  */
 public function getPostCount($className = 'disBoard', $id = 0)
 {
     $c = $this->modx->newQuery($className);
     if ($className == 'disBoard') {
         if (!$id) {
             $c->select(array('post_count' => "SUM({$this->modx->escape('disBoard')}.{$this->modx->escape('total_posts')})"));
         } else {
             $c->select(array($this->modx->getSelectColumns('disBoard', 'disBoard', '', array('post_count'))));
             $c->where(array('id' => $id));
         }
     } else {
         if ($className == 'disThread') {
             $c->select(array($this->modx->getSelectColumns('disThread', 'disThread', '', array('replies'))));
             $c->where(array('id' => $id));
         }
     }
     if ($stmt = $c->prepare()) {
         if ($stmt->execute()) {
             if ($results = $stmt->fetchAll(PDO::FETCH_COLUMN)) {
                 $count = reset($results);
                 $count = intval($count);
             }
         }
     }
     return !$results ? 0 : $className == 'disBoard' ? $count : $count + 1;
     // +1 for original thread start post
 }
Ejemplo n.º 10
0
 /**
  * Verification of resource status
  *
  * @param int $id
  *
  * @return bool|int
  */
 public function checkResource($id = 0)
 {
     $tmp = array();
     if (empty($this->pdoTools->config['showHidden'])) {
         $tmp['hidemenu'] = 0;
     }
     if (empty($this->pdoTools->config['showUnpublished'])) {
         $tmp['published'] = 1;
     }
     if (!empty($this->pdoTools->config['hideUnsearchable'])) {
         $tmp['searchable'] = 1;
     }
     if (!empty($tmp)) {
         $tmp['id'] = $id;
         $q = $this->modx->newQuery('modResource', $tmp);
         $q->select('id');
         $tstart = microtime(true);
         if ($q->prepare() && $q->stmt->execute()) {
             $this->modx->queryTime += microtime(true) - $tstart;
             $this->modx->executedQueries++;
             $res = $q->stmt->fetch(PDO::FETCH_COLUMN);
             return (bool) $res;
         }
     }
     return true;
 }
 /**
  * Refresh Resource URI fields for children of the specified parent.
  *
  * @static
  * @param modX &$modx A reference to a valid modX instance.
  * @param int $parent The id of a Resource parent to start from (default is 0, the root)
  * @param array $options An array of various options for the method:
  *      - resetOverrides: if true, Resources with uri_override set to true will be included
  *      - contexts: an optional array of context keys to limit the refresh scope
  * @return void
  */
 public static function refreshURIs(modX &$modx, $parent = 0, array $options = array())
 {
     $resetOverrides = array_key_exists('resetOverrides', $options) ? (bool) $options['resetOverrides'] : false;
     $contexts = array_key_exists('contexts', $options) ? explode(',', $options['contexts']) : null;
     $criteria = $modx->newQuery('linguaSiteContent');
     $criteria->where(array('lang_id' => $options['lang_id'], 'parent' => $parent));
     if (!$resetOverrides) {
         $criteria->where(array('uri_override' => false));
     }
     if (!empty($contexts)) {
         $criteria->where(array('context_key:IN' => $contexts));
     }
     /** @var Resource $resource */
     $resources = $modx->getIterator('linguaSiteContent', $criteria);
     foreach ($resources as $resource) {
         $resource->set('refreshURIs', true);
         if ($resetOverrides) {
             $resource->set('uri_override', false);
         }
         if (!$resource->get('uri_override')) {
             $resource->set('uri', '');
         }
         $resource->save();
     }
 }
Ejemplo n.º 12
0
 /**
  * Overrides xPDOObject::save to handle closure table edits.
  *
  * @param boolean $cacheFlag
  * @return boolean
  */
 public function save($cacheFlag = null)
 {
     $new = $this->isNew();
     if ($new) {
         if (!$this->get('createdon')) {
             $this->set('createdon', strftime('%Y-%m-%d %H:%M:%S'));
         }
         $ip = $this->get('ip');
         if (empty($ip) && !empty($_SERVER['REMOTE_ADDR'])) {
             $this->set('ip', $_SERVER['REMOTE_ADDR']);
         }
     }
     $saved = parent::save($cacheFlag);
     if ($saved && $new) {
         $id = $this->get('id');
         $parent = $this->get('parent');
         /* create self closure */
         $cl = $this->xpdo->newObject('quipCommentClosure');
         $cl->set('ancestor', $id);
         $cl->set('descendant', $id);
         if ($cl->save() === false) {
             $this->remove();
             return false;
         }
         /* create closures and calculate rank */
         $c = $this->xpdo->newQuery('quipCommentClosure');
         $c->where(array('descendant' => $parent, 'ancestor:!=' => 0));
         $c->sortby('depth', 'DESC');
         $gparents = $this->xpdo->getCollection('quipCommentClosure', $c);
         $cgps = count($gparents);
         $gps = array();
         $i = $cgps;
         /** @var quipCommentClosure $gparent */
         foreach ($gparents as $gparent) {
             $gps[] = str_pad($gparent->get('ancestor'), 10, '0', STR_PAD_LEFT);
             /** @var quipCommentClosure $obj */
             $obj = $this->xpdo->newObject('quipCommentClosure');
             $obj->set('ancestor', $gparent->get('ancestor'));
             $obj->set('descendant', $id);
             $obj->set('depth', $i);
             $obj->save();
             $i--;
         }
         $gps[] = str_pad($id, 10, '0', STR_PAD_LEFT);
         /* add self closure too */
         /* add root closure */
         /** @var quipCommentClosure $cl */
         $cl = $this->xpdo->newObject('quipCommentClosure');
         $cl->set('ancestor', 0);
         $cl->set('descendant', $id);
         $cl->set('depth', $cgps);
         $cl->save();
         /* set rank */
         $rank = implode('-', $gps);
         $this->set('rank', $rank);
         $this->save();
     }
     return $saved;
 }
Ejemplo n.º 13
0
 /**
  * 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;
 }
Ejemplo n.º 14
0
 /** @inheritdoc} */
 public function getClientStatus()
 {
     $statuses = array();
     $q = $this->modx->newQuery('MlmSystemStatus', array('class' => 'MlmSystemClient', 'active' => 1));
     $q->sortby('rank', 'ASC');
     $q->select('id');
     if ($q->prepare() && $q->stmt->execute()) {
         $statuses = $q->stmt->fetchAll(PDO::FETCH_COLUMN);
     }
     return $statuses;
 }
Ejemplo n.º 15
0
 /**
  * Search and return array with resources that matched for LIKE search
  *
  * @param $query
  *
  * @return array
  */
 public function simpleSearch($query)
 {
     $string = preg_replace('/[^_-а-яёa-z0-9\\s\\.\\/]+/iu', ' ', $this->modx->stripTags($query));
     $result = array();
     $q = $this->modx->newQuery('mseIntro');
     $q->select('`resource`');
     $q->where(array('intro:LIKE' => '%' . $string . '%'));
     if ($q->prepare() && $q->stmt->execute()) {
         $result = $q->stmt->fetchAll(PDO::FETCH_COLUMN);
     }
     return $result;
 }
Ejemplo n.º 16
0
    /**
     * Loads a lexicon topic from the cache. If not found, tries to generate a
     * cache file from the database.
     *
     * @access public
     * @param string $namespace The namespace to load from. Defaults to 'core'.
     * @param string $topic The topic to load. Defaults to 'default'.
     * @param string $language The language to load. Defaults to 'en'.
     * @return array The loaded lexicon array.
     */
    public function loadCache($namespace = 'core', $topic = 'default', $language = '') {
        if (empty($language)) $language = $this->modx->getOption('cultureKey',null,'en');
        $key = $this->getCacheKey($namespace, $topic, $language);
        $enableCache = ($namespace != 'core' && !$this->modx->getOption('cache_noncore_lexicon_topics',null,true)) ? false : true;

        $cached = $this->modx->cacheManager->get($key, array(
            xPDO::OPT_CACHE_KEY => $this->modx->getOption('cache_lexicon_topics_key', null, 'lexicon_topics'),
            xPDO::OPT_CACHE_HANDLER => $this->modx->getOption('cache_lexicon_topics_handler', null, $this->modx->getOption(xPDO::OPT_CACHE_HANDLER)),
            xPDO::OPT_CACHE_FORMAT => (integer) $this->modx->getOption('cache_lexicon_topics_format', null, $this->modx->getOption(xPDO::OPT_CACHE_FORMAT, null, xPDOCacheManager::CACHE_PHP)),
        ));
        if (!$enableCache || $cached == null) {
            $results= false;

            /* load file-based lexicon */
            $results = $this->getFileTopic($language,$namespace,$topic);
            if ($results === false) { /* default back to en */
                $results = $this->getFileTopic('en',$namespace,$topic);
                if ($results === false) {
                    $results = array();
                }
            }

            /* get DB overrides */
            $c= $this->modx->newQuery('modLexiconEntry');
            $c->innerJoin('modNamespace','Namespace');
            $c->where(array(
                'modLexiconEntry.topic' => $topic,
                'modLexiconEntry.language' => $language,
                'Namespace.name' => $namespace,
            ));
            $c->sortby($this->modx->getSelectColumns('modLexiconEntry','modLexiconEntry','',array('name')),'ASC');
            $entries= $this->modx->getCollection('modLexiconEntry',$c);
            if (!empty($entries)) {
                foreach ($entries as $entry) {
                    $results[$entry->get('name')]= $entry->get('value');
                }
            }
            if ($enableCache) {
                $cached = $this->modx->cacheManager->generateLexiconTopic($key,$results);
            } else {
                $cached = $results;
            }
        }
        if (empty($cached)) {
            $this->modx->log(xPDO::LOG_LEVEL_DEBUG, "An error occurred while trying to cache {$key} (lexicon/language/namespace/topic)");
        }
        return $cached;
    }
Ejemplo n.º 17
0
 /**
  * @return array
  */
 public function smfGetContexts()
 {
     $contexts = array();
     $c = $this->modx->newQuery('modContext', array('key:!=' => 'mgr'));
     $c->select('key');
     $c->sortby('rank', 'ASC');
     $setting = $this->modx->getOption('smf_user_contexts');
     if (!empty($setting)) {
         $setting = array_map('trim', explode(',', $setting));
         $c->where(array('key:IN' => $setting));
     }
     if ($c->prepare() && $c->stmt->execute()) {
         $contexts = $c->stmt->fetchAll(PDO::FETCH_COLUMN);
     }
     return $contexts;
 }
Ejemplo n.º 18
0
 /**
  * Grabs context specific settings from the current namespace, and loads them into $this->config.
  * Also returns the newly overridden values in an array.
  *
  * @param $contextKey
  * @return array
  */
 public function loadContextSettingsFromNamespace($contextKey)
 {
     $config = array();
     $c = $this->modx->newQuery('modContextSetting');
     $c->where(array('context_key' => $contextKey, 'key:LIKE' => $this->namespace . '.%'));
     $c->limit(0);
     /** @var \modSystemSetting[] $iterator */
     $iterator = $this->modx->getIterator('modContextSetting', $c);
     foreach ($iterator as $setting) {
         $key = $setting->get('key');
         $key = substr($key, strlen($this->namespace) + 1);
         $config[$key] = $setting->get('value');
     }
     $this->config = array_merge($this->config, $config);
     return $config;
 }
Ejemplo n.º 19
0
 public function getQuery($currentParent)
 {
     /* build query */
     $c = $this->modx->newQuery('modResource');
     $c->leftJoin('modResource', 'Children');
     $c->select($this->modx->getSelectColumns('modResource', 'modResource'));
     $c->select(array('COUNT(Children.id) AS children'));
     $c->where(array('parent' => $currentParent));
     /* if restricting to contexts */
     if (!empty($this->config['context'])) {
         $ctxs = $this->prepareForIn($this->config['context']);
         $c->where(array('modResource.context_key:IN' => $ctxs));
     } else {
         $c->where(array('modResource.context_key' => $this->modx->context->get('key')));
     }
     /* if excluding resources */
     if (!empty($this->config['excludeResources'])) {
         $ex = $this->prepareForIn($this->config['excludeResources']);
         $c->where(array('modResource.id:NOT IN' => $ex));
     }
     /* if excluding all children of certain resources */
     if (!empty($this->config['excludeChildrenOf'])) {
         $excludingParents = is_array($this->config['excludeChildrenOf']) ? $this->config['excludeChildrenOf'] : explode(',', $this->config['excludeChildrenOf']);
         $excludedChildren = array();
         foreach ($excludingParents as $excludingParent) {
             $childrenIds = $this->modx->getChildIds($excludingParent, 10);
             $excludedChildren = array_merge($excludedChildren, $childrenIds);
         }
         $excludedChildren = array_unique($excludedChildren);
         $c->where(array('modResource.id:NOT IN' => $excludedChildren));
     }
     /* if restricting to templates */
     if (!empty($this->config['allowedtemplates'])) {
         $tpls = $this->prepareForIn($this->config['allowedtemplates']);
         $c->innerJoin('modTemplate', 'Template');
         $c->where(array('Template.' . $this->config['templateFilter'] . ':IN' => $tpls));
     }
     /* where filtering */
     if (!empty($this->config['where'])) {
         $where = is_array($this->config['where']) ? $this->config['where'] : $this->modx->fromJSON($this->config['where']);
         $c->where($where);
     }
     /* sorting/grouping */
     $c->sortby($this->config['sortBy'], $this->config['sortDir']);
     $c->groupby('modResource.id');
     return $c;
 }
Ejemplo n.º 20
0
 /**
  * @param $resource_id
  */
 public function rankResourceImages($resource_id)
 {
     $q = $this->modx->newQuery('msResourceFile', array('resource_id' => $resource_id, 'parent' => 0, 'type' => 'image'));
     $q->select('id');
     $q->sortby('rank ASC, createdon', 'ASC');
     if ($q->prepare() && $q->stmt->execute()) {
         $sql = '';
         $table = $this->modx->getTableName('msResourceFile');
         if ($ids = $q->stmt->fetchAll(PDO::FETCH_COLUMN)) {
             foreach ($ids as $k => $id) {
                 $sql .= "UPDATE {$table} SET `rank` = '{$k}' WHERE `type` = 'image' AND (`id` = '{$id}' OR `parent` = '{$id}');";
             }
         }
         $sql .= "ALTER TABLE {$table} ORDER BY `rank` ASC;";
         $this->modx->exec($sql);
     }
 }
Ejemplo n.º 21
0
 /**
  * @param bool|string $link_type
  * @param bool|int $parent
  */
 public function clearLinks($link_type = false, $parent = false)
 {
     $c = $this->modx->newQuery('modDevToolsLink');
     if ($link_type) {
         $c->where(array('link_type:LIKE' => $link_type . '-%'));
     }
     if ($parent) {
         $c->where(array('parent' => $parent));
     }
     $links = $this->modx->getIterator('modDevToolsLink', $c);
     /**
      * @var modDevToolsLink $link
      */
     foreach ($links as $link) {
         $link->remove();
     }
 }
function getResourceBypass(modX &$modx, $criteria)
{
    $resource = null;
    $c = $modx->newQuery('modResource');
    $c->select(array('id', 'published'));
    $c->where($criteria);
    $c->prepare();
    $sql = $c->toSql();
    $stmt = $modx->query($sql);
    if ($stmt && $stmt instanceof PDOStatement) {
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            $resource = $row;
        }
        $stmt->closeCursor();
    }
    return $resource;
}
Ejemplo n.º 23
0
 /**
  * Check to see if the
  * @param modUser|null $user
  * @param string $context
  * @return bool
  */
 public function checkResourceGroupAccess($user = null, $context = '')
 {
     $context = !empty($context) ? $context : '';
     $c = $this->xpdo->newQuery('modResourceGroup');
     $c->innerJoin('modTemplateVarResourceGroup', 'TemplateVarResourceGroups', array('TemplateVarResourceGroups.documentgroup = modResourceGroup.id', 'TemplateVarResourceGroups.tmplvarid' => $this->get('id')));
     $resourceGroups = $this->xpdo->getCollection('modResourceGroup', $c);
     $hasAccess = true;
     if (!empty($resourceGroups)) {
         $hasAccess = false;
         /** @var modResourceGroup $resourceGroup */
         foreach ($resourceGroups as $resourceGroup) {
             if ($resourceGroup->hasAccess($user, $context)) {
                 $hasAccess = true;
                 break;
             }
         }
     }
     return $hasAccess;
 }
 public static function listPackageVersions(modX &$modx, $criteria, $limit = 0, $offset = 0) {
     $result = array('collection' => array(), 'total' => 0);
     $c = $modx->newQuery('transport.modTransportPackage');
     $c->select($modx->getSelectColumns('transport.modTransportPackage','modTransportPackage'));
     $c->select(array('Provider.name AS provider_name'));
     $c->leftJoin('transport.modTransportProvider','Provider');
     $c->where($criteria);
     $result['total'] = $modx->getCount('modTransportPackage',$c);
     $c->sortby('modTransportPackage.version_major', 'DESC');
     $c->sortby('modTransportPackage.version_minor', 'DESC');
     $c->sortby('modTransportPackage.version_patch', 'DESC');
     $c->sortby('IF(modTransportPackage.release = "" OR modTransportPackage.release = "ga" OR modTransportPackage.release = "pl","z",modTransportPackage.release) DESC','');
     $c->sortby('modTransportPackage.release_index', 'DESC');
     if((int)$limit > 0) {
         $c->limit((int)$limit, (int)$offset);
     }
     $result['collection'] = $modx->getCollection('transport.modTransportPackage',$c);
     return $result;
 }
 /**
  * Search for package to satisfy a dependency.
  *
  * @param string $package The name of the dependent package.
  * @param string $constraint The version constraint the package must satisfy.
  * @param modTransportProvider|null $provider A reference which is set to the
  * modTransportProvider which satisfies the dependency.
  *
  * @return array|bool The metadata for the package version which satisfies the dependency, or FALSE.
  */
 public function findResolution($package, $constraint, &$provider = null)
 {
     $resolution = false;
     $conditions = array('active' => true);
     switch (strtolower($package)) {
         case 'php':
             /* you must resolve php dependencies manually */
             $this->xpdo->log(xPDO::LOG_LEVEL_WARN, "PHP version dependencies must be resolved manually", '', __METHOD__, __FILE__, __LINE__);
             break;
         case 'modx':
         case 'revo':
         case 'revolution':
             /* resolve core dependencies manually for now */
             $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "MODX core version dependencies must be resolved manually", '', __METHOD__, __FILE__, __LINE__);
             break;
         default:
             /* TODO: scan for local packages to satisfy dependency */
             /* see if current provider can satisfy dependency */
             /** @var modTransportProvider $provider */
             $provider = $this->Provider;
             if ($provider) {
                 $resolution = $provider->latest($package, $constraint);
             }
             /* loop through active providers if all else fails */
             if ($resolution === false) {
                 $query = $this->xpdo->newQuery('transport.modTransportProvider', $conditions);
                 $query->sortby('priority', 'ASC');
                 /** @var modTransportProvider $p */
                 foreach ($this->xpdo->getIterator('transport.modTransportProvider', $query) as $p) {
                     $resolution = $p->latest($package, $constraint);
                     if ($resolution) {
                         $provider = $p;
                         break;
                     }
                 }
             }
             if ($resolution === false) {
                 $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Could not find package to satisfy dependency {$package} @ {$constraint} from your currently active providers", '', __METHOD__, __FILE__, __LINE__);
             }
             break;
     }
     return $resolution;
 }
Ejemplo n.º 26
0
 public function getDomains()
 {
     /* array cache $options */
     $options = array('cache_key' => 'config/domains', 'cacheTime' => 0);
     if (!($domains = $this->getCache($options))) {
         $q = $this->modx->newQuery('sbdfDomain');
         $q->innerJoin('modResource', 'modResource', 'modResource.id = sbdfDomain.resource');
         $q->select('sbdfDomain.domain,modResource.id,modResource.uri');
         $q->where('sbdfDomain.active=1');
         if ($q->prepare() and $q->stmt->execute()) {
             $rows = $q->stmt->fetchAll(PDO::FETCH_ASSOC);
             foreach ($rows as $row) {
                 $domains[$row['domain']] = array('id' => $row['id'], 'alias' => trim($row['uri'], '/'));
             }
         }
         $this->setCache($domains, $options);
     }
     return (array) $domains;
 }
Ejemplo n.º 27
-1
 public function handleRequest()
 {
     $requestParamAlias = $this->modx->getOption('request_param_alias', null, 'q');
     if (!isset($_REQUEST[$requestParamAlias])) {
         return true;
     }
     $this->pieces = explode('/', trim($_REQUEST[$requestParamAlias], ' '));
     $pieces = array_flip($this->pieces);
     $c = $this->modx->newQuery('TaggerGroup');
     $c->select($this->modx->getSelectColumns('TaggerGroup', '', '', array('alias')));
     $c->prepare();
     $c->stmt->execute();
     $this->groups = $c->stmt->fetchAll(PDO::FETCH_COLUMN, 0);
     foreach ($this->groups as $group) {
         if (isset($pieces[$group])) {
             $this->tags[$group] = $pieces[$group];
         }
     }
     if (count($this->tags) == 0) {
         return false;
     }
     asort($this->tags);
     if ($this->pieces[count($this->pieces) - 1] != '') {
         $this->modx->sendRedirect(MODX_SITE_URL . implode('/', $this->pieces) . '/', array('responseCode' => 'HTTP/1.1 301 Moved Permanently'));
     }
     if (count($this->pieces) == 0 || count($this->pieces) == 1 && $this->pieces[0] == '') {
         return false;
     }
     $this->processRequest();
     return true;
 }
Ejemplo n.º 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;
 }
Ejemplo n.º 29
-1
 /**
  * Plugin to run the page parser and display the number of comments on the resource.
  * @return boolean
  */
 public function mtcount()
 {
     // get a reference to the output
     $output =& $this->modx->resource->_output;
     // Choosing a pattern all of our values ​​from the resource
     if (preg_match_all("/{%mt(.*?)%}/", $output, $mt_list)) {
         $r = array();
         $c = array();
         $lisrArray = $mt_list[1];
         array_walk($lisrArray, 'trim');
         // Divide into two arrays, one for the id of the resource, the other by conversation name
         foreach ($lisrArray as $key => $value) {
             if ($value[0] == 'r') {
                 $r[$key] = substr($value, 2);
             } else {
                 $c[$key] = substr($value, 2);
             }
         }
         // If the array is not empty, choose the number of comments on the resource id (column rid)
         if ($r && is_array($r)) {
             array_walk($r, 'intval');
             $rr = $this->modx->newQuery('modxTalksConversation', array('rid:IN' => $r));
             if ($rr->prepare() && $rr->stmt->execute()) {
                 $results = $rr->stmt->fetchAll(PDO::FETCH_ASSOC);
                 foreach ($results as $resultr) {
                     $objMt = json_decode($resultr['modxTalksConversation_properties']);
                     if (in_array('r_' . $resultr['modxTalksConversation_rid'], $lisrArray)) {
                         $mt_list[1][array_search('r_' . $resultr['modxTalksConversation_rid'], $lisrArray)] = isset($objMt->comments->total) ? $objMt->comments->total : 0;
                     }
                 }
             }
         }
         foreach ($r as $n) {
             $k = array_search('r_' . $n, $mt_list[1], true);
             if ($k !== false) {
                 $mt_list[1][$k] = 0;
             }
         }
         // If the array is not empty, choose the number of comments on the conversation name (column conversation)
         if ($c && is_array($c)) {
             $rr = $this->modx->newQuery('modxTalksConversation', array('conversation:IN' => $c));
             if ($rr->prepare() && $rr->stmt->execute()) {
                 $results = $rr->stmt->fetchAll(PDO::FETCH_ASSOC);
                 foreach ($results as $resultr) {
                     $objMt = json_decode($resultr['modxTalksConversation_properties']);
                     if (in_array('c_' . $resultr['modxTalksConversation_conversation'], $lisrArray)) {
                         $mt_list[1][array_search('c_' . $resultr['modxTalksConversation_conversation'], $lisrArray)] = $objMt->comments->total;
                     }
                 }
             }
         }
         // Replace all your templates in the resource to the correct values
         $output = str_replace($mt_list[0], $mt_list[1], $output);
     }
     return true;
 }
Ejemplo n.º 30
-1
 /**
  * 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();
                 }
             }
         }
     }
 }