/**
  * Gets the current thread
  * 
  * @static
  * @param modX $modx
  * @param quipThread $thread
  * @param int $parent
  * @param string $ids
  * @param string $sortBy
  * @param string $sortByAlias
  * @param string $sortDir
  * @return array
  */
 public static function getThread(modX $modx, quipThread $thread, $parent = 0, $ids = '', $sortBy = 'rank', $sortByAlias = 'quipComment', $sortDir = 'ASC')
 {
     $c = $modx->newQuery('quipComment');
     $c->innerJoin('quipThread', 'Thread');
     $c->leftJoin('quipCommentClosure', 'Descendants');
     $c->leftJoin('quipCommentClosure', 'RootDescendant', 'RootDescendant.descendant = quipComment.id AND RootDescendant.ancestor = 0');
     $c->leftJoin('quipCommentClosure', 'Ancestors');
     $c->leftJoin('modUser', 'Author');
     $c->leftJoin('modResource', 'Resource');
     $c->where(array('quipComment.thread' => $thread->get('name'), 'quipComment.deleted' => false));
     if (!$thread->checkPolicy('moderate')) {
         $c->andCondition(array('quipComment.approved' => true), null, 2);
     }
     if (!empty($parent)) {
         $c->where(array('Descendants.ancestor' => $parent));
     }
     $total = $modx->getCount('quipComment', $c);
     if (!empty($ids)) {
         $c->where(array('Descendants.ancestor:IN' => $ids));
     }
     $c->select($modx->getSelectColumns('quipComment', 'quipComment'));
     $c->select(array('Thread.resource', 'Thread.idprefix', 'Thread.existing_params', 'RootDescendant.depth', 'Author.username', 'Resource.pagetitle', 'Resource.context_key'));
     $c->sortby($modx->escape($sortByAlias) . '.' . $modx->escape($sortBy), $sortDir);
     $comments = $modx->getCollection('quipComment', $c);
     return array('results' => $comments, 'total' => $total);
 }
 /**
  * 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
 }
Example #3
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;
 }
 /**
  * Update all Articles URIs to reflect the new blog alias
  *
  * @param string $newAlias
  * @param string $oldAlias
  * @return bool
  */
 public function updateChildrenURIs($newAlias, $oldAlias)
 {
     $useMultiByte = $this->getOption('use_multibyte', null, false) && function_exists('mb_strlen');
     $encoding = $this->getOption('modx_charset', null, 'UTF-8');
     $oldAliasLength = ($useMultiByte ? mb_strlen($oldAlias, $encoding) : strlen($oldAlias)) + 1;
     $uriField = $this->xpdo->escape('uri');
     $sql = 'UPDATE ' . $this->xpdo->getTableName('Article') . '
         SET ' . $uriField . ' = CONCAT("' . $newAlias . '",SUBSTRING(' . $uriField . ',' . $oldAliasLength . '))
         WHERE
             ' . $this->xpdo->escape('parent') . ' = ' . $this->get('id') . '
         AND SUBSTRING(' . $uriField . ',1,' . $oldAliasLength . ') = "' . $oldAlias . '/"';
     $this->xpdo->log(xPDO::LOG_LEVEL_DEBUG, $sql);
     $this->xpdo->exec($sql);
     return true;
 }
 /**
  * Check for any Form Customization rules for this TV
  * @param string $value
  * @param modResource $resource
  * @return mixed
  */
 public function checkForFormCustomizationRules($value, &$resource)
 {
     if ($this->xpdo->request && $this->xpdo->user instanceof modUser) {
         if (empty($resource)) {
             $resource =& $this->xpdo->resource;
         }
         if ($this->xpdo->getOption('form_customization_use_all_groups', null, false)) {
             $userGroups = $this->xpdo->user->getUserGroups();
         } else {
             $primaryGroup = $this->xpdo->user->getPrimaryGroup();
             if ($primaryGroup) {
                 $userGroups = array($primaryGroup->get('id'));
             }
         }
         $c = $this->xpdo->newQuery('modActionDom');
         $c->innerJoin('modFormCustomizationSet', 'FCSet');
         $c->innerJoin('modFormCustomizationProfile', 'Profile', 'FCSet.profile = Profile.id');
         $c->leftJoin('modFormCustomizationProfileUserGroup', 'ProfileUserGroup', 'Profile.id = ProfileUserGroup.profile');
         $c->leftJoin('modFormCustomizationProfile', 'UGProfile', 'UGProfile.id = ProfileUserGroup.profile');
         $ruleFieldName = $this->xpdo->escape('rule');
         $c->where(array(array("(modActionDom.{$ruleFieldName} = 'tvDefault'\n                   OR modActionDom.{$ruleFieldName} = 'tvVisible'\n                   OR modActionDom.{$ruleFieldName} = 'tvTitle')"), "'tv{$this->get('id')}' IN ({$this->xpdo->escape('modActionDom')}.{$this->xpdo->escape('name')})", 'FCSet.active' => true, 'Profile.active' => true));
         if (!empty($userGroups)) {
             $c->where(array(array('ProfileUserGroup.usergroup:IN' => $userGroups, array('OR:ProfileUserGroup.usergroup:IS' => null, 'AND:UGProfile.active:=' => true)), 'OR:ProfileUserGroup.usergroup:=' => null), xPDOQuery::SQL_AND, null, 2);
         }
         if (!empty($this->xpdo->request) && !empty($this->xpdo->request->action)) {
             $c->where(array('modActionDom.action' => $this->xpdo->request->action));
         }
         $c->select($this->xpdo->getSelectColumns('modActionDom', 'modActionDom'));
         $c->select(array('FCSet.constraint_class', 'FCSet.constraint_field', 'FCSet.' . $this->xpdo->escape('constraint'), 'FCSet.template'));
         $c->sortby('FCSet.template', 'ASC');
         $c->sortby('modActionDom.rank', 'ASC');
         $domRules = $this->xpdo->getCollection('modActionDom', $c);
         /** @var modActionDom $rule */
         foreach ($domRules as $rule) {
             if (!empty($resource)) {
                 $template = $rule->get('template');
                 if (!empty($template) && $template != $resource->get('template')) {
                     continue;
                 }
                 $constraintClass = $rule->get('constraint_class');
                 if (!empty($constraintClass)) {
                     if (!$resource instanceof $constraintClass) {
                         continue;
                     }
                     $constraintField = $rule->get('constraint_field');
                     $constraint = $rule->get('constraint');
                     if ($resource->get($constraintField) != $constraint) {
                         continue;
                     }
                 }
             }
             switch ($rule->get('rule')) {
                 case 'tvVisible':
                     if ($rule->get('value') == 0) {
                         $this->set('type', 'hidden');
                     }
                     break;
                 case 'tvDefault':
                     $v = $rule->get('value');
                     if (empty($resourceId)) {
                         $value = $v;
                         $this->set('value', $v);
                     }
                     $this->set('default_text', $v);
                     break;
                 case 'tvTitle':
                     $v = $rule->get('value');
                     $this->set('caption', $v);
                     break;
             }
         }
         unset($domRules, $rule, $userGroups, $v, $c);
     }
     return $value;
 }
 /**
  * Clear the caches of all sources
  * @param array $options
  * @return void
  */
 public function clearCache(array $options = array())
 {
     /** @var modCacheManager $cacheManager */
     $cacheManager = $this->xpdo->getCacheManager();
     if (empty($cacheManager)) {
         return;
     }
     $c = $this->xpdo->newQuery('modContext');
     $c->select($this->xpdo->escape('key'));
     $options[xPDO::OPT_CACHE_KEY] = $this->getOption('cache_media_sources_key', $options, 'media_sources');
     $options[xPDO::OPT_CACHE_HANDLER] = $this->getOption('cache_media_sources_handler', $options, $this->getOption(xPDO::OPT_CACHE_HANDLER, $options));
     $options[xPDO::OPT_CACHE_FORMAT] = (int) $this->getOption('cache_media_sources_format', $options, $this->getOption(xPDO::OPT_CACHE_FORMAT, $options, xPDOCacheManager::CACHE_PHP));
     $options[xPDO::OPT_CACHE_ATTEMPTS] = (int) $this->getOption('cache_media_sources_attempts', $options, $this->getOption(xPDO::OPT_CACHE_ATTEMPTS, $options, 10));
     $options[xPDO::OPT_CACHE_ATTEMPT_DELAY] = (int) $this->getOption('cache_media_sources_attempt_delay', $options, $this->getOption(xPDO::OPT_CACHE_ATTEMPT_DELAY, $options, 1000));
     if ($c->prepare() && $c->stmt->execute()) {
         while ($row = $c->stmt->fetch(PDO::FETCH_ASSOC)) {
             if ($row && !empty($row['key'])) {
                 $cacheManager->delete($row['key'] . '/source', $options);
             }
         }
     }
 }
 /**
  * Gets a requested resource and all required data.
  *
  * @param string $method The method, 'id', or 'alias', by which to perform
  * the resource lookup.
  * @param string|integer $identifier The identifier with which to search.
  * @param array $options An array of options for the resource fetching
  * @return modResource The requested modResource instance or request
  * is forwarded to the error page, or unauthorized page.
  */
 public function getResource($method, $identifier, array $options = array())
 {
     $resource = null;
     if ($method == 'alias') {
         $resourceId = $this->modx->aliasMap[$identifier];
     } else {
         $resourceId = $identifier;
     }
     if (!is_numeric($resourceId)) {
         $this->modx->sendErrorPage();
     }
     $isForward = array_key_exists('forward', $options) && !empty($options['forward']);
     $fromCache = false;
     $cacheKey = $this->modx->context->get('key') . "/resources/{$resourceId}";
     $cachedResource = $this->modx->cacheManager->get($cacheKey, array(xPDO::OPT_CACHE_KEY => $this->modx->getOption('cache_resource_key', null, 'resource'), xPDO::OPT_CACHE_HANDLER => $this->modx->getOption('cache_resource_handler', null, $this->modx->getOption(xPDO::OPT_CACHE_HANDLER)), xPDO::OPT_CACHE_FORMAT => (int) $this->modx->getOption('cache_resource_format', null, $this->modx->getOption(xPDO::OPT_CACHE_FORMAT, null, xPDOCacheManager::CACHE_PHP))));
     if (is_array($cachedResource) && array_key_exists('resource', $cachedResource) && is_array($cachedResource['resource'])) {
         /** @var modResource $resource */
         $resource = $this->modx->newObject($cachedResource['resourceClass']);
         if ($resource) {
             $resource->fromArray($cachedResource['resource'], '', true, true, true);
             $resource->_content = $cachedResource['resource']['_content'];
             $resource->_isForward = isset($cachedResource['resource']['_isForward']) && !empty($cachedResource['resource']['_isForward']);
             if (isset($cachedResource['contentType'])) {
                 $contentType = $this->modx->newObject('modContentType');
                 $contentType->fromArray($cachedResource['contentType'], '', true, true, true);
                 $resource->addOne($contentType, 'ContentType');
             }
             if (isset($cachedResource['resourceGroups'])) {
                 $rGroups = array();
                 foreach ($cachedResource['resourceGroups'] as $rGroupKey => $rGroup) {
                     $rGroups[$rGroupKey] = $this->modx->newObject('modResourceGroupResource', $rGroup);
                 }
                 $resource->addMany($rGroups);
             }
             if (isset($cachedResource['policyCache'])) {
                 $resource->setPolicies(array($this->modx->context->get('key') => $cachedResource['policyCache']));
             }
             if (isset($cachedResource['elementCache'])) {
                 $this->modx->elementCache = $cachedResource['elementCache'];
             }
             if (isset($cachedResource['sourceCache'])) {
                 $this->modx->sourceCache = $cachedResource['sourceCache'];
             }
             if ($resource->get('_jscripts')) {
                 $this->modx->jscripts = $this->modx->jscripts + $resource->get('_jscripts');
             }
             if ($resource->get('_sjscripts')) {
                 $this->modx->sjscripts = $this->modx->sjscripts + $resource->get('_sjscripts');
             }
             if ($resource->get('_loadedjscripts')) {
                 $this->modx->loadedjscripts = array_merge($this->modx->loadedjscripts, $resource->get('_loadedjscripts'));
             }
             $isForward = $resource->_isForward;
             $resource->setProcessed(true);
             $fromCache = true;
         }
     }
     if (!$fromCache || !is_object($resource)) {
         $criteria = $this->modx->newQuery('modResource');
         $criteria->select(array($this->modx->escape('modResource') . '.*'));
         $criteria->where(array('id' => $resourceId, 'deleted' => '0'));
         if (!$this->modx->hasPermission('view_unpublished') || $this->modx->getSessionState() !== modX::SESSION_STATE_INITIALIZED) {
             $criteria->where(array('published' => 1));
         }
         if ($resource = $this->modx->getObject('modResource', $criteria)) {
             if ($resource instanceof modResource) {
                 if ($resource->get('context_key') !== $this->modx->context->get('key')) {
                     if (!$isForward || $isForward && !$this->modx->getOption('allow_forward_across_contexts', $options, false)) {
                         if (!$this->modx->getCount('modContextResource', array($this->modx->context->get('key'), $resourceId))) {
                             return null;
                         }
                     }
                 }
                 $resource->_isForward = $isForward;
                 if (!$resource->checkPolicy('view')) {
                     $this->modx->sendUnauthorizedPage();
                 }
                 if ($tvs = $resource->getMany('TemplateVars', 'all')) {
                     /** @var modTemplateVar $tv */
                     foreach ($tvs as $tv) {
                         $resource->set($tv->get('name'), array($tv->get('name'), $tv->getValue($resource->get('id')), $tv->get('display'), $tv->get('display_params'), $tv->get('type')));
                     }
                 }
                 $this->modx->resourceGenerated = true;
             }
         }
     } elseif ($fromCache && $resource instanceof modResource && !$resource->get('deleted')) {
         if ($resource->checkPolicy('load') && ($resource->get('published') || $this->modx->getSessionState() === modX::SESSION_STATE_INITIALIZED && $this->modx->hasPermission('view_unpublished'))) {
             if ($resource->get('context_key') !== $this->modx->context->get('key')) {
                 if (!$isForward || $isForward && !$this->modx->getOption('allow_forward_across_contexts', $options, false)) {
                     if (!$this->modx->getCount('modContextResource', array($this->modx->context->get('key'), $resourceId))) {
                         return null;
                     }
                 }
             }
             if (!$resource->checkPolicy('view')) {
                 $this->modx->sendUnauthorizedPage();
             }
         } else {
             return null;
         }
         $this->modx->invokeEvent('OnLoadWebPageCache');
     }
     return $resource;
 }
Example #8
0
     $object['table'] = str_replace("CREATE TABLE {$modx->escape($extraTable)}", "CREATE TABLE {$modx->escape('[[++table_prefix]]' . $extraTableName)}", $resultSet[1]);
 } else {
     $object['drop'] = "DROP TABLE IF EXISTS {$modx->escape($extraTableName)}";
     $object['table'] = $resultSet[1];
 }
 /* collect the rows and generate INSERT statements */
 $object['data'] = array();
 $stmt = $modx->query("SELECT * FROM {$modx->escape($extraTable)}");
 while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
     if ($instances === 0) {
         $fields = implode(', ', array_map(array($modx, 'escape'), array_keys($row)));
     }
     $values = array();
     while (list($key, $value) = each($row)) {
         switch (gettype($value)) {
             case 'string':
                 $values[] = $modx->quote($value);
                 break;
             case 'NULL':
             case 'array':
             case 'object':
             case 'resource':
             case 'unknown type':
                 $values[] = 'NULL';
                 break;
             default:
                 $values[] = (string) $value;
                 break;
         }
     }
     $values = implode(', ', $values);
     if ($addTablePrefix) {
         $object['data'][] = "INSERT INTO {$modx->escape('[[++table_prefix]]' . $extraTableName)} ({$fields}) VALUES ({$values})";
 /**
  * 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;
 }
Example #10
0
 /**
  * Get the number of unanswered questions.
  * @return int
  */
 public function countUnansweredQuestions()
 {
     $response = $this->xpdo->call('disThread', 'fetchUnansweredQuestions', array(&$this->xpdo, "{$this->xpdo->escape('disThread')}.{$this->xpdo->escape('post_last_on')}", 'DESC', 10, 0, false, true));
     return number_format($response['total']);
 }
 /**
  * Indicates if a previous version of the package is installed.
  *
  * @return boolean True if a previous version of the package is installed.
  */
 public function previousVersionInstalled()
 {
     $this->parseSignature();
     $count = $this->xpdo->getCount('transport.modTransportPackage', array(array("UCASE({$this->xpdo->escape('package_name')}) LIKE UCASE({$this->xpdo->quote($this->identifier)})"), 'installed:IS NOT' => null, 'signature:!=' => $this->get('signature')));
     return $count > 0;
 }
Example #12
0
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;
}
$modx->resourceIdentifier = $modx->resource->get('id');
$modx->getService('error', 'error.modError');
$modx->getRequest();
$modx->getParser();
$modx->resourceMethod = 'id';
$modx->resource->_contextKey = $modx->context->get('key');
$modx->invokeEvent('OnLoadWebDocument');
require_once MODX_CORE_PATH . "components/tag_manager2/model/tm_base.class.php";
$tag_manager = new tagManagerBase($modx);
Example #13
0
 public function process()
 {
     //$startTime = microtime(true);
     try {
         $vaporOptions = array('excludeExtraTablePrefix' => array(), 'excludeExtraTables' => array(), 'excludeFiles' => array(MODX_BASE_PATH . 'vapor', MODX_BASE_PATH . 'phpmyadmin', MODX_BASE_PATH . 'assets', MODX_BASE_PATH . 'core'));
         if (is_readable(VAPOR_DIR . 'config.php')) {
             $vaporConfigOptions = @(include VAPOR_DIR . 'config.php');
             if (is_array($vaporConfigOptions)) {
                 $vaporOptions = array_merge($vaporOptions, $vaporConfigOptions);
             }
         }
         if (!XPDO_CLI_MODE && !ini_get('safe_mode')) {
             set_time_limit(0);
         }
         $options = array('log_level' => xPDO::LOG_LEVEL_INFO, 'log_target' => array('target' => 'FILE', 'options' => array('filename' => 'vapor-' . strftime('%Y%m%dT%H%M%S', $this->getProperty('startTime')) . '.log')), xPDO::OPT_CACHE_DB => false, xPDO::OPT_SETUP => true);
         $modx = new modX('', $options);
         $modx->setLogTarget($options['log_target']);
         $modx->setLogLevel($options['log_level']);
         $modx->setOption(xPDO::OPT_CACHE_DB, false);
         $modx->setOption(xPDO::OPT_SETUP, true);
         $modx->setDebug(-1);
         $modx->startTime = $this->getProperty('startTime');
         $modx->getVersionData();
         $modxVersion = $modx->version['full_version'];
         if (version_compare($modxVersion, '2.2.1-pl', '>=')) {
             $modx->initialize('mgr', $options);
         } else {
             $modx->initialize('mgr');
         }
         /*$modx->setLogTarget($options['log_target']);
           $modx->setLogLevel($options['log_level']);*/
         $modx->setOption(xPDO::OPT_CACHE_DB, false);
         $modx->setOption(xPDO::OPT_SETUP, true);
         $modx->setDebug(-1);
         $modxDatabase = $modx->getOption('dbname', $options, $modx->getOption('database', $options));
         $modxTablePrefix = $modx->getOption('table_prefix', $options, '');
         $core_path = realpath($modx->getOption('core_path', $options, MODX_CORE_PATH)) . '/';
         $assets_path = realpath($modx->getOption('assets_path', $options, MODX_ASSETS_PATH)) . '/';
         $manager_path = realpath($modx->getOption('manager_path', $options, MODX_MANAGER_PATH)) . '/';
         $base_path = realpath($modx->getOption('base_path', $options, MODX_BASE_PATH)) . '/';
         $modx->log(modX::LOG_LEVEL_INFO, "core_path=" . $core_path);
         $modx->log(modX::LOG_LEVEL_INFO, "assets_path=" . $assets_path);
         $modx->log(modX::LOG_LEVEL_INFO, "manager_path=" . $manager_path);
         $modx->log(modX::LOG_LEVEL_INFO, "base_path=" . $base_path);
         $modx->loadClass('transport.modPackageBuilder', '', false, true);
         $builder = new modPackageBuilder($modx);
         /** @var modWorkspace $workspace */
         $workspace = $modx->getObject('modWorkspace', 1);
         if (!$workspace) {
             $modx->log(modX::LOG_LEVEL_FATAL, "no workspace!");
         }
         $package = $builder->createPackage(PKG_NAME, PKG_VERSION, PKG_RELEASE);
         /* Defines the classes to extract (also used for truncation) */
         $classes = $this->getClassesList();
         $attributes = array('vehicle_class' => 'xPDOFileVehicle');
         /* get all files from the components directory */
         /*$modx->log(modX::LOG_LEVEL_INFO, "Packaging " . MODX_CORE_PATH . 'components');
           $package->put(
               array(
                   'source' => MODX_CORE_PATH . 'components',
                   'target' => 'return MODX_CORE_PATH;'
               ),
               array(
                   'vehicle_class' => 'xPDOFileVehicle'
               )
           );*/
         /* get all files from the assets directory */
         /*$modx->log(modX::LOG_LEVEL_INFO, "Packaging " . MODX_BASE_PATH . 'assets');
           $package->put(
               array(
                   'source' => MODX_BASE_PATH . 'assets',
                   'target' => 'return MODX_BASE_PATH;'
               ),
               array(
                   'vehicle_class' => 'xPDOFileVehicle'
               )
           );*/
         /* get all files from the manager/components directory */
         /*$modx->log(modX::LOG_LEVEL_INFO, "Packaging " . MODX_MANAGER_PATH . 'components');
           $package->put(
               array(
                   'source' => MODX_MANAGER_PATH . 'components',
                   'target' => 'return MODX_MANAGER_PATH;'
               ),
               array(
                   'vehicle_class' => 'xPDOFileVehicle'
               )
           );*/
         /* find other files/directories in the MODX_BASE_PATH */
         $excludes = array('_build', 'setup', 'assets', 'ht.access', 'index.php', 'config.core.php', dirname(MODX_CORE_PATH) . '/' === MODX_BASE_PATH ? basename(MODX_CORE_PATH) : 'core', dirname(MODX_CONNECTORS_PATH) . '/' === MODX_BASE_PATH ? basename(MODX_CONNECTORS_PATH) : 'connectors', dirname(MODX_MANAGER_PATH) . '/' === MODX_BASE_PATH ? basename(MODX_MANAGER_PATH) : 'manager');
         if (isset($vaporOptions['excludeFiles']) && is_array($vaporOptions['excludeFiles'])) {
             $excludes = array_unique($excludes + $vaporOptions['excludeFiles']);
         }
         /*if ($dh = opendir(MODX_BASE_PATH)) {
           $includes = array();
           while (($file = readdir($dh)) !== false) {
               /* ignore files/dirs starting with . or matching an exclude */
         /*if (strpos($file, '.') === 0 || in_array(strtolower($file), $excludes)) {
                       continue;
                   }
                   $includes[] = array(
                       'source' => MODX_BASE_PATH . $file,
                       'target' => 'return MODX_BASE_PATH;'
                   );
               }
               closedir($dh);
               foreach ($includes as $include) {
                   $modx->log(modX::LOG_LEVEL_INFO, "Packaging " . $include['source']);
                   $package->put(
                       $include,
                       array(
                           'vehicle_class' => 'xPDOFileVehicle'
                       )
                   );
               }
           }*/
         foreach ($this->getProperty('sources') as $source_id) {
             // Try to get mediaSource
             $loaded = $this->getSource($source_id);
             if ($loaded !== true) {
                 return $this->failure($loaded);
             }
             /* Why for??
                if (!$this->source->checkPolicy('delete')) {
                    return $this->failure($this->modx->lexicon('permission_denied'));
                }*/
             if ($properties = $this->source->getBases('') and $properties['pathIsRelative'] and $path = $properties['path']) {
                 if ($dh = opendir(MODX_BASE_PATH . $path)) {
                     $includes = array();
                     while (($file = readdir($dh)) !== false) {
                         /* ignore files/dirs starting with . or matching an exclude */
                         if (strpos($file, '.') === 0 || in_array(strtolower($file), $excludes)) {
                             continue;
                         }
                         $includes[] = array('source' => MODX_BASE_PATH . $path . $file, 'target' => "return MODX_BASE_PATH . '{$path}/';");
                     }
                     closedir($dh);
                     foreach ($includes as $include) {
                         $modx->log(modX::LOG_LEVEL_INFO, "Packaging " . $include['source']);
                         $package->put($include, array('vehicle_class' => 'xPDOFileVehicle'));
                     }
                 }
             }
         }
         if (!XPDO_CLI_MODE && !ini_get('safe_mode')) {
             set_time_limit(0);
         }
         /* package up the vapor model for use on install */
         $modx->log(modX::LOG_LEVEL_INFO, "Packaging vaporVehicle class");
         /*$package->put(
               array(
                   'source' => VAPOR_DIR . 'model/vapor',
                   'target' => "return MODX_CORE_PATH . 'components/vapor/model/';"
               ),
               array(
                   'vehicle_class' => 'xPDOFileVehicle',
                   'validate' => array(
                       array(
                           'type' => 'php',
                           'source' => VAPOR_DIR . 'scripts/validate.truncate_tables.php',
                           'classes' => $classes
                       ),
                   ),
                   'resolve' => array(
                       array(
                           'type' => 'php',
                           'source' => VAPOR_DIR . 'scripts/resolve.vapor_model.php'
                       )
                   )
               )
           );*/
         $attributes = array('preserve_keys' => true, 'update_object' => true);
         /* get the extension_packages and resolver */
         if ($this->getProperty('includeExtensionPackages')) {
             $object = $modx->getObject('modSystemSetting', array('key' => 'extension_packages'));
             if ($object) {
                 $extPackages = $object->get('value');
                 $extPackages = $modx->fromJSON($extPackages);
                 foreach ($extPackages as &$extPackage) {
                     if (!is_array($extPackage)) {
                         continue;
                     }
                     foreach ($extPackage as $pkgName => &$pkg) {
                         if (!empty($pkg['path']) && strpos($pkg['path'], '[[++') === false) {
                             if (substr($pkg['path'], 0, 1) !== '/' || strpos($pkg['path'], $base_path) !== 0 && strpos($pkg['path'], $core_path) !== 0) {
                                 $path = realpath($pkg['path']);
                                 if ($path === false) {
                                     $path = $pkg['path'];
                                 } else {
                                     $path = rtrim($path, '/') . '/';
                                 }
                             } else {
                                 $path = $pkg['path'];
                             }
                             if (strpos($path, $core_path) === 0) {
                                 $path = str_replace($core_path, '[[++core_path]]', $path);
                             } elseif (strpos($path, $assets_path) === 0) {
                                 $path = str_replace($assets_path, '[[++assets_path]]', $path);
                             } elseif (strpos($path, $manager_path) === 0) {
                                 $path = str_replace($manager_path, '[[++manager_path]]', $path);
                             } elseif (strpos($path, $base_path) === 0) {
                                 $path = str_replace($base_path, '[[++base_path]]', $path);
                             }
                             $pkg['path'] = $path;
                         }
                     }
                 }
                 $modx->log(modX::LOG_LEVEL_INFO, "Setting extension packages to: " . print_r($extPackages, true));
                 $object->set('value', $modx->toJSON($extPackages));
                 $package->put($object, array_merge($attributes, array('resolve' => array(array('type' => 'php', 'source' => VAPOR_DIR . 'scripts/resolve.extension_packages.php')))));
             }
         }
         /* loop through the classes and package the objects */
         foreach ($classes as $class) {
             if (!XPDO_CLI_MODE && !ini_get('safe_mode')) {
                 set_time_limit(0);
             }
             $instances = 0;
             $classCriteria = null;
             $classAttributes = $attributes;
             switch ($class) {
                 case 'modSession':
                     /* skip sessions */
                     continue 2;
                 case 'modSystemSetting':
                     $classCriteria = array('key:!=' => 'extension_packages');
                     break;
                 case 'modWorkspace':
                     /** @var modWorkspace $object */
                     foreach ($modx->getIterator('modWorkspace', $classCriteria) as $object) {
                         if (strpos($object->path, $core_path) === 0) {
                             $object->set('path', str_replace($core_path, '{core_path}', $object->path));
                         } elseif (strpos($object->path, $assets_path) === 0) {
                             $object->set('path', str_replace($assets_path, '{assets_path}', $object->path));
                         } elseif (strpos($object->path, $manager_path) === 0) {
                             $object->set('path', str_replace($manager_path, '{manager_path}', $object->path));
                         } elseif (strpos($object->path, $base_path) === 0) {
                             $object->set('path', str_replace($base_path, '{base_path}', $object->path));
                         }
                         if ($package->put($object, $classAttributes)) {
                             $instances++;
                         } else {
                             $modx->log(modX::LOG_LEVEL_WARN, "Could not package {$class} instance with pk: " . print_r($object->getPrimaryKey(), true));
                         }
                     }
                     $modx->log(modX::LOG_LEVEL_INFO, "Packaged {$instances} of {$class}");
                     continue 2;
                 case 'transport.modTransportPackage':
                     $modx->loadClass($class);
                     $response = $modx->call('modTransportPackage', 'listPackages', array(&$modx, $workspace->get('id')));
                     if (isset($response['collection'])) {
                         foreach ($response['collection'] as $object) {
                             $packagesDir = MODX_CORE_PATH . 'packages/';
                             if ($object->getOne('Workspace')) {
                                 $packagesDir = $object->Workspace->get('path') . 'packages/';
                             }
                             $pkgSource = $object->get('source');
                             $folderPos = strrpos($pkgSource, '/');
                             $sourceDir = $folderPos > 1 ? substr($pkgSource, 0, $folderPos + 1) : '';
                             $source = realpath($packagesDir . $pkgSource);
                             $target = 'MODX_CORE_PATH . "packages/' . $sourceDir . '"';
                             $classAttributes = array_merge($attributes, array('resolve' => array(array('type' => 'file', 'source' => $source, 'target' => "return {$target};"))));
                             if ($package->put($object, $classAttributes)) {
                                 $instances++;
                             } else {
                                 $modx->log(modX::LOG_LEVEL_WARN, "Could not package {$class} instance with pk: " . print_r($object->getPrimaryKey(), true));
                             }
                         }
                     }
                     $modx->log(modX::LOG_LEVEL_INFO, "Packaged {$instances} of {$class}");
                     continue 2;
                 case 'sources.modMediaSource':
                     foreach ($modx->getIterator('sources.modMediaSource') as $object) {
                         $classAttributes = $attributes;
                         /** @var modMediaSource $object */
                         if ($object->get('is_stream') && $object->initialize()) {
                             $sourceBases = $object->getBases('');
                             $source = $object->getBasePath();
                             if (!$sourceBases['pathIsRelative'] && strpos($source, '://') === false) {
                                 $sourceBasePath = $source;
                                 if (strpos($source, $base_path) === 0) {
                                     $sourceBasePath = str_replace($base_path, '', $sourceBasePath);
                                     $classAttributes['resolve'][] = array('type' => 'php', 'source' => VAPOR_DIR . 'scripts/resolve.media_source.php', 'target' => $sourceBasePath, 'targetRelative' => true);
                                 } else {
                                     /* when coming from Windows sources, remove "{volume}:" */
                                     if (strpos($source, ':\\') !== false || strpos($source, ':/') !== false) {
                                         $sourceBasePath = str_replace('\\', '/', substr($source, strpos($source, ':') + 1));
                                     }
                                     $target = 'dirname(MODX_BASE_PATH) . "/sources/' . ltrim(dirname($sourceBasePath), '/') . '/"';
                                     $classAttributes['resolve'][] = array('type' => 'file', 'source' => $source, 'target' => "return {$target};");
                                     $classAttributes['resolve'][] = array('type' => 'php', 'source' => VAPOR_DIR . 'scripts/resolve.media_source.php', 'target' => $sourceBasePath, 'targetRelative' => false, 'targetPrepend' => "return dirname(MODX_BASE_PATH) . '/sources/';");
                                 }
                             }
                         }
                         if ($package->put($object, $classAttributes)) {
                             $instances++;
                         } else {
                             $modx->log(modX::LOG_LEVEL_WARN, "Could not package {$class} instance with pk: " . print_r($object->getPrimaryKey(), true));
                         }
                     }
                     $modx->log(modX::LOG_LEVEL_INFO, "Packaged {$instances} of {$class}");
                     continue 2;
                 default:
                     break;
             }
             /** @var xPDOObject $object */
             foreach ($modx->getIterator($class, $classCriteria) as $object) {
                 if ($package->put($object, $classAttributes)) {
                     $instances++;
                 } else {
                     $modx->log(modX::LOG_LEVEL_WARN, "Could not package {$class} instance with pk: " . print_r($object->getPrimaryKey(), true));
                 }
             }
             $modx->log(modX::LOG_LEVEL_INFO, "Packaged {$instances} of {$class}");
         }
         /* collect table names from classes and grab any additional tables/data not listed */
         $coreTables = array();
         $extraTables = array();
         foreach ($classes as $class) {
             $coreTables[$class] = $modx->quote($modx->literal($modx->getTableName($class)));
         }
         if ($coreTables) {
             $stmt = $modx->query("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = '{$modxDatabase}' AND TABLE_NAME NOT IN (" . implode(',', $coreTables) . ")");
             $extraTables = $stmt->fetchAll(PDO::FETCH_COLUMN);
         }
         if (is_array($extraTables) && !empty($extraTables)) {
             //$modx->loadClass('vapor.vaporVehicle', VAPOR_DIR . 'model/', true, true);
             $modx->loadClass('vapor.vaporVehicle', VAPOR_DIR, true, true);
             $excludeExtraTablePrefix = isset($vaporOptions['excludeExtraTablePrefix']) && is_array($vaporOptions['excludeExtraTablePrefix']) ? $vaporOptions['excludeExtraTablePrefix'] : array();
             $excludeExtraTables = isset($vaporOptions['excludeExtraTables']) && is_array($vaporOptions['excludeExtraTables']) ? $vaporOptions['excludeExtraTables'] : array();
             foreach ($extraTables as $extraTable) {
                 if (in_array($extraTable, $excludeExtraTables)) {
                     continue;
                 }
                 if (!XPDO_CLI_MODE && !ini_get('safe_mode')) {
                     set_time_limit(0);
                 }
                 $instances = 0;
                 $object = array();
                 $attributes = array('vehicle_package' => 'vapor', 'vehicle_class' => 'vaporVehicle');
                 /* remove modx table_prefix if table starts with it */
                 $extraTableName = $extraTable;
                 if (!empty($modxTablePrefix) && strpos($extraTableName, $modxTablePrefix) === 0) {
                     $extraTableName = substr($extraTableName, strlen($modxTablePrefix));
                     $addTablePrefix = true;
                 } elseif (!empty($modxTablePrefix) || in_array($extraTableName, $excludeExtraTablePrefix)) {
                     $addTablePrefix = false;
                 } else {
                     $addTablePrefix = true;
                 }
                 $object['tableName'] = $extraTableName;
                 $modx->log(modX::LOG_LEVEL_INFO, "Extracting non-core table {$extraTableName}");
                 /* generate the CREATE TABLE statement */
                 $stmt = $modx->query("SHOW CREATE TABLE {$modx->escape($extraTable)}");
                 $resultSet = $stmt->fetch(PDO::FETCH_NUM);
                 $stmt->closeCursor();
                 if (isset($resultSet[1])) {
                     if ($addTablePrefix) {
                         $object['drop'] = "DROP TABLE IF EXISTS {$modx->escape('[[++table_prefix]]' . $extraTableName)}";
                         $object['table'] = str_replace("CREATE TABLE {$modx->escape($extraTable)}", "CREATE TABLE {$modx->escape('[[++table_prefix]]' . $extraTableName)}", $resultSet[1]);
                     } else {
                         $object['drop'] = "DROP TABLE IF EXISTS {$modx->escape($extraTableName)}";
                         $object['table'] = $resultSet[1];
                     }
                     /* collect the rows and generate INSERT statements */
                     $object['data'] = array();
                     $stmt = $modx->query("SELECT * FROM {$modx->escape($extraTable)}");
                     while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                         if ($instances === 0) {
                             $fields = implode(', ', array_map(array($modx, 'escape'), array_keys($row)));
                         }
                         $values = array();
                         while (list($key, $value) = each($row)) {
                             switch (gettype($value)) {
                                 case 'string':
                                     $values[] = $modx->quote($value);
                                     break;
                                 case 'NULL':
                                 case 'array':
                                 case 'object':
                                 case 'resource':
                                 case 'unknown type':
                                     $values[] = 'NULL';
                                     break;
                                 default:
                                     $values[] = (string) $value;
                                     break;
                             }
                         }
                         $values = implode(', ', $values);
                         if ($addTablePrefix) {
                             $object['data'][] = "INSERT INTO {$modx->escape('[[++table_prefix]]' . $extraTableName)} ({$fields}) VALUES ({$values})";
                         } else {
                             $object['data'][] = "INSERT INTO {$modx->escape($extraTable)} ({$fields}) VALUES ({$values})";
                         }
                         $instances++;
                     }
                 }
                 if (!$package->put($object, $attributes)) {
                     $modx->log(modX::LOG_LEVEL_WARN, "Could not package rows for table {$extraTable}: " . print_r($object, true));
                 } else {
                     $modx->log(modX::LOG_LEVEL_INFO, "Packaged {$instances} rows for table {$extraTable}");
                 }
             }
         }
         if (!XPDO_CLI_MODE && !ini_get('safe_mode')) {
             set_time_limit(0);
         }
         if (!$package->pack()) {
             $message = "Error extracting package, could not pack transport: {$package->signature}";
             $modx->log(modX::LOG_LEVEL_ERROR, $message);
             //echo "{$message}\n";
         } else {
             $message = "Completed extracting package: {$package->signature}";
             $modx->log(modX::LOG_LEVEL_INFO, $message);
             //echo "{$message}\n";
         }
         $endTime = microtime(true);
         $msg = sprintf("Vapor execution completed without exception in %2.4fs", $endTime - $this->getProperty('startTime'));
         $modx->log(modX::LOG_LEVEL_INFO, $msg);
         return $this->success($msg, array('signature' => $package->signature));
     } catch (Exception $e) {
         if (empty($endTime)) {
             $endTime = microtime(true);
         }
         if (!empty($modx)) {
             $modx->log(modX::LOG_LEVEL_ERROR, $e->getMessage());
             $msg = sprintf("Vapor execution completed with exception in %2.4fs", $endTime - $this->getProperty('startTime'));
             $modx->log(modX::LOG_LEVEL_INFO, $msg);
             return $this->failure($msg);
         } else {
             //echo $e->getMessage() . "\n";
         }
         $msg = sprintf("Vapor execution completed with exception in %2.4fs\n", $endTime - $this->getProperty('startTime'));
         $modx->log(modX::LOG_LEVEL_INFO, $msg);
         return $this->failure($msg);
     }
     return $modx->success(printf("Vapor execution completed without exception in %2.4fs\n", $endTime - $this->getProperty('startTime')));
 }