Пример #1
0
 public function init()
 {
     if (isset($this->sp['resource'])) {
         if (!$this->sp['resource']->richtext) {
             return false;
         }
     }
     $useEditor = $this->modx->getOption('use_editor', false);
     $whichEditor = $this->modx->getOption('which_editor', '');
     if ($useEditor && $whichEditor != 'MarkdownEditor') {
         $initCondition = $this->md->getOption('init.condition');
         if (empty($initCondition)) {
             $initCondition = '[]';
         }
         $initCondition = $this->modx->fromJSON($initCondition);
         if (!empty($initCondition)) {
             $c = $this->modx->newQuery('modResource');
             $c->where([['id' => $this->sp['resource']->id], $initCondition]);
             $check = $this->modx->getObject('modResource', $c);
             if ($check) {
                 $this->modx->setOption('which_editor', 'MarkdownEditor');
                 $whichEditor = 'MarkdownEditor';
             }
         }
     }
     if ($useEditor && $whichEditor == 'MarkdownEditor') {
         return true;
     }
     return false;
 }
Пример #2
0
 /**
  * Ensure all tests have a reference to the MODX object
  */
 public function setUp()
 {
     $this->modx =& MODxTestHarness::getFixture('modX', 'modx');
     if ($this->modx->request) {
         $this->modx->request->loadErrorHandler();
         $this->modx->error->reset();
     }
     /* setup some basic test-environment options to allow us to simulate a site */
     $this->modx->setOption('http_host', 'unit.modx.com');
     $this->modx->setOption('base_url', '/');
     $this->modx->setOption('site_url', 'http://unit.modx.com/');
 }
Пример #3
0
 /**
  * Get the configured editor name
  *
  * @return string
  */
 protected function getEditorName()
 {
     // First check for an RTE defined on our particular "namespace"
     $editor = $this->modx->getOption("{$this->config['namespace']}.which_editor", null, $this->modx->getOption("{$this->config['namespace']}.which_editor", $this->options, null));
     if (!$editor || empty($editor)) {
         // No particular namespace editor found, let's fall back to the global one
         $editor = $this->modx->getOption('which_editor', null, null);
     } else {
         // We have an RTE defined, which might not be the "default" system wide one (which_editor setting)
         $this->modx->setOption('which_editor', $editor);
     }
     return $editor;
 }
Пример #4
0
 /**
  * Return the appropriate Resource controller class based on the class_key request parameter
  *
  * @static
  * @param modX $modx A reference to the modX instance
  * @param string $className The controller class name that is attempting to be loaded
  * @param array $config An array of configuration options for the action
  * @return modManagerController The proper controller class
  */
 public static function getInstance(modX &$modx, $className, array $config = array())
 {
     $resourceClass = 'modDocument';
     $isDerivative = false;
     if (!empty($_REQUEST['class_key'])) {
         $isDerivative = true;
         $resourceClass = in_array($_REQUEST['class_key'], array('modDocument', 'modResource')) ? 'modDocument' : $_REQUEST['class_key'];
         if ($resourceClass == 'modResource') {
             $resourceClass = 'modDocument';
         }
     } else {
         if (!empty($_REQUEST['id']) && $_REQUEST['id'] != 'undefined' && strlen($_REQUEST['id']) === strlen((int) $_REQUEST['id'])) {
             /** @var modResource $resource */
             $resource = $modx->getObject('modResource', array('id' => $_REQUEST['id']));
             if ($resource && !in_array($resource->get('class_key'), array('modDocument', 'modResource'))) {
                 $isDerivative = true;
                 $resourceClass = $resource->get('class_key');
             } else {
                 if ($resource && $resource->get('class_key') == 'modResource') {
                     /* fix improper class key */
                     $resource->set('class_key', 'modDocument');
                     $resource->save();
                 }
             }
         }
     }
     if ($isDerivative) {
         $resourceClass = str_replace(array('../', '..', '/', '\\'), '', $resourceClass);
         if (!class_exists($resourceClass) && !$modx->loadClass($resourceClass)) {
             $resourceClass = 'modDocument';
         }
         $delegateView = $modx->call($resourceClass, 'getControllerPath', array(&$modx));
         $action = strtolower(str_replace(array('Resource', 'ManagerController'), '', $className));
         $className = str_replace('mod', '', $resourceClass) . ucfirst($action) . 'ManagerController';
         $controllerFile = $delegateView . $action . '.class.php';
         if (!file_exists($controllerFile)) {
             // We more than likely are using a custom manager theme without overridden controller, let's try with the default theme
             $theme = $modx->getOption('manager_theme', null, 'default');
             $modx->setOption('manager_theme', 'default');
             $delegateView = $modx->call($resourceClass, 'getControllerPath', array(&$modx));
             $controllerFile = $delegateView . $action . '.class.php';
             // Restore custom theme (so we don't process/use default theme assets)
             $modx->setOption('manager_theme', $theme);
         }
         require_once $controllerFile;
     }
     $controller = new $className($modx, $config);
     $controller->resourceClass = $resourceClass;
     return $controller;
 }
Пример #5
0
 /**
  * Show the AJAX result
  *
  * @param array $options Template options
  * @return string
  */
 public function ajaxResult($options)
 {
     $options['language'] = in_array($options['language'], $this->getOption('languages')) ? $options['language'] : 'en';
     $this->modx->setOption('cultureKey', $options['language']);
     $output = array();
     if ($options['add']) {
         $index = $this->add($options['add']);
         if ($index !== false) {
             $fields = array_merge($_SESSION['rememberThis'][$index]['element'], array('deleteurl' => $this->modx->makeUrl($this->modx->getOption('site_start'), '', array($this->getOption('queryDelete') => $index + 1)), 'deleteid' => $index + 1));
             $output['result'] = $this->modx->getChunk($this->getOption('rowTpl'), $fields);
             $output['count'] = count($_SESSION['rememberThis']);
         }
         if ($this->getOption('debug')) {
             $output['debug'] = '<pre>DEBUG: $_SESSION[\'rememberThis\'] = ' . print_r($_SESSION['rememberThis'], true) . '</pre>';
         }
     } else {
         if ($options['delete']) {
             $this->delete($options['delete']);
             if (count($_SESSION['rememberThis']) > 0) {
                 $output['result'] = '';
                 $output['count'] = count($_SESSION['rememberThis']);
             } else {
                 $output['result'] = $this->modx->getChunk($this->getOption('noResultsTpl'));
                 $output['count'] = $this->getOption('showZeroCount') ? '0' : '';
             }
             if ($this->getOption('debug')) {
                 $output['debug'] = '<pre>DEBUG: $_SESSION["rememberThis"] = ' . print_r($_SESSION['rememberThis'], true) . '</pre>';
             }
         }
     }
     return $output;
 }
 /**
  * Return the appropriate Resource controller class based on the class_key request parameter
  * 
  * @static
  * @param modX $modx A reference to the modX instance
  * @param string $className The controller class name that is attempting to be loaded
  * @param array $config An array of configuration options for the action
  * @return modManagerController The proper controller class
  */
 public static function getInstance(modX &$modx, $className, array $config = array())
 {
     $resourceClass = 'modDocument';
     $isDerivative = false;
     if (!empty($_REQUEST['class_key'])) {
         $isDerivative = true;
         $resourceClass = in_array($_REQUEST['class_key'], array('modDocument', 'modResource')) ? 'modDocument' : $_REQUEST['class_key'];
         if ($resourceClass == 'modResource') {
             $resourceClass = 'modDocument';
         }
     } else {
         if (!empty($_REQUEST['id']) && $_REQUEST['id'] != 'undefined') {
             /** @var modResource $resource */
             $resource = $modx->getObject('modResource', $_REQUEST['id']);
             if ($resource && !in_array($resource->get('class_key'), array('modDocument', 'modResource'))) {
                 $isDerivative = true;
                 $resourceClass = $resource->get('class_key');
             } else {
                 if ($resource && $resource->get('class_key') == 'modResource') {
                     /* fix improper class key */
                     $resource->set('class_key', 'modDocument');
                     $resource->save();
                 }
             }
         }
     }
     if ($isDerivative) {
         $resourceClass = str_replace(array('../', '..', '/', '\\'), '', $resourceClass);
         if (!class_exists($resourceClass) && !$modx->loadClass($resourceClass)) {
             $resourceClass = 'modDocument';
         }
         $delegateView = $modx->call($resourceClass, 'getControllerPath', array(&$modx));
         $action = strtolower(str_replace(array('Resource', 'ManagerController'), '', $className));
         $className = str_replace('mod', '', $resourceClass) . ucfirst($action) . 'ManagerController';
         $controllerFile = $delegateView . $action . '.class.php';
         if (!file_exists($controllerFile)) {
             $modx->setOption('manager_theme', 'default');
             $delegateView = $modx->call($resourceClass, 'getControllerPath', array(&$modx));
             $controllerFile = $delegateView . $action . '.class.php';
         }
         require_once $controllerFile;
     }
     $controller = new $className($modx, $config);
     $controller->resourceClass = $resourceClass;
     return $controller;
 }
Пример #7
0
 /**
  * Ensure all tests have a reference to the MODX object
  */
 public function setUp()
 {
     $this->modx =& MODxTestHarness::getFixture('modX', 'modx');
     if ($this->modx->request) {
         $this->modx->request->loadErrorHandler();
         $this->modx->error->reset();
     }
     /* setup some basic test-environment options to allow us to simulate a site */
     $this->modx->setOption('http_host', 'unit.modx.com');
     $this->modx->setOption('base_url', '/');
     $this->modx->setOption('site_url', 'http://unit.modx.com/');
     $corePath = $this->modx->getOption('base_path') . 'extras/minishop/core/components/minishop2/';
     require_once $corePath . 'model/minishop2/minishop2.class.php';
     $this->modx->setOption('minishop2.assets_path', $this->modx->getOption('base_path') . 'extras/minishop/assets/components/minishop2/');
     $this->modx->setOption('minishop2.assets_url', $this->modx->getOption('base_url') . 'extras/minishop/assets/components/minishop2/');
     $this->modx->miniShop2 = new miniShop2($this->modx);
     $this->modx->lexicon->load('minishop2:default');
     $this->path = array('processors_path' => $this->modx->getOption('processorsPath', $this->modx->miniShop2->config, $corePath . 'processors/'));
 }
Пример #8
0
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);
    }
}

/* handle the request */
$connectorRequestClass = $modx->getOption('modConnectorRequest.class',null,'modConnectorRequest');
$modx->config['modRequest.class'] = $connectorRequestClass;
$modx->getRequest();
$modx->request->sanitizeRequest();
Пример #9
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)) . '/';
 $base_path = realpath($modx->getOption('base_path', $options, MODX_BASE_PATH)) . '/';
Пример #10
0
 /**
  * Switch order status
  *
  * @param integer $order_id The id of msOrder
  * @param integer $status_id The id of msOrderStatus
  *
  * @return boolean|string
  */
 public function changeOrderStatus($order_id, $status_id)
 {
     // This method can be overriden by order class
     if (empty($this->order) || !is_object($this->order)) {
         $ctx = !$this->modx->context->key || $this->modx->context->key == 'mgr' ? 'web' : $this->modx->context->key;
         $this->initialize($ctx);
     }
     if (is_object($this->order) && method_exists($this->order, 'changeOrderStatus')) {
         return $this->order->changeOrderStatus($order_id, $status_id);
     }
     $error = '';
     /* @var msOrder $order */
     if (!($order = $this->modx->getObject('msOrder', $order_id))) {
         $error = 'ms2_err_order_nf';
     }
     /* @var msOrderStatus $status */
     if (!($status = $this->modx->getObject('msOrderStatus', array('id' => $status_id, 'active' => 1)))) {
         $error = 'ms2_err_status_nf';
     } else {
         if ($old_status = $this->modx->getObject('msOrderStatus', array('id' => $order->get('status'), 'active' => 1))) {
             if ($old_status->get('final')) {
                 $error = 'ms2_err_status_final';
             } else {
                 if ($old_status->get('fixed')) {
                     if ($status->get('rank') <= $old_status->get('rank')) {
                         $error = 'ms2_err_status_fixed';
                     }
                 }
             }
         }
     }
     if ($order->get('status') == $status_id) {
         $error = 'ms2_err_status_same';
     }
     if (!empty($error)) {
         return $this->modx->lexicon($error);
     }
     $response = $this->invokeEvent('msOnBeforeChangeOrderStatus', array('order' => $order, 'status' => $order->get('status')));
     if (!$response['success']) {
         return $response['message'];
     }
     $order->set('status', $status_id);
     if ($order->save()) {
         $response = $this->invokeEvent('msOnChangeOrderStatus', array('order' => $order, 'status' => $status_id));
         if (!$response['success']) {
             return $response['message'];
         }
         $this->orderLog($order->get('id'), 'status', $status_id);
         /* @var modContext $context */
         if ($context = $this->modx->getObject('modContext', array('key' => $order->get('context')))) {
             $context->prepare(true);
             $lang = $context->getOption('cultureKey');
             $this->modx->setOption('cultureKey', $lang);
             $this->modx->lexicon->load($lang . ':minishop2:default', $lang . ':minishop2:cart');
         }
         $pls = $order->toArray();
         $pls['cost'] = $this->formatPrice($pls['cost']);
         $pls['cart_cost'] = $this->formatPrice($pls['cart_cost']);
         $pls['delivery_cost'] = $this->formatPrice($pls['delivery_cost']);
         $pls['weight'] = $this->formatWeight($pls['weight']);
         $pls['payment_link'] = '';
         if ($payment = $order->getOne('Payment')) {
             if ($class = $payment->get('class')) {
                 $this->loadCustomClasses('payment');
                 if (class_exists($class)) {
                     /* @var msPaymentHandler|PayPal $handler */
                     $handler = new $class($order);
                     if (method_exists($handler, 'getPaymentLink')) {
                         $link = $handler->getPaymentLink($order);
                         $pls['payment_link'] = $this->modx->lexicon('ms2_payment_link', array('link' => $link));
                     }
                 }
             }
         }
         /* @var modChunk $chunk*/
         if ($status->get('email_manager')) {
             $subject = '';
             if ($chunk = $this->modx->newObject('modChunk', array('snippet' => $status->get('subject_manager')))) {
                 $chunk->setCacheable(false);
                 $subject = $this->processTags($chunk->process($pls));
             }
             $body = 'no chunk set';
             if ($chunk = $this->modx->getObject('modChunk', $status->get('body_manager'))) {
                 $chunk->setCacheable(false);
                 $body = $this->processTags($chunk->process($pls));
             }
             $emails = array_map('trim', explode(',', $this->modx->getOption('ms2_email_manager', null, $this->modx->getOption('emailsender'))));
             if (!empty($subject)) {
                 foreach ($emails as $email) {
                     if (preg_match('/^[^@а-яА-Я]+@[^@а-яА-Я]+(?<!\\.)\\.[^\\.а-яА-Я]{2,}$/m', $email)) {
                         $this->sendEmail($email, $subject, $body);
                     }
                 }
             }
         }
         if ($status->get('email_user')) {
             /* @var modUserProfile $profile */
             if ($profile = $this->modx->getObject('modUserProfile', array('internalKey' => $order->get('user_id')))) {
                 $subject = '';
                 if ($chunk = $this->modx->newObject('modChunk', array('snippet' => $status->get('subject_user')))) {
                     $chunk->setCacheable(false);
                     $subject = $this->processTags($chunk->process($pls));
                 }
                 $body = 'no chunk set';
                 if ($chunk = $this->modx->getObject('modChunk', $status->get('body_user'))) {
                     $chunk->setCacheable(false);
                     $body = $this->processTags($chunk->process($pls));
                 }
                 $email = $profile->get('email');
                 if (!empty($subject) && preg_match('/^[^@а-яА-Я]+@[^@а-яА-Я]+(?<!\\.)\\.[^\\.а-яА-Я]{2,}$/m', $email)) {
                     $this->sendEmail($email, $subject, $body);
                 }
             }
         }
     }
     return true;
 }
Пример #11
0
/**
 * Include the main MODX Class
 */
require_once dirname(dirname(__FILE__)) . '/config.core.php';
if (!(include_once MODX_CORE_PATH . 'model/modx/modx.class.php')) {
    include MODX_CORE_PATH . 'error/unavailable.include.php';
    die('HandyMan temporarily unavailable!');
}
/**
 * Instantiate the main MODX class for the manager context, load the parser and the lexicon service.
 */
$modx = new modX();
$modx->initialize('mgr');
$modx->getParser();
$modx->getService('lexicon', 'modLexicon');
$modx->setOption('modRequest.class', 'modRequest');
$modx->getRequest();
/* Include the main HandyMan class.
 * This class takes care of authentication and provides the extension
 * with functions to execute the requests.
 *
 * After inclusion, set up the $hm variable as the main object.
 **/
define('HANDYMAN', true);
$hmPath = $modx->getOption('handyman.core_path');
if (empty($hmPath)) {
    $hmPath = MODX_CORE_PATH . 'components/handyman/';
}
require_once $hmPath . 'classes/handyman.class.php';
$hm = new HandyMan($modx);
$hm->initialize();
Пример #12
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')));
 }
Пример #13
0
$modx->setOption('site_status', false);
/**
 * Paths for types of elements
 *
 * @var array $elements [type_name => path_to_files]
 */
$types = ['snippets' => ['modSnippet', '.php', 'name', "<?php\n"], 'templates' => ['modTemplate', '.html', 'templatename', ''], 'chunks' => ['modChunk', '.html', 'name', ''], 'plugins' => ['modPlugin', '.php', 'name', "<?php\n"]];
foreach (array_keys($types) as $type) {
    $elements[$type] = $type . '/';
    $cat_paths[$type][0] = $elements[$type];
}
/**
 * Paths for categories
 *
 * @var array $cat_paths [type][category_id => relative_path_to_category]
 */
$cc = $modx->getCollection('modCategory');
$cat_list = [];
foreach ($elements as $key => $value) {
    foreach ($cc as $c) {
        $croot = $value . pathTo($c, $cc);
        $cat_paths[$key][$c->id] = $croot . '/';
        $cat_list[$c->id] = $c->category;
    }
}
// if (count($cat_list)) $cat_list = array_flip($cat_list);
/**
 * Save content of non-static elements into files
 */
foreach ($types as $key => $value) {
    $et = $modx->getCollection($value[0]);
    foreach ($et as &$element) {
        if ($element->isStatic() == 0 && !in_array($cat_list[$element->category], $blacklist)) {
            $filename = $fs_prefix . $cat_paths[$key][$element->category] . str_replace(' ', '_', transliterate($element->{$value}[2])) . $value[1];
            $element->set('source', $filesystem_id);
            $element->set('static', 1);
            $element->set('static_file', $filename);
            $element->set('locked', 1);
            $element->save();
        }
    }
}
/**
 * Maintenance mode off
 */
$modx->setOption('site_status', true);