/**
  * Load the attributes for the ACLs for the context
  *
  * @static
  * @param modX $modx A reference to the modX instance
  * @param string $context The context to load from. If empty, will use the current context.
  * @param int $userId The ID of the user to grab ACL records for.
  * @return array An array of loaded attributes
  */
 public static function loadAttributes(&$modx, $context = '', $userId = 0)
 {
     $attributes = array();
     $accessTable = $modx->getTableName('modAccessNamespace');
     $policyTable = $modx->getTableName('modAccessPolicy');
     $memberTable = $modx->getTableName('modUserGroupMember');
     $memberRoleTable = $modx->getTableName('modUserGroupRole');
     if ($userId > 0) {
         $sql = "SELECT acl.target, acl.principal, mr.authority, acl.policy, p.data FROM {$accessTable} acl " . "LEFT JOIN {$policyTable} p ON p.id = acl.policy " . "JOIN {$memberTable} mug ON acl.principal_class = 'modUserGroup' " . "AND mug.member = :principal " . "AND mug.user_group = acl.principal " . "JOIN {$memberRoleTable} mr ON mr.id = mug.role " . "AND mr.authority <= acl.authority " . "ORDER BY acl.target, acl.principal, mr.authority, acl.policy";
         $bindings = array(':principal' => $userId);
         $query = new xPDOCriteria($modx, $sql, $bindings);
         if ($query->stmt && $query->stmt->execute()) {
             while ($row = $query->stmt->fetch(PDO::FETCH_ASSOC)) {
                 $attributes[$row['target']][] = array('principal' => $row['principal'], 'authority' => $row['authority'], 'policy' => $row['data'] ? $modx->fromJSON($row['data'], true) : array());
             }
         }
     } else {
         $sql = "SELECT acl.target, acl.principal, 0 AS authority, acl.policy, p.data FROM {$accessTable} acl " . "LEFT JOIN {$policyTable} p ON p.id = acl.policy " . "WHERE acl.principal_class = 'modUserGroup' " . "AND acl.principal = 0 " . "ORDER BY acl.target, acl.principal, acl.authority, acl.policy";
         $query = new xPDOCriteria($modx, $sql);
         if ($query->stmt && $query->stmt->execute()) {
             while ($row = $query->stmt->fetch(PDO::FETCH_ASSOC)) {
                 $attributes[$row['target']][] = array('principal' => 0, 'authority' => $row['authority'], 'policy' => $row['data'] ? $modx->fromJSON($row['data'], true) : array());
             }
         }
     }
     return $attributes;
 }
Пример #2
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;
 }
 public static function listPackages(modX &$modx, $workspace, $limit = 0, $offset = 0) {
     $result = array('collection' => array(), 'total' => 0);
     $c = $modx->newQuery('transport.modTransportPackage');
     $c->leftJoin('transport.modTransportProvider','Provider', array("modTransportPackage.provider = Provider.id"));
     $c->where(array(
         'workspace' => $workspace,
     ));
     $c->where(array(
         "(SELECT
             `signature`
           FROM {$modx->getTableName('modTransportPackage')} AS `latestPackage`
           WHERE `latestPackage`.`package_name` = `modTransportPackage`.`package_name`
           ORDER BY
              `latestPackage`.`version_major` DESC,
              `latestPackage`.`version_minor` DESC,
              `latestPackage`.`version_patch` DESC,
              IF(`release` = '' OR `release` = 'ga' OR `release` = 'pl','z',`release`) DESC,
              `latestPackage`.`release_index` DESC
           LIMIT 1) = `modTransportPackage`.`signature`",
     ));
     $result['total'] = $modx->getCount('modTransportPackage',$c);
     $c->select(array(
         'modTransportPackage.*',
     ));
     $c->select('`Provider`.`name` AS `provider_name`');
     $c->sortby('`modTransportPackage`.`signature`', 'ASC');
     if ($limit > 0) $c->limit($limit, $offset);
     $result['collection'] = $modx->getCollection('transport.modTransportPackage',$c);
     return $result;
 }
 public static function listPackages(modX &$modx, $workspace, $limit = 0, $offset = 0) {
     $result = array('collection' => array(), 'total' => 0);
     $c = $modx->newQuery('transport.modTransportPackage');
     $c->leftJoin('transport.modTransportProvider','Provider', array("modTransportPackage.provider = Provider.id"));
     $c->where(array(
         'workspace' => $workspace,
     ));
     $c->where(array(
         "(SELECT TOP 1
             latestPackage.signature
           FROM {$modx->getTableName('modTransportPackage')} AS latestPackage
           WHERE latestPackage.package_name = modTransportPackage.package_name
           ORDER BY
              latestPackage.version_major DESC,
              latestPackage.version_minor DESC,
              latestPackage.version_patch DESC,
              CASE WHEN latestPackage.release = '' OR latestPackage.release = 'ga' OR latestPackage.release = 'pl' THEN 'z' ELSE latestPackage.release END DESC,
              latestPackage.release_index DESC
           ) = modTransportPackage.signature",
     ));
     $result['total'] = $modx->getCount('modTransportPackage',$c);
     $c->select(array(
         'modTransportPackage.*',
     ));
     $c->select('Provider.name AS provider_name');
     $c->sortby('modTransportPackage.signature', 'ASC');
     if ($limit > 0) $c->limit($limit, $offset);
     $result['collection'] = $modx->getCollection('transport.modTransportPackage',$c);
     return $result;
 }
Пример #5
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;
 }
 /**
  * Load the attributes for the ACLs for the Resource Group
  *
  * @static
  * @param modX $modx A reference to the modX instance
  * @param string $context The context to load from. If empty, will use the current context.
  * @param int $userId The ID of the user to grab ACL records for.
  * @return array An array of loaded attributes
  */
 public static function loadAttributes(&$modx, $context = '', $userId = 0)
 {
     $attributes = array();
     if (empty($context)) {
         $context = $modx->context->get('key');
     }
     $enabled = (bool) $modx->getOption('access_resource_group_enabled', null, true);
     if ($context !== $modx->context->get('key') && $modx->getContext($context)) {
         $enabled = (bool) $modx->contexts[$context]->getOption('access_resource_group_enabled', $enabled);
     }
     if ($enabled) {
         $accessTable = $modx->getTableName('modAccessResourceGroup');
         $policyTable = $modx->getTableName('modAccessPolicy');
         $memberTable = $modx->getTableName('modUserGroupMember');
         $memberRoleTable = $modx->getTableName('modUserGroupRole');
         $legacyDocGroups = array();
         if ($userId > 0) {
             $sql = "SELECT acl.target, acl.principal, mr.authority, acl.policy, p.data FROM {$accessTable} acl " . "LEFT JOIN {$policyTable} p ON p.id = acl.policy " . "JOIN {$memberTable} mug ON acl.principal_class = 'modUserGroup' " . "AND (acl.context_key = :context OR acl.context_key IS NULL OR acl.context_key = '') " . "AND mug.member = :principal " . "AND mug.user_group = acl.principal " . "JOIN {$memberRoleTable} mr ON mr.id = mug.role " . "AND mr.authority <= acl.authority " . "ORDER BY acl.target, acl.principal, mr.authority, acl.policy";
             $bindings = array(':principal' => $userId, ':context' => $context);
             $query = new xPDOCriteria($modx, $sql, $bindings);
             if ($query->stmt && $query->stmt->execute()) {
                 while ($row = $query->stmt->fetch(PDO::FETCH_ASSOC)) {
                     $attributes[$row['target']][] = array('principal' => $row['principal'], 'authority' => $row['authority'], 'policy' => $row['data'] ? $modx->fromJSON($row['data'], true) : array());
                     $legacyDocGroups[$row['target']] = $row['target'];
                 }
             }
         } else {
             $sql = "SELECT acl.target, acl.principal, 0 AS authority, acl.policy, p.data FROM {$accessTable} acl " . "LEFT JOIN {$policyTable} p ON p.id = acl.policy " . "WHERE acl.principal_class = 'modUserGroup' " . "AND acl.principal = 0 " . "AND (acl.context_key = :context OR acl.context_key IS NULL OR acl.context_key = '') " . "ORDER BY acl.target, acl.principal, acl.authority, acl.policy";
             $bindings = array(':context' => $context);
             $query = new xPDOCriteria($modx, $sql, $bindings);
             if ($query->stmt && $query->stmt->execute()) {
                 while ($row = $query->stmt->fetch(PDO::FETCH_ASSOC)) {
                     $attributes[$row['target']][] = array('principal' => 0, 'authority' => $row['authority'], 'policy' => $row['data'] ? $modx->fromJSON($row['data'], true) : array());
                     $legacyDocGroups[$row['target']] = $row['target'];
                 }
             }
         }
         $_SESSION['modx.user.' . ($userId > 0 ? (string) $userId : '0') . '.resourceGroups'] = array($context => array_values($legacyDocGroups));
     }
     return $attributes;
 }
 /**
  * Return current number of order
  *
  * @return string
  */
 public function getnum()
 {
     $table = $this->modx->getTableName('msOrder');
     $cur = date('ym');
     $sql = $this->modx->query("SELECT `num` FROM {$table} WHERE `num` LIKE '{$cur}%' ORDER BY `id` DESC LIMIT 1");
     $num = $sql->fetch(PDO::FETCH_COLUMN);
     if (empty($num)) {
         $num = date('ym') . '/0';
     }
     $num = explode('/', $num);
     $num = $cur . '/' . ($num[1] + 1);
     return $num;
 }
 /**
  * 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;
 }
Пример #9
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);
     }
 }
Пример #10
0
 /**
  * Loads the access control policies applicable to this template variable.
  *
  * {@inheritdoc}
  */
 public function findPolicy($context = '')
 {
     $policy = array();
     $context = !empty($context) ? $context : $this->xpdo->context->get('key');
     if ($context === $this->xpdo->context->get('key')) {
         $catEnabled = (bool) $this->xpdo->getOption('access_category_enabled', null, true);
         $rgEnabled = (bool) $this->xpdo->getOption('access_resource_group_enabled', null, true);
     } elseif ($this->xpdo->getContext($context)) {
         $catEnabled = (bool) $this->xpdo->contexts[$context]->getOption('access_category_enabled', true);
         $rgEnabled = (bool) $this->xpdo->contexts[$context]->getOption('access_resource_group_enabled', true);
     }
     $enabled = $catEnabled || $rgEnabled;
     if ($enabled) {
         if (empty($this->_policies) || !isset($this->_policies[$context])) {
             if ($rgEnabled) {
                 $accessTable = $this->xpdo->getTableName('modAccessResourceGroup');
                 $policyTable = $this->xpdo->getTableName('modAccessPolicy');
                 $resourceGroupTable = $this->xpdo->getTableName('modTemplateVarResourceGroup');
                 $sql = "SELECT Acl.target, Acl.principal, Acl.authority, Acl.policy, Policy.data FROM {$accessTable} Acl " . "LEFT JOIN {$policyTable} Policy ON Policy.id = Acl.policy " . "JOIN {$resourceGroupTable} ResourceGroup ON Acl.principal_class = 'modUserGroup' " . "AND (Acl.context_key = :context OR Acl.context_key IS NULL OR Acl.context_key = '') " . "AND ResourceGroup.tmplvarid = :element " . "AND ResourceGroup.documentgroup = Acl.target " . "ORDER BY Acl.target, Acl.principal, Acl.authority";
                 $bindings = array(':element' => $this->get('id'), ':context' => $context);
                 $query = new xPDOCriteria($this->xpdo, $sql, $bindings);
                 if ($query->stmt && $query->stmt->execute()) {
                     while ($row = $query->stmt->fetch(PDO::FETCH_ASSOC)) {
                         $policy['modAccessResourceGroup'][$row['target']][] = array('principal' => $row['principal'], 'authority' => $row['authority'], 'policy' => $row['data'] ? $this->xpdo->fromJSON($row['data'], true) : array());
                     }
                 }
             }
             if ($catEnabled) {
                 $accessTable = $this->xpdo->getTableName('modAccessCategory');
                 $categoryClosureTable = $this->xpdo->getTableName('modCategoryClosure');
                 $sql = "SELECT Acl.target, Acl.principal, Acl.authority, Acl.policy, Policy.data FROM {$accessTable} Acl " . "LEFT JOIN {$policyTable} Policy ON Policy.id = Acl.policy " . "JOIN {$categoryClosureTable} CategoryClosure ON CategoryClosure.descendant = :category " . "AND Acl.principal_class = 'modUserGroup' " . "AND CategoryClosure.ancestor = Acl.target " . "AND (Acl.context_key = :context OR Acl.context_key IS NULL OR Acl.context_key = '') " . "ORDER BY CategoryClosure.depth DESC, target, principal, authority ASC";
                 $bindings = array(':category' => $this->get('category'), ':context' => $context);
                 $query = new xPDOCriteria($this->xpdo, $sql, $bindings);
                 if ($query->stmt && $query->stmt->execute()) {
                     while ($row = $query->stmt->fetch(PDO::FETCH_ASSOC)) {
                         $policy['modAccessCategory'][$row['target']][] = array('principal' => $row['principal'], 'authority' => $row['authority'], 'policy' => $row['data'] ? $this->xpdo->fromJSON($row['data'], true) : array());
                     }
                 }
             }
             $this->_policies[$context] = $policy;
         } else {
             $policy = $this->_policies[$context];
         }
     }
     return $policy;
 }
Пример #11
0
 /**
  * Accurate sorting of resource files
  *
  * @param $resource_id
  */
 public function rankResourceImages($resource_id)
 {
     if (!$this->modx->getOption('ms2gallery_exact_sorting', null, true, true)) {
         return;
     }
     $q = $this->modx->newQuery('msResourceFile', array('resource_id' => $resource_id, 'parent' => 0));
     $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 (`id` = {$id} OR `parent` = {$id});";
             }
         }
         $sql .= "ALTER TABLE {$table} ORDER BY `rank` ASC;";
         $this->modx->exec($sql);
     }
 }
 public static function listPackages(modX &$modx, $workspace, $limit = 0, $offset = 0, $search = '')
 {
     $result = array('collection' => array(), 'total' => 0);
     $c = $modx->newQuery('transport.modTransportPackage');
     $c->leftJoin('transport.modTransportProvider', 'Provider', array("modTransportPackage.provider = Provider.id"));
     $c->where(array('workspace' => $workspace));
     $c->where(array("(SELECT\n                `signature`\n              FROM {$modx->getTableName('modTransportPackage')} AS `latestPackage`\n              WHERE `latestPackage`.`package_name` = `modTransportPackage`.`package_name`\n              ORDER BY\n                `latestPackage`.`version_major` DESC,\n                `latestPackage`.`version_minor` DESC,\n                `latestPackage`.`version_patch` DESC,\n                IF(`release` = '' OR `release` = 'ga' OR `release` = 'pl','z',IF(`release` = 'dev','a',`release`)) DESC,\n                `latestPackage`.`release_index` DESC\n              LIMIT 1) = `modTransportPackage`.`signature`"));
     if (!empty($search)) {
         $c->where(array('modTransportPackage.signature:LIKE' => '%' . $search . '%', 'OR:modTransportPackage.package_name:LIKE' => '%' . $search . '%'));
     }
     $result['total'] = $modx->getCount('modTransportPackage', $c);
     $c->select(array('modTransportPackage.*'));
     $c->select('`Provider`.`name` AS `provider_name`');
     $c->sortby('`modTransportPackage`.`signature`', 'ASC');
     if ($limit > 0) {
         $c->limit($limit, $offset);
     }
     $result['collection'] = $modx->getCollection('transport.modTransportPackage', $c);
     return $result;
 }
Пример #13
0
 /**
  * Get the cache of Users and User Groups from the Discuss database
  * @return boolean
  */
 protected function collectUserCaches()
 {
     $this->log('Collecting User cache...');
     $userTable = $this->modx->getTableName('disUser');
     $stmt = $this->modx->query('SELECT id,username,integrated_id FROM ' . $userTable . ' ORDER BY username ASC');
     if ($stmt) {
         while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
             $this->memberCache[$row['integrated_id']] = $row['id'];
             $this->memberNameCache[$row['integrated_id']] = $row['username'];
         }
         $stmt->closeCursor();
     }
     $this->log('Collecting User Group cache...');
     $userGroupTable = $this->modx->getTableName('disUserGroupProfile');
     $stmt = $this->modx->query('SELECT id,name,integrated_id FROM ' . $userGroupTable . ' ORDER BY name ASC');
     if ($stmt) {
         while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
             $this->memberGroupCache[$row['integrated_id']] = $row['id'];
         }
         $stmt->closeCursor();
     }
     return true;
 }
Пример #14
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')));
 }
Пример #15
0
 /**
  * Find all policies for this object
  * 
  * @param string $context
  * @return array
  */
 public function findPolicy($context = '')
 {
     $policy = array();
     $enabled = true;
     $context = 'mgr';
     if ($context === $this->xpdo->context->get('key')) {
         $enabled = (bool) $this->xpdo->getOption('access_media_source_enabled', null, true);
     } elseif ($this->xpdo->getContext($context)) {
         $enabled = (bool) $this->xpdo->contexts[$context]->getOption('access_media_source_enabled', true);
     }
     if ($enabled) {
         if (empty($this->_policies) || !isset($this->_policies[$context])) {
             $accessTable = $this->xpdo->getTableName('sources.modAccessMediaSource');
             $sourceTable = $this->xpdo->getTableName('sources.modMediaSource');
             $policyTable = $this->xpdo->getTableName('modAccessPolicy');
             $sql = "SELECT Acl.target, Acl.principal, Acl.authority, Acl.policy, Policy.data FROM {$accessTable} Acl " . "LEFT JOIN {$policyTable} Policy ON Policy.id = Acl.policy " . "JOIN {$sourceTable} Source ON Acl.principal_class = 'modUserGroup' " . "AND (Acl.context_key = :context OR Acl.context_key IS NULL OR Acl.context_key = '') " . "AND Source.id = Acl.target " . "WHERE Acl.target = :source " . "GROUP BY Acl.target, Acl.principal, Acl.authority, Acl.policy";
             $bindings = array(':source' => $this->get('id'), ':context' => $context);
             $query = new xPDOCriteria($this->xpdo, $sql, $bindings);
             if ($query->stmt && $query->stmt->execute()) {
                 while ($row = $query->stmt->fetch(PDO::FETCH_ASSOC)) {
                     $policy['sources.modAccessMediaSource'][$row['target']][] = array('principal' => $row['principal'], 'authority' => $row['authority'], 'policy' => $row['data'] ? $this->xpdo->fromJSON($row['data'], true) : array());
                 }
             }
             $this->_policies[$context] = $policy;
         } else {
             $policy = $this->_policies[$context];
         }
     }
     return $policy;
 }
Пример #16
0
             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()));
         }
     }
     $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();
 foreach ($classes as $class) {
     $coreTables[$class] = $modx->quote($modx->literal($modx->getTableName($class)));
 }
 $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);
     $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;
Пример #17
0
$discuss = $modx->getService('discuss', 'Discuss', $modx->getOption('discuss.core_path', null, $modx->getOption('core_path') . 'components/discuss/') . 'model/discuss/');
if (!$discuss instanceof Discuss) {
    return '';
}
/* setup mem limits */
ini_set('memory_limit', '1024M');
set_time_limit(0);
@ob_end_clean();
echo '<pre>';
/* fix num_replies */
$sql = 'SELECT
    disThread.id,
    disThread.title,
    disThread.replies,
    (
        SELECT COUNT(`Posts`.`id`) FROM ' . $modx->getTableName('disPost') . ' AS `Posts`
        WHERE `Posts`.`thread` = `disThread`.`id`
    ) AS `real_count`
    FROM ' . $modx->getTableName('disThread') . ' `disThread`
    ORDER BY `disThread`.`id` ASC';
$stmt = $modx->query($sql);
if ($stmt) {
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $row['real_count'] = $row['real_count'] - 1;
        // First post does not count as reply
        //$modx->log(modX::LOG_LEVEL_ERROR,$row['title'] . ' Real: ' . $row['real_count'] . ' Set: '.$row['replies']);
        if (!empty($row['real_count']) && $row['real_count'] != $row['replies']) {
            $modx->log(modX::LOG_LEVEL_ERROR, 'Setting "' . $row['title'] . '" to ' . $row['real_count'] . ' from ' . $row['replies']);
            $modx->exec('UPDATE ' . $modx->getTableName('disThread') . '
                SET `replies` = ' . $row['real_count'] . '
                WHERE `id` = ' . $row['id']);
Пример #18
0
            $user->set('active', 1);
            $user->set('password', $password);
            $profile->set('email', $email);
            $profile->set('internalKey', 0);
            $user->addOne($profile, 'Profile');
            // save user
            if (!$user->save()) {
                print 'ERROR: Could not save user.';
            }
        }
        // Add User to a User Group
        $Member = $modx->newObject('modUserGroupMember');
        $Member->set('user_group', $usergroup->get('id'));
        $Member->set('member', $user->get('id'));
        // Grant the user a role within that group
        $Member->set('role', 1);
        $Member->set('rank', 0);
        if (!$Member->save()) {
            print 'ERROR: Could not add User to User Group';
            exit;
        }
    }
}
// Flush Permissions ??
// Clear Cache
$modx->query("TRUNCATE TABLE " . $modx->getTableName("modSession"));
$modx->cacheManager->refresh();
$login_id = $page1->get('id');
$url = $modx->makeUrl($login_id, '', '', 'full');
print 'SUCCESS.  You can log in at <a href="' . $url . '">Login Page</a>';
/*EOF*/
Пример #19
0
 /**
  * Merge another user into this account
  *
  * @param disUser $oldUser
  * @return boolean
  */
 public function merge(disUser &$oldUser)
 {
     $success = true;
     $user = $this->getOne('User');
     if (empty($user)) {
         return false;
     }
     $oldModxUser = $oldUser->getOne('User');
     if (empty($oldModxUser)) {
         return false;
     }
     $this->xpdo->beginTransaction();
     /* merge post count */
     $posts = $user->get('posts');
     $posts = $posts + $oldUser->get('posts');
     $this->set('posts', $posts);
     /* merge ignore boards */
     $ibs = $this->get('ignore_boards');
     $ibs = explode(',', $ibs);
     $oldIbs = $oldUser->get('ignore_boards');
     $oldIbs = explode(',', $oldIbs);
     $ibs = array_merge($oldIbs, $ibs);
     $this->set('ignore_boards', implode(',', $ibs));
     /* merge signature if needed */
     $signature = $this->get('signature');
     $oldSignature = $oldUser->get('signature');
     if (empty($signature) && !empty($oldSignature)) {
         $this->set('signature', $oldSignature);
     }
     /* merge title if needed */
     $title = $this->get('title');
     $oldTitle = $oldUser->get('title');
     if (empty($title) && !empty($oldTitle)) {
         $this->set('title', $oldTitle);
     }
     /* merge primary_group if needed */
     $pg = $this->get('primary_group');
     $oldPg = $oldUser->get('primary_group');
     if (empty($pg) && !empty($oldPg)) {
         $this->set('primary_group', $oldPg);
     }
     $this->set('integrated_id', $oldUser->get('integrated_id'));
     $this->set('synced', true);
     $this->set('syncedat', $this->xpdo->discuss->now());
     $this->save();
     /* grant old usergroups to this user */
     $oldUserGroups = $this->xpdo->getCollection('modUserGroupMember', array('member' => $oldModxUser->get('id')));
     $ugs = array();
     foreach ($oldUserGroups as $oldUserGroup) {
         $ugs[] = $oldUserGroup->get('user_group');
     }
     $ugs = array_unique($ugs);
     foreach ($ugs as $ug) {
         $user->joinGroup($ug);
     }
     /* merge in posts, change authors */
     $sql = 'UPDATE ' . $this->xpdo->getTableName('disPost') . '
         SET `author` = ' . $this->get('id') . '
         WHERE `author` = ' . $oldUser->get('id') . '
     ';
     $this->xpdo->query($sql);
     $sql = 'UPDATE ' . $this->xpdo->getTableName('disThread') . '
         SET `author_first` = ' . $this->get('id') . '
         WHERE `author_first` = ' . $oldUser->get('id') . '
     ';
     $this->xpdo->query($sql);
     $sql = 'UPDATE ' . $this->xpdo->getTableName('disThread') . '
         SET `author_last` = ' . $this->get('id') . '
         WHERE `author_last` = ' . $oldUser->get('id') . '
     ';
     $this->xpdo->query($sql);
     /* merge in disThreadRead */
     $sql = 'UPDATE ' . $this->xpdo->getTableName('disThreadRead') . '
         SET `user` = ' . $this->get('id') . '
         WHERE `user` = ' . $oldUser->get('id') . '
     ';
     $this->xpdo->query($sql);
     /* merge in disThreadUser */
     $sql = 'UPDATE ' . $this->xpdo->getTableName('disThreadUser') . '
         SET `user` = ' . $this->get('id') . '
         WHERE `user` = ' . $oldUser->get('id') . '
     ';
     $this->xpdo->query($sql);
     /* merge in disUserFriend */
     $sql = 'UPDATE ' . $this->xpdo->getTableName('disUserFriend') . '
         SET `user` = ' . $this->get('id') . '
         WHERE `user` = ' . $oldUser->get('id') . '
     ';
     $this->xpdo->query($sql);
     $sql = 'UPDATE ' . $this->xpdo->getTableName('disUserFriend') . '
         SET `friend` = ' . $this->get('id') . '
         WHERE `friend` = ' . $oldUser->get('id') . '
     ';
     $this->xpdo->query($sql);
     /* merge in disUserNotification */
     $sql = 'UPDATE ' . $this->xpdo->getTableName('disUserNotification') . '
         SET `user` = ' . $this->get('id') . '
         WHERE `user` = ' . $oldUser->get('id') . '
     ';
     $this->xpdo->query($sql);
     /* merge in disModerator */
     $sql = 'UPDATE ' . $this->xpdo->getTableName('disModerator') . '
         SET `user` = ' . $this->get('id') . '
         WHERE `user` = ' . $oldUser->get('id') . '
     ';
     $this->xpdo->query($sql);
     /* remove old user sessions */
     $sql = 'DELETE FROM ' . $this->xpdo->getTableName('disUserFriend') . '
         WHERE `user` = ' . $oldUser->get('id') . '
     ';
     $this->xpdo->query($sql);
     /* merge all PMs users fields for user */
     $c = $this->xpdo->newQuery('disThread');
     $c->innerJoin('disThreadUser', 'Users');
     $c->leftJoin('disThreadRead', 'Reads', 'Reads.user = ' . $oldUser->get('id') . ' AND disThread.id = Reads.thread');
     $c->where(array('disThread.private' => true, 'Users.user' => $oldUser->get('id')));
     $pms = $this->xpdo->getCollection('disThread', $c);
     foreach ($pms as $pm) {
         $users = $pm->get('users');
         $users = explode(',', $users);
         $users = array_diff($users, array($oldUser->get('id')));
         $users[] = $this->get('id');
         $pm->set('users', implode(',', $users));
         $pm->save();
     }
     /* remove old users */
     $oldUser->remove();
     $oldModxUser->remove();
     /* check for post group advance */
     $this->checkForPostGroupAdvance();
     $this->xpdo->commit();
     return $success;
 }
Пример #20
0
$discuss = $modx->getService('discuss', 'Discuss', $modx->getOption('discuss.core_path', null, $modx->getOption('core_path') . 'components/discuss/') . 'model/discuss/');
if (!$discuss instanceof Discuss) {
    return '';
}
/* setup mem limits */
ini_set('memory_limit', '1024M');
set_time_limit(0);
@ob_end_clean();
echo '<pre>';
/* fix num_topics */
$sql = 'SELECT
    disBoard.id,
    disBoard.name,
    disBoard.num_topics,
    (
        SELECT COUNT(`Threads`.`id`) FROM ' . $modx->getTableName('disThread') . ' AS `Threads`
        WHERE `Threads`.`board` = `disBoard`.`id`
    ) AS `real_count`
    FROM ' . $modx->getTableName('disBoard') . ' `disBoard`
    ORDER BY `disBoard`.`map` ASC';
$stmt = $modx->query($sql);
if ($stmt) {
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        if (!empty($row['real_count']) && $row['real_count'] != $row['num_topics']) {
            $modx->log(modX::LOG_LEVEL_ERROR, 'Setting "' . $row['name'] . '" to ' . $row['real_count'] . ' from ' . $row['num_topics']);
            $modx->exec('UPDATE ' . $modx->getTableName('disBoard') . '
                SET `num_topics` = ' . $row['real_count'] . '
                WHERE `id` = ' . $row['id']);
        }
    }
    $stmt->closeCursor();
Пример #21
0
/**
 * Logout all users, clear the cache, make sure config file is writable
 *
 */
function prepare_modx_upgrade($data)
{
    $core_path = $data['core_path'];
    chmod($core_path . 'config/config.inc.php', DIR_PERMS);
    // This might brick if the install isn't working.
    require_once $data['base_path'] . 'index.php';
    $modx = new modX();
    $modx->initialize('mgr');
    // See http://tracker.modx.com/issues/9916
    $sessionTable = $modx->getTableName('modSession');
    $modx->query("TRUNCATE TABLE {$sessionTable}");
    @$modx->cacheManager->refresh();
}