PHP Method modX::log Code Examples

PHP modX::log - 30 examples found. These are the top rated real world PHP examples of method modX::log extracted from open source projects. You can rate examples to help us improve the quality of examples
Example #1
0
 /**
  * @param modX $modx
  * @param array $config
  */
 public function __construct(modX &$modx, $config = array())
 {
     $this->modx =& $modx;
     $config = array_merge(array('firstClass' => 'first', 'lastClass' => 'last', 'hereClass' => 'active', 'parentClass' => '', 'rowClass' => '', 'outerClass' => '', 'innerClass' => '', 'levelClass' => '', 'selfClass' => '', 'webLinkClass' => '', 'limit' => 0, 'hereId' => 0), $config, array('return' => 'data'));
     if (empty($config['tplInner']) && !empty($config['tplOuter'])) {
         $config['tplInner'] = $config['tplOuter'];
     }
     if (empty($config['hereId']) && !empty($modx->resource)) {
         $config['hereId'] = $modx->resource->id;
     }
     $fqn = $modx->getOption('pdoFetch.class', null, 'pdotools.pdofetch', true);
     if ($pdoClass = $modx->loadClass($fqn, '', false, true)) {
         $this->pdoTools = new $pdoClass($modx, $config);
     } elseif ($pdoClass = $modx->loadClass($fqn, MODX_CORE_PATH . 'components/pdotools/model/', false, true)) {
         $this->pdoTools = new $pdoClass($modx, $config);
     } else {
         $this->modx->log(modX::LOG_LEVEL_ERROR, 'Could not load pdoFetch from "MODX_CORE_PATH/components/pdotools/model/".');
         return false;
     }
     if ($config['hereId'] && ($currentResource = $this->pdoTools->getObject('modResource', $config['hereId']))) {
         $tmp = $modx->getParentIds($currentResource['id'], 100, array('context' => $currentResource['context_key']));
         $tmp[] = $config['hereId'];
         $this->parentTree = array_flip($tmp);
     }
     $modx->lexicon->load('pdotools:pdomenu');
     return true;
 }
 /**
  * @param modX $modx
  * @param array $config
  */
 function __construct(modX &$modx, array $config = array())
 {
     $this->modx =& $modx;
     $corePath = $this->modx->getOption('msprofile_core_path', $config, $this->modx->getOption('core_path') . 'components/msprofile/');
     $assetsUrl = $this->modx->getOption('msprofile_assets_url', $config, $this->modx->getOption('assets_url') . 'components/msprofile/');
     $connectorUrl = $assetsUrl . 'connector.php';
     $this->config = array_merge(array('assetsUrl' => $assetsUrl, 'cssUrl' => $assetsUrl . 'css/', 'jsUrl' => $assetsUrl . 'js/', 'imagesUrl' => $assetsUrl . 'images/', 'connectorUrl' => $connectorUrl, 'corePath' => $corePath, 'modelPath' => $corePath . 'model/', 'chunksPath' => $corePath . 'elements/chunks/', 'templatesPath' => $corePath . 'elements/templates/', 'chunkSuffix' => '.chunk.tpl', 'snippetsPath' => $corePath . 'elements/snippets/', 'processorsPath' => $corePath . 'processors/'), $config);
     $this->modx->addPackage('msprofile', $this->config['modelPath']);
     $this->modx->lexicon->load('msprofile:default');
     if ($this->ms2 = $modx->getService('miniShop2')) {
         $this->ms2->initialize($this->modx->context->key);
     } else {
         $this->modx->log(modX::LOG_LEVEL_ERROR, 'msProfile requires installed miniShop2.');
     }
 }
 /**
  * @param modX $modx
  * @param array $config
  */
 public function __construct(modX &$modx, $config = array())
 {
     $this->modx =& $modx;
     $fqn = $modx->getOption('pdoTools.class', null, 'pdotools.pdotools', true);
     if ($pdoClass = $modx->loadClass($fqn, '', false, true)) {
         $this->pdoTools = new $pdoClass($modx, $config);
     } elseif ($pdoClass = $modx->loadClass($fqn, MODX_CORE_PATH . 'components/pdotools/model/', false, true)) {
         $this->pdoTools = new $pdoClass($modx, $config);
     } else {
         $this->modx->log(modX::LOG_LEVEL_ERROR, 'Could not load pdoTools from "MODX_CORE_PATH/components/pdotools/model/".');
         return false;
     }
     $modx->lexicon->load('pdotools:pdopage');
     return true;
 }
Example #4
0
 public function put($artifact, $attributes = array())
 {
     $added = false;
     if (!empty($artifact)) {
         $vehiclePackage = isset($attributes['vehicle_package']) ? $attributes['vehicle_package'] : 'transport';
         $vehiclePackagePath = isset($attributes['vehicle_package_path']) ? $attributes['vehicle_package_path'] : '';
         $vehicleClass = isset($attributes['vehicle_class']) ? $attributes['vehicle_class'] : '';
         $vehicleParentClass = isset($attributes['vehicle_parent_class']) ? $attributes['vehicle_parent_class'] : '';
         if (!empty($vehicleParentClass)) {
             $this->xpdo->loadClass('transport.' . $vehicleParentClass, '', true, true);
         }
         if (empty($vehicleClass)) {
             $vehicleClass = $options['vehicle_class'] = 'xPDOObjectVehicle';
         }
         if (!empty($vehiclePackage)) {
             $vehicleClass = "{$vehiclePackage}.{$vehicleClass}";
             $className = $this->xpdo->loadClass($vehicleClass, $vehiclePackagePath, true, true);
         } else {
             $className = $vehicleClass;
         }
         if ($className) {
             /** @var \xPDOVehicle $vehicle */
             $vehicle = new $className();
             $vehicle->put($this, $artifact, $attributes);
             if ($added = $vehicle->store($this)) {
                 $this->registerVehicle($vehicle);
             }
         } else {
             $this->xpdo->log(\xPDO::LOG_LEVEL_ERROR, "The specified xPDOVehicle class ({$vehiclePackage}.{$vehicleClass}) could not be loaded.");
         }
     }
     return $added;
 }
Example #5
0
 /**
  * Validates a field based on a custom rule, if specified
  *
  * @access public
  * @param string $key The key of the field
  * @param mixed $value The value of the field
  * @param string $type Optional. The type of the validator to apply. Can
  * either be a method name of rsvpmeValidator or a Snippet name.
  * @return boolean True if validation was successful. If not, will store
  * error messages to $this->errors.
  */
 public function validate($key, $value, $type = '')
 {
     $validated = false;
     $hasParams = $this->config['use_multibyte'] ? mb_strpos($type, '=', 0, $this->config['encoding']) : strpos($type, '=');
     $param = null;
     if ($hasParams !== false) {
         $len = $this->config['use_multibyte'] ? mb_strlen($type, $this->config['encoding']) : strlen($type);
         $s = $this->config['use_multibyte'] ? mb_substr($type, $hasParams + 1, $len, $this->config['encoding']) : substr($type, $hasParams + 1, $len);
         $param = str_replace('`', '', $s);
         $type = $this->config['use_multibyte'] ? mb_substr($type, 0, $hasParams, $this->config['encoding']) : substr($type, 0, $hasParams);
     }
     $invNames = array('validate', 'validateFields', '_addError', '__construct');
     if (method_exists($this, $type) && !in_array($type, $invNames)) {
         /* built-in validator */
         $validated = $this->{$type}($key, $value, $param);
     } elseif ($snippet = $this->modx->getObject('modSnippet', array('name' => $type))) {
         /* custom snippet validator */
         $props = array_merge($this->rsvpme->config, array('key' => $key, 'value' => $value, 'param' => $param, 'type' => $type, 'validator' => &$this, 'errors' => &$this->errors));
         $validated = $snippet->process($props);
     } else {
         /* no validator found */
         $this->modx->log(modX::LOG_LEVEL_ERROR, '[RSVPMe] Could not find validator "' . $type . '" for field "' . $key . '".');
         $validated = true;
     }
     if (is_array($validated) && !empty($validated)) {
         foreach ($validated as $key => $errMsg) {
             $this->_addError($key, $errMsg);
         }
         $validated = false;
     } elseif ($validated !== '1' && $validated !== 1 && $validated !== true) {
         $this->_addError($key, $validated);
         $validated = false;
     }
     return $validated;
 }
 /**
  * If for some reason the server does not have allow_url_fopen or cURL
  * enabled, use this function to get the file via fsockopen.
  *
  * @access protected
  * @param string $url The source URL to retrieve
  * @return string The response from the server
  */
 protected function _getByFsockopen($url)
 {
     $purl = parse_url($url);
     $host = $purl['host'];
     $path = !empty($purl['path']) ? $purl['path'] : '/';
     if (!empty($purl['query'])) {
         $path .= '?' . $purl['query'];
     }
     $port = !empty($purl['port']) ? $purl['port'] : '80';
     $timeout = 10;
     $response = '';
     $fp = @fsockopen($host, $port, $errno, $errstr, $timeout);
     if (!$fp) {
         $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, 'Could not retrieve from ' . $url);
     } else {
         fwrite($fp, "GET {$path} HTTP/1.0\r\n" . "Host: {$host}\r\n" . "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.3) Gecko/20060426 Firefox/1.5.0.3\r\n" . "Accept: */*\r\n" . "Accept-Language: en-us,en;q=0.5\r\n" . "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n" . "Keep-Alive: 300\r\n" . "Connection: keep-alive\r\n" . "Referer: http://{$host}\r\n\r\n");
         while ($line = fread($fp, 4096)) {
             $response .= $line;
         }
         fclose($fp);
         $pos = strpos($response, "\r\n\r\n");
         $response = substr($response, $pos + 4);
     }
     return $response;
 }
 /**
  * Get the correct controller path for the class
  *
  * @return string
  */
 protected function getController()
 {
     $expectedFile = trim($this->request->action, '/');
     $basePath = $this->getOption('basePath');
     $controllerClassPrefix = $this->getOption('controllerClassPrefix', 'modController');
     $controllerClassSeparator = $this->getOption('controllerClassSeparator', '_');
     $controllerClassFilePostfix = $this->getOption('controllerClassFilePostfix', '.php');
     /* handle [object]/[id] pathing */
     $expectedArray = explode('/', $expectedFile);
     if (empty($expectedArray)) {
         $expectedArray = array(rtrim($expectedFile, '/') . '/');
     }
     $id = array_pop($expectedArray);
     if (!file_exists($basePath . $expectedFile . $controllerClassFilePostfix) && intval($id) > 0) {
         $expectedFile = implode('/', $expectedArray);
         if (empty($expectedFile)) {
             $expectedFile = $id;
             $id = null;
         }
         $this->requestPrimaryKey = $id;
     }
     foreach ($this->iterateDirectories($basePath . '/*' . $controllerClassFilePostfix, GLOB_NOSORT) as $controller) {
         $controller = $basePath != '/' ? str_replace($basePath, '', $controller) : $controller;
         $controller = trim($controller, '/');
         $controllerFile = str_replace(array($controllerClassFilePostfix), array(''), $controller);
         $controllerClass = str_replace(array('/', $controllerClassFilePostfix), array($controllerClassSeparator, ''), $controller);
         if (strnatcasecmp($expectedFile, $controllerFile) == 0) {
             require_once $basePath . $controller;
             return $controllerClassPrefix . $controllerClassSeparator . $controllerClass;
         }
     }
     $this->modx->log(modX::LOG_LEVEL_INFO, 'Could not find expected controller: ' . $expectedFile);
     return null;
 }
 /**
  * Check if the search string starts with one of the allowed aliases and
  * prepare the url param string if successful.
  *
  * @access public
  * @param string $search A string to search the allowed aliases in
  * @return boolean
  */
 public function searchAliases($search)
 {
     // strip cultureKey i.e. in Babel installations.
     $search = preg_replace('#^' . $this->modx->cultureKey . '/(.*)#i', '$1', $search);
     $valid = false;
     // loop through the allowed aliases
     if (is_array($this->requests) && count($this->requests)) {
         foreach ($this->requests as $request) {
             // check if searched string starts with the alias
             if (0 === strpos($search, $request['alias'])) {
                 // strip alias from seached string
                 $this->urlParams = substr($search, strlen($request['alias']));
                 // set the found resource id
                 $this->resourceId = $request['resourceId'];
                 // set the found alias
                 $this->alias = $request['alias'];
                 // and set the found regEx
                 $this->regEx = $request['regEx'];
                 $valid = true;
                 break;
             }
         }
     } else {
         if ($this->getOption('debug')) {
             $this->modx->log(modX::LOG_LEVEL_INFO, 'CustomRequest Plugin: No valid configs found.');
         }
     }
     return $valid;
 }
Example #9
0
 /**
  * Prepare a JSON encoded object and return a valid JSON encoded Image+ object
  *
  * @param $json JSON value to prepare
  * @param array $opts
  * @param modTemplateVar $tv
  * @return string
  */
 public function prepareTvValue($json, $opts = array(), modTemplateVar $tv)
 {
     // Prepare value
     $decoded = json_decode($json);
     if (!$decoded) {
         // The variable does not contain an Image+ image object
         if ($json != '') {
             // Get Media Source
             /** @var modMediaSource $source */
             if ($tv) {
                 $source = $tv->getSource($this->modx->resource ? $this->modx->resource->get('context_key') : 'mgr');
             } else {
                 $source = $this->modx->getObject('modMediaSource', $this->modx->getOption('default_media_source'));
             }
             if (!($source && $source->getWorkingContext())) {
                 $this->modx->log(xPDO::LOG_LEVEL_ERROR, 'Invalid Media Source', '', 'Image+');
                 return '';
             }
             $source->setRequestProperties($_REQUEST);
             $source->initialize();
             // The variable contains a value and has to be converted to an Image+ image object
             $imgPath = $source->getBasePath() . $json;
             if (file_exists($imgPath)) {
                 $size = getimagesize($imgPath);
             } else {
                 $this->modx->log(xPDO::LOG_LEVEL_INFO, 'The template variabe value does not contain an existing image', '', 'Image+');
             }
             $json = json_encode(array('altTag' => '', 'crop' => array('height' => $size ? $size[1] : 0, 'width' => $size ? $size[0] : 0, 'x' => 0, 'y' => 0), 'sourceImg' => array('height' => $size ? $size[1] : 0, 'width' => $size ? $size[0] : 0, 'source' => $source->get('id'), 'src' => $json), 'targetHeight' => (int) $opts['targetHeight'], 'targetWidth' => (int) $opts['targetWidth']));
         }
     }
     return $json;
 }
Example #10
0
 /**
  * Return a scaled, cached version of the source image for front-end use
  *
  * @param string $json
  * @param array $opts
  * @param modTemplateVar $tv
  * @internal param array $params
  * @return string
  */
 public function getImageURL($json, $opts = array(), modTemplateVar $tv)
 {
     // Check system settings for crop engine override
     $engineClass = $this->modx->getOption('imageplus.crop_engine_class', null, false);
     // Do some basic intelligent sniffing
     if (!$engineClass) {
         if (CropEngines\PhpThumbsUp::engineRequirementsMet($this->modx)) {
             $engineClass = '\\ImagePlus\\CropEngines\\PhpThumbsUp';
         } else {
             if (CropEngines\PhpThumbOf::engineRequirementsMet($this->modx)) {
                 $engineClass = '\\ImagePlus\\CropEngines\\PhpThumbOf';
             }
         }
     }
     /**
      * @var ImagePlus\CropEngines\AbstractCropEngine $cropEngine
      */
     $cropEngine = new $engineClass($this->modx);
     // Check crop engine is usable
     if (!$cropEngine->engineRequirementsMet($this->modx)) {
         $this->modx->log(xPDO::LOG_LEVEL_ERROR, "Requirements not met for crop engine [{$engineClass}]", '', 'Image+');
         return 'Image+ error - requirements not met for crop engine';
     }
     return $cropEngine->getImageUrl($json, $opts, $tv);
 }
Example #11
0
 /**
  * Validates a field based on a custom rule, if specified
  *
  * @access public
  * @param string $key The key of the field
  * @param mixed $value The value of the field
  * @param string $type Optional. The type of the validator to apply. Can
  * either be a method name of fiValidator or a Snippet name.
  * @return boolean True if validation was successful. If not, will store
  * error messages to $this->errors.
  */
 public function validate($key, $value, $type = '')
 {
     /** @var boolean|array $validated */
     $validated = false;
     /** @var mixed $value Trim spaces from the value before validating **/
     if (!empty($this->config['trim_values_before_validation'])) {
         $value = trim($value);
     }
     /** @var boolean $hasParams */
     $hasParams = $this->config['use_multibyte'] ? mb_strpos($type, '=', 0, $this->config['encoding']) : strpos($type, '=');
     /** @var string|null $param The parameter value, if one is set */
     $param = null;
     if ($hasParams !== false) {
         $len = $this->config['use_multibyte'] ? mb_strlen($type, $this->config['encoding']) : strlen($type);
         $s = $this->config['use_multibyte'] ? mb_substr($type, $hasParams + 1, $len, $this->config['encoding']) : substr($type, $hasParams + 1, $len);
         $param = str_replace(array('`', '^'), '', $s);
         $type = $this->config['use_multibyte'] ? mb_substr($type, 0, $hasParams, $this->config['encoding']) : substr($type, 0, $hasParams);
     }
     /** @var array $invNames An array of invalid hook names to skip */
     $invNames = array('validate', 'validateFields', 'addError', '__construct');
     $customValidators = !empty($this->config['customValidators']) ? $this->config['customValidators'] : '';
     $customValidators = explode(',', $customValidators);
     if (method_exists($this, $type) && !in_array($type, $invNames)) {
         /* built-in validator */
         $validated = $this->{$type}($key, $value, $param);
         /* only allow specified validators to prevent brute force execution of unwanted snippets */
     } else {
         if (in_array($type, $customValidators)) {
             /* attempt to grab custom validator */
             /** @var modSnippet|null $snippet */
             $snippet = $this->modx->getObject('modSnippet', array('name' => $type));
             if ($snippet) {
                 /* custom snippet validator */
                 $props = array_merge($this->formit->config, array('key' => $key, 'value' => $value, 'param' => $param, 'type' => $type, 'validator' => &$this, 'errors' => &$this->errors));
                 $validated = $snippet->process($props);
             } else {
                 /* no validator found */
                 $this->modx->log(modX::LOG_LEVEL_ERROR, '[FormIt] Could not find validator "' . $type . '" for field "' . $key . '".');
                 $validated = true;
             }
         } else {
             $this->modx->log(modX::LOG_LEVEL_INFO, '[FormIt] Validator "' . $type . '" for field "' . $key . '" was not specified in the customValidators property.');
             $validated = true;
         }
     }
     /** handle return value errors */
     if (!empty($validated)) {
         if (is_array($validated)) {
             foreach ($validated as $key => $errMsg) {
                 $this->addError($key, $errMsg);
             }
             $validated = false;
         } elseif ($validated !== '1' && $validated !== 1 && $validated !== true) {
             $this->addError($key, $validated);
             $validated = false;
         }
     }
     return $validated;
 }
 /**
  * Loads the error handling class for the request.
  *
  * @param string $class The class to use as the error handler.
  */
 public function loadErrorHandler($class = 'modError')
 {
     if ($className = $this->modx->loadClass('error.' . $class, '', false, true)) {
         $this->modx->error = new $className($this->modx);
     } else {
         $this->modx->log(modX::LOG_LEVEL_FATAL, 'Error handling class could not be loaded: ' . $class);
     }
 }
Example #13
0
 /**
  * Load the dictionary storage mechanism
  * @return null|fiDictionary
  */
 public function loadDictionary()
 {
     if ($this->modx->loadClass('formit.fiDictionary', $this->formit->config['modelPath'], true, true)) {
         $this->dictionary = new fiDictionary($this->formit, $this->config);
     } else {
         $this->modx->log(modX::LOG_LEVEL_ERROR, '[FormIt] Could not load Dictionary class.');
     }
     return $this->dictionary;
 }
Example #14
0
    /**
     * A method to load some overrides, when needed, to tweak some RTEs, add some methods...
     *
     * @return void
     */
    public function loadOverrides()
    {
        if (!$this->override) {
            return;
        }
        $override = dirname(__DIR__) . "/assets/{$this->override}";
        if (!file_exists($override)) {
            $this->modx->log(\modX::LOG_LEVEL_INFO, __METHOD__ . ' override not found : ' . $override);
            return;
        }
        $data = file_get_contents($override);
        $this->modx->controller->addHtml(<<<HTML
<script>
{$data}
</script>
HTML
);
    }
 /**
  * Process the response and format in the proper response format.
  *
  * @param bool $success Whether or not this response is successful.
  * @param string $message Optional. The response message.
  * @param array|xPDOObject $object Optional. The response return object.
  * @param int $status Optional. The response code.
  */
 protected function process($success = true, $message = '', $object = array(), $status = 200)
 {
     $response = array($this->getOption('responseMessageKey', 'message') => $message, $this->getOption('responseObjectKey', 'object') => is_object($object) ? $object->toArray() : $object, $this->getOption('responseSuccessKey', 'success') => $success);
     if (empty($success) && !empty($this->errors)) {
         $response[$this->getOption('responseErrorsKey', 'errors')] = $this->errors;
     }
     $this->modx->log(modX::LOG_LEVEL_DEBUG, '[REST] Sending REST response: ' . print_r($response, true));
     $this->response = $response;
     $this->responseStatus = empty($status) ? empty($success) ? $this->getOption('defaultFailureStatusCode', 200) : $this->getOption('defaultSuccessStatusCode', 200) : $status;
 }
Example #16
0
 /**
  * Loads the Hooks class.
  *
  * @access public
  * @param string $type The type of hook to load.
  * @param array $config An array of configuration parameters for the
  * hooks class
  * @return siHooks An instance of the fiHooks class.
  */
 public function loadHooks($type = 'post', $config = array())
 {
     if (!$this->modx->loadClass('simplesearch.siHooks', $this->config['modelPath'], true, true)) {
         $this->modx->log(modX::LOG_LEVEL_ERROR, '[SimpleSearch] Could not load Hooks class.');
         return false;
     }
     $type = $type . 'Hooks';
     $this->{$type} = new siHooks($this, $config);
     return $this->{$type};
 }
 /**
  * Get a lexicon string by its index.
  *
  * @access public
  * @param string $key The key of the lexicon string.
  * @param array $params An assocative array of placeholder
  * keys and values to parse
  * @return string The text of the lexicon key, blank if not found.
  */
 public function process($key, array $params = array())
 {
     /* make sure key exists */
     if (!is_string($key) || !isset($this->_lexicon[$key])) {
         $this->modx->log(xPDO::LOG_LEVEL_DEBUG, 'Language string not found: "' . $key . '"');
         return $key;
     }
     /* if params are passed, allow for parsing of [[+key]] values to strings */
     return empty($params) ? $this->_lexicon[$key] : $this->_parse($this->_lexicon[$key], $params);
 }
 /**
  * Loads the Hooks class.
  *
  * @access public
  * @param $type string The type of hook to load.
  * @param $config array An array of configuration parameters for the
  * hooks class
  * @return fiHooks An instance of the fiHooks class.
  */
 public function loadHooks($type = 'post', $config = array())
 {
     if (!$this->modx->loadClass('formit.fiHooks', $this->config['modelPath'], true, true)) {
         $this->modx->log(modX::LOG_LEVEL_ERROR, '[FormIt] Could not load Hooks class.');
         return false;
     }
     $typeVar = $type . 'Hooks';
     $this->{$typeVar} = new fiHooks($this, $config, $type);
     return $this->{$typeVar};
 }
 /**
  * Sends a REST request to the provider
  *
  * @param string $path The path of the request
  * @param string $method The method of the request (GET/POST)
  * @param array $params An array of parameters to send to the REST request
  * @return modRestResponse|bool The response from the REST request, or false
  */
 public function request($path, $method = 'GET', $params = array())
 {
     $response = false;
     $service = $this->getClient();
     if ($service) {
         $response = $service->request($this->get('service_url'), $path, $method, $this->args($params));
     } else {
         $this->xpdo->log(modX::LOG_LEVEL_ERROR, $this->xpdo->lexicon('provider_err_no_client'), '', __METHOD__, __FILE__, __LINE__);
     }
     return $response;
 }
Example #20
0
 /**
  * Load a hook.
  *
  * @access public
  * @param string $name The name of the hook to load
  * @param array $scriptProperties A configuration array of variables to run
  * the hook with
  * @return mixed The return value of the hook
  */
 public function load($name = '', array $scriptProperties = array())
 {
     if (empty($name)) {
         return false;
     }
     $success = false;
     $hookFile = $this->discuss->config['hooksPath'] . strtolower($name) . '.php';
     if (file_exists($hookFile)) {
         $discuss =& $this->discuss;
         $modx =& $this->modx;
         $options =& $this->discuss->controller->options;
         if (isset($scriptProperties['controller'])) {
             $controller =& $scriptProperties['controller'];
         }
         $success = (include $hookFile);
     } else {
         $this->modx->log(modX::LOG_LEVEL_ERROR, '[Discuss] Hook not found: ' . $hookFile);
     }
     return $success;
 }
Example #21
0
 /**
  * Load the modLexicon service
  *
  * @return boolean
  */
 protected function _loadLexicon()
 {
     if (!$this->xpdo->lexicon) {
         $this->xpdo->lexicon = $this->xpdo->getService('lexicon', 'modLexicon');
         if (empty($this->xpdo->lexicon)) {
             $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, '[Quip] Could not load MODx lexicon.');
             return false;
         }
     }
     return true;
 }
Example #22
0
 /**
  * @param string $message
  */
 public function debug($message)
 {
     if ($this->config['debug']) {
         if ($message instanceof xPDOObject) {
             $message = $message->toArray();
         }
         if (is_array($message)) {
             $message = print_r($message, 1);
         }
         $this->modx->log(modX::LOG_LEVEL_ERROR, $message);
     }
 }
 /**
  * Sends a redirect to the specified URL using the specified method.
  *
  * Valid $type values include:
  *    REDIRECT_REFRESH  Uses the header refresh method
  *    REDIRECT_META  Sends a a META HTTP-EQUIV="Refresh" tag to the output
  *    REDIRECT_HEADER  Uses the header location method
  *
  * REDIRECT_HEADER is the default.
  *
  * @param string $url The URL to redirect the client browser to.
  * @param array|boolean $options An array of options for the redirect OR
  * indicates if redirect attempts should be counted and limited to 3 (latter is deprecated
  * usage; use count_attempts in options array).
  * @param string $type The type of redirection to attempt (deprecated, use type in
  * options array).
  * @param string $responseCode The type of HTTP response code HEADER to send for the
  * redirect (deprecated, use responseCode in options array)
  * @return void|boolean
  */
 public function sendRedirect($url, $options = false, $type = '', $responseCode = '')
 {
     if (!is_array($options)) {
         $options = array('count_attempts' => (bool) $options);
     }
     $options = array_merge(array('count_attempts' => false, 'type' => $type, 'responseCode' => $responseCode), $options);
     $url = str_replace('&amp;', '&', $url);
     if (empty($url)) {
         $this->modx->log(modX::LOG_LEVEL_ERROR, "Attempted to redirect to an empty URL.");
         return false;
     }
     if (!$this->modx->getRequest()) {
         $this->modx->log(modX::LOG_LEVEL_FATAL, "Could not load request class.");
     }
     if (isset($options['preserve_request']) && !empty($options['preserve_request'])) {
         $this->modx->request->preserveRequest('referrer.redirected');
     }
     if ($options['count_attempts']) {
         /* append the redirect count string to the url */
         $currentNumberOfRedirects = isset($_REQUEST['err']) ? $_REQUEST['err'] : 0;
         if ($currentNumberOfRedirects > 3) {
             $this->modx->log(modX::LOG_LEVEL_FATAL, 'Redirection attempt failed - please ensure the resource you\'re trying to redirect to exists. <p>Redirection URL: <i>' . $url . '</i></p>');
         } else {
             $currentNumberOfRedirects += 1;
             if (strpos($url, "?") > 0) {
                 $url .= "&err={$currentNumberOfRedirects}";
             } else {
                 $url .= "?err={$currentNumberOfRedirects}";
             }
         }
     }
     switch ($options['type']) {
         case 'REDIRECT_REFRESH':
             $header = 'Refresh: 0;URL=' . $url;
             break;
         case 'REDIRECT_META':
             $header = '<META HTTP-EQUIV="Refresh" CONTENT="0; URL=' . $url . '" />';
             echo $header;
             exit;
         default:
             if (strpos($url, '://') === false && !(substr($url, 0, 1) === '/' || substr($url, 0, 2) === './' || substr($url, 0, 3) === '../')) {
                 $url = $this->modx->getOption('site_url', null, '/') . $url;
             }
             $header = 'Location: ' . $url;
             break;
     }
     @session_write_close();
     if (!empty($options['responseCode']) && strpos($options['responseCode'], '30') !== false) {
         header($options['responseCode']);
     }
     header($header);
     exit;
 }
 /**
  * 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);
     }
 }
Example #25
0
 public static function getInstance(modX &$modx, $className, $properties = array())
 {
     $modx->log(1, print_r($properties, 1));
     switch ($properties['action']) {
         case 'pay':
             $className = 'modWebOrdersActionsProcessProcessor_ActionPay';
             break;
         default:
     }
     /** @var modProcessor $processor */
     $processor = new $className($modx, $properties);
     return $processor;
 }
Example #26
0
 /**
  * Remove a subscription to this thread for the User
  *
  * @param int $userId ID of disUser
  * @return bool True if successful
  */
 public function removeSubscription($userId)
 {
     $success = false;
     $notify = $this->xpdo->getObject('disUserNotification', array('user' => $userId, 'thread' => $this->get('id')), false);
     if ($notify) {
         if (!$notify->remove()) {
             $this->xpdo->log(modX::LOG_LEVEL_ERROR, '[Discuss] Could not remove notification: ' . print_r($notify->toArray(), true));
         } else {
             $success = true;
         }
     }
     return $success;
 }
Example #27
0
 public function dbSaveAndEmail()
 {
     $this->dbSave();
     if (!$this->hook->hasErrors()) {
         // exclude fields from email send
         $this->excludeFields();
         $newData = array('formName' => $this->config->senderName);
         // Save Fields
         foreach ($this->config->data as $field => $value) {
             if (is_array($value)) {
                 switch ($this->formArray[$field]['type']) {
                     case 'select':
                     case 'checkbox':
                     case 'radio':
                         $value = implode(', ', $value);
                         break;
                 }
             }
             $newData['message'] .= $this->formArray[$field]['label'] . ' ' . $value . '<br>';
             $newData[$this->formArray[$field]['id']] = $value;
         }
         $message = $this->fmz->getChunk($this->config->emailTpl, $newData);
         $this->modx->getService('mail', 'mail.modPHPMailer');
         if ($this->config->mandrillApiUsername && $this->config->mandrillApiKey) {
             $this->modx->mail->mailer->Mailer = 'smtp';
             $this->modx->mail->mailer->SMTPAuth = true;
             $this->modx->mail->set(modMail::MAIL_SMTP_HOSTS, 'smtp.mandrillapp.com');
             $this->modx->mail->set(modMail::MAIL_SMTP_PORT, '587');
             $this->modx->mail->mailer->Username = $this->config->mandrillApiUsername;
             $this->modx->mail->set(modMail::MAIL_SMTP_PASS, $this->config->mandrillApiKey);
             $this->modx->mail->set(modMail::MAIL_SMTP_PREFIX, 'tls');
         }
         $this->modx->mail->set(modMail::MAIL_BODY, $message);
         $this->modx->mail->set(modMail::MAIL_FROM, $this->config->emailFrom);
         $this->modx->mail->set(modMail::MAIL_FROM_NAME, $this->config->senderName);
         $this->modx->mail->set(modMail::MAIL_SUBJECT, $this->config->subject);
         $tos = explode(',', $this->config->emailTo);
         foreach ($tos as $to) {
             $this->modx->mail->address('to', $to);
         }
         if ($this->config->replyTo) {
             $this->modx->mail->address('reply-to', $this->config->replyTo);
         }
         $this->modx->mail->setHTML(true);
         if (!$this->modx->mail->send()) {
             $this->modx->log(modX::LOG_LEVEL_ERROR, 'An error occurred while trying to email the Admin: ' . $this->modx->mail->mailer->ErrorInfo);
         }
         $this->modx->mail->reset();
     }
     return true;
 }
 /**
  * Add an element to the list
  *
  * @param integer $docId
  * @return bool|integer
  */
 private function add($docId)
 {
     $found = 0;
     $newElement = array();
     $newElement['rememberId'] = $docId;
     if (!$this->getOption('packagename')) {
         // no packagename -> resource
         $resource = $this->modx->getObject('modResource', array('id' => $docId));
         $tvs = array();
         $templateVars =& $resource->getMany('TemplateVars');
         foreach ($templateVars as $templateVar) {
             $tvs[$this->getOption('tvPrefix') . $templateVar->get('name')] = $templateVar->renderOutput($resource->get('id'));
         }
         $row = array_merge($resource->toArray(), $tvs);
     } else {
         $packagepath = $this->modx->getOption('core_path') . 'components/' . $this->getOption('packagename') . '/';
         $modelpath = $packagepath . 'model/';
         $this->modx->addPackage($this->getOption('packagename'), $modelpath);
         $resource = $this->modx->getObject($this->getOption('classname'), array($this->getOption('keyname') => $docId));
         if ($resource) {
             $joinvalues = array();
             $joinoption = $this->getOption('joins');
             if ($joinoption) {
                 foreach ($joinoption as $join) {
                     $values = $resource->getOne($join);
                     $joinvalues[$join] = $values->toArray();
                 }
             }
             $row = array_merge($joinvalues, $resource->toArray());
         } else {
             $this->modx->log(xPDO::LOG_LEVEL_ERROR, 'Could not retreive an object with key "' . $this->getOption('keyname') . '" and value "' . $docId . '"', '', 'RememberThis');
             return false;
         }
     }
     $newElement['identifier'] = $row[$this->getOption('keyname')];
     $newElement['itemtitle'] = $this->modx->getChunk($this->getOption('itemTitleTpl'), $row);
     foreach ($_SESSION['rememberThis'] as &$element) {
         if (!count(array_diff_assoc($element['element'], $newElement))) {
             $found = 1;
         }
     }
     if (!$found) {
         $_SESSION['rememberThis'][] = array('element' => $newElement);
         if ($this->getOption('useCookie')) {
             $this->setCookie();
         }
         return key($_SESSION['rememberThis']);
     } else {
         return false;
     }
 }
 /**
  * Check to see if the TV has access to a Template
  *
  * @param mixed $templatePk Either the ID, name or object of the Template
  * @return boolean Whether or not the TV has access to the specified Template
  */
 public function hasTemplate($templatePk)
 {
     if (!is_int($templatePk) && !is_object($templatePk)) {
         $template = $this->xpdo->getObject('modTemplate', array('templatename' => $templatePk));
         if (empty($template) || !is_object($template) || !$template instanceof modTemplate) {
             $this->xpdo->log(modX::LOG_LEVEL_ERROR, 'modTemplateVar::hasTemplate - No template: ' . $templatePk);
             return false;
         }
     } else {
         $template =& $templatePk;
     }
     $templateVarTemplate = $this->xpdo->getObject('modTemplateVarTemplate', array('tmplvarid' => $this->get('id'), 'templateid' => is_object($template) ? $template->get('id') : $template));
     return !empty($templateVarTemplate) && is_object($templateVarTemplate);
 }
Example #30
0
 /**
  * @return string
  */
 public function logCallTrace()
 {
     $e = new Exception();
     $trace = explode("\n", $e->getTraceAsString());
     $trace = array_reverse($trace);
     array_shift($trace);
     array_pop($trace);
     $length = count($trace);
     $result = array();
     for ($i = 0; $i < $length; $i++) {
         $result[] = str_replace(MODX_BASE_PATH, '/', $i + 1 . '.' . substr($trace[$i], strpos($trace[$i], ' ')));
     }
     $this->modx->log(modX::LOG_LEVEL_ERROR, "\n" . implode("\n", $result));
 }