Пример #1
0
 /**
  * Sets up the fixture, for example, opens a network connection.
  * This method is called before a test is executed.
  */
 protected function setUp()
 {
     require_once dirname(__FILE__) . '/build.config.php';
     require_once dirname(__FILE__) . '/uthelpers.class.php';
     require_once MODX_CORE_PATH . 'model/modx/modx.class.php';
     $modx = new modX();
     $modx->initialize('mgr');
     $modx->getService('error', 'error.modError', '', '');
     $this->utHelpers = new UtHelpers();
     $this->mc = new MyComponentProject($modx);
     $this->mc->init(array(), 'unittest');
     $this->mc->createCategories();
     $this->mc->createBasics();
     $this->modx =& $this->mc->modx;
     if ($this->mc->props['categories']['UnitTest']['category'] != 'UnitTest') {
         die('wrong config');
     }
     if (strstr($this->mc->targetRoot, 'unittest')) {
         // $this->utHelpers->rrmdir($this->mc->targetRoot);
     } else {
         die('Wrong Target Root!');
     }
     $modx->setLogLevel(modX::LOG_LEVEL_INFO);
     $modx->setLogTarget('ECHO');
 }
Пример #2
0
 public static function loadModxInstance()
 {
     require_once MODX_CORE_PATH . 'model/modx/modx.class.php';
     $modx = new modX();
     $modx->initialize('mgr');
     echo XPDO_CLI_MODE ? '' : '<pre>';
     $modx->setLogLevel(modX::LOG_LEVEL_INFO);
     $modx->setLogTarget('ECHO');
     $modx->loadClass('transport.modPackageBuilder', '', false, true);
     return $modx;
 }
Пример #3
0
 public function initialize($contextKey = 'web', $options = null)
 {
     parent::initialize($contextKey, $options);
     $corePath = $this->getOption('subdomainsfolder_core_path', null, $this->getOption('core_path', null, MODX_CORE_PATH) . 'components/subdomainsfolder/');
     $this->SubdomainsFolder = $this->getService('SubdomainsFolder', 'SubdomainsFolder', $corePath . 'model/subdomainsfolder/');
     if ($this->SubdomainsFolder) {
         $this->SubdomainsFolder->initialize($this->context->key);
         $this->domains = $this->SubdomainsFolder->Tools->getDomains();
     } else {
         $this->log(modX::LOG_LEVEL_ERROR, 'modModX requires installed SubdomainsFolder.');
     }
 }
Пример #4
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;
 }
Пример #5
0
 /**
  * Loads a new modX instance
  *
  * @throws \RuntimeException
  * @return \modX
  */
 public static function loadMODX()
 {
     if (self::$modx) {
         return self::$modx;
     }
     if (!file_exists(GITIFY_WORKING_DIR . 'config.core.php')) {
         throw new \RuntimeException('There does not seem to be a MODX installation here. ');
     }
     require_once GITIFY_WORKING_DIR . 'config.core.php';
     require_once MODX_CORE_PATH . 'model/modx/modx.class.php';
     $modx = new \modX();
     $modx->initialize('mgr');
     $modx->getService('error', 'error.modError', '', '');
     $modx->setLogTarget('ECHO');
     self::$modx = $modx;
     return $modx;
 }
Пример #6
0
 /**
  * Sets up the fixture, for example, opens a network connection.
  * This method is called before each test is executed.
  */
 protected function setUp()
 {
     // echo "\n---------------- SETUP --------------------";
     require_once dirname(__FILE__) . '/build.config.php';
     require_once dirname(__FILE__) . '/uthelpers.class.php';
     require_once MODX_CORE_PATH . 'model/modx/modx.class.php';
     $this->utHelpers = new UtHelpers();
     $modx = new modX();
     $modx->initialize('mgr');
     $modx->getService('error', 'error.modError', '', '');
     $modx->getService('lexicon', 'modLexicon');
     $modx->getRequest();
     $homeId = $modx->getOption('site_start');
     $homeResource = $modx->getObject('modResource', $homeId);
     if ($homeResource instanceof modResource) {
         $modx->resource = $homeResource;
     } else {
         echo "\nNo Resource\n";
     }
     $modx->setLogLevel(modX::LOG_LEVEL_ERROR);
     $modx->setLogTarget('ECHO');
     require_once MODX_ASSETS_PATH . 'mycomponents/mycomponent/core/components/mycomponent/model/mycomponent/mycomponentproject.class.php';
     /* @var $categoryObj modCategory */
     $this->mc = new MyComponentProject($modx);
     $this->mc->init(array(), 'unittest');
     $this->modx =& $modx;
     $this->category = key($this->mc->props['categories']);
     $this->packageNameLower = $this->mc->packageNameLower;
     if ($this->category != 'UnitTest') {
         session_write_close();
         die('wrong config - NEVER run unit test on a real project!');
     }
     $category = $this->modx->getCollection('modCategory', array('category' => 'UnitTest'));
     foreach ($category as $categoryObj) {
         $categoryObj->remove();
     }
     $namespace = $this->modx->getObject('modNamespace', array('name' => 'unittest'));
     if ($namespace) {
         $namespace->remove();
     }
     $this->utHelpers->rrmdir($this->mc->targetRoot);
     $this->utHelpers->removeElements($this->modx, $this->mc);
     $this->utHelpers->removeResources($this->modx, $this->mc);
     //$this->mc->createCategory();
     //$this->mc->createNamespace();
 }
Пример #7
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;
 }
Пример #8
0
<?php

if (!defined('MODX_BASE_PATH')) {
    require 'build.config.php';
}
/* define sources */
$root = dirname(dirname(__FILE__)) . '/';
$sources = array('root' => $root, 'build' => $root . '_build/', 'source_core' => $root . 'core/components/' . PKG_NAME_LOWER, 'model' => $root . 'core/components/' . PKG_NAME_LOWER . '/model/', 'schema' => $root . 'core/components/' . PKG_NAME_LOWER . '/model/schema/', 'xml' => $root . 'core/components/' . PKG_NAME_LOWER . '/model/schema/' . PKG_NAME_LOWER . '.mysql.schema.xml');
unset($root);
require MODX_CORE_PATH . 'model/modx/modx.class.php';
require $sources['build'] . '/includes/functions.php';
$modx = new modX();
$modx->initialize('mgr');
$modx->getService('error', 'error.modError');
$modx->setLogLevel(modX::LOG_LEVEL_INFO);
$modx->setLogTarget('ECHO');
$modx->loadClass('transport.modPackageBuilder', '', false, true);
if (!XPDO_CLI_MODE) {
    echo '<pre>';
}
/** @var xPDOManager $manager */
$manager = $modx->getManager();
/** @var xPDOGenerator $generator */
$generator = $manager->getGenerator();
// Remove old model
rrmdir($sources['model'] . PKG_NAME_LOWER . '/mysql');
// Generate a new one
$generator->parseSchema($sources['xml'], $sources['model']);
$modx->log(modX::LOG_LEVEL_INFO, 'Model generated.');
if (!XPDO_CLI_MODE) {
    echo '</pre>';
Пример #9
0
<?php

// setting up modx access
require_once '/PATH_TO_MODX/config.core.php';
require_once '/PATH_TO_MODX_CORE/model/modx/modx.class.php';
$modx = new modX();
$modx->initialize('web');
$modx->getService('error', 'error.modError');
// define locations  UPDATE BEFORE USING!
// base file path to where static files will be saved
$basepath = '/FULL_SERVER_PATH/public_html/';
// url to your modx install
$mdxurl = 'http://URL-TO-MODX-INSTALL/';
// - - - - - - - - - end configuration - - - - - - - - -
// getting the published ids
// get collection of resources, determine id and if published
$docs = $modx->getCollection('modResource');
foreach ($docs as $doc) {
    $pub = $doc->get('published');
    $folder = $doc->get('isfolder');
    $rid = $doc->get('id');
    $web_url = $doc->get('uri');
    // if published, fetch url and build static webpage
    if ($pub == '1' && $folder == '0') {
        // determine if folders exist and create if not
        $path_parts = pathinfo($basepath . $web_url);
        $target_path = $path_parts['dirname'];
        if (!file_exists($target_path)) {
            mkdir($target_path, 0755, true);
        }
        // get the webpage from MODX
Пример #10
0
@include(dirname(__FILE__) . '/config.core.php');
if (!defined('MODX_CORE_PATH')) define('MODX_CORE_PATH', dirname(dirname(__FILE__)) . '/core/');
if (!include_once(MODX_CORE_PATH . 'model/modx/modx.class.php')) die();

/* instantiate the modX class with the appropriate configuration */
if (empty($options) || !is_array($options)) $options = array();
$modx= new modX('', $options);

/* set debugging/logging options */
//$modx->setDebug(E_ALL & ~E_NOTICE);
$modx->setLogLevel(modX::LOG_LEVEL_ERROR);
//$modx->setLogTarget('FILE');

/* initialize the proper context */
$ctx = isset($_REQUEST['ctx']) && !empty($_REQUEST['ctx']) ? $_REQUEST['ctx'] : 'mgr';
$modx->initialize($ctx);

if (defined('MODX_REQP') && MODX_REQP === false) {
} else if (!$modx->context->checkPolicy('load')) {
    @session_write_close();
    die();
}

if ($ctx == 'mgr') {
    $ml = $modx->getOption('manager_language',null,'en');
    if ($ml != 'en') {
        $modx->lexicon->load($ml.':core:default');
        $modx->setOption('cultureKey',$ml);
    }
}
Пример #11
0
 /**
  * Create or grab a reference to a static xPDO/modX instance.
  *
  * The instances can be reused by multiple tests and test suites.
  *
  * @param string $class A fixture class to get an instance of.
  * @param string $name A unique identifier for the fixture.
  * @param boolean $new
  * @param array $options An array of configuration options for the fixture.
  * @return object|null An instance of the specified fixture class or null on failure.
  */
 public static function &getFixture($class, $name, $new = false, array $options = array())
 {
     if (!$new && array_key_exists($name, self::$fixtures) && self::$fixtures[$name] instanceof $class) {
         $fixture =& self::$fixtures[$name];
     } else {
         $properties = array();
         include_once dirname(dirname(dirname(__FILE__))) . '/core/model/modx/modx.class.php';
         include dirname(__FILE__) . '/properties.inc.php';
         self::$properties = $properties;
         if (array_key_exists('debug', self::$properties)) {
             self::$debug = (bool) self::$properties['debug'];
         }
         $fixture = null;
         $driver = self::$properties['xpdo_driver'];
         switch ($class) {
             case 'modX':
                 if (!defined('MODX_REQP')) {
                     define('MODX_REQP', false);
                 }
                 if (!defined('MODX_CONFIG_KEY')) {
                     define('MODX_CONFIG_KEY', array_key_exists('config_key', self::$properties) ? self::$properties['config_key'] : 'test');
                 }
                 $fixture = new modX(null, self::$properties["{$driver}_array_options"]);
                 if ($fixture instanceof modX) {
                     $logLevel = array_key_exists('logLevel', self::$properties) ? self::$properties['logLevel'] : modX::LOG_LEVEL_WARN;
                     $logTarget = array_key_exists('logTarget', self::$properties) ? self::$properties['logTarget'] : (XPDO_CLI_MODE ? 'ECHO' : 'HTML');
                     $fixture->setLogLevel($logLevel);
                     $fixture->setLogTarget($logTarget);
                     if (!empty(self::$debug)) {
                         $fixture->setDebug(self::$properties['debug']);
                     }
                     $fixture->initialize(self::$properties['context']);
                     $fixture->user = $fixture->newObject('modUser');
                     $fixture->user->set('id', $fixture->getOption('modx.test.user.id', null, 1));
                     $fixture->user->set('username', $fixture->getOption('modx.test.user.username', null, 'test'));
                     $fixture->getRequest();
                     $fixture->getParser();
                     $fixture->request->loadErrorHandler();
                 }
                 break;
             case 'xPDO':
                 $fixture = new xPDO(self::$properties["{$driver}_string_dsn_test"], self::$properties["{$driver}_string_username"], self::$properties["{$driver}_string_password"], self::$properties["{$driver}_array_options"], self::$properties["{$driver}_array_driverOptions"]);
                 if ($fixture instanceof xPDO) {
                     $logLevel = array_key_exists('logLevel', self::$properties) ? self::$properties['logLevel'] : xPDO::LOG_LEVEL_WARN;
                     $logTarget = array_key_exists('logTarget', self::$properties) ? self::$properties['logTarget'] : (XPDO_CLI_MODE ? 'ECHO' : 'HTML');
                     $fixture->setLogLevel($logLevel);
                     $fixture->setLogTarget($logTarget);
                     if (!empty(self::$debug)) {
                         $fixture->setDebug(self::$properties['debug']);
                     }
                 }
                 break;
             default:
                 $fixture = new $class($options);
                 break;
         }
         if ($fixture !== null && $fixture instanceof $class) {
             self::$fixtures[$name] = $fixture;
         } else {
             die("Error setting fixture {$name} of expected class {$class}.");
         }
     }
     return $fixture;
 }
Пример #12
0
 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', $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 = $startTime;
 $modx->getVersionData();
 $modxVersion = $modx->version['full_version'];
 if (version_compare($modxVersion, '2.2.1-pl', '>=')) {
     $modx->initialize('mgr', $options);
 } else {
     $modx->initialize('mgr');
 }
 if (!$modx->hasPermission('Vapor')) {
     die('Access denied');
 }
 $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)) . '/';
Пример #13
0
 protected function setUp()
 {
     require_once dirname(__FILE__) . '/build.config.php';
     require_once dirname(__FILE__) . '/uthelpers.class.php';
     require_once MODX_CORE_PATH . 'model/modx/modx.class.php';
     $this->utHelpers = new UtHelpers();
     $modx = new modX();
     $this->modx =& $modx;
     $modx->initialize('mgr');
     $modx->getService('error', 'error.modError', '', '');
     $modx->getService('lexicon', 'modLexicon');
     $modx->getRequest();
     $homeId = $modx->getOption('site_start');
     $homeResource = $modx->getObject('modResource', $homeId);
     if ($homeResource instanceof modResource) {
         $modx->resource = $homeResource;
     } else {
         echo "\nNo Resource\n";
     }
     $modx->setLogLevel(modX::LOG_LEVEL_ERROR);
     $modx->setLogTarget('ECHO');
     require_once MODX_ASSETS_PATH . 'mycomponents/mycomponent/core/components/mycomponent/model/mycomponent/mycomponentproject.class.php';
     require_once MODX_ASSETS_PATH . 'mycomponents/mycomponent/core/components/mycomponent/model/mycomponent/lexiconcodefile.class.php';
     /* @var $categoryObj modCategory */
     $this->mc = new MyComponentProject($modx);
     $this->mc->init(array(), 'unittest');
     $this->dataDir = dirname(__FILE__) . '/data/';
     $this->dataDir = str_replace('\\', '/', $this->dataDir);
     $this->targetRoot = dirname(dirname(dirname(dirname(__FILE__)))) . '/unittest/';
     $this->targetRoot = str_replace('\\', '/', $this->targetRoot);
     $this->targetRoot = strtolower($this->targetRoot);
     $this->utHelpers->rrmdir($this->targetRoot);
     @mkdir($this->targetRoot, '0644', true);
     $this->targetCore = $this->targetRoot . 'core/components/unittest/';
     @mkdir($this->targetCore, '0644', true);
     $this->targetCore = str_replace('\\', '/', $this->targetCore);
     $this->targetLexDir = $this->targetCore . 'lexicon/';
     $this->targetLexDir = str_replace('\\', '/', $this->targetLexDir);
     @mkdir($this->targetLexDir . 'en', '0644', true);
     copy($this->dataDir . 'default.inc.php', $this->targetLexDir . 'en/default.inc.php');
     copy($this->dataDir . 'chunks.inc.php', $this->targetLexDir . 'en/chunks.inc.php');
     copy($this->dataDir . 'properties.inc.php', $this->targetLexDir . 'en/properties.inc.php');
     $this->targetModelDir = $this->targetCore . 'model/';
     $this->targetModelDir = str_replace('\\', '/', $this->targetModelDir);
     @mkdir($this->targetModelDir, '0644', true);
     copy($this->dataDir . 'example.class.php', $this->targetModelDir . 'example.class.php');
     $this->targetDataDir = $this->targetRoot . '_build/data/';
     $this->targetDataDir = str_replace('\\', '/', $this->targetDataDir);
     @mkdir($this->targetDataDir, '0644', true);
     copy($this->dataDir . 'transport.menus.php', $this->targetDataDir . 'transport.menus.php');
     copy($this->dataDir . 'transport.settings.php', $this->targetDataDir . 'transport.settings.php');
     $this->targetJsDir = $this->targetRoot . 'assets/components/unittest/js/';
     $this->targetJsDir = str_replace('\\', '/', $this->targetJsDir);
     @mkdir($this->targetJsDir, '0644', true);
     copy($this->dataDir . 'example.js', $this->targetJsDir . 'example.js');
     $this->targetChunkDir = $this->targetCore . 'elements/chunks/';
     $this->targetChunkDir = str_replace('\\', '/', $this->targetChunkDir);
     @mkdir($this->targetChunkDir, '0644', true);
     copy($this->dataDir . 'chunk1.chunk.html', $this->targetChunkDir . 'chunk1.chunk.html');
     $this->targetPropertiesDir = $this->targetRoot . '_build/data/properties/';
     $this->targetPropertiesDir = str_replace('\\', '/', $this->targetPropertiesDir);
     @mkdir($this->targetPropertiesDir, '0644', true);
     copy($this->dataDir . 'properties.propertyset1.propertyset.php', $this->targetPropertiesDir . 'properties.propertyset1.propertyset.php');
     copy($this->dataDir . 'properties.snippet1.snippet.php', $this->targetPropertiesDir . 'properties.snippet1.snippet.php');
     $this->languages = array('en' => array('default', 'properties', 'forms'));
     $this->assertNotEmpty($this->targetRoot, 'Empty Root');
     $this->assertNotEmpty($this->targetCore, 'Empty target core');
     $this->assertNotEmpty($this->targetLexDir, 'Empty target lex dir');
     $this->assertNotEmpty($this->targetModelDir, 'Empty Model dir');
     $this->assertNotEmpty($this->targetJsDir, 'Empty JS dir');
     $this->assertNotEmpty($this->targetChunkDir, 'Empty chunk dir');
 }
Пример #14
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();
}
Пример #15
0
$resource_id = !empty($_GET['page_id']) && is_numeric($_GET['page_id']) ? $_GET['page_id'] : 1;
$output = array('prod_list' => '', 'pages' => '', 'total' => 0, 'pageCount' => 1, 'onPageLimit' => 1);
require_once '../../../config.core.php';
require_once MODX_CORE_PATH . 'model/modx/modx.class.php';
$modx = new modX();
//get resourse context_key
$context_key = 'web';
$query = $modx->newQuery('modResource', array('id' => $resource_id, 'published' => true, 'deleted' => false));
$query->select($modx->getSelectColumns('modResource', '', '', array('context_key')));
$stmt = $query->prepare();
if ($stmt) {
    if ($value = $modx->getValue($stmt)) {
        $context_key = $value;
    }
}
$modx->initialize($context_key);
//get resource
$criteria = $modx->newQuery('modResource');
$criteria->select(array($modx->escape('modResource') . '.*'));
$criteria->where(array('id' => $resource_id, 'deleted' => false, 'published' => true));
$modx->resource = $modx->getObject('modResource', $criteria);
if (!is_object($modx->resource) || !$modx->resource->checkPolicy('view')) {
    echo json_encode($output);
    exit;
}
$modx->resourceIdentifier = $modx->resource->get('id');
$modx->getService('error', 'error.modError');
$modx->getRequest();
$modx->getParser();
$modx->resourceMethod = 'id';
$modx->resource->_contextKey = $modx->context->get('key');
Пример #16
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')));
 }