/**
  * 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);
 }
Esempio n. 2
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;
 }
 /**
  * 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
 }
Esempio n. 4
0
 /**
  * Grabs all descendants of this post.
  *
  * @access public
  * @param int $depth If set, will limit to specified depth
  * @return array A collection of quipComment objects.
  */
 public function getDescendants($depth = 0)
 {
     $c = $this->xpdo->newQuery('quipComment');
     $c->select($this->xpdo->getSelectColumns('quipComment', 'quipComment'));
     $c->select(array('Descendants.depth'));
     $c->innerJoin('quipCommentClosure', 'Descendants');
     $c->innerJoin('quipCommentClosure', 'Ancestors');
     $c->where(array('Descendants.ancestor' => $this->get('id')));
     if ($depth) {
         $c->where(array('Descendants.depth:<=' => $depth));
     }
     $c->sortby('quipComment.rank', 'ASC');
     return $this->xpdo->getCollection('quipComment', $c);
 }
Esempio n. 5
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;
    }
 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;
 }
 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;
 }
 /**
  * Parse inherit binding
  *
  * @param string $default The value to default if there is no inherited value
  * @param int $resourceId The current Resource, if any
  * @return string The inherited value
  */
 public function processInheritBinding($default = '', $resourceId = null)
 {
     $output = $default;
     /* Default to param value if no content from parents */
     $resource = null;
     $resourceColumns = $this->xpdo->getSelectColumns('modResource', '', '', array('id', 'parent'));
     $resourceQuery = new xPDOCriteria($this->xpdo, "SELECT {$resourceColumns} FROM {$this->xpdo->getTableName('modResource')} WHERE id = ?");
     if (!empty($resourceId) && (!$this->xpdo->resource instanceof modResource || $this->xpdo->resource->get('id') != $resourceId)) {
         if ($resourceQuery->stmt && $resourceQuery->stmt->execute(array($resourceId))) {
             $result = $resourceQuery->stmt->fetchAll(PDO::FETCH_ASSOC);
             $resource = reset($result);
         }
     } else {
         if ($this->xpdo->resource instanceof modResource) {
             $resource = $this->xpdo->resource->get(array('id', 'parent'));
         }
     }
     if (!empty($resource)) {
         $currentResource = $resource;
         while ($currentResource['parent'] != 0) {
             if ($resourceQuery->stmt && $resourceQuery->stmt->execute(array($currentResource['parent']))) {
                 $result = $resourceQuery->stmt->fetchAll(PDO::FETCH_ASSOC);
                 $currentResource = reset($result);
             } else {
                 break;
             }
             if (!empty($currentResource)) {
                 $tv = $this->getValue($currentResource['id']);
                 if (($tv === '0' || !empty($tv)) && substr($tv, 0, 1) != '@') {
                     $output = $tv;
                     break;
                 }
             } else {
                 break;
             }
         }
     }
     return $output;
 }
Esempio n. 9
0
 public static function getList(modX &$modx, array $scriptProperties = array())
 {
     $sort = $modx->getOption('sort', $scriptProperties, 'rank');
     $cacheKey = 'gallery/item/list/' . md5(serialize($scriptProperties));
     if ($modx->getCacheManager() && ($cache = $modx->cacheManager->get($cacheKey))) {
         $items = array();
         foreach ($cache['items'] as $data) {
             /** @var galItem $item */
             $item = $modx->newObject('galItem');
             $item->fromArray($data, '', true, true);
             $items[] = $item;
         }
         if (in_array(strtolower($sort), array('random', 'rand()', 'rand'))) {
             shuffle($items);
         }
         $data = array('items' => $items, 'total' => $cache['total'], 'album' => $cache['album']);
     } else {
         $album = $modx->getOption('album', $scriptProperties, false);
         $tag = $modx->getOption('tag', $scriptProperties, '');
         $limit = $modx->getOption('limit', $scriptProperties, 0);
         $start = $modx->getOption('start', $scriptProperties, 0);
         /* Fix to make it work with getPage which uses "offset" instead of "start" */
         $offset = $modx->getOption('offset', $scriptProperties, 0);
         if ($offset > 0) {
             $start = $offset;
         }
         $sortAlias = $modx->getOption('sortAlias', $scriptProperties, 'galItem');
         if ($sort == 'rank') {
             $sortAlias = 'AlbumItems';
         }
         $dir = $modx->getOption('dir', $scriptProperties, 'ASC');
         $showInactive = $modx->getOption('showInactive', $scriptProperties, false);
         $activeAlbum = array('id' => '', 'name' => '', 'description' => '');
         $tagc = $modx->newQuery('galTag');
         $tagc->setClassAlias('TagsJoin');
         $tagc->select('GROUP_CONCAT(' . $modx->getSelectColumns('galTag', 'TagsJoin', '', array('tag')) . ')');
         $tagc->where($modx->getSelectColumns('galTag', 'TagsJoin', '', array('item')) . ' = ' . $modx->getSelectColumns('galItem', 'galItem', '', array('id')));
         $tagc->prepare();
         $tagSql = $tagc->toSql();
         $c = $modx->newQuery('galItem');
         $c->innerJoin('galAlbumItem', 'AlbumItems');
         $c->innerJoin('galAlbum', 'Album', $modx->getSelectColumns('galAlbumItem', 'AlbumItems', '', array('album')) . ' = ' . $modx->getSelectColumns('galAlbum', 'Album', '', array('id')));
         /* pull by album */
         if (!empty($album)) {
             $albumField = is_numeric($album) ? 'id' : 'name';
             $albumWhere = $albumField == 'name' ? array('name' => $album) : $album;
             /** @var galAlbum $album */
             $album = $modx->getObject('galAlbum', $albumWhere);
             if (empty($album)) {
                 return '';
             }
             $c->where(array('Album.' . $albumField => $album->get($albumField)));
             $activeAlbum['id'] = $album->get('id');
             $activeAlbum['name'] = $album->get('name');
             $activeAlbum['description'] = $album->get('description');
             $activeAlbum['year'] = $album->get('year');
             unset($albumWhere, $albumField);
         }
         if (!empty($tag)) {
             /* pull by tag */
             $c->innerJoin('galTag', 'Tags');
             $c->where(array('Tags.tag' => $tag));
             if (empty($album)) {
                 $activeAlbum['id'] = 0;
                 $activeAlbum['name'] = $tag;
                 $activeAlbum['description'] = '';
             }
         }
         $c->where(array('galItem.mediatype' => $modx->getOption('mediatype', $scriptProperties, 'image')));
         if (!$showInactive) {
             $c->where(array('galItem.active' => true));
         }
         $count = $modx->getCount('galItem', $c);
         $c->select($modx->getSelectColumns('galItem', 'galItem'));
         $c->select(array('(' . $tagSql . ') AS tags'));
         if (in_array(strtolower($sort), array('random', 'rand()', 'rand'))) {
             $c->sortby('RAND()', $dir);
         } else {
             $c->sortby($sortAlias . '.' . $sort, $dir);
         }
         if (!empty($limit)) {
             $c->limit($limit, $start);
         }
         $items = $modx->getCollection('galItem', $c);
         $data = array('items' => $items, 'total' => $count, 'album' => $activeAlbum);
         $cache = array('items' => array(), 'total' => $count, 'album' => $activeAlbum);
         /** @var galItem $item */
         foreach ($items as $item) {
             $cache['items'][] = $item->toArray('', true);
         }
         $modx->cacheManager->set($cacheKey, $cache);
     }
     return $data;
 }
 /**
  * Get the Resource's full alias path.
  *
  * @param string $alias Optional. The alias to check. If not set, will
  * then build it from the pagetitle if automatic_alias is set to true.
  * @param array $fields Optional. An array of field values to use instead of
  * using the current modResource fields.
  * @return string
  */
 public function getAliasPath($alias = '', array $fields = array())
 {
     if (empty($fields)) {
         $fields = $this->toArray();
     }
     $workingContext = $this->xpdo->getContext($fields['context_key']);
     if (empty($fields['uri_override']) || empty($fields['uri'])) {
         /* auto assign alias if using automatic_alias */
         if (empty($alias) && $workingContext->getOption('automatic_alias', false)) {
             $alias = $this->cleanAlias($fields['pagetitle']);
         } elseif (empty($alias) && isset($fields['id']) && !empty($fields['id'])) {
             $alias = $this->cleanAlias($fields['id']);
         } else {
             $alias = $this->cleanAlias($alias);
         }
         $fullAlias = $alias;
         $isHtml = true;
         $extension = '';
         $containerSuffix = $workingContext->getOption('container_suffix', '');
         /* @var modContentType $contentType process content type */
         if (!empty($fields['content_type']) && ($contentType = $this->xpdo->getObject('modContentType', $fields['content_type']))) {
             $extension = $contentType->getExtension();
             $isHtml = strpos($contentType->get('mime_type'), 'html') !== false;
         }
         /* set extension to container suffix if Resource is a folder, HTML content type, and the container suffix is set */
         if (!empty($fields['isfolder']) && $isHtml && !empty($containerSuffix)) {
             $extension = $containerSuffix;
         }
         $aliasPath = '';
         /* if using full alias paths, calculate here */
         if ($workingContext->getOption('use_alias_path', false)) {
             $pathParentId = $fields['parent'];
             $parentResources = array();
             $query = $this->xpdo->newQuery('modResource');
             $query->select($this->xpdo->getSelectColumns('modResource', '', '', array('parent', 'alias')));
             $query->where("{$this->xpdo->escape('id')} = ?");
             $query->prepare();
             $query->stmt->execute(array($pathParentId));
             $currResource = $query->stmt->fetch(PDO::FETCH_ASSOC);
             while ($currResource) {
                 $parentAlias = $currResource['alias'];
                 if (empty($parentAlias)) {
                     $parentAlias = "{$pathParentId}";
                 }
                 $parentResources[] = "{$parentAlias}";
                 $pathParentId = $currResource['parent'];
                 $query->stmt->execute(array($pathParentId));
                 $currResource = $query->stmt->fetch(PDO::FETCH_ASSOC);
             }
             $aliasPath = !empty($parentResources) ? implode('/', array_reverse($parentResources)) : '';
             if (strlen($aliasPath) > 0 && $aliasPath[strlen($aliasPath) - 1] !== '/') {
                 $aliasPath .= '/';
             }
         }
         $fullAlias = $aliasPath . $fullAlias . $extension;
     } else {
         $fullAlias = $fields['uri'];
     }
     return $fullAlias;
 }
 /**
  * Search and return array with resources ids as a key and sum of weight as value
  *
  * @param $query
  *
  * @return array
  */
 public function Search($query)
 {
     $string = preg_replace('/[^_-а-яёa-z0-9\\s\\.\\/]+/iu', ' ', $this->modx->stripTags($query));
     $this->log('Filtered search query: "' . mb_strtolower($query . '"', 'UTF-8'));
     $string = $this->query = $this->addAliases($string);
     $this->log('Search query with processed aliases: "' . mb_strtolower($string . '"', 'UTF-8'));
     $words = $this->getBaseForms($string, false);
     $result = $all_words = $found_words = array();
     // Search by words index
     if (!empty($words)) {
         $q = $this->modx->newQuery('mseWord');
         $q->select($this->modx->getSelectColumns('mseWord', 'mseWord'));
         $q->where(array('word:IN' => array_keys($words), 'field:IN' => array_keys($this->fields)));
         $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 (isset($result[$row['resource']])) {
                     $result[$row['resource']] += $this->fields[$row['field']] * $row['count'];
                 } else {
                     $result[$row['resource']] = $this->fields[$row['field']] * $row['count'];
                 }
                 if (isset($words[$row['word']])) {
                     $all_words[$row['resource']][$words[$row['word']]] = 1;
                     $found_words[$words[$row['word']]] = 1;
                 }
             }
         }
     }
     $added = 0;
     if (!empty($found_words)) {
         $this->log('Found results by words INDEX (' . implode(',', array_keys($words)) . '): ' . count($result));
     } else {
         $this->log('Nothing found by words INDEX');
     }
     // Add bonuses
     if (empty($this->config['onlyIndex'])) {
         $bulk_words = $this->getBulkWords($query);
         $tmp_words = preg_split($this->config['split_words'], $query, -1, PREG_SPLIT_NO_EMPTY);
         if (count($bulk_words) > 1 || count($tmp_words) > 1 || empty($result)) {
             if (!empty($this->config['exact_match_bonus']) || !empty($this->config['all_words_bonus'])) {
                 $exact = $this->simpleSearch($query);
                 // Exact match bonus
                 if (!empty($this->config['exact_match_bonus'])) {
                     foreach ($exact as $v) {
                         if (isset($result[$v])) {
                             $result[$v] += $this->config['exact_match_bonus'];
                             //$this->log('Added "exact match bonus" for a resource '.$v.' for words "'.implode(', ', $words).'": +'.$this->config['exact_match_bonus']);
                         } else {
                             $result[$v] = $this->config['exact_match_bonus'];
                             //$this->log('Found resource '.$v.' by LIKE search with all words "'.implode(', ',$words).'": +'.$this->config['exact_match_bonus']);
                             $added++;
                         }
                     }
                 }
                 if (!empty($this->config['all_words_bonus'])) {
                     if (count($bulk_words) > 1) {
                         // All words bonus
                         foreach ($all_words as $k => $v) {
                             if (count($bulk_words) == count($v)) {
                                 $result[$k] += $this->config['all_words_bonus'];
                                 //$this->log('Added "all words bonus" for a resource '.$k.' for words "'.implode(', ', $words).'": +'.$this->config['all_words_bonus']);
                             }
                         }
                     }
                 }
             }
         } elseif (!empty($this->config['like_match_bonus'])) {
             // Add the whole possible results for query
             $all_results = $this->simpleSearch($query);
             foreach ($all_results as $v) {
                 if (!isset($result[$v])) {
                     $weight = round($this->config['like_match_bonus']);
                     $result[$v] = $weight;
                     //$this->log('Found resource '.$v.' by LIKE search with all words "'.$query.'": +'.$weight);
                     $added++;
                 }
             }
         }
         // Add matches by %LIKE% search
         if (!empty($this->config['like_match_bonus']) && ($not_found = array_diff($bulk_words, $words))) {
             foreach ($not_found as $word) {
                 $found = $this->simpleSearch($word);
                 foreach ($found as $v) {
                     $weight = round($this->config['like_match_bonus']);
                     if (!isset($result[$v])) {
                         $result[$v] = $weight;
                         //$this->log('Found resource '.$v.' by LIKE search with single word "'.$word.'": +'.$weight);
                         $added++;
                     } else {
                         $result[$v] += $weight;
                         //$this->log('Added "LIKE bonus" for a resource '.$v.' for word "'.$word.'": +'.$weight);
                     }
                 }
             }
         }
         $this->log('Added resources by LIKE search: ' . $added);
     }
     // Log the search query
     /** @var mseQuery $object */
     if ($object = $this->modx->getObject('mseQuery', array('query' => $query))) {
         $object->set('quantity', $object->get('quantity') + 1);
     } else {
         $object = $this->modx->newObject('mseQuery');
         $object->set('query', $query);
         $object->set('quantity', 1);
     }
     $object->set('found', count($result));
     $object->save();
     arsort($result);
     return $result;
 }
Esempio n. 12
0
if (!$discuss instanceof Discuss) {
    return '';
}
define('DISCUSS_IMPORT_MODE', true);
/* setup mem limits */
ini_set('memory_limit', '1024M');
set_time_limit(0);
@ob_end_clean();
echo '<pre>';
$modx->user = $modx->getObject('modUser', 1);
$discuss->initialize('web');
/* load and run importer */
if ($discuss->loadImporter('disSmfImport')) {
    $c = $modx->newQuery('disThread');
    $c->innerJoin('disPost', 'LastPost');
    $c->select($modx->getSelectColumns('disThread', 'disThread'));
    $c->select($modx->getSelectColumns('disPost', 'LastPost', '', array('createdon')));
    $c->where(array('disThread.post_last_on' => 0));
    $threads = $modx->getIterator('disThread', $c);
    /** @var disThread $thread */
    foreach ($threads as $thread) {
        $discuss->import->log('Fixing post_last_on for: ' . $thread->get('title'));
        $thread->set('post_last_on', strtotime($thread->get('createdon')));
        $thread->save();
    }
} else {
    $modx->log(xPDO::LOG_LEVEL_ERROR, 'Failed to load Import class.');
}
$mtime = microtime();
$mtime = explode(" ", $mtime);
$mtime = $mtime[1] + $mtime[0];
Esempio n. 13
0
//ini_set('display_errors',1);
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
    exit;
}
if (!defined('MODX_API_MODE')) {
    define('MODX_API_MODE', true);
}
$resource_id = !empty($_GET['page_id']) && is_numeric($_GET['page_id']) ? $_GET['page_id'] : 1;
$output = array('prod_list' => '', 'pages' => '', 'total' => 0, 'pageCount' => 1, 'onPageLimit' => 1);
require_once '../../../config.core.php';
require_once MODX_CORE_PATH . 'model/modx/modx.class.php';
$modx = new modX();
//get resourse context_key
$context_key = 'web';
$query = $modx->newQuery('modResource', array('id' => $resource_id, 'published' => true, 'deleted' => false));
$query->select($modx->getSelectColumns('modResource', '', '', array('context_key')));
$stmt = $query->prepare();
if ($stmt) {
    if ($value = $modx->getValue($stmt)) {
        $context_key = $value;
    }
}
$modx->initialize($context_key);
//get resource
$criteria = $modx->newQuery('modResource');
$criteria->select(array($modx->escape('modResource') . '.*'));
$criteria->where(array('id' => $resource_id, 'deleted' => false, 'published' => true));
$modx->resource = $modx->getObject('modResource', $criteria);
if (!is_object($modx->resource) || !$modx->resource->checkPolicy('view')) {
    echo json_encode($output);
    exit;
Esempio n. 14
0
 /**
  * Import Users into the Discuss database
  * @return boolean
  */
 public function importUsers()
 {
     $stmt = $this->pdo->query('
         SELECT * FROM ' . $this->getFullTableName('members') . '
         ORDER BY `memberName` ASC
     ' . (!$this->config['live'] ? 'LIMIT 10' : ''));
     if (!$stmt) {
         return false;
     }
     while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
         if (!$row) {
             continue;
         }
         /* first create modUser objects if they dont already exist */
         $c = $this->modx->newQuery('modUser');
         $c->innerJoin('modUserProfile', 'Profile');
         $c->select($this->modx->getSelectColumns('modUser', 'modUser'));
         $c->select($this->modx->getSelectColumns('modUserProfile', 'Profile', '', array('email')));
         $c->where(array('modUser.username' => $row['memberName']));
         $modxUser = $this->modx->getObject('modUser', $c);
         if ($modxUser) {
             /*
              * Not the same user, so do not create a modUser object. We will create a disUser object
              * that will, on authentication, check to see if the passwords match.
              * If not, it will ask the user to choose a different username on a separate login page (a Discuss-specific one).
              * If they match, it will auto-sync the disUser account to the modUser account.
              *
              * (On 2nd thought, this is such a small case, skipping for now)
              */
             //$modxUser = false;
         } elseif (!$modxUser) {
             /**
              * No modUser exists with that username and email, so we'll create one.
              * @var modUser $modxUser
              */
             $modxUser = $this->modx->newObject('modUser');
             $modxUser->fromArray(array('username' => $row['memberName'], 'password' => $row['passwd'], 'salt' => $row['passwordSalt'], 'class_key' => 'modUser', 'active' => (bool) $row['is_activated']));
             if ($this->config['live']) {
                 $modxUser->save();
             }
             /** @var modUserProfile $modxUserProfile */
             $modxUserProfile = $this->modx->newObject('modUserProfile');
             $modxUserProfile->fromArray(array('email' => $row['emailAddress'], 'gender' => $row['gender'], 'fullname' => $row['realName'], 'dob' => strtotime($row['birthdate']), 'website' => $row['websiteUrl'], 'address' => $row['location'], 'lastlogin' => $row['lastLogin']));
             if ($this->config['live']) {
                 $modxUserProfile->set('internalKey', $modxUser->get('id'));
                 $modxUserProfile->save();
             }
         }
         /* else we already have a modUser that matches the email and username. Auto-sync!
         
                     /* now create disUser object */
         $name = explode(' ', $row['realName']);
         /** @var disUser $user */
         $user = $this->modx->newObject('disUser');
         $user->fromArray(array('username' => $row['memberName'], 'password' => $row['passwd'], 'email' => $row['emailAddress'], 'ip' => $row['memberIP'], 'synced' => false, 'source' => 'smf', 'createdon' => strftime(DisSmfImport::DATETIME_FORMATTED, $row['dateRegistered']), 'name_first' => $name[0], 'name_last' => isset($name[1]) ? $name[1] : '', 'gender' => $row['gender'] == 1 ? 'm' : 'f', 'birthdate' => $row['birthdate'], 'website' => $row['websiteUrl'], 'location' => $row['location'], 'status' => $row['is_activated'] ? 1 : 0, 'confirmed' => true, 'confirmedon' => $this->now(), 'signature' => $row['signature'], 'title' => $row['usertitle'], 'posts' => $row['posts'], 'show_email' => $row['hideEmail'] ? 0 : 1, 'show_online' => $row['showOnline'] ? 1 : 0, 'salt' => $row['passwordSalt'], 'ignore_boards' => $row['ignoreBoards'], 'integrated_id' => $row['ID_MEMBER']));
         $this->log('Creating User ' . $row['memberName']);
         $this->memberCache[$row['ID_MEMBER']] = $user->get('id');
         $this->memberNameCache[$row['memberName']] = $user->get('id');
         if ($this->config['live']) {
             if ($modxUser) {
                 $user->set('user', $modxUser->get('id'));
             }
             $user->save();
         }
         if ($modxUser) {
             $this->importUserGroupMemberships($user, $row);
         }
     }
     /* end while */
     $stmt->closeCursor();
     return true;
 }
Esempio n. 15
0
/* setup mem limits */
ini_set('memory_limit', '1024M');
set_time_limit(0);
@ob_end_clean();
echo '<pre>';
$modx->user = $modx->getObject('modUser', 1);
$discuss->initialize('web');
function disParseCodeCallback($matches)
{
    $str = str_replace(array('<br />', '&nbsp;', '&#039;'), array("\n", ' ', "'"), $matches[0]);
    return html_entity_decode($str, ENT_COMPAT, 'UTF-8');
}
/* load and run importer */
if ($discuss->loadImporter('disSmfImport')) {
    $c = $modx->newQuery('disPost');
    $c->select($modx->getSelectColumns('disPost', 'disPost'));
    $c->where(array('message:LIKE' => '%[code%'));
    $posts = $modx->getIterator('disPost', $c);
    /** @var disPost $post */
    foreach ($posts as $post) {
        $discuss->import->log('Fixing br tags for: ' . $post->get('title'));
        $message = $post->get('message');
        $message = preg_replace_callback("#\\[code\\](.*?)\\[/code\\]#si", 'disParseCodeCallback', $message);
        $message = preg_replace_callback("#\\[code=[\"']?(.*?)[\"']?\\](.*?)\\[/code\\]#si", 'disParseCodeCallback', $message);
        $post->set('message', $message);
        $post->save();
    }
} else {
    $modx->log(xPDO::LOG_LEVEL_ERROR, 'Failed to load Import class.');
}
$mtime = microtime();
Esempio n. 16
0
$cacheManager->writeFile(dirname(__FILE__) . '/data/transport.core.events.php', $content);
unset($content, $collection, $key, $c);
// Get all Content Types
$content = "<?php\n";
$query = $modx->newQuery('modContentType');
$query->sortby('id');
$collection = $modx->getCollection('modContentType', $query);
foreach ($collection as $key => $c) {
    $content .= $cacheManager->generateObject($c, "collection['{$key}']", false, false, 'xpdo');
}
$cacheManager->writeFile(dirname(__FILE__) . '/data/transport.core.content_types.php', $content);
unset($content, $collection, $key, $c);
// Get all System Settings
$content = "<?php\n";
$query = $modx->newQuery('modSystemSetting');
$query->select($modx->getSelectColumns('modSystemSetting', '', '', array('editedon'), true));
$query->where(array('namespace' => 'core'));
$query->sortby('`key`');
$collection = $modx->getCollection('modSystemSetting', $query);
foreach ($collection as $key => $c) {
    $content .= $cacheManager->generateObject($c, "collection['{$key}']", false, false, 'xpdo');
}
$cacheManager->writeFile(dirname(__FILE__) . '/data/transport.core.system_settings.php', $content);
unset($content, $collection, $key, $c);
// Get all Context Settings
$content = "<?php\n";
$query = $modx->newQuery('modContextSetting');
$query->select($modx->getSelectColumns('modContextSetting', '', '', array('editedon'), true));
$query->where(array('namespace' => 'core'));
$query->sortby('`context_key`');
$query->sortby('`key`');
Esempio n. 17
-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;
 }