Exemple #1
0
 /**
  * Save a template with the current params. Writes file to `Create::$path`.
  * Override default save to add timestamp in file name.
  *
  * @param array $params
  * @return string A result string on success of writing the file. If any errors occur along
  *         the way such as missing information boolean false is returned.
  */
 protected function _save(array $params = array())
 {
     $defaults = array('namespace' => null, 'class' => null);
     $params += $defaults;
     if (empty($params['class']) || empty($this->_library['path'])) {
         return false;
     }
     $contents = $this->_template();
     $result = String::insert($contents, $params);
     $namespace = str_replace($this->_library['prefix'], '\\', $params['namespace']);
     $date = date('YmdHis');
     $path = str_replace('\\', '/', "{$namespace}\\{$date}_{$params['class']}");
     $path = $this->_library['path'] . stristr($path, '/');
     $file = str_replace('//', '/', "{$path}.php");
     $directory = dirname($file);
     $relative = str_replace($this->_library['path'] . '/', "", $file);
     if (!is_dir($directory) && !mkdir($directory, 0755, true)) {
         return false;
     }
     if (file_exists($file)) {
         $prompt = "{$relative} already exists. Overwrite?";
         $choices = array('y', 'n');
         if ($this->in($prompt, compact('choices')) !== 'y') {
             return "{$params['class']} skipped.";
         }
     }
     if (file_put_contents($file, "<?php\n\n{$result}\n\n?>")) {
         return "{$params['class']} created in {$relative}.";
     }
     return false;
 }
Exemple #2
0
 /**
  * Generate hashed and salted token from `'prefix'` and `md5` hashed `$email` value
  * @param $email string User email that will be used as base for secret token
  * @param array $options Supported options:
  *        - `'prefix'` _string|int_ If not passed this method will generate random int from
  *          `100000` to `999999`. Hashed email will be prefixed with value of this option.
  *          Example: `'prefix_value' . md5($email)`
  *        - All other options are same as `lithium\util\String::hash()`
  * @return string Hashed prefixed email salted and hashed again
  * @see lithium\util\String::hash()
  */
 public static function generate($email, array $options = array())
 {
     $options += array('prefix' => null, 'salt' => LI3_UM_TokenSalt, 'type' => 'sha256');
     $prefix = $options['prefix'] ? $options['prefix'] : mt_rand(100000, 999999);
     unset($options['prefix']);
     return String::hash($prefix . md5($email), $options);
 }
 /**
  * Override the save method to handle view specific params.
  *
  * @param array $params
  * @return mixed
  */
 protected function _save(array $params = array())
 {
     $params['path'] = Inflector::underscore($this->request->action);
     $params['file'] = $this->request->args(0);
     $contents = $this->_template();
     $result = String::insert($contents, $params);
     if (!empty($this->_library['path'])) {
         $path = $this->_library['path'] . "/views/{$params['path']}/{$params['file']}";
         $file = str_replace('//', '/', "{$path}.php");
         $directory = dirname($file);
         if (!is_dir($directory)) {
             if (!mkdir($directory, 0755, true)) {
                 return false;
             }
         }
         $directory = str_replace($this->_library['path'] . '/', '', $directory);
         if (file_exists($file)) {
             $prompt = "{$file} already exists. Overwrite?";
             $choices = array('y', 'n');
             if ($this->in($prompt, compact('choices')) !== 'y') {
                 return "{$params['file']} skipped.";
             }
         }
         if (is_int(file_put_contents($file, $result))) {
             return "{$params['file']}.php created in {$directory}.";
         }
     }
     return false;
 }
Exemple #4
0
 /**
  * Obtain the session key.
  *
  * For this adapter, it is a UUID based on the SERVER_ADDR variable.
  *
  * @return string UUID.
  */
 public static function key()
 {
     $context = function ($value) use(&$config) {
         return isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : '127.0.0.1';
     };
     return String::uuid($context);
 }
Exemple #5
0
 public static function addModules($modules)
 {
     $modules = (array) $modules;
     $calledClass = get_called_class();
     $baseClassName = array_pop(explode('\\', $calledClass));
     if (!isset(self::$_modules[$calledClass])) {
         self::$_modules[$calledClass] = array();
     }
     foreach ($modules as $name => $config) {
         if (is_integer($name) and is_string($config)) {
             $name = $config;
             $config = array();
         }
         $current = isset(self::$_modules[$calledClass][$name]) ? self::$_modules[$calledClass][$name] : ($current = array());
         $defaults = array('class' => String::insert('\\app\\modules\\{:class}\\{:name}Module', array('class' => $baseClassName, 'name' => ucfirst($name))), 'partial' => String::insert('modules/{:class}/{:name}', array('class' => $baseClassName, 'name' => $name)));
         self::$_modules[$calledClass][$name] = $config + $defaults + $current;
         if (!class_exists(self::$_modules[$calledClass][$name]['class'])) {
             throw new \Exception('Module class ' . self::$_modules[$calledClass][$name]['class'] . ' not found.');
         }
         if (isset($config['filters'])) {
             foreach ($config['filters'] as $function => $filter) {
                 static::applyFilter($function, $filter);
             }
         }
     }
     return true;
 }
Exemple #6
0
 /**
  * Process incoming messages
  *
  * @param string $data
  * @return string
  */
 public function process($data)
 {
     $responses = $this->_responses;
     $model = $this->_classes['model'];
     $location = null;
     extract($data);
     $words = preg_split("/[\\s]/", $message, 2);
     if ($words[0] != '~weather') {
         return;
     }
     if (!isset($words[1])) {
         return String::insert($responses['missing'], compact('user'));
     }
     $location = $model::find('search', $words[1]);
     if (!$location || isset($location->title)) {
         return String::insert($responses['unknown'], compact('user') + array('location' => $words[1]));
     }
     if (isset($location->location)) {
         $location = $model::find('search', $location->location[0]->name);
         if (!$location || isset($location->title)) {
             return String::insert($responses['unknown'], compact('user') + array('location' => $words[1]));
         }
     }
     $station = $location->nearby_weather_stations->airport->station[0];
     $weather = $model::find('station', (string) $station->icao);
     if (!$weather || isset($weather->title)) {
         return String::insert($responses['unknown'], compact('user') + array('location', $words[1]));
     }
     return String::insert($responses['weather'], compact('user') + array('city' => (string) $station->city, 'state' => (string) $station->state, 'country' => (string) $station->country, 'icao' => (string) $station->icao, 'temperature' => (string) $weather->temperature_string, 'windchill' => (string) $weather->windchill_string, 'wind' => (string) $weather->wind_string));
 }
 /**
  * With lots of various rules we created 4 various rulesets for operators. If one
  * of the tokens or content is found we use the given regex on the joined array.
  *
  * @param  Testable $testable The testable object
  * @return void
  */
 public function apply($testable, array $config = array())
 {
     $tokens = $testable->tokens();
     foreach ($this->inspector as $inspector) {
         if (isset($inspector['tokens'])) {
             $byToken = $testable->findAll($inspector['tokens']);
         } else {
             $byToken = array();
         }
         if (isset($inspector['content'])) {
             $byContent = $testable->findAllContent($inspector['content']);
         } else {
             $byContent = array();
         }
         foreach (array_merge($byToken, $byContent) as $id) {
             $token = $tokens[$id];
             $isPHP = $testable->isPHP($token['line']);
             if ($isPHP && empty($token['isString'])) {
                 $pattern = String::insert($inspector['regex'], array('content' => preg_quote($token['content'], "/")));
                 $firstId = $id - $inspector['relativeTokens']['before'];
                 $firstId = $firstId < 0 ? 0 : $firstId;
                 $length = $inspector['relativeTokens']['length'];
                 $inspectTokens = array_slice($tokens, $firstId, $length);
                 $html = null;
                 foreach ($inspectTokens as $htmlToken) {
                     $html .= $htmlToken['content'];
                 }
                 if (preg_match($pattern, $html) === 0) {
                     $this->addViolation(array('message' => String::insert($inspector['message'], $token), 'line' => $token['line']));
                 }
             }
         }
     }
 }
Exemple #8
0
 /**
  * Process incoming messages.
  *
  * @param string $data
  * @return string
  */
 public function process($data)
 {
     $model = $this->_classes['model'];
     extract($data);
     if ($message[0] != '~') {
         return;
     }
     list($command, $recipient) = preg_split("/[\\s]/", $message, 2) + array(null, null);
     if (!($recipient = trim($recipient))) {
         return;
     }
     if ($command == '~inc') {
         if ($recipient == $user) {
             return String::insert($this->_responses['self'], compact('user'));
         }
         $model::increment($recipient);
         $current = $model::current($recipient);
         return String::insert($this->_responses['update'], compact('recipient', 'current'));
     } elseif ($command == '~dec') {
         if ($model::current($recipient) == 0) {
             return String::insert($this->_responses['decrementFail'], compact('recipient'));
         }
         $model::decrement($recipient);
         $current = $model::current($recipient);
         return String::insert($this->_responses['update'], compact('recipient', 'current'));
     } elseif ($command == '~karma') {
         $current = $model::current($recipient);
         return String::insert($this->_responses['current'], compact('recipient', 'current'));
     }
 }
Exemple #9
0
 public function url($url, array $options = [])
 {
     $absolute = static::_url();
     return function ($self, $params) use($url, $absolute, $options) {
         $style = ['style' => $options['key']];
         return $absolute . String::insert($url, $style);
     };
 }
Exemple #10
0
 /**
  * Constructor.
  *
  * @param array $config Configuration options.
  */
 public function __construct(array $config = array())
 {
     $defaults = array('scheme' => 'https', 'host' => '{:login}.freshbooks.com', 'port' => null, 'login' => null, 'password' => '', 'auth' => 'Basic', 'version' => '1.1', 'path' => '/api/2.1');
     $config += $defaults;
     $config['host'] = String::insert($config['host'], $config);
     $config['login'] = $config['password'];
     $config['password'] = '******';
     parent::__construct($config);
 }
Exemple #11
0
 public function interpolate($file)
 {
     $styles = $this->_config['styles'];
     $return = [];
     foreach ($styles as $style => $dimension) {
         $return[$dimension] = String::insert($file, ['style' => $style]);
     }
     return $return;
 }
Exemple #12
0
 protected function _paths($type, array $params)
 {
     if (!isset($this->_paths[$type])) {
         throw new TemplateException("Invalid template type '{$type}'.");
     }
     return array_map(function ($path) use($params) {
         return String::insert($path, $params);
     }, (array) $this->_paths[$type]);
 }
 protected function _render($method, $string, $params, $options = array())
 {
     $defaults = array();
     $options += $defaults;
     foreach ($params as $key => $value) {
         $params[$key] = $this->_context->applyHandler($this, $method, $key, $value, $options);
     }
     $strings = $this->_context ? $this->_context->strings() : $this->_strings;
     return String::insert(isset($strings[$string]) ? $strings[$string] : $string, $params);
 }
Exemple #14
0
 public static function __init()
 {
     parent::__init();
     static::applyFilter('create', function ($self, $params, $chain) {
         if (empty($params['data']['id'])) {
             $params['data']['id'] = String::uuid();
         }
         return $chain->next($self, $params, $chain);
     });
 }
 /**
  * Will iterate over each line checking if any weak comparison operators
  * are used within the code.
  *
  * @param  Testable $testable The testable object
  * @return void
  */
 public function apply($testable, array $config = array())
 {
     $tokens = $testable->tokens();
     $message = 'Weak comparison operator {:key} used, try {:value} instead';
     $filtered = $testable->findAll(array_keys($this->inspectableTokens));
     foreach ($filtered as $id) {
         $token = $tokens[$id];
         $this->addWarning(array('message' => String::insert($message, array('key' => token_name($token['id']), 'value' => $this->inspectableTokens[$token['id']])), 'line' => $token['line']));
     }
 }
 /**
  * Renders content from a template file provided by `template()`.
  *
  * @param string $template
  * @param array $data
  * @param array $options
  * @return string
  */
 public function render($template, $data = array(), $options = array())
 {
     $context = array();
     $this->_context = $options['context'] + $this->_context;
     foreach (array_keys($this->_context) as $key) {
         $context[$key] = $this->__get($key);
     }
     $data = array_merge($this->_toString($context), $this->_toString($data));
     return String::insert($template, $data, $options);
 }
Exemple #17
0
 /**
  * Appends a message to a log file.
  *
  * @see lithium\analysis\Logger::$_priorities
  * @param string $priority The message priority. See `Logger::$_priorities`.
  * @param string $message The message to write to the log.
  * @return \Closure Function returning boolean `true` on successful write, `false` otherwise.
  */
 public function write($priority, $message)
 {
     $config = $this->_config;
     return function ($self, $params) use(&$config) {
         $path = $config['path'] . '/' . $config['file']($params, $config);
         $params['timestamp'] = date($config['timestamp']);
         $message = String::insert($config['format'], $params);
         return file_put_contents($path, $message, FILE_APPEND);
     };
 }
Exemple #18
0
 /**
  * Outputs a stack trace based on the supplied options.
  *
  * @param array $options Format for outputting stack trace. Available options are:
  *        - `'args'`: A boolean indicating if arguments should be included.
  *        - `'depth'`: The maximum depth of the trace.
  *        - `'format'`: Either `null`, `'points'` or `'array'`.
  *        - `'includeScope'`: A boolean indicating if items within scope
  *           should be included.
  *        - `'scope'`: Scope for items to include.
  *        - `'start'`: The depth to start with.
  *        - `'trace'`: A trace to use instead of generating one.
  * @return string|array|null Stack trace formatted according to `'format'` option.
  */
 public static function trace(array $options = array())
 {
     $defaults = array('depth' => 999, 'format' => null, 'args' => false, 'start' => 0, 'scope' => array(), 'trace' => array(), 'includeScope' => true, 'closures' => true);
     $options += $defaults;
     $backtrace = $options['trace'] ?: debug_backtrace();
     $scope = $options['scope'];
     $count = count($backtrace);
     $back = array();
     $traceDefault = array('line' => '??', 'file' => '[internal]', 'class' => null, 'function' => '[main]');
     for ($i = $options['start']; $i < $count && $i < $options['depth']; $i++) {
         $trace = array_merge(array('file' => '[internal]', 'line' => '??'), $backtrace[$i]);
         $function = '[main]';
         if (isset($backtrace[$i + 1])) {
             $next = $backtrace[$i + 1] + $traceDefault;
             $function = $next['function'];
             if (!empty($next['class'])) {
                 $function = $next['class'] . '::' . $function . '(';
                 if ($options['args'] && isset($next['args'])) {
                     $args = array_map(array('static', 'export'), $next['args']);
                     $function .= join(', ', $args);
                 }
                 $function .= ')';
             }
         }
         if ($options['closures'] && strpos($function, '{closure}') !== false) {
             $function = static::_closureDef($backtrace[$i], $function);
         }
         if (in_array($function, array('call_user_func_array', 'trigger_error'))) {
             continue;
         }
         $trace['functionRef'] = $function;
         if ($options['format'] === 'points' && $trace['file'] !== '[internal]') {
             $back[] = array('file' => $trace['file'], 'line' => $trace['line']);
         } elseif (is_string($options['format']) && $options['format'] !== 'array') {
             $back[] = String::insert($options['format'], array_map(function ($data) {
                 return is_object($data) ? get_class($data) : $data;
             }, $trace));
         } elseif (empty($options['format'])) {
             $back[] = $function . ' - ' . $trace['file'] . ', line ' . $trace['line'];
         } else {
             $back[] = $trace;
         }
         if (!empty($scope) && array_intersect_assoc($scope, $trace) == $scope) {
             if (!$options['includeScope']) {
                 $back = array_slice($back, 0, count($back) - 1);
             }
             break;
         }
     }
     if ($options['format'] === 'array' || $options['format'] === 'points') {
         return $back;
     }
     return join("\n", $back);
 }
 /**
  * Writes the message to the configured cache adapter.
  *
  * @param string $type
  * @param string $message
  * @return closure Function returning boolean `true` on successful write, `false` otherwise.
  */
 public function write($type, $message)
 {
     $config = $this->_config + $this->_classes;
     return function ($self, $params) use($config) {
         $params += array('timestamp' => strtotime('now'));
         $key = $config['key'];
         $key = is_callable($key) ? $key($params) : String::insert($key, $params);
         $cache = $config['cache'];
         return $cache::write($config['config'], $key, $params['message'], $config['expiry']);
     };
 }
Exemple #20
0
 /**
  * Main method
  * @param  array  $menu    The menu description.
  * @param  array  $options Options.
  * @return string          The HTML buffer.
  */
 public function display(array $menu, array $options = array())
 {
     $options += static::$defaults;
     $menu = $this->_prepare($menu, $options);
     $out = String::insert($options['open'], $options);
     foreach ($menu as $item) {
         $out .= String::insert($options['content'], $item);
     }
     $out .= $options['close'];
     return $out;
 }
Exemple #21
0
 /**
  * Returns the template paths.
  *
  * @param mixed $type
  * @param array $params
  * @return mixed
  */
 public function template($type, array $params = array())
 {
     if (!isset($this->_config['paths'][$type])) {
         return null;
     }
     $library = Libraries::get(isset($params['library']) ? $params['library'] : true);
     $params['library'] = $library['path'];
     return array_map(function ($item) use($params) {
         return String::insert($item, $params);
     }, (array) $this->_config['paths'][$type]);
 }
Exemple #22
0
 public function template($type, array $params)
 {
     foreach ((array) $this->_paths[$type] as $path) {
         if (!file_exists($path = String::insert($path, $params))) {
             continue;
         }
         self::$templateData[] = compact('type', 'params') + array('return' => $path);
         return $path;
     }
     self::$templateData[] = compact('type', 'params') + array('return' => false);
     return false;
 }
Exemple #23
0
 /**
  * Returns the template paths.
  *
  * @param mixed $type
  * @param array $options
  * @return mixed
  */
 public function template($type, $options = array())
 {
     if (!isset($this->_config['paths'][$type])) {
         return null;
     }
     $options['library'] = isset($options['library']) ? $options['library'] : 'app';
     $library = Libraries::get($options['library']);
     $options['library'] = $library['path'];
     return array_map(function ($item) use($options) {
         return String::insert($item, $options);
     }, (array) $this->_config['paths'][$type]);
 }
Exemple #24
0
 public function _item($type, $params = array())
 {
     $defaults = array('namespace' => null, 'name' => null, 'menu' => null);
     $params += $defaults;
     $params['namespace'] = str_replace('/', '.', $params['namespace']);
     if ($type == 'group') {
         return String::insert("-group {:namespace}\n{:menu}\n", $params);
     }
     if ($type == 'case') {
         return String::insert("-case {:namespace}.{:name}\n", $params);
     }
     return String::insert("\n{:menu}\n", $params);
 }
Exemple #25
0
 public function query($connection, $service, array $options)
 {
     if (!($path = $this->service($service))) {
         throw new UnexpectedValueException("Service configuration `{$name}` not defined.");
     }
     $url = String::insert($path, array_map('rawurlencode', $options));
     if (!($result = $connection->get($url))) {
         return;
     }
     if (!($config = $this->_decode($service, $result))) {
         return;
     }
     return $this->_instance('location', $config);
 }
Exemple #26
0
 /**
  * Format a message with formatter.
  *
  * @see li3_mailer\net\mail\transport\adapter\Debug::_formatters()
  * @param object $message Message to format.
  * @param string $format Formatter name to use.
  * @return string Formatted log entry.
  */
 protected function format($message, $format)
 {
     $formatters = $this->_formatters();
     $formatter = isset($formatters[$format]) ? $formatters[$format] : null;
     switch (true) {
         case $formatter instanceof Closure:
             return $formatter($message);
         case is_string($formatter):
             $data = $this->_message_data($message);
             return String::insert($formatter, $data);
         default:
             throw new RuntimeException("Formatter for format `{$format}` is neither string nor closure.");
     }
 }
Exemple #27
0
 public static function parse($conditions, $data, array $options = array())
 {
     $params = compact('conditions', 'data', 'options');
     return static::_filter(__METHOD__, $params, function ($self, $params) {
         extract($params);
         $defaults = array();
         $options += $defaults;
         $check = String::insert($conditions, Set::flatten($data));
         if (strpbrk($check, '&|')) {
             return eval("return (boolean)({$check});");
         }
         // TODO: take care, that spaces are around operator
         return $self::invokeMethod('compare', explode(" ", $check, 3));
     });
 }
 public static function __init()
 {
     parent::__init();
     static::applyFilter('create', function ($self, $params, $chain) {
         if (empty($params['data']['secret'])) {
             $params['data']['secret'] = bin2hex(String::random(16));
         }
         return $chain->next($self, $params, $chain);
     });
     static::finder('getApplicationByIdAndSecret', function ($self, $params, $chain) {
         // Do stuff
         $data = $chain->next($self, $params, $chain);
         return $data ?: null;
     });
 }
Exemple #29
0
 /**
  * Process incoming messages
  *
  * @param string $data
  * @return string
  */
 public function process($data)
 {
     $responses = $this->_responses;
     $model = $this->_classes['model'];
     $key = null;
     extract($data);
     if ($message[0] == '~') {
         $words = preg_split("/[\\s]/", $message, 4);
         if ($words[0] == '~tell') {
             if (count($words) > 3 && $words[2] == 'about') {
                 $key = $words[3];
                 $to = $words[1];
             }
         } else {
             $key = ltrim($words[0], '~');
             $to = $user;
             if ($key == 'forget') {
                 $response = $this->_forget($words[1]);
                 return String::insert($response, array('user' => $to, 'tell' => $words[1]));
             }
         }
         $tell = $model::find('first', ['conditions' => compact('key')]);
         if (!$tell) {
             /* Not catching unknown tells, those could as well be other commands. */
             return;
         }
         return String::insert($responses['success'], array('user' => $to, 'tell' => $tell->key, 'answer' => $tell->value));
     }
     if (stripos($message, $nick) !== false) {
         $words = preg_split("/[\\s]/", $message, 4);
         if ($words[1] == 'forget') {
             $response = $this->_forget($words[2]);
             return String::insert($response, array('user' => $user, 'tell' => $words[2]));
         }
         if (!empty($words[2]) && $words[2] == 'is') {
             $tell = $model::find('first', ['conditions' => ['key' => $words[1]]]);
             if ($tell) {
                 return String::insert($responses['known'], array('user' => $user, 'tell' => $tell->key, 'answer' => $tell->value));
             }
             $tell = $model::create(['key' => $words[1], 'value' => $words[3], 'created' => date('Y-m-d H:i:s')]);
             if ($tell->save()) {
                 return String::insert($responses['remember'], array('user' => $user, 'tell' => $tell->key));
             }
         }
     }
 }
Exemple #30
0
 public function address($extract = null)
 {
     if (!$extract) {
         return $this->_address;
     }
     if (is_string($extract)) {
         if (strpos($extract, '{:')) {
             return preg_replace('/\\{:\\w+\\}/', '', String::insert($extract, $this->_address));
         }
         return isset($this->_address[$extract]) ? $this->_address[$extract] : null;
     }
     if (is_array($extract)) {
         $address = $this->_address;
         return array_filter(array_map(function ($key) use($address) {
             return isset($address[$key]) ? $address[$key] : null;
         }, array_combine($extract, $extract)));
     }
 }