Пример #1
0
 public static function add(phpThumbOn $ThumbOn, modX $modx)
 {
     $from = $ThumbOn->getOption('input');
     $to = $ThumbOn->getOption('_cacheFileName');
     $options = $ThumbOn->getOption('_options', array('f' => $ThumbOn::DEFAULT_EXT));
     $noImage = $ThumbOn->getOption('noimage');
     $modx->addPackage("phpthumbon", $ThumbOn->getOption('modelPath'));
     switch ($ThumbOn->getOption('queue')) {
         case 2:
             //Отправляем в очередь и сжимаем картику noimage
             $path = $ThumbOn->getOption('assetsPath', MODX_BASE_PATH . '/assets/') . "/components/phpthumbon/cache/";
             $tmp = md5(serialize($options)) . "." . $options['f'];
             $ThumbOn->makeDir($path);
             if (file_exists($path . $tmp)) {
                 copy($path . $tmp, $to);
             } else {
                 if ($to = $ThumbOn->loadResizer($noImage, $to)) {
                     copy($to, $path . $tmp);
                 }
             }
             $modx->newObject("ThumbImages", array('image' => $from, 'cache_image' => $to, 'config' => $options, 'isend' => $from == $noImage))->save();
             break;
         case 1:
         default:
             //Отправляем в очередь и сразу отдаем картинку noimage
             if (!file_exists($to)) {
                 copy($noImage, $to);
             }
             $modx->newObject("ThumbImages", array('image' => $from, 'cache_image' => $to, 'config' => $options, 'isend' => 0))->save();
             break;
     }
     return $to;
 }
Пример #2
0
 /**
  * Returns a modChunk object from a template file.
  *
  * @access private
  * @param string $name The name of the Chunk. Will parse to name.chunk.tpl by default.
  * @param string $suffix The suffix to add to the chunk filename.
  * @return modChunk/boolean Returns the modChunk object if found, otherwise
  * false.
  */
 private function _getTplChunk($name, $suffix = '.chunk.tpl')
 {
     $chunk = false;
     $f = $this->config['chunksPath'] . strtolower($name) . $suffix;
     if (file_exists($f)) {
         $o = file_get_contents($f);
         /** @var modChunk $chunk */
         $chunk = $this->modx->newObject('modChunk');
         $chunk->set('name', $name);
         $chunk->setContent($o);
     }
     return $chunk;
 }
Пример #3
0
 /**
  * Get a modElement instance taking advantage of the modX::$sourceCache.
  *
  * @param string $class The modElement derivative class to load.
  * @param string $name An element name or raw tagName to identify the modElement instance.
  * @return modElement|null An instance of the specified modElement derivative class.
  */
 public function getElement($class, $name)
 {
     $realname = $this->realname($name);
     if (array_key_exists($class, $this->modx->sourceCache) && array_key_exists($realname, $this->modx->sourceCache[$class])) {
         /** @var modElement $element */
         $element = $this->modx->newObject($class);
         $element->fromArray($this->modx->sourceCache[$class][$realname]['fields'], '', true, true);
         $element->setPolicies($this->modx->sourceCache[$class][$realname]['policies']);
         if (!empty($this->modx->sourceCache[$class][$realname]['source'])) {
             if (!empty($this->modx->sourceCache[$class][$realname]['source']['class_key'])) {
                 $sourceClassKey = $this->modx->sourceCache[$class][$realname]['source']['class_key'];
                 $this->modx->loadClass('sources.modMediaSource');
                 /* @var modMediaSource $source */
                 $source = $this->modx->newObject($sourceClassKey);
                 $source->fromArray($this->modx->sourceCache[$class][$realname]['source'], '', true, true);
                 $element->addOne($source, 'Source');
             }
         }
     } else {
         /** @var modElement $element */
         $element = $this->modx->getObjectGraph($class, array('Source' => array()), array('name' => $realname), true);
         if ($element && array_key_exists($class, $this->modx->sourceCache)) {
             $this->modx->sourceCache[$class][$realname] = array('fields' => $element->toArray(), 'policies' => $element->getPolicies(), 'source' => $element->Source ? $element->Source->toArray() : array());
         }
     }
     if ($element instanceof modElement) {
         $element->set('name', $name);
     }
     return $element;
 }
 public function transfer($signature, $target = null, array $args = array())
 {
     $result = false;
     $metadata = $this->info($signature);
     if (!empty($metadata)) {
         /** @var modTransportPackage $package */
         $package = $this->xpdo->newObject('transport.modTransportPackage');
         $package->set('signature', $signature);
         $package->set('state', 1);
         $package->set('workspace', 1);
         $package->set('created', date('Y-m-d h:i:s'));
         $package->set('provider', $this->get('id'));
         $package->set('metadata', $metadata);
         $package->set('package_name', $metadata['name']);
         $package->parseSignature();
         $package->setPackageVersionData();
         $locationArgs = isset($metadata['file']) ? array_merge($metadata['file'], $args) : $args;
         $url = $this->downloadUrl($signature, $this->arg('location', $locationArgs), $args);
         if (!empty($url)) {
             if (empty($target)) {
                 $target = $this->xpdo->getOption('core_path', $args, MODX_CORE_PATH) . 'packages/';
             }
             if ($package->transferPackage($url, $target)) {
                 if ($package->save()) {
                     $package->getTransport();
                     $result = $package;
                 }
             }
         }
     }
     return $result;
 }
Пример #5
0
 public function postInstall()
 {
     /* fix settings_version */
     /** @var \modSystemSetting $object */
     $object = $this->xpdo->getObject('modSystemSetting', array('key' => 'settings_version'));
     if (!$object) {
         $object = $this->xpdo->newObject('modSystemSetting');
         $object->fromArray(array('key' => 'settings_version', 'area' => 'system', 'namespace' => 'core', 'xtype' => 'textfield'), '', true);
     }
     $object->set('value', $this->xpdo->version['full_version']);
     $object->save(false);
     /* fix session_cookie_domain */
     $object = $this->xpdo->getObject('modSystemSetting', array('key' => 'session_cookie_domain'));
     if (!$object) {
         $object = $this->xpdo->newObject('modSystemSetting');
         $object->fromArray(array('key' => 'session_cookie_domain', 'area' => 'session', 'namespace' => 'core', 'xtype' => 'textfield'), '', true);
     }
     $object->set('value', '');
     $object->save(false);
     /* fix session_cookie_path */
     $object = $this->xpdo->getObject('modSystemSetting', array('key' => 'session_cookie_path'));
     if (!$object) {
         $object = $this->xpdo->newObject('modSystemSetting');
         $object->fromArray(array('key' => 'session_cookie_path', 'area' => 'session', 'namespace' => 'core', 'xtype' => 'textfield'), '', true);
     }
     $object->set('value', $this->xpdo->getOption('base_url', null, MODX_BASE_URL));
     $object->save(false);
 }
Пример #6
0
 /**
  * Get the statistics for the bottom area of the forums
  * @return void
  */
 protected function getStatistics()
 {
     $this->setPlaceholder('totalPosts', number_format((int) $this->getPostCount()));
     $this->setPlaceholder('totalTopics', number_format((int) $this->getThreadCount()));
     $this->setPlaceholder('totalMembers', number_format((int) $this->modx->getCount('disUser')));
     /* active in last 40 */
     if ($this->modx->getOption('discuss.show_whos_online', null, true)) {
         $this->setPlaceholder('activeUsers', $this->discuss->hooks->load('user/active_in_last'));
     } else {
         $this->setPlaceholder('activeUsers', '');
     }
     /* total active */
     $this->setPlaceholder('totalMembersActive', number_format((int) $this->modx->getCount('disSession', array('user:!=' => 0))));
     $this->setPlaceholder('totalVisitorsActive', number_format((int) $this->modx->getCount('disSession', array('user' => 0))));
     /**
      * forum activity
      * @var disForumActivity $activity
      */
     $activity = $this->modx->getObject('disForumActivity', array('day' => date('Y-m-d')));
     if (!$activity) {
         $activity = $this->modx->newObject('disForumActivity');
         $activity->set('day', date('Y-m-d'));
         $activity->save();
     }
     $this->setPlaceholders($activity->toArray('activity.'));
 }
 /**
  * Method for routing POST requests. Can be overridden; default behavior automates xPDOObject, class-based requests.
  * @abstract
  */
 public function post()
 {
     $properties = $this->getProperties();
     if (!empty($this->postRequiredFields)) {
         if (!$this->checkRequiredFields($this->postRequiredFields)) {
             return $this->failure($this->modx->lexicon('error'));
         }
     }
     if (!empty($this->postRequiredRelatedObjects)) {
         if (!$this->checkRequiredRelatedObjects($this->postRequiredRelatedObjects)) {
             return $this->failure();
         }
     }
     /** @var xPDOObject $object */
     $this->object = $this->modx->newObject($this->classKey);
     $this->object->fromArray($properties);
     $beforePost = $this->beforePost();
     if ($beforePost !== true && $beforePost !== null) {
         return $this->failure($beforePost === false ? $this->errorMessage : $beforePost);
     }
     if (!$this->object->{$this->postMethod}()) {
         $this->setObjectErrors();
         if ($this->hasErrors()) {
             return $this->failure();
         } else {
             return $this->failure($this->modx->lexicon('rest.err_class_save', array('class_key' => $this->classKey)));
         }
     }
     $objectArray = $this->object->toArray();
     $this->afterPost($objectArray);
     return $this->success('', $objectArray);
 }
Пример #8
0
 /**
  * Checks user permissions to view the results
  *
  * @param array $rows
  *
  * @return array
  */
 public function checkPermissions($rows = array())
 {
     $permissions = array();
     if (!empty($this->config['checkPermissions'])) {
         $tmp = array_map('trim', explode(',', $this->config['checkPermissions']));
         foreach ($tmp as $v) {
             $permissions[$v] = true;
         }
     } else {
         return $rows;
     }
     $total = $this->modx->getPlaceholder($this->config['totalVar']);
     foreach ($rows as $key => $row) {
         /** @var modAccessibleObject $object */
         $object = $this->modx->newObject($this->config['class']);
         $object->_fields['id'] = $row['id'];
         if ($object instanceof modAccessibleObject && !$object->checkPolicy($permissions)) {
             unset($rows[$key]);
             $this->addTime($this->config['class'] . ' #' . $row['id'] . ' was excluded from results, because you do not have enough permissions');
             $total--;
         }
     }
     $this->addTime('Checked for permissions "' . implode(',', array_keys($permissions)) . '"');
     $this->modx->setPlaceholder($this->config['totalVar'], $total);
     return $rows;
 }
Пример #9
0
 /**
  * Setup this resource as an archive so that FURLs can be effectively mapped
  *
  * @param integer $resourceId The ID of the resource to allow as an archive
  * @param string $prefix The filterPrefix used by that archive
  */
 public function makeArchive($resourceId, $prefix = 'arc_')
 {
     $value = $resourceId . ':' . $prefix;
     $isNew = false;
     $setting = $this->modx->getObject('modSystemSetting', array('key' => 'archivist.archive_ids'));
     if (!$setting) {
         /** @var modSystemSetting $setting */
         $setting = $this->modx->newObject('modSystemSetting');
         $setting->fromArray(array('key' => 'archivist.archive_ids', 'namespace' => 'archivist', 'area' => 'furls', 'xtype' => 'textfield'), '', true, true);
         $isNew = true;
     } else {
         $oldValue = $setting->get('value');
         if (strpos($oldValue, $resourceId . ':') !== false) {
             /* dont append if already there */
             $value = $oldValue;
         } else {
             $value = $oldValue . ',' . $value;
         }
     }
     $setting->set('value', $value);
     $saved = $setting->save();
     if ($isNew) {
         $this->_clearCache();
     }
     return $saved;
 }
Пример #10
0
 /**
  * Overrides xPDOObject::save to handle closure table edits.
  *
  * @param boolean $cacheFlag
  * @return boolean
  */
 public function save($cacheFlag = null)
 {
     $new = $this->isNew();
     if ($new) {
         if (!$this->get('createdon')) {
             $this->set('createdon', strftime('%Y-%m-%d %H:%M:%S'));
         }
         $ip = $this->get('ip');
         if (empty($ip) && !empty($_SERVER['REMOTE_ADDR'])) {
             $this->set('ip', $_SERVER['REMOTE_ADDR']);
         }
     }
     $saved = parent::save($cacheFlag);
     if ($saved && $new) {
         $id = $this->get('id');
         $parent = $this->get('parent');
         /* create self closure */
         $cl = $this->xpdo->newObject('quipCommentClosure');
         $cl->set('ancestor', $id);
         $cl->set('descendant', $id);
         if ($cl->save() === false) {
             $this->remove();
             return false;
         }
         /* create closures and calculate rank */
         $c = $this->xpdo->newQuery('quipCommentClosure');
         $c->where(array('descendant' => $parent, 'ancestor:!=' => 0));
         $c->sortby('depth', 'DESC');
         $gparents = $this->xpdo->getCollection('quipCommentClosure', $c);
         $cgps = count($gparents);
         $gps = array();
         $i = $cgps;
         /** @var quipCommentClosure $gparent */
         foreach ($gparents as $gparent) {
             $gps[] = str_pad($gparent->get('ancestor'), 10, '0', STR_PAD_LEFT);
             /** @var quipCommentClosure $obj */
             $obj = $this->xpdo->newObject('quipCommentClosure');
             $obj->set('ancestor', $gparent->get('ancestor'));
             $obj->set('descendant', $id);
             $obj->set('depth', $i);
             $obj->save();
             $i--;
         }
         $gps[] = str_pad($id, 10, '0', STR_PAD_LEFT);
         /* add self closure too */
         /* add root closure */
         /** @var quipCommentClosure $cl */
         $cl = $this->xpdo->newObject('quipCommentClosure');
         $cl->set('ancestor', 0);
         $cl->set('descendant', $id);
         $cl->set('depth', $cgps);
         $cl->save();
         /* set rank */
         $rank = implode('-', $gps);
         $this->set('rank', $rank);
         $this->save();
     }
     return $saved;
 }
 public static function getInstance(modX &$modx, $className, $properties = array())
 {
     $classKey = !empty($properties['class_key']) ? $properties['class_key'] : 'modDocument';
     $object = $modx->newObject($classKey);
     $className = 'msCategoryDisableCacheCreateProcessor';
     $processor = new $className($modx, $properties);
     return $processor;
 }
Пример #12
0
 /**
  * Parse a chunk (with template bindings)
  * Modified parseTplElement method from getResources package (https://github.com/opengeek/getResources)
  *
  * @param $type
  * @param $source
  * @param null $properties
  * @return bool
  */
 private function parseChunk($type, $source, $properties = null)
 {
     $output = false;
     if (!is_string($type) || !in_array($type, $this->_validTypes)) {
         $type = $this->modx->getOption('tplType', $properties, '@CHUNK');
     }
     $content = false;
     switch ($type) {
         case '@FILE':
             $path = $this->modx->getOption('tplPath', $properties, $this->modx->getOption('assets_path', $properties, MODX_ASSETS_PATH) . 'elements/chunks/');
             $key = $path . $source;
             if (!isset($this->_tplCache['@FILE'])) {
                 $this->_tplCache['@FILE'] = array();
             }
             if (!array_key_exists($key, $this->_tplCache['@FILE'])) {
                 if (file_exists($key)) {
                     $content = file_get_contents($key);
                 }
                 $this->_tplCache['@FILE'][$key] = $content;
             } else {
                 $content = $this->_tplCache['@FILE'][$key];
             }
             if (!empty($content) && $content !== '0') {
                 $chunk = $this->modx->newObject('modChunk', array('name' => $key));
                 $chunk->setCacheable(false);
                 $output = $chunk->process($properties, $content);
             }
             break;
         case '@INLINE':
             $uniqid = uniqid();
             $chunk = $this->modx->newObject('modChunk', array('name' => "{$type}-{$uniqid}"));
             $chunk->setCacheable(false);
             $output = $chunk->process($properties, $source);
             break;
         case '@CHUNK':
         default:
             $chunk = null;
             if (!isset($this->_tplCache['@CHUNK'])) {
                 $this->_tplCache['@CHUNK'] = array();
             }
             if (!array_key_exists($source, $this->_tplCache['@CHUNK'])) {
                 if ($chunk = $this->modx->getObject('modChunk', array('name' => $source))) {
                     $this->_tplCache['@CHUNK'][$source] = $chunk->toArray('', true);
                 } else {
                     $this->_tplCache['@CHUNK'][$source] = false;
                 }
             } elseif (is_array($this->_tplCache['@CHUNK'][$source])) {
                 $chunk = $this->modx->newObject('modChunk');
                 $chunk->fromArray($this->_tplCache['@CHUNK'][$source], '', true, true, true);
             }
             if (is_object($chunk)) {
                 $chunk->setCacheable(false);
                 $output = $chunk->process($properties);
             }
             break;
     }
     return $output;
 }
Пример #13
0
 /**
  * Creates an element object of the specified type
  * 
  * @param modX $modx
  * @param string $type
  * @param string $name
  * 
  * @return Element | boolean
  */
 public static function create(modX $modx, $type, $name)
 {
     $element = $modx->newObject($type);
     $element->set(Element::get_name_field($type), $name);
     if ($element->save()) {
         return new Element($element);
     }
     return false;
 }
Пример #14
0
 /**
  * Gets the correct render given paths and type of render
  *
  * @param array $params The parameters to pass to the render
  * @param mixed $value The value of the TV
  * @param array $paths An array of paths to search
  * @param string $method The type of Render (input/output/properties)
  * @param integer $resourceId The ID of the current Resource
  * @param string $type The type of render to display
  * @return string
  */
 public function getRender($params, $value, array $paths, $method, $resourceId = 0, $type = 'text')
 {
     if (empty($type)) {
         $type = 'text';
     }
     if (empty($this->xpdo->resource)) {
         if (!empty($resourceId)) {
             $this->xpdo->resource = $this->xpdo->getObject('modResource', $resourceId);
         }
         if (empty($this->xpdo->resource) || empty($resourceId)) {
             $this->xpdo->resource = $this->xpdo->newObject('modResource');
             $this->xpdo->resource->set('id', 0);
         }
     }
     if ($className = $this->checkForRegisteredRenderMethod($type, $method)) {
         /** @var modTemplateVarOutputRender $render */
         $render = new $className($this);
         $output = $render->render($value, $params);
     } else {
         $deprecatedClassName = $method == 'input' ? 'modTemplateVarInputRenderDeprecated' : 'modTemplateVarOutputRenderDeprecated';
         $render = new $deprecatedClassName($this);
         foreach ($paths as $path) {
             $renderFile = $path . $type . '.class.php';
             if (file_exists($renderFile)) {
                 $className = (include $renderFile);
                 $this->registerRenderMethod($type, $method, $className);
                 if (class_exists($className)) {
                     /** @var modTemplateVarOutputRender $render */
                     $render = new $className($this);
                 }
                 break;
             }
             /* 2.1< backwards compat */
             $renderFile = $path . $type . '.php';
             if (file_exists($renderFile)) {
                 $render = new $deprecatedClassName($this);
                 $params['modx.renderFile'] = $renderFile;
                 break;
             }
         }
         $output = $render->render($value, $params);
         /* if no output, fallback to text */
         if (empty($output)) {
             $p = $this->xpdo->getOption('processors_path') . 'element/tv/renders/mgr/' . $method . '/';
             $className = $method == 'output' ? 'modTemplateVarOutputRenderText' : 'modTemplateVarInputRenderText';
             if (!class_exists($className) && file_exists($p . 'text.class.php')) {
                 $className = (include $p . 'text.class.php');
             }
             if (class_exists($className)) {
                 $render = new $className($this);
                 $output = $render->render($value, $params);
             }
         }
     }
     return $output;
 }
Пример #15
0
 /**
  * Retrieve the menus for the given "container"
  *
  * @param string $name
  *
  * @return array
  */
 protected function getCache($name)
 {
     $key = $this->getCacheKey($name);
     $menus = $this->modx->cacheManager->get($key, array(xPDO::OPT_CACHE_KEY => $this->modx->getOption('cache_menu_key', null, 'menu'), xPDO::OPT_CACHE_HANDLER => $this->modx->getOption('cache_menu_handler', null, $this->modx->getOption(xPDO::OPT_CACHE_HANDLER)), xPDO::OPT_CACHE_FORMAT => (int) $this->modx->getOption('cache_menu_format', null, $this->modx->getOption(xPDO::OPT_CACHE_FORMAT, null, xPDOCacheManager::CACHE_PHP))));
     if ($menus == null || !is_array($menus)) {
         /** @var modMenu $menu */
         $menu = $this->modx->newObject('modMenu');
         $menus = $menu->rebuildCache($name);
         unset($menu);
     }
     return $menus;
 }
Пример #16
0
 /**
  * @param $parent xPDOObject
  * @param $child xPDOObject
  * @param $linkType
  */
 public function createLink($parent, $child, $linkType)
 {
     $c = array('parent' => $parent->get('id'), 'child' => $child->get('id'), 'link_type' => $linkType);
     $link = $this->modx->getObject('modDevToolsLink', $c);
     if (!$link) {
         $this->debug('Try to create link with criteria ' . print_r($c, 1));
         $link = $this->modx->newObject('modDevToolsLink', $c);
         $link->save();
     } else {
         $this->debug('Link is already exists with criteria ' . print_r($c, 1));
     }
 }
Пример #17
0
 /**
  * Function for logging changes of the order
  *
  * @param integer $order_id The id of the order
  * @param string $action The name of action made with order
  * @param string $entry The value of action
  *
  * @return boolean
  */
 public function orderLog($order_id, $action = 'status', $entry)
 {
     /* @var msOrder $order */
     if (!($order = $this->modx->getObject('msOrder', $order_id))) {
         return false;
     }
     if (empty($this->modx->request)) {
         $this->modx->getRequest();
     }
     $user_id = $action == 'status' && $entry == 1 || !$this->modx->user->id ? $order->get('user_id') : $this->modx->user->id;
     $log = $this->modx->newObject('msOrderLog', array('order_id' => $order_id, 'user_id' => $user_id, 'timestamp' => time(), 'action' => $action, 'entry' => $entry, 'ip' => $this->modx->request->getClientIp()));
     return $log->save();
 }
Пример #18
0
 /**
  * Allow for Users to use derivative classes for their processors
  *
  * @static
  * @param modX $modx
  * @param $className
  * @param array $properties
  * @return modProcessor
  */
 public static function getInstance(modX &$modx, $className, $properties = array())
 {
     $classKey = !empty($properties['class_key']) ? $properties['class_key'] : 'modUser';
     $object = $modx->newObject($classKey);
     if (!in_array($classKey, array('modUser', ''))) {
         $className = $classKey . 'CreateProcessor';
         if (!class_exists($className)) {
             $className = 'modUserCreateProcessor';
         }
     }
     /** @var modProcessor $processor */
     $processor = new $className($modx, $properties);
     return $processor;
 }
Пример #19
0
function duplicateLevel(modX &$modx, $oldKey, $newKey, $parent = 0, $newParent = 0)
{
    $resources = $modx->getCollection('modResource', array('context_key' => $oldKey, 'parent' => $parent));
    if (count($resources) <= 0) {
        return array();
    }
    foreach ($resources as $oldResource) {
        $oldResourceArray = $oldResource->toArray();
        $newResource = $modx->newObject('modResource');
        $newResource->fromArray($oldResourceArray);
        $newResource->set('parent', $newParent);
        $newResource->set('context_key', $newKey);
        $newResource->save();
        duplicateLevel($modx, $oldKey, $newKey, $oldResourceArray['id'], $newResource->get('id'));
    }
}
Пример #20
0
 /**
  * Grab a persistent instance of the xPDO class to share connection data
  * across multiple tests and test suites.
  * 
  * @param array $options An array of configuration parameters.
  * @return xPDO An xPDO object instance.
  */
 public static function _getConnection($options = array())
 {
     $modx = FiTestHarness::$modx;
     if (is_object($modx)) {
         if (!$modx->request) {
             $modx->getRequest();
         }
         if (!$modx->error) {
             $modx->request->loadErrorHandler();
         }
         $modx->error->reset();
         FiTestHarness::$modx = $modx;
         return FiTestHarness::$modx;
     }
     /* include config.core.php */
     $properties = array();
     $config = array();
     include strtr(realpath(dirname(__FILE__)) . '/config.inc.php', '\\', '/');
     require_once $config['modx_base_path'] . 'config.core.php';
     require_once MODX_CORE_PATH . 'config/' . MODX_CONFIG_KEY . '.inc.php';
     require_once MODX_CORE_PATH . 'model/modx/modx.class.php';
     include_once strtr(realpath(dirname(__FILE__)) . '/properties.inc.php', '\\', '/');
     if (!defined('MODX_REQP')) {
         define('MODX_REQP', false);
     }
     $modx = new modX(null, $properties);
     $ctx = !empty($options['ctx']) ? $options['ctx'] : 'web';
     $modx->initialize($ctx);
     $debug = !empty($options['debug']);
     $modx->setDebug($debug);
     if (!empty($properties['logTarget'])) {
         $modx->setLogTarget($properties['logTarget']);
     }
     if (!empty($properties['logLevel'])) {
         $modx->setLogLevel($properties['logLevel']);
     }
     $modx->user = $modx->newObject('modUser');
     $modx->user->set('id', $modx->getOption('modx.test.user.id', null, 1));
     $modx->user->set('username', $modx->getOption('modx.test.user.username', null, 'test'));
     $modx->getRequest();
     $modx->getParser();
     $modx->request->loadErrorHandler();
     @error_reporting(E_ALL);
     @ini_set('display_errors', true);
     FiTestHarness::$modx = $modx;
     return $modx;
 }
Пример #21
0
 /**
  * Add a subscription to this thread for the User
  * 
  * @param int $userId ID of disUser
  * @return bool True if successful
  */
 public function addSubscription($userId)
 {
     $success = false;
     $notify = $this->xpdo->getObject('disUserNotification', array('user' => $userId, 'thread' => $this->get('id')), false);
     if (!$notify) {
         $notify = $this->xpdo->newObject('disUserNotification');
         $notify->set('user', $userId);
         $notify->set('thread', $this->get('id'));
         $notify->set('board', $this->get('board'));
         if (!$notify->save()) {
             $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, '[Discuss] Could not create notification: ' . print_r($notify->toArray(), true));
         } else {
             $success = true;
         }
     }
     return $success;
 }
Пример #22
0
 /**
  * Get a modElement instance taking advantage of the modX::$sourceCache.
  *
  * @param string $class The modElement derivative class to load.
  * @param string $name An element name or raw tagName to identify the modElement instance.
  * @return modElement|null An instance of the specified modElement derivative class.
  */
 public function getElement($class, $name)
 {
     $realname = $this->realname($name);
     if (array_key_exists($class, $this->modx->sourceCache) && array_key_exists($realname, $this->modx->sourceCache[$class])) {
         /** @var modElement $element */
         $element = $this->modx->newObject($class);
         $element->fromArray($this->modx->sourceCache[$class][$realname]['fields'], '', true, true);
         $element->setPolicies($this->modx->sourceCache[$class][$realname]['policies']);
         if (!empty($this->modx->sourceCache[$class][$realname]['source'])) {
             if (!empty($this->modx->sourceCache[$class][$realname]['source']['class_key'])) {
                 $sourceClassKey = $this->modx->sourceCache[$class][$realname]['source']['class_key'];
                 $this->modx->loadClass('sources.modMediaSource');
                 /* @var modMediaSource $source */
                 $source = $this->modx->newObject($sourceClassKey);
                 $source->fromArray($this->modx->sourceCache[$class][$realname]['source'], '', true, true);
                 $element->addOne($source, 'Source');
             }
         }
     } else {
         /** @var modElement $element */
         $element = $this->modx->getObjectGraph($class, array('Source' => array()), array('name' => $realname), true);
         if ($element && array_key_exists($class, $this->modx->sourceCache)) {
             $this->modx->sourceCache[$class][$realname] = array('fields' => $element->toArray(), 'policies' => $element->getPolicies(), 'source' => $element->Source ? $element->Source->toArray() : array());
         } elseif (!$element) {
             $evtOutput = $this->modx->invokeEvent('OnElementNotFound', array('class' => $class, 'name' => $realname));
             $element = false;
             if ($evtOutput != false) {
                 foreach ((array) $evtOutput as $elm) {
                     if (!empty($elm) && is_string($elm)) {
                         $element = $this->modx->newObject($class, array('name' => $realname, 'snippet' => $elm));
                     } elseif ($elm instanceof modElement) {
                         $element = $elm;
                     }
                     if ($element) {
                         break;
                     }
                 }
             }
         }
     }
     if ($element instanceof modElement) {
         $element->set('name', $name);
     }
     return $element;
 }
Пример #23
0
 /**
  * Returns a modChunk object from a template file.
  *
  * @access private
  * @param string $name The name of the Chunk. Will parse to name.chunk.tpl
  * @return modChunk/boolean Returns the modChunk object if found, otherwise
  * false.
  */
 private function _getTplChunk($name)
 {
     $chunk = false;
     if (file_exists($name)) {
         $f = $name;
     } else {
         $lowerCaseName = $this->config['use_multibyte'] ? mb_strtolower($name, $this->config['encoding']) : strtolower($name);
         $f = $this->config['chunksPath'] . $lowerCaseName . '.chunk.tpl';
     }
     if (file_exists($f)) {
         $o = file_get_contents($f);
         /** @var modChunk $chunk */
         $chunk = $this->modx->newObject('modChunk');
         $chunk->set('name', $name);
         $chunk->setContent($o);
     }
     return $chunk;
 }
Пример #24
0
 /**
  * Join a User Group, and optionally assign a Role.
  *
  * @access public
  * @param mixed $groupId Either the name or ID of the User Group to join.
  * @param mixed $roleId Optional. Either the name or ID of the Role to
  * @param integer $rank Optional.
  * assign to for the group.
  * @return boolean True if successful.
  */
 public function joinGroup($groupId, $roleId = null, $rank = null)
 {
     $joined = false;
     $groupPk = is_string($groupId) ? array('name' => $groupId) : $groupId;
     /** @var modUserGroup $userGroup */
     $userGroup = $this->xpdo->getObject('modUserGroup', $groupPk);
     if (empty($userGroup)) {
         $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, 'User Group not found with key: ' . $groupId);
         return $joined;
     }
     /** @var modUserGroupRole $role */
     if (!empty($roleId)) {
         $rolePk = is_string($roleId) ? array('name' => $roleId) : $roleId;
         $role = $this->xpdo->getObject('modUserGroupRole', $rolePk);
         if (empty($role)) {
             $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, 'Role not found with key: ' . $role);
             return $joined;
         }
     }
     /** @var modUserGroupMember $member */
     $member = $this->xpdo->getObject('modUserGroupMember', array('member' => $this->get('id'), 'user_group' => $userGroup->get('id')));
     if (empty($member)) {
         if ($rank == null) {
             $rank = count($this->getMany('UserGroupMembers'));
         }
         $member = $this->xpdo->newObject('modUserGroupMember');
         $member->set('member', $this->get('id'));
         $member->set('user_group', $userGroup->get('id'));
         $member->set('rank', $rank);
         if (!empty($role)) {
             $member->set('role', $role->get('id'));
         }
         $joined = $member->save();
         if (!$joined) {
             $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, 'An unknown error occurred preventing adding the User to the User Group.');
         } else {
             unset($_SESSION["modx.user.{$this->get('id')}.userGroupNames"], $_SESSION["modx.user.{$this->get('id')}.userGroups"]);
         }
     } else {
         $joined = true;
     }
     return $joined;
 }
 /**
  * Support method for createSystemSettings(), insert system setting to database
  * @param $key string
  * @param $value string
  * @param string $xtype string
  * @param string $area string
  */
 protected function createSystemSetting($key, $value, $xtype = 'textfield', $area = 'default')
 {
     $ct = $this->modx->getObject('modSystemSetting', array('key' => $key));
     if (!$ct) {
         /** @var \modSystemSetting $setting */
         $setting = $this->modx->newObject('modSystemSetting');
         $setting->set('key', $key);
         $setting->set('value', $value);
         $setting->set('namespace', $this->config->getLowCaseName());
         $setting->set('area', $area);
         $setting->set('xtype', $xtype);
         $setting->save();
     } else {
         $ct->set('value', $value);
         $ct->set('namespace', $this->config->getLowCaseName());
         $ct->set('area', $area);
         $ct->set('xtype', $xtype);
         $ct->save();
     }
 }
Пример #26
0
 /**
  * Grab a persistent instance of the xPDO class to share connection data
  * across multiple tests and test suites.
  * 
  * @param array $options An array of configuration parameters.
  * @return xPDO An xPDO object instance.
  */
 public static function _getConnection($options = array())
 {
     if (is_object(MODxTestHarness::$modx)) {
         return MODxTestHarness::$modx;
     }
     /* include config.core.php */
     $properties = array();
     require_once strtr(realpath(dirname(dirname(dirname(__FILE__)))) . '/config.core.php', '\\', '/');
     require_once MODX_CORE_PATH . 'config/' . MODX_CONFIG_KEY . '.inc.php';
     require_once MODX_CORE_PATH . 'model/modx/modx.class.php';
     include_once strtr(realpath(dirname(__FILE__)) . '/properties.inc.php', '\\', '/');
     $modx = new modX(null, $properties);
     $ctx = !empty($options['ctx']) ? $options['ctx'] : 'web';
     $modx->initialize($ctx);
     $debug = !empty($options['debug']);
     $modx->setDebug($debug);
     $modx->user = $modx->newObject('modUser');
     $modx->user->set('id', $modx->getOption('modx.test.user.id', 1));
     $modx->user->set('username', $modx->getOption('modx.test.user.username', 'test'));
     MODxTestHarness::$modx = $modx;
     return $modx;
 }
Пример #27
0
 /**
  * Process the current queue with the queue placeholders.
  *
  * @access public
  * @param string $queue The queue name.
  * @param string $outputSeparator Separator between two joined elements.
  * @param boolean $clear Clear queue after process.
  * @return string Processed template.
  */
 public function process($queue = '', $outputSeparator = "\r\n", $clear = TRUE)
 {
     $queue = !empty($queue) ? $queue : $this->queue;
     if ($this->options['profile']) {
         $this->profile[$queue]['render'] = isset($this->profile[$queue]['render']) ? $this->profile[$queue]['render'] : 0;
         $start = microtime(TRUE);
     }
     if (!empty($this->templates[$queue])) {
         // Recursive join templates object
         $templates = array();
         foreach ($this->templates[$queue]->templates as $key => $value) {
             $templates = array_merge($templates, $this->templatesJoinRecursive($value, $key . '.', $outputSeparator));
         }
         $template = implode($outputSeparator, $templates);
         // Process the whole template
         $chunk = $this->modx->newObject('modChunk', array('name' => '{tmp}-' . uniqid()));
         $chunk->setCacheable(false);
         $output = $chunk->process($this->placeholders[$queue], $template);
         unset($chunk);
         // Unmask uncached elements (will be parsed outside of this)
         if ($this->options['parseLazy']) {
             $output = str_replace(array('[[¡'), array('[[!'), $output);
         }
     } else {
         $output = '';
     }
     if ($clear) {
         $this->clearPlaceholders($queue);
         $this->clearTemplates($queue);
     }
     if ($this->options['profile']) {
         $end = microtime(TRUE);
         $this->profile[$queue]['render'] += $end - $start;
     }
     return $output;
 }
Пример #28
0
/* override with your own defines here (see build.config.sample.php) */
require_once $sources['build'] . 'build.config.php';
require_once MODX_CORE_PATH . 'model/modx/modx.class.php';
$modx = new modX();
$modx->initialize('mgr');
echo '<pre>';
/* used for nice formatting of log messages */
$modx->setLogLevel(modX::LOG_LEVEL_INFO);
$modx->setLogTarget('ECHO');
$modx->loadClass('transport.modPackageBuilder', '', false, true);
$builder = new modPackageBuilder($modx);
$builder->directory = dirname(dirname(__FILE__)) . '/_package/';
$builder->createPackage(PKG_EXTRA_NAME, PKG_VERSION, PKG_RELEASE);
$builder->registerNamespace(PKG_NAME_LOWER, false, true, '{core_path}components/' . PKG_NAME_LOWER . '/');
//-- CREATE THE CATEGORY OBJECT
$category = $modx->newObject('modCategory');
$category->set('id', 1);
$category->set('category', PKG_NAME);
/* add snippets */
$modx->log(modX::LOG_LEVEL_INFO, 'Packaging in snippets...');
$snippets = (include $sources['data'] . 'transport.snippets.php');
if (empty($snippets)) {
    $modx->log(modX::LOG_LEVEL_ERROR, 'Could not package in snippets.');
}
$category->addMany($snippets);
/* add chunks */
$chunks = (include $sources['data'] . 'transport.chunks.php');
if (is_array($chunks)) {
    $category->addMany($chunks);
} else {
    $modx->log(modX::LOG_LEVEL_ERROR, 'Adding chunks failed.');
$category = $modx->newObject('modCategory');
$category->set('category', PKG_NAME);
/* create category vehicle */
$attr = array(xPDOTransport::UNIQUE_KEY => 'category', xPDOTransport::PRESERVE_KEYS => false, xPDOTransport::UPDATE_OBJECT => true, xPDOTransport::RELATED_OBJECTS => true);
/* add snippets */
if (defined('BUILD_SNIPPET_UPDATE')) {
    $attr[xPDOTransport::RELATED_OBJECT_ATTRIBUTES]['Snippets'] = array(xPDOTransport::PRESERVE_KEYS => false, xPDOTransport::UPDATE_OBJECT => BUILD_SNIPPET_UPDATE, xPDOTransport::UNIQUE_KEY => 'name');
    $snippets = (include $sources['data'] . 'transport.snippets.php');
    if (!is_array($snippets)) {
        $modx->log(modX::LOG_LEVEL_ERROR, 'Could not package in snippets.');
    } else {
        $category->addMany($snippets);
        $modx->log(modX::LOG_LEVEL_INFO, 'Packaged in ' . count($snippets) . ' snippets.');
    }
}
/* add chunks */
if (defined('BUILD_CHUNK_UPDATE')) {
    $attr[xPDOTransport::RELATED_OBJECT_ATTRIBUTES]['Chunks'] = array(xPDOTransport::PRESERVE_KEYS => false, xPDOTransport::UPDATE_OBJECT => BUILD_CHUNK_UPDATE, xPDOTransport::UNIQUE_KEY => 'name');
    $chunks = (include $sources['data'] . 'transport.chunks.php');
    if (!is_array($chunks)) {
        $modx->log(modX::LOG_LEVEL_ERROR, 'Could not package in chunks.');
    } else {
        $category->addMany($chunks);
        $modx->log(modX::LOG_LEVEL_INFO, 'Packaged in ' . count($chunks) . ' chunks.');
    }
}
/* add plugins */
if (defined('BUILD_PLUGIN_UPDATE')) {
    $attr[xPDOTransport::RELATED_OBJECT_ATTRIBUTES]['Plugins'] = array(xPDOTransport::PRESERVE_KEYS => false, xPDOTransport::UPDATE_OBJECT => BUILD_PLUGIN_UPDATE, xPDOTransport::UNIQUE_KEY => 'name');
    $attr[xPDOTransport::RELATED_OBJECT_ATTRIBUTES]['PluginEvents'] = array(xPDOTransport::PRESERVE_KEYS => true, xPDOTransport::UPDATE_OBJECT => BUILD_PLUGIN_UPDATE, xPDOTransport::UNIQUE_KEY => array('pluginid', 'event'));
    $plugins = (include $sources['data'] . 'transport.plugins.php');
    if (!is_array($plugins)) {
        $modx->log(modX::LOG_LEVEL_ERROR, 'Could not package in plugins.');
    } else {
        $category->addMany($plugins);
        $modx->log(modX::LOG_LEVEL_INFO, 'Packaged in ' . count($plugins) . ' plugins.');
    }
}
$vehicle = $builder->createVehicle($category, $attr);
/* now pack in resolvers */
$vehicle->resolve('file', array('source' => $sources['source_assets'], 'target' => "return MODX_ASSETS_PATH . 'components/';"));
$vehicle->resolve('file', array('source' => $sources['source_core'], 'target' => "return MODX_CORE_PATH . 'components/';"));
foreach ($BUILD_RESOLVERS as $resolver) {
    if ($vehicle->resolve('php', array('source' => $sources['resolvers'] . 'resolve.' . $resolver . '.php'))) {
        $modx->log(modX::LOG_LEVEL_INFO, 'Added resolver "' . $resolver . '" to category.');
    } else {
        $modx->log(modX::LOG_LEVEL_INFO, 'Could not add resolver "' . $resolver . '" to category.');
    }
}
flush();
$builder->putVehicle($vehicle);
/* now pack in the license file, readme and setup options */
$builder->setPackageAttributes(array('changelog' => file_get_contents($sources['docs'] . 'changelog.txt'), 'license' => file_get_contents($sources['docs'] . 'license.txt'), 'readme' => file_get_contents($sources['docs'] . 'readme.txt'), 'chunks' => $BUILD_CHUNKS, 'setup-options' => array('source' => $sources['build'] . 'setup.options.php')));
$modx->log(modX::LOG_LEVEL_INFO, 'Added package attributes and setup options.');
/* zip up package */
$modx->log(modX::LOG_LEVEL_INFO, 'Packing up transport package zip...');
$builder->pack();
$mtime = microtime();
$mtime = explode(" ", $mtime);
$mtime = $mtime[1] + $mtime[0];
$tend = $mtime;
$totalTime = $tend - $tstart;
$totalTime = sprintf("%2.4f s", $totalTime);
$signature = $builder->getSignature();
if (defined('PKG_AUTO_INSTALL') && PKG_AUTO_INSTALL) {
    $sig = explode('-', $signature);
    $versionSignature = explode('.', $sig[1]);
    /* @var modTransportPackage $package */
    if (!($package = $modx->getObject('transport.modTransportPackage', array('signature' => $signature)))) {
        $package = $modx->newObject('transport.modTransportPackage');
Пример #30
0
 public static function getList(modX &$modx, array $scriptProperties = array())
 {
     $sort = $modx->getOption('sort', $scriptProperties, 'rank');
     $cacheKey = 'gallery/item/list/' . md5(serialize($scriptProperties));
     if ($modx->getCacheManager() && ($cache = $modx->cacheManager->get($cacheKey))) {
         $items = array();
         foreach ($cache['items'] as $data) {
             /** @var galItem $item */
             $item = $modx->newObject('galItem');
             $item->fromArray($data, '', true, true);
             $items[] = $item;
         }
         if (in_array(strtolower($sort), array('random', 'rand()', 'rand'))) {
             shuffle($items);
         }
         $data = array('items' => $items, 'total' => $cache['total'], 'album' => $cache['album']);
     } else {
         $album = $modx->getOption('album', $scriptProperties, false);
         $tag = $modx->getOption('tag', $scriptProperties, '');
         $limit = $modx->getOption('limit', $scriptProperties, 0);
         $start = $modx->getOption('start', $scriptProperties, 0);
         /* Fix to make it work with getPage which uses "offset" instead of "start" */
         $offset = $modx->getOption('offset', $scriptProperties, 0);
         if ($offset > 0) {
             $start = $offset;
         }
         $sortAlias = $modx->getOption('sortAlias', $scriptProperties, 'galItem');
         if ($sort == 'rank') {
             $sortAlias = 'AlbumItems';
         }
         $dir = $modx->getOption('dir', $scriptProperties, 'ASC');
         $showInactive = $modx->getOption('showInactive', $scriptProperties, false);
         $activeAlbum = array('id' => '', 'name' => '', 'description' => '');
         $tagc = $modx->newQuery('galTag');
         $tagc->setClassAlias('TagsJoin');
         $tagc->select('GROUP_CONCAT(' . $modx->getSelectColumns('galTag', 'TagsJoin', '', array('tag')) . ')');
         $tagc->where($modx->getSelectColumns('galTag', 'TagsJoin', '', array('item')) . ' = ' . $modx->getSelectColumns('galItem', 'galItem', '', array('id')));
         $tagc->prepare();
         $tagSql = $tagc->toSql();
         $c = $modx->newQuery('galItem');
         $c->innerJoin('galAlbumItem', 'AlbumItems');
         $c->innerJoin('galAlbum', 'Album', $modx->getSelectColumns('galAlbumItem', 'AlbumItems', '', array('album')) . ' = ' . $modx->getSelectColumns('galAlbum', 'Album', '', array('id')));
         /* pull by album */
         if (!empty($album)) {
             $albumField = is_numeric($album) ? 'id' : 'name';
             $albumWhere = $albumField == 'name' ? array('name' => $album) : $album;
             /** @var galAlbum $album */
             $album = $modx->getObject('galAlbum', $albumWhere);
             if (empty($album)) {
                 return '';
             }
             $c->where(array('Album.' . $albumField => $album->get($albumField)));
             $activeAlbum['id'] = $album->get('id');
             $activeAlbum['name'] = $album->get('name');
             $activeAlbum['description'] = $album->get('description');
             $activeAlbum['year'] = $album->get('year');
             unset($albumWhere, $albumField);
         }
         if (!empty($tag)) {
             /* pull by tag */
             $c->innerJoin('galTag', 'Tags');
             $c->where(array('Tags.tag' => $tag));
             if (empty($album)) {
                 $activeAlbum['id'] = 0;
                 $activeAlbum['name'] = $tag;
                 $activeAlbum['description'] = '';
             }
         }
         $c->where(array('galItem.mediatype' => $modx->getOption('mediatype', $scriptProperties, 'image')));
         if (!$showInactive) {
             $c->where(array('galItem.active' => true));
         }
         $count = $modx->getCount('galItem', $c);
         $c->select($modx->getSelectColumns('galItem', 'galItem'));
         $c->select(array('(' . $tagSql . ') AS tags'));
         if (in_array(strtolower($sort), array('random', 'rand()', 'rand'))) {
             $c->sortby('RAND()', $dir);
         } else {
             $c->sortby($sortAlias . '.' . $sort, $dir);
         }
         if (!empty($limit)) {
             $c->limit($limit, $start);
         }
         $items = $modx->getCollection('galItem', $c);
         $data = array('items' => $items, 'total' => $count, 'album' => $activeAlbum);
         $cache = array('items' => array(), 'total' => $count, 'album' => $activeAlbum);
         /** @var galItem $item */
         foreach ($items as $item) {
             $cache['items'][] = $item->toArray('', true);
         }
         $modx->cacheManager->set($cacheKey, $cache);
     }
     return $data;
 }