/** * Load the attributes for the ACLs for the context * * @static * @param modX $modx A reference to the modX instance * @param string $context The context to load from. If empty, will use the current context. * @param int $userId The ID of the user to grab ACL records for. * @return array An array of loaded attributes */ public static function loadAttributes(&$modx, $context = '', $userId = 0) { $attributes = array(); $accessTable = $modx->getTableName('modAccessNamespace'); $policyTable = $modx->getTableName('modAccessPolicy'); $memberTable = $modx->getTableName('modUserGroupMember'); $memberRoleTable = $modx->getTableName('modUserGroupRole'); if ($userId > 0) { $sql = "SELECT acl.target, acl.principal, mr.authority, acl.policy, p.data FROM {$accessTable} acl " . "LEFT JOIN {$policyTable} p ON p.id = acl.policy " . "JOIN {$memberTable} mug ON acl.principal_class = 'modUserGroup' " . "AND mug.member = :principal " . "AND mug.user_group = acl.principal " . "JOIN {$memberRoleTable} mr ON mr.id = mug.role " . "AND mr.authority <= acl.authority " . "ORDER BY acl.target, acl.principal, mr.authority, acl.policy"; $bindings = array(':principal' => $userId); $query = new xPDOCriteria($modx, $sql, $bindings); if ($query->stmt && $query->stmt->execute()) { while ($row = $query->stmt->fetch(PDO::FETCH_ASSOC)) { $attributes[$row['target']][] = array('principal' => $row['principal'], 'authority' => $row['authority'], 'policy' => $row['data'] ? $modx->fromJSON($row['data'], true) : array()); } } } else { $sql = "SELECT acl.target, acl.principal, 0 AS authority, acl.policy, p.data FROM {$accessTable} acl " . "LEFT JOIN {$policyTable} p ON p.id = acl.policy " . "WHERE acl.principal_class = 'modUserGroup' " . "AND acl.principal = 0 " . "ORDER BY acl.target, acl.principal, acl.authority, acl.policy"; $query = new xPDOCriteria($modx, $sql); if ($query->stmt && $query->stmt->execute()) { while ($row = $query->stmt->fetch(PDO::FETCH_ASSOC)) { $attributes[$row['target']][] = array('principal' => 0, 'authority' => $row['authority'], 'policy' => $row['data'] ? $modx->fromJSON($row['data'], true) : array()); } } } return $attributes; }
protected function install($packagesDir, $dir, $packagesBaseUrl, OutputInterface $output) { $configContent = $this->modx->fromJSON(file_get_contents($packagesDir . $dir . '/_build/config.json')); $this->config = new Config($this->modx, $dir); $this->config->parseConfig($configContent); $this->packageCorePath = $packagesDir . $dir . "/core/components/" . $this->config->getLowCaseName() . "/"; $this->packageCorePath = str_replace('\\', '/', $this->packageCorePath); $this->packageAssetsPath = $packagesDir . $dir . "/assets/components/" . $this->config->getLowCaseName() . "/"; $this->packageAssetsPath = str_replace('\\', '/', $this->packageAssetsPath); $this->packageAssetsUrl = $packagesBaseUrl . $dir . '/assets/components/' . $this->config->getLowCaseName() . '/'; $this->createNamespace(); $this->createMenusAndActions(); $this->createSystemSettings($packagesDir, $packagesBaseUrl); $this->createTables(); $this->clearCache(); /** @var \GitPackage $packageObject */ $packageObject = $this->modx->newObject('GitPackage'); $packageObject->set('version', $this->config->getVersion()); $packageObject->set('description', $this->config->getDescription()); $packageObject->set('author', $this->config->getAuthor()); $packageObject->set('name', $this->config->getName()); $packageObject->set('dir_name', $dir); $packageObject->set('config', $this->modx->toJSON($configContent)); $packageObject->save(); }
/** * Allow user to prepare single row by custom snippet before render chunk * This method was developed in cooperation with Agel_Nash * * @param array $row * * @return array */ public function prepareRow($row = array()) { if ($this->preparing) { return $row; } if (!empty($this->config['prepareSnippet'])) { $this->preparing = true; $name = trim($this->config['prepareSnippet']); array_walk_recursive($row, function (&$value) { $value = str_replace(array('[', ']', '{', '}'), array('*(*(*(*(*(*', '*)*)*)*)*)*', '~(~(~(~(~(~', '~)~)~)~)~)~'), $value); }); $tmp = $this->runSnippet($name, array('pdoTools' => $this, 'pdoFetch' => $this, 'row' => $row)); $tmp = $tmp[0] == '[' || $tmp[0] == '{' ? $this->modx->fromJSON($tmp, 1) : unserialize($tmp); if (!is_array($tmp)) { $this->addTime('Preparation snippet must return an array, instead of "' . gettype($tmp) . '"'); } else { $row = array_merge($row, $tmp); } $this->preparing = false; array_walk_recursive($row, function (&$value) { $value = str_replace(array('*(*(*(*(*(*', '*)*)*)*)*)*', '~(~(~(~(~(~', '~)~)~)~)~)~'), array('[', ']', '{', '}'), $value); }); } return $row; }
/** * Allow user to prepare single row by custom snippet before render chunk * This method was developed in cooperation with Agel_Nash * * @param array $row * * @return array */ public function prepareRow($row = array()) { if ($this->preparing) { return $row; } if (!empty($this->config['prepareSnippet'])) { $this->preparing = true; $name = trim($this->config['prepareSnippet']); /** @var modSnippet $snippet */ if (!($snippet = $this->getStore($name, 'snippet'))) { if ($snippet = $this->modx->getObject('modSnippet', array('name' => $name))) { $this->setStore($name, $snippet, 'snippet'); } else { $this->addTime('Could not load snippet "' . $name . '" for preparation of row.'); return ''; } } $snippet->_cacheable = false; $snippet->_processed = false; $tmp = $snippet->process(array('pdoTools' => $this, 'pdoFetch' => $this, 'row' => $row)); $tmp = $tmp[0] == '[' || $tmp[0] == '{' ? $this->modx->fromJSON($tmp, 1) : unserialize($tmp); if (!is_array($tmp)) { $this->addTime('Preparation snippet must return an array, instead of "' . gettype($tmp) . '"'); } else { $row = array_merge($row, $tmp); } $this->preparing = false; } return $row; }
/** * Redirect to a specified URL. * * Properties needed: * - redirectTo - the ID of the Resource to redirect to. * * @param array $fields An array of cleaned POST fields * @return boolean False if unsuccessful. */ public function redirect(array $fields = array()) { if (empty($this->formit->config['redirectTo'])) { return false; } $redirectParams = !empty($this->formit->config['redirectParams']) ? $this->formit->config['redirectParams'] : ''; if (!empty($redirectParams)) { $prefix = $this->modx->getOption('placeholderPrefix', $this->formit->config, 'fi.'); $this->modx->setPlaceholders($fields, $prefix); $this->modx->parser->processElementTags('', $redirectParams, true, true); $redirectParams = $this->modx->fromJSON($redirectParams); if (empty($redirectParams)) { $redirectParams = ''; } } $contextKey = $this->modx->context->get('key'); $resource = $this->modx->getObject('modResource', $this->formit->config['redirectTo']); if ($resource) { $contextKey = $resource->get('context_key'); } if (!is_numeric($this->formit->config['redirectTo']) && isset($fields[$this->formit->config['redirectTo']]) && is_numeric($fields[$this->formit->config['redirectTo']])) { $url = $this->modx->makeUrl($fields[$this->formit->config['redirectTo']], $contextKey, $redirectParams, 'full'); } elseif (!is_numeric($this->formit->config['redirectTo']) && substr($this->formit->config['redirectTo'], 0, 4) === "http") { $url = $this->formit->config['redirectTo']; } else { $url = $this->modx->makeUrl($this->formit->config['redirectTo'], $contextKey, $redirectParams, 'full'); } $this->setRedirectUrl($url); return true; }
/** * Get an array of settings for the container. * @return array */ public function getContainerSettings() { $settings = $this->getProperties('articles'); if (!empty($settings)) { $settings = is_array($settings) ? $settings : $this->xpdo->fromJSON($settings); } return !empty($settings) ? $settings : array(); }
/** * PDFresource constructor * * @param modX $modx A reference to the modX instance. * @param array $options An array of options. Optional. */ function __construct(modX &$modx, array $options = array()) { $this->modx =& $modx; $corePath = $this->getOption('core_path', $options, $this->modx->getOption('core_path') . 'components/' . $this->namespace . '/'); $assetsPath = $this->getOption('assets_path', $options, $this->modx->getOption('assets_path') . 'components/' . $this->namespace . '/'); $assetsUrl = $this->getOption('assets_url', $options, $this->modx->getOption('assets_url') . 'components/' . $this->namespace . '/'); $pdfPath = $this->getOption('pdf_path', $options, $this->modx->getOption('assets_path') . 'pdf/'); $pdfUrl = $this->getOption('pdf_url', $options, $this->modx->getOption('assets_url') . 'pdf/'); // Load some default paths for easier management $this->options = array_merge(array('namespace' => $this->namespace, 'version' => $this->version, 'assetsPath' => $assetsPath, 'assetsUrl' => $assetsUrl, 'cssUrl' => $assetsUrl . 'css/', 'jsUrl' => $assetsUrl . 'js/', 'imagesUrl' => $assetsUrl . 'images/', 'corePath' => $corePath, 'modelPath' => $corePath . 'model/', 'vendorPath' => $corePath . 'vendor/', 'chunksPath' => $corePath . 'elements/chunks/', 'pagesPath' => $corePath . 'elements/pages/', 'snippetsPath' => $corePath . 'elements/snippets/', 'pluginsPath' => $corePath . 'elements/plugins/', 'controllersPath' => $corePath . 'controllers/', 'processorsPath' => $corePath . 'processors/', 'templatesPath' => $corePath . 'templates/', 'connectorUrl' => $assetsUrl . 'connector.php', 'pdfPath' => $pdfPath, 'pdfUrl' => $pdfUrl), $options); // Init mPDF options $mode = $this->modx->getOption('mode', $options, ''); $format = $this->modx->getOption('format', $options, 'A4'); $default_font_size = intval($this->modx->getOption('defaultFontSize', $options, 0)); $default_font = $this->modx->getOption('defaultFont', $options, ''); $mgl = intval($this->modx->getOption('mgl', $options, 15)); $mgr = intval($this->modx->getOption('mgr', $options, 15)); $mgt = intval($this->modx->getOption('mgt', $options, 16)); $mgb = intval($this->modx->getOption('mgb', $options, 16)); $mgh = intval($this->modx->getOption('mgb', $options, 9)); $mgf = intval($this->modx->getOption('mgf', $options, 9)); $orientation = $this->modx->getOption('orientation', $options, 'P'); parent::mPDF($mode, $format, $default_font_size, $default_font, $mgl, $mgr, $mgt, $mgb, $mgh, $mgf, $orientation); $customFonts = $this->modx->fromJSON($this->modx->getOption('customFonts', $options, '')); if (is_array($customFonts)) { foreach ($customFonts as $f => $fs) { $this->fontdata[$f] = $fs; if (isset($fs['R']) && $fs['R']) { $this->available_unifonts[] = $f; } if (isset($fs['B']) && $fs['B']) { $this->available_unifonts[] = $f . 'B'; } if (isset($fs['I']) && $fs['I']) { $this->available_unifonts[] = $f . 'I'; } if (isset($fs['BI']) && $fs['BI']) { $this->available_unifonts[] = $f . 'BI'; } } } else { $this->modx->log(modX::LOG_LEVEL_ERROR, 'customFonts does not contain an array.', '', 'PDFresource'); } $this->default_available_fonts = $this->available_unifonts; }
public static function getInstance(modX &$modx, $className, $properties = array()) { if (isset($properties['data'])) { $data = (array) $modx->fromJSON($properties['data']); $properties = array_merge($properties, $data); unset($properties['data'], $data); } return parent::getInstance($modx, $className, $properties); }
/** * Load the attributes for the ACLs for the Resource Group * * @static * @param modX $modx A reference to the modX instance * @param string $context The context to load from. If empty, will use the current context. * @param int $userId The ID of the user to grab ACL records for. * @return array An array of loaded attributes */ public static function loadAttributes(&$modx, $context = '', $userId = 0) { $attributes = array(); if (empty($context)) { $context = $modx->context->get('key'); } $enabled = (bool) $modx->getOption('access_resource_group_enabled', null, true); if ($context !== $modx->context->get('key') && $modx->getContext($context)) { $enabled = (bool) $modx->contexts[$context]->getOption('access_resource_group_enabled', $enabled); } if ($enabled) { $accessTable = $modx->getTableName('modAccessResourceGroup'); $policyTable = $modx->getTableName('modAccessPolicy'); $memberTable = $modx->getTableName('modUserGroupMember'); $memberRoleTable = $modx->getTableName('modUserGroupRole'); $legacyDocGroups = array(); if ($userId > 0) { $sql = "SELECT acl.target, acl.principal, mr.authority, acl.policy, p.data FROM {$accessTable} acl " . "LEFT JOIN {$policyTable} p ON p.id = acl.policy " . "JOIN {$memberTable} mug ON acl.principal_class = 'modUserGroup' " . "AND (acl.context_key = :context OR acl.context_key IS NULL OR acl.context_key = '') " . "AND mug.member = :principal " . "AND mug.user_group = acl.principal " . "JOIN {$memberRoleTable} mr ON mr.id = mug.role " . "AND mr.authority <= acl.authority " . "ORDER BY acl.target, acl.principal, mr.authority, acl.policy"; $bindings = array(':principal' => $userId, ':context' => $context); $query = new xPDOCriteria($modx, $sql, $bindings); if ($query->stmt && $query->stmt->execute()) { while ($row = $query->stmt->fetch(PDO::FETCH_ASSOC)) { $attributes[$row['target']][] = array('principal' => $row['principal'], 'authority' => $row['authority'], 'policy' => $row['data'] ? $modx->fromJSON($row['data'], true) : array()); $legacyDocGroups[$row['target']] = $row['target']; } } } else { $sql = "SELECT acl.target, acl.principal, 0 AS authority, acl.policy, p.data FROM {$accessTable} acl " . "LEFT JOIN {$policyTable} p ON p.id = acl.policy " . "WHERE acl.principal_class = 'modUserGroup' " . "AND acl.principal = 0 " . "AND (acl.context_key = :context OR acl.context_key IS NULL OR acl.context_key = '') " . "ORDER BY acl.target, acl.principal, acl.authority, acl.policy"; $bindings = array(':context' => $context); $query = new xPDOCriteria($modx, $sql, $bindings); if ($query->stmt && $query->stmt->execute()) { while ($row = $query->stmt->fetch(PDO::FETCH_ASSOC)) { $attributes[$row['target']][] = array('principal' => 0, 'authority' => $row['authority'], 'policy' => $row['data'] ? $modx->fromJSON($row['data'], true) : array()); $legacyDocGroups[$row['target']] = $row['target']; } } } $_SESSION['modx.user.' . ($userId > 0 ? (string) $userId : '0') . '.resourceGroups'] = array($context => array_values($legacyDocGroups)); } return $attributes; }
/** * Get options for reCaptcha from snippet * * @param array $scriptProperties * @return array|void */ public function getOptions(array $scriptProperties = array()) { $opt = $this->modx->getOption('recaptchaJs', $scriptProperties, '{}'); $opt = $this->modx->fromJSON($opt); if (empty($opt)) { $opt = array(); } /* backwards compat */ $backwardOpt = array('theme' => $this->modx->getOption('recaptchaTheme', $scriptProperties, 'clean'), 'width' => $this->modx->getOption('recaptchaWidth', $scriptProperties, 500), 'height' => $this->modx->getOption('recaptchaHeight', $scriptProperties, 300), 'lang' => $this->modx->getOption('cultureKey', null, 'en')); $opt = array_merge($backwardOpt, $opt); return $opt; }
/** * Translate a string using a named transliteration table. * * @param string $string The string to transliterate. * * @return string The translated string. */ public function translate($string) { $exclude = $this->modx->getOption('friendly_alias_ytranslit_exclude', '', '/^[_-a-zA-z\\d\\s\\:\\(\\)]+$/i', true); if (empty($string) || preg_match($exclude, $string)) { return $string; } $extension = ''; if (preg_match('#\\.[0-9a-z]+$#i', $string, $matches)) { $extension = $matches[0]; $string = preg_replace('#' . $extension . '$#', '', $string); } $trim = $this->modx->getOption('friendly_alias_trim_chars', null, '/.-_', true); $string = str_replace(str_split($trim), ' ', $string); $service = $this->modx->getOption('friendly_alias_ytranslit_url', null, 'https://translate.yandex.net/api/v1.5/tr.json/translate?key=[[+key]]&lang=ru-en&text=', true); $key = trim($this->modx->getOption('friendly_alias_ytranslit_key', null, '')); if (empty($key)) { $this->modx->log(modX::LOG_LEVEL_ERROR, '[yTranslit] You must specify the API key! Please, get it from http://api.yandex.ru/key/form.xml?service=trnsl.'); return $string; } else { $request = str_replace('[[+key]]', $key, $service) . urlencode($string); if (function_exists('curl_init')) { $url = parse_url($request); parse_str($url['query'], $params); /** @var modRestCurlClient $client */ $client = $this->modx->getService('rest.modRestCurlClient'); $result = $client->request($url['scheme'] . '://' . $url['host'], $url['path'], 'GET', $params, array('curlopt_timeout' => $this->modx->getOption('friendly_alias_ytranslit_timeout', null, 1, true), 'curlopt_returntransfer' => 1)); } else { $result = file_get_contents($request); } $arr = $this->modx->fromJSON($result); if (!is_array($arr)) { $this->modx->log(modX::LOG_LEVEL_ERROR, "[yTranslit] Service unavailable.\nRequest: {$request}.\nResponse: {$result}"); } elseif ($arr['code'] != 200 || empty($arr['text'][0])) { $this->modx->log(modX::LOG_LEVEL_ERROR, '[yTranslit] Service returned an error. ' . print_r($arr, true)); } else { $string = $arr['text'][0]; } return $string . strtolower($extension); } }
/** * Constructor */ public function __construct(modX &$modx) { $this->modx = $modx; // require original phpconsole class $phpconsole_file = dirname(__FILE__) . '/vendor/phpconsole.php'; if (file_exists($phpconsole_file)) { require_once $phpconsole_file; } else { return false; } // make sure phpconsole should be enabled if (!$this->modx->getOption('phpconsole.enabled', null, false)) { return false; } // load config $this->config = new \Phpconsole\Config(); // set default project $this->project = $this->modx->getOption('phpconsole.project', null, 'default'); $configSetting = $this->modx->fromJSON($this->modx->getOption('phpconsole.config', null, '')); if (!empty($configSetting)) { // load config from system setting $this->config->loadFromArray($configSetting); } else { if (file_exists(MODX_CORE_PATH . 'config/phpconsole-config.inc.php')) { // load config from file $this->config->loadFromLocation(MODX_CORE_PATH . 'config/phpconsole-config.inc.php'); } else { // if no config exists, switch back to the FILE logTarget $this->modx->setLogTarget('FILE'); return false; } } // initialize phpconsole $this->phpconsole = new \Phpconsole\Phpconsole($this->config); // set logTarget to ARRAY_EXTENDED to store all log() calls in an array $this->modx->setLogTarget(array('target' => 'ARRAY_EXTENDED', 'options' => array('var' => &$this->logArray))); // register a shoutdown function to log fatal errors in phpconsole register_shutdown_function('phpconsoleFatalLogger'); }
/** * Function for formatting price * * @param string $price * * @return string $price */ public function formatPrice($price = '0') { $pf = $this->modx->fromJSON($this->modx->getOption('ms2_price_format', null, '[2, ".", " "]')); if (is_array($pf)) { $price = number_format($price, $pf[0], $pf[1], $pf[2]); } if ($this->modx->getOption('ms2_price_format_no_zeros', null, true)) { if (preg_match('/\\..*$/', $price, $matches)) { $tmp = rtrim($matches[0], '.0'); $price = str_replace($matches[0], $tmp, $price); } } return $price; }
public function getQuery($currentParent) { /* build query */ $c = $this->modx->newQuery('modResource'); $c->leftJoin('modResource', 'Children'); $c->select($this->modx->getSelectColumns('modResource', 'modResource')); $c->select(array('COUNT(Children.id) AS children')); $c->where(array('parent' => $currentParent)); /* if restricting to contexts */ if (!empty($this->config['context'])) { $ctxs = $this->prepareForIn($this->config['context']); $c->where(array('modResource.context_key:IN' => $ctxs)); } else { $c->where(array('modResource.context_key' => $this->modx->context->get('key'))); } /* if excluding resources */ if (!empty($this->config['excludeResources'])) { $ex = $this->prepareForIn($this->config['excludeResources']); $c->where(array('modResource.id:NOT IN' => $ex)); } /* if excluding all children of certain resources */ if (!empty($this->config['excludeChildrenOf'])) { $excludingParents = is_array($this->config['excludeChildrenOf']) ? $this->config['excludeChildrenOf'] : explode(',', $this->config['excludeChildrenOf']); $excludedChildren = array(); foreach ($excludingParents as $excludingParent) { $childrenIds = $this->modx->getChildIds($excludingParent, 10); $excludedChildren = array_merge($excludedChildren, $childrenIds); } $excludedChildren = array_unique($excludedChildren); $c->where(array('modResource.id:NOT IN' => $excludedChildren)); } /* if restricting to templates */ if (!empty($this->config['allowedtemplates'])) { $tpls = $this->prepareForIn($this->config['allowedtemplates']); $c->innerJoin('modTemplate', 'Template'); $c->where(array('Template.' . $this->config['templateFilter'] . ':IN' => $tpls)); } /* where filtering */ if (!empty($this->config['where'])) { $where = is_array($this->config['where']) ? $this->config['where'] : $this->modx->fromJSON($this->config['where']); $c->where($where); } /* sorting/grouping */ $c->sortby($this->config['sortBy'], $this->config['sortDir']); $c->groupby('modResource.id'); return $c; }
/** * Loads the access control policies applicable to this template variable. * * {@inheritdoc} */ public function findPolicy($context = '') { $policy = array(); $context = !empty($context) ? $context : $this->xpdo->context->get('key'); if ($context === $this->xpdo->context->get('key')) { $catEnabled = (bool) $this->xpdo->getOption('access_category_enabled', null, true); $rgEnabled = (bool) $this->xpdo->getOption('access_resource_group_enabled', null, true); } elseif ($this->xpdo->getContext($context)) { $catEnabled = (bool) $this->xpdo->contexts[$context]->getOption('access_category_enabled', true); $rgEnabled = (bool) $this->xpdo->contexts[$context]->getOption('access_resource_group_enabled', true); } $enabled = $catEnabled || $rgEnabled; if ($enabled) { if (empty($this->_policies) || !isset($this->_policies[$context])) { if ($rgEnabled) { $accessTable = $this->xpdo->getTableName('modAccessResourceGroup'); $policyTable = $this->xpdo->getTableName('modAccessPolicy'); $resourceGroupTable = $this->xpdo->getTableName('modTemplateVarResourceGroup'); $sql = "SELECT Acl.target, Acl.principal, Acl.authority, Acl.policy, Policy.data FROM {$accessTable} Acl " . "LEFT JOIN {$policyTable} Policy ON Policy.id = Acl.policy " . "JOIN {$resourceGroupTable} ResourceGroup ON Acl.principal_class = 'modUserGroup' " . "AND (Acl.context_key = :context OR Acl.context_key IS NULL OR Acl.context_key = '') " . "AND ResourceGroup.tmplvarid = :element " . "AND ResourceGroup.documentgroup = Acl.target " . "ORDER BY Acl.target, Acl.principal, Acl.authority"; $bindings = array(':element' => $this->get('id'), ':context' => $context); $query = new xPDOCriteria($this->xpdo, $sql, $bindings); if ($query->stmt && $query->stmt->execute()) { while ($row = $query->stmt->fetch(PDO::FETCH_ASSOC)) { $policy['modAccessResourceGroup'][$row['target']][] = array('principal' => $row['principal'], 'authority' => $row['authority'], 'policy' => $row['data'] ? $this->xpdo->fromJSON($row['data'], true) : array()); } } } if ($catEnabled) { $accessTable = $this->xpdo->getTableName('modAccessCategory'); $categoryClosureTable = $this->xpdo->getTableName('modCategoryClosure'); $sql = "SELECT Acl.target, Acl.principal, Acl.authority, Acl.policy, Policy.data FROM {$accessTable} Acl " . "LEFT JOIN {$policyTable} Policy ON Policy.id = Acl.policy " . "JOIN {$categoryClosureTable} CategoryClosure ON CategoryClosure.descendant = :category " . "AND Acl.principal_class = 'modUserGroup' " . "AND CategoryClosure.ancestor = Acl.target " . "AND (Acl.context_key = :context OR Acl.context_key IS NULL OR Acl.context_key = '') " . "ORDER BY CategoryClosure.depth DESC, target, principal, authority ASC"; $bindings = array(':category' => $this->get('category'), ':context' => $context); $query = new xPDOCriteria($this->xpdo, $sql, $bindings); if ($query->stmt && $query->stmt->execute()) { while ($row = $query->stmt->fetch(PDO::FETCH_ASSOC)) { $policy['modAccessCategory'][$row['target']][] = array('principal' => $row['principal'], 'authority' => $row['authority'], 'policy' => $row['data'] ? $this->xpdo->fromJSON($row['data'], true) : array()); } } } $this->_policies[$context] = $policy; } else { $policy = $this->_policies[$context]; } } return $policy; }
public function __construct(modX &$modx, array $config = array()) { $this->modx =& $modx; $corePath = $this->modx->getOption('msearch2.core_path', $config, $this->modx->getOption('core_path') . 'components/msearch2/'); $assetsUrl = $this->modx->getOption('msearch2.assets_url', $config, $this->modx->getOption('assets_url') . 'components/msearch2/'); $actionUrl = $this->modx->getOption('msearch2.action_url', $config, $assetsUrl . 'action.php'); $connectorUrl = $assetsUrl . 'connector.php'; $this->config = array_merge(array('assetsUrl' => $assetsUrl, 'cssUrl' => $assetsUrl . 'css/', 'jsUrl' => $assetsUrl . 'js/', 'imagesUrl' => $assetsUrl . 'images/', 'customPath' => $corePath . 'custom/', 'connectorUrl' => $connectorUrl, 'actionUrl' => $actionUrl, 'corePath' => $corePath, 'modelPath' => $corePath . 'model/', 'templatesPath' => $corePath . 'elements/templates/', 'processorsPath' => $corePath . 'processors/', 'cacheTime' => 1800, 'languages' => array('ru_RU' => array('storage' => 'file'), 'en_EN' => array('storage' => 'file')), 'min_word_length' => $this->modx->getOption('mse2_index_min_words_length', null, 3, true), 'exact_match_bonus' => $this->modx->getOption('mse2_search_exact_match_bonus', null, 5, true), 'all_words_bonus' => $this->modx->getOption('mse2_search_all_words_bonus', null, 5, true), 'introCutBefore' => 50, 'introCutAfter' => 250, 'filter_delimeter' => '|', 'method_delimeter' => ':', 'values_delimeter' => ',', 'split_words' => $this->modx->getOption('mse2_search_split_words', null, '#\\s#', true), 'split_all' => '#\\s|[,.:;!?"\'(){}\\/\\#]#', 'suggestionsRadio' => array()), $config); if (!is_array($this->config['languages'])) { $this->config['languages'] = $modx->fromJSON($this->config['languages']); } if (!is_array($this->config['suggestionsRadio'])) { $this->config['suggestionsRadio'] = array_map('trim', explode(',', $this->config['suggestionsRadio'])); } $this->modx->addPackage('msearch2', $this->config['modelPath']); $this->modx->lexicon->load('msearch2:default'); }
/** * Redirect to a specified URL. * * Properties needed: * - redirectTo - the ID of the Resource to redirect to. * * @param array $fields An array of cleaned POST fields * @return boolean False if unsuccessful. */ public function redirect(array $fields = array()) { if (empty($this->quip->config['redirectTo'])) { return false; } $redirectParams = !empty($this->quip->config['redirectParams']) ? $this->quip->config['redirectParams'] : ''; if (!empty($redirectParams)) { $prefix = $this->modx->getOption('placeholderPrefix', $this->quip->config, 'fi.'); $this->modx->setPlaceholders($fields, $prefix); $this->modx->parser->processElementTags('', $redirectParams, true, true); $redirectParams = $this->modx->fromJSON($redirectParams); if (empty($redirectParams)) { $redirectParams = ''; } } $url = $this->modx->makeUrl($this->quip->config['redirectTo'], '', $redirectParams, 'abs'); $this->setRedirectUrl($url); return true; }
/** @inheritdoc} */ public function submit($data = array()) { $response = $this->ms2->invokeEvent('msOnSubmitOrder', array('data' => $data, 'order' => $this)); if (!$response['success']) { return $this->error($response['message']); } if (!empty($response['data']['data'])) { $this->set($response['data']['data']); } $response = $this->getDeliveryRequiresFields(); if ($this->ms2->config['json_response']) { $response = $this->modx->fromJSON($response); } $requires = $response['data']['requires']; $errors = array(); foreach ($requires as $v) { if (!empty($v) && empty($this->order[$v])) { $errors[] = $v; } } if (!empty($errors)) { return $this->error('ms2_order_err_requires', $errors); } $user_id = $this->ms2->getCustomerId(); $cart_status = $this->ms2->cart->status(); $delivery_cost = $this->getCost(false, true); $createdon = date('Y-m-d H:i:s'); /* @var msOrder $order */ $order = $this->modx->newObject('msOrder'); $order->fromArray(array('user_id' => $user_id, 'createdon' => $createdon, 'num' => $this->getnum(), 'delivery' => $this->order['delivery'], 'payment' => $this->order['payment'], 'cart_cost' => $cart_status['total_cost'], 'weight' => $cart_status['total_weight'], 'delivery_cost' => $delivery_cost, 'cost' => $cart_status['total_cost'] + $delivery_cost, 'status' => 0, 'context' => $this->ms2->config['ctx'])); // Adding address /* @var msOrderAddress $address */ $address = $this->modx->newObject('msOrderAddress'); $address->fromArray(array_merge($this->order, array('user_id' => $user_id, 'createdon' => $createdon))); $order->addOne($address); // Adding products $cart = $this->ms2->cart->get(); $products = array(); foreach ($cart as $v) { /* @var msOrderProduct $product */ $product = $this->modx->newObject('msOrderProduct'); $product->fromArray(array_merge($v, array('product_id' => $v['id'], 'cost' => $v['price'] * $v['count']))); $products[] = $product; } $order->addMany($products); $response = $this->ms2->invokeEvent('msOnBeforeCreateOrder', array('msOrder' => $order, 'order' => $this)); if (!$response['success']) { return $this->error($response['message']); } if ($order->save()) { $response = $this->ms2->invokeEvent('msOnCreateOrder', array('msOrder' => $order, 'order' => $this)); if (!$response['success']) { return $this->error($response['message']); } $this->ms2->cart->clean(); $this->clean(); if (empty($_SESSION['minishop2']['orders'])) { $_SESSION['minishop2']['orders'] = array(); } $_SESSION['minishop2']['orders'][] = $order->get('id'); // Trying to set status "new" $response = $this->ms2->changeOrderStatus($order->get('id'), 1); if ($response !== true) { return $this->error($response, array('msorder' => $order->get('id'))); } elseif ($payment = $this->modx->getObject('msPayment', array('id' => $order->get('payment'), 'active' => 1))) { $response = $payment->send($order); if ($this->config['json_response']) { @session_write_close(); exit(is_array($response) ? $this->modx->toJSON($response) : $response); } else { if (!empty($response['data']['redirect'])) { $this->modx->sendRedirect($response['data']['redirect']); exit; } elseif (!empty($response['data']['msorder'])) { $this->modx->sendRedirect($this->modx->makeUrl($this->modx->resource->id), array('msorder' => $response['data']['msorder'])); exit; } else { $this->modx->sendRedirect($this->modx->makeUrl($this->modx->resource->id)); exit; } } } else { if ($this->ms2->config['json_response']) { return $this->success('', array('msorder' => $order->get('id'))); } else { $this->modx->sendRedirect($this->modx->makeUrl($this->modx->resource->id), array('msorder' => $response['data']['msorder'])); exit; } } } return $this->error(); }
/** @inheritdoc} */ public function formatOutcoming($sum = '0') { $pf = $this->modx->fromJSON($this->MlmSystem->getOption('format_outcoming', null, '[2, ".", " "]')); $noZeros = $this->MlmSystem->getOption('format_outcoming_no_zeros', null, true); return $this->sumFormat($sum, $pf, $noZeros); }
/** * Find all policies for this object * * @param string $context * @return array */ public function findPolicy($context = '') { $policy = array(); $enabled = true; $context = 'mgr'; if ($context === $this->xpdo->context->get('key')) { $enabled = (bool) $this->xpdo->getOption('access_media_source_enabled', null, true); } elseif ($this->xpdo->getContext($context)) { $enabled = (bool) $this->xpdo->contexts[$context]->getOption('access_media_source_enabled', true); } if ($enabled) { if (empty($this->_policies) || !isset($this->_policies[$context])) { $accessTable = $this->xpdo->getTableName('sources.modAccessMediaSource'); $sourceTable = $this->xpdo->getTableName('sources.modMediaSource'); $policyTable = $this->xpdo->getTableName('modAccessPolicy'); $sql = "SELECT Acl.target, Acl.principal, Acl.authority, Acl.policy, Policy.data FROM {$accessTable} Acl " . "LEFT JOIN {$policyTable} Policy ON Policy.id = Acl.policy " . "JOIN {$sourceTable} Source ON Acl.principal_class = 'modUserGroup' " . "AND (Acl.context_key = :context OR Acl.context_key IS NULL OR Acl.context_key = '') " . "AND Source.id = Acl.target " . "WHERE Acl.target = :source " . "GROUP BY Acl.target, Acl.principal, Acl.authority, Acl.policy"; $bindings = array(':source' => $this->get('id'), ':context' => $context); $query = new xPDOCriteria($this->xpdo, $sql, $bindings); if ($query->stmt && $query->stmt->execute()) { while ($row = $query->stmt->fetch(PDO::FETCH_ASSOC)) { $policy['sources.modAccessMediaSource'][$row['target']][] = array('principal' => $row['principal'], 'authority' => $row['authority'], 'policy' => $row['data'] ? $this->xpdo->fromJSON($row['data'], true) : array()); } } $this->_policies[$context] = $policy; } else { $policy = $this->_policies[$context]; } } return $policy; }
$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 */ $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'];
/** * Loads a variable number of topic areas. They must reside as topicname. * inc.php files in their proper culture directory. Can load an infinite * number of topic areas via a dynamic number of arguments. * * They are loaded by language:namespace:topic, namespace:topic, or just * topic. Examples: $modx->lexicon->load('en:core:snippet'); $modx->lexicon- * >load ('demo:test'); $modx->lexicon->load('chunk'); * * @access public */ public function load() { $topics = func_get_args(); /* allow for dynamic number of lexicons to load */ if ($this->modx->context && $this->modx->context->get('key') == 'mgr') { $defaultLanguage = $this->modx->getOption('manager_language', null, $this->modx->getOption('cultureKey', null, 'en')); } else { $defaultLanguage = $this->modx->getOption('cultureKey', null, 'en'); } foreach ($topics as $topicStr) { if (!is_string($topicStr) || $topicStr == '') { continue; } if (in_array($topicStr, $this->_loadedTopics)) { continue; } $nspos = strpos($topicStr, ':'); $topic = str_replace('.', '/', $topicStr); /** @deprecated 2.0.0 Allow for lexicon subdirs */ /* if no namespace, search all lexicons */ if ($nspos === false) { foreach ($this->_paths as $namespace => $path) { $entries = $this->loadCache($namespace, $topic); if (is_array($entries)) { if (!array_key_exists($defaultLanguage, $this->_lexicon)) { $this->_lexicon[$defaultLanguage] = array(); } $this->_lexicon[$defaultLanguage] = is_array($this->_lexicon[$defaultLanguage]) ? array_merge($this->_lexicon[$defaultLanguage], $entries) : $entries; } } } else { /* if namespace, search specified lexicon */ $params = explode(':', $topic); if (count($params) <= 2) { $language = $defaultLanguage; $namespace = $params[0]; $topic_parsed = $params[1]; } else { $language = $params[0]; $namespace = $params[1]; $topic_parsed = $params[2]; } $englishEntries = $language != 'en' ? $this->loadCache($namespace, $topic_parsed, 'en') : false; $entries = $this->loadCache($namespace, $topic_parsed, $language); if (!is_array($entries)) { if (is_string($entries) && !empty($entries)) { $entries = $this->modx->fromJSON($entries); } if (empty($entries)) { $entries = array(); } } if (is_array($englishEntries) && !empty($englishEntries)) { $entries = array_merge($englishEntries, $entries); } if (is_array($entries)) { $this->_loadedTopics[] = $topicStr; if (!array_key_exists($language, $this->_lexicon)) { $this->_lexicon[$language] = array(); } $this->_lexicon[$language] = is_array($this->_lexicon[$language]) ? array_merge($this->_lexicon[$language], $entries) : $entries; } } } }
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'))); }
/** * Convert JSON into an array * * @param string $data * @return array */ protected function fromJSON($data) { return $this->modx->fromJSON($data); }
/** * Create a PDF with the options set in the class * * @param modResource $resource * @param string|boolean $aliasPath * @return string */ public function createPDF($resource, $aliasPath) { // Create folders if (!@is_dir($this->getOption('pdfPath'))) { if (!@mkdir($this->getOption('pdfPath'), $this->modx->getOption('new_folder_permissions', null, 0775))) { $this->modx->log(modX::LOG_LEVEL_ERROR, 'Could not create the pdf output path: ' . $this->getOption('pdfPath'), '', 'PDFresource'); return; } } if ($aliasPath && !@is_dir($this->getOption('pdfPath') . $aliasPath)) { if (!@mkdir($this->getOption('pdfPath') . $aliasPath, $this->modx->getOption('new_folder_permissions', null, 0775))) { $this->modx->log(modX::LOG_LEVEL_ERROR, 'Could not create the pdf alias path: ' . $this->getOption('pdfPath') . $aliasPath, '', 'PDFresource'); return; } } // Get options $id = $resource->get('id'); $pdfTpl = $this->getOption('pdfTpl', null, 'tplPDF'); $cssTpl = $this->getOption('cssTpl', null, 'tplCSS'); $optionsTV = $this->getOption('pdfTvOptions', null, 'pdf_options'); $processTVs = $this->getOption('processTVs', null, false); $tvPrefix = $this->getOption('tvPrefix', null, 'tv.'); $placeholder = $resource->toArray(); // Prepare template variables and resource based options $pdfOptions = null; $tvs = $this->modx->getCollection('modTemplateVar'); foreach ($tvs as $tv) { /** @var modTemplateVar $tv */ $placeholder[$tvPrefix . $tv->get('name')] = $processTVs ? $tv->renderOutput($id) : $tv->getValue($id); if ($tv->get('name') == $optionsTV && $tv->getValue($id) != '') { $pdfOptions = $this->modx->fromJSON($tv->getValue($id)); if ($pdfOptions) { $pdfTpl = $this->modx->getOption('pdfTpl', $pdfOptions, $pdfTpl); $cssTpl = $this->modx->getOption('cssTpl', $pdfOptions, $cssTpl); } } } // Parse template chunks $placeholder['tplPath'] = $this->modx->getOption('assets_path'); $html = $this->getChunk($pdfTpl, $placeholder); $this->modx->getParser()->processElementTags('', $html, false, false, '[[', ']]', array(), $this->modx->getOption('max_iterations')); $this->modx->getParser()->processElementTags('', $html, true, true, '[[', ']]', array(), $this->modx->getOption('max_iterations')); $css = $this->getChunk($cssTpl, $placeholder); unset($placeholder); // Generate PDF file $this->initPDF(array('mode' => $this->getOption('mode', $pdfOptions, 'utf-8'), 'format' => $this->getOption('format', $pdfOptions, 'A4'), 'defaultFontSize' => intval($this->getOption('defaultFontSize', $pdfOptions, 8)), 'defaultFont' => $this->getOption('defaultFont', $pdfOptions, ''), 'mgl' => intval($this->getOption('mgl', $pdfOptions, 10)), 'mgr' => intval($this->getOption('mgr', $pdfOptions, 10)), 'mgt' => intval($this->getOption('mgt', $pdfOptions, 7)), 'mgb' => intval($this->getOption('mgb', $pdfOptions, 7)), 'mgh' => intval($this->getOption('mgh', $pdfOptions, 10)), 'mgf' => intval($this->getOption('mgf', $pdfOptions, 10)), 'orientation' => $this->getOption('orientation', $pdfOptions, 'P'))); $this->pdf->SetTitle($resource->get('pagetitle')); $this->pdf->SetAuthor($this->getOption('author', $pdfOptions, $this->modx->getOption('site_name'))); $this->pdf->SetCreator($this->getOption('creator', $pdfOptions, $this->modx->getOption('site_url') . ' powered by PDFresource/mPDF')); // Password protection $userPassword = $this->getOption('userPassword', $pdfOptions, ''); $ownerPassword = $this->getOption('ownerPassword', $pdfOptions, ''); $permissions = $this->modx->fromJSON($this->getOption('permissions', $pdfOptions, '')); if ($userPassword || $ownerPassword) { // Set default permissions if needed $permissions = $permissions ? $permissions : array(); // Random owner password if needed $ownerPassword = $ownerPassword ? $ownerPassword : null; $this->pdf->SetProtection($permissions, $userPassword, $ownerPassword, 128); } // Call additional mPDF methods $mpdfMethods = $this->modx->fromJSON($this->getOption('mPDFMethods', $pdfOptions, '')); $mpdfMethods = is_array($mpdfMethods) ? $mpdfMethods : array(); foreach ($mpdfMethods as $methodName) { $value = $this->getOption($methodName, $pdfOptions, ''); $value = is_array($value) ? $value : $this->modx->fromJSON($value); if ($value && method_exists($this->pdf, $methodName)) { call_user_func_array(array($this->pdf, $methodName), $value); } } $this->pdf->WriteHTML($css, 1); $this->pdf->WriteHTML($html, 2); if ($aliasPath) { return $this->pdf->Output($this->getOption('pdfPath') . $aliasPath . $resource->get('alias') . '.pdf', 'F'); } else { return $this->pdf->Output('', 'S'); } }
/** * Check a MODX processor response and return results * * @param string $result The response * @return array */ public function getResults(&$result) { $response = ltrim(rtrim($result->response, ')'), '('); $response = $this->modx->fromJSON($response); return !empty($response['results']) ? $response['results'] : array(); }
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; }