function install() { if (empty($this->args)) { return $this->main(); } $args = $this->args; if (!empty($args[0]) && $args[0] == 'all') { $this->_getFiles(); $args = $this->files; } if (!empty($this->params['f'])) { $this->args = $args; $this->uninstall(); } foreach ($args as $arg) { if ($sql = $this->_getFile($arg)) { $sql = String::insert($sql, array('prefix' => $this->Db->tablePrefix), array('before' => '{', 'after' => '}', 'clean' => true)); $this->Db->query($sql); $this->out('OK: ' . $arg . ' created'); } else { $this->out($arg . ' not found'); } } $this->out('... done'); }
protected static function _html($params) { $params['message'] = nl2br($params['message']); $params['trace'] = nl2br($params['trace']); $error = String::insert(__d('ninja', '<h3>Unexpected Exception::class</h3><p><hr /><strong>:message</strong><hr /><br />:file at line :line</p><h4>Stack Trace:</h4><p>:trace</p>', true), $params); return $error; }
/** * Step 1: database * * @return void */ public function database() { $this->pageTitle = __('Step 1: Database', true); if (!empty($this->data)) { // test database connection if (mysql_connect($this->data['Install']['host'], $this->data['Install']['login'], $this->data['Install']['password']) && mysql_select_db($this->data['Install']['database'])) { // rename database.php.install rename(APP . 'config' . DS . 'database.php.install', APP . 'config' . DS . 'database.php'); // open database.php file App::import('Core', 'File'); $file = new File(APP . 'config' . DS . 'database.php', true); $content = $file->read(); // write database.php file if (!class_exists('String')) { App::import('Core', 'String'); } $this->data['Install']['prefix'] = ''; //disabled $content = String::insert($content, $this->data['Install'], array('before' => '{default_', 'after' => '}')); if ($file->write($content)) { $this->redirect(array('action' => 'data')); } else { $this->Session->setFlash(__('Could not write database.php file.', true)); } } else { $this->Session->setFlash(__('Could not connect to database.', true)); } } }
/** * particularidade() Faz em tempo de execução mudanças que sejam imprescindíveis * para a geração correta do código de barras * Particularmente para o Banrisul, ele acrescenta ao array OB::$Data, que * guarda as variáveis que geram o código de barras, uma nova variável * $DuploDigito, específica desse banco * * @version 0.1 28/05/2011 Initial */ public function particularidade($object) { $codigo = String::insert('21:Agencia:CodigoCedente:NossoNumero041', $object->Data); $dv1 = Math::Mod10($codigo); $dv2 = Math::Mod11($codigo . $dv1); return $object->Data['DuploDigito'] = self::DuploDigito($codigo); }
/** * http://www.paypalobjects.com/de_DE/html/IntegrationCenter/ic_std-variable-reference.html * Setup the config based on Config settings */ public function __construct(View $View, $settings = array()) { $this->settings = $this->_defaults; if ($x = Configure::read('Localization.decimalPoint')) { $this->settings['dec'] = $x; } if ($x = Configure::read('Localization.thousandsSeparator')) { $this->settings['sep'] = $x; } $this->settings = array_merge($this->settings, (array) Configure::read('PayPal')); if ($this->settings['live']) { $this->formOptions['server'] = 'https://www.paypal.com'; } else { $this->formOptions['server'] = 'https://www.sandbox.paypal.com'; } $data = array('HTTP_HOST' => HTTP_HOST, 'HTTP_BASE' => HTTP_BASE); $this->formOptions['notify_url'] = String::insert($this->settings['notify_url'], $data, array('before' => '{', 'after' => '}', 'clean' => true)); $this->formOptions['business'] = $this->settings['email']; $this->formOptions['lc'] = $this->settings['locale']; $this->formOptions['amount'] = $this->settings['amount']; $this->formOptions['no_shipping'] = (int) (!$this->settings['shipping']); $this->formOptions['currency_code'] = $this->settings['currency_code']; if ($this->settings['cancel_return']) { $this->formOptions['cancel_return'] = Router::url(null, true); } //pr($this->formOptions); die(); parent::__construct($View, $settings); }
/** * Returns a string with all spaces converted to $replacement and non word characters removed. * * @param string $string * @param string $replacement * @return string * @static */ static function slug($string, $replacement = '-') { $string = trim($string); $map = array('/à|á|å|â|ä/' => 'a', '/è|é|ê|ẽ|ë/' => 'e', '/ì|í|î/' => 'i', '/ò|ó|ô|ø/' => 'o', '/ù|ú|ů|û/' => 'u', '/ç|č/' => 'c', '/ñ|ň/' => 'n', '/ľ/' => 'l', '/ý/' => 'y', '/ť/' => 't', '/ž/' => 'z', '/š/' => 's', '/æ/' => 'ae', '/ö/' => 'oe', '/ü/' => 'ue', '/Ä/' => 'Ae', '/Ü/' => 'Ue', '/Ö/' => 'Oe', '/ß/' => 'ss', '/[^\\w\\s]/' => ' ', '/\\s+/' => $replacement, String::insert('/^[:replacement]+|[:replacement]+$/', array('replacement' => preg_quote($replacement, '/'))) => ''); $string = preg_replace(array_keys($map), array_values($map), $string); return low($string); }
/** * read * * Bespoke read method to read the api of an external translations api * * @param Model $model * @param array $queryData * @param mixed $recursive * @return void */ public function read(Model $model, $queryData = array(), $recursive = null) { $class = get_class($model); $config = $class::config(); $url = String::insert($this->config['host'], $queryData['conditions'] + $config); $result = $this->execute($url); if (!$result) { return $result; } if ($queryData['fields'] === 'COUNT(*) AS count') { return count(current($result)); } $defaults = array_intersect_key($queryData['conditions'] + $config, array_flip(array('domain', 'category', 'locale'))); $return = array(); foreach (current($result) as $key => $value) { if (is_array($value)) { foreach ($value as $case => $val) { $return[] = array($model->alias => array('key' => $key, 'value' => $val, 'plural_case' => $case) + $defaults); } } else { $return[] = array($model->alias => array('key' => $key, 'value' => $value, 'plural_case' => null) + $defaults); } } return $return; }
public function tableEnd($data = [], $options = []) { $this->mergeOptions('table', $options); $this->insertData($options, $data); $this->insertData($options, $options); return String::insert("</:tag>", $options); }
/** * Render one (or more) hidden links. * * @param integer $num Number of random and unique links to create. * @return string Hidden links HTML. */ public function render($num = 1) { if (!($lnk = Common::read('Security.HttpBL.honeyPot', $this->settings['honeyPot']))) { return; } $all = $this->settings['links']; $len = rand(4, 16); $min = array(48, 65, 97); $max = array(57, 90, 122); $txt = ''; $res = array(); while (strlen($txt) < $len) { $rnd = rand(0, 2); $txt .= chr(rand($min[$rnd], $max[$rnd])); } if ($num > count($all)) { $num = count($all); } if (0 == $num) { return; } $rnd = array_rand($all, $num); foreach ((array) $rnd as $key) { $res[] = String::insert($all[$key], compact('lnk', 'str')); } return implode(' ', $res); }
/** * Extends model construction * * ### Extended functionality: * - allows use of :ALIAS: in virtual field definitions to be replaced with the * model's alias * * @param mixed $id Sets the model's id on startup * @param string $table The name of the database table to use * @param string $ds The datasource connection name * @see Model::__construct() */ public function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); foreach ($this->virtualFields as &$virtualField) { $virtualField = String::insert($virtualField, array('ALIAS' => $this->alias), array('after' => ':')); } $this->order = String::insert($this->order, array('ALIAS' => $this->alias), array('after' => ':')); }
private function shouldBeWritable() { foreach ($this->_writableDirectories() as $key => $directory) { if (is_writable($directory)) { $this->errors[$key]['message'] = String::insert(__('Warning: :directory is not writable', true), compact('directory')); $this->errors[$key]['solution'] = String::insert(__('Solution: change :directory permissions to 775', true), compact('directory')); } } }
/** * Interpolates a string by substituting tokens in a string * * Default interpolations: * - `:webroot` Path to the webroot folder * - `:model` The current model e.g images * - `:field` The database field * - `:filename` The filename * - `:extension` The extension of the file e.g png * - `:id` The record id * - `:style` The current style e.g thumb * - `:hash` Generates a hash based on the filename * * @param string $string The string to be interpolated with data. * @param string $name The name of the model e.g. Image * @param int $id The id of the record e.g 1 * @param string $field The name of the database field e.g file * @param string $style The style to use. Should be specified in the behavior settings. * @param array $options You can override the default interpolations by passing an array of key/value * pairs or add extra interpolations. For example, if you wanted to change the hash method * you could pass `array('hash' => sha1($id . Configure::read('Security.salt')))` * @return array Settings array containing interpolated strings along with the other settings for the field. */ public static function run($string, $name, $id, $field, $filename, $style = 'original', $data = array()) { $info = new SplFileInfo($filename); $data += array('webroot' => preg_replace('/\\/$/', '', WWW_ROOT), 'model' => Inflector::tableize($name), 'field' => strtolower($field), 'filename' => $info->getBasename($info->getExtension()), 'extension' => $info->getExtension(), 'id' => $id, 'style' => $style, 'hash' => md5($info->getFilename() . Configure::read('Security.salt'))); foreach (static::$_interpolations as $name => $closure) { $data[$name] = $closure($info); } return String::insert($string, $data); }
/** * Prints calculated results * * @param array $times Array of time values * * @return void */ protected function _results($times) { $duration = array_sum($times); $requests = count($times); $this->out(String::insert(__d('debug_kit', 'Total Requests made: :requests'), compact('requests'))); $this->out(String::insert(__d('debug_kit', 'Total Time elapsed: :duration (seconds)'), compact('duration'))); $this->out(""); $this->out(String::insert(__d('debug_kit', 'Requests/Second: :rps req/sec'), array('rps' => round($requests / $duration, 3)))); $this->out(String::insert(__d('debug_kit', 'Average request time: :average-time seconds'), array('average-time' => round($duration / $requests, 3)))); $this->out(String::insert(__d('debug_kit', 'Standard deviation of average request time: :std-dev'), array('std-dev' => round($this->_deviation($times, true), 3)))); $this->out(String::insert(__d('debug_kit', 'Longest/shortest request: :longest sec/:shortest sec'), array('longest' => round(max($times), 3), 'shortest' => round(min($times), 3)))); $this->out(""); }
public function setUp() { parent::setUp(); if (!CakePlugin::loaded('Common')) { CakePlugin::load('Common'); } $this->CakeRequest = $this->getMock('CakeRequest', array('is')); $this->Controller = $this->getMock('TestCommonController', array('redirect', 'referer', 'set'), array($this->CakeRequest, new CakeResponse())); $this->Controller->Components = $this->getMock('ComponentCollection', array('init')); $this->Controller->eventManager = $this->getMock('CommonEventManager', array('listPlugins')); $this->Controller->eventManager->expects($this->any())->method('listPlugins')->will($this->returnValue(array())); $this->Controller->Session = $this->getMock('SessionComponent', array('setFlash'), array($this->Controller->Components)); $this->Controller->constructClasses(); $this->flashMessage = String::insert($this->Controller->alertMessages['delete.success']['message'], array('modelName' => 'Test'), array('clean' => true)); }
function install($url, $name) { $this->formattedOut(String::insert(__d('plugin', "Instalando [u]:plugin[/u]...", true), array('plugin' => $url))); // $this->_create($name); $path = $this->params['working'] . DS . 'plugins' . DS . $name; if ($this->_install($url, $path, $name)) { $this->formattedOut(__d('plugin', '[fg=black][bg=green] OK [/bg][/fg]', true)); $this->_createUrlFile($url, $path); $this->_runInstallHook($name); return true; } else { $this->formattedOut(__d('plugin', '[fg=black][bg=red] ERRO [/bg][/fg]', true)); } return false; }
public function timeAgoInWords($dateTime, $options = array()) { if (!isset($this->Asset) || !$this->settings['relativeTime']['enabled'] || isset($options['useCore'])) { unset($options['useCore']); return parent::timeAgoInWords($dateTime, $options); } if (!$this->_jsAdded) { if ($this->settings['relativeTime']['jsPacket'] !== false) { $this->Asset->js(array('jquery.timeago', 'jquery.mi.relativeTime'), $this->settings['relativeTime']['jsPacket']); } $this->_jsAdded = true; } $date = date('Y-m-d H:i:s O', $this->fromString($dateTime)); return String::insert($this->settings['relativeTime']['tag'], array_merge($options, compact('date'))); }
/** * __replace * * Helper function for replacing args * * @param mixed $msg * @param mixed $args * @return string */ function __replace($msg, $args) { if (is_null($args)) { return $msg; } if (strpos($msg, '{') !== false) { if (count($args) === 1 && isset($args[0])) { $msg = preg_replace('@{\\w+}@', $args[0], $msg, 1); } else { $msg = String::insert($msg, $args, array('before' => '{', 'after' => '}')); } } else { $msg = vsprintf($msg, $args); } return $msg; }
public function arrayToList($array = array(), $class = null, $div = false) { if (!empty($class['div'])) { $div = true; } if (!is_array($class)) { $class = array('div' => $class, 'div-id' => null, 'ul' => $class, 'ul-id' => null, 'li' => null); } $class = array_merge(array('div' => null, 'div_id' => null, 'ul' => null, 'ul_id' => null, 'li' => null), $class); $base = '%s'; if ($div) { $base = '<div id=":div_id" class=":div">%s</div>'; } $base = sprintf($base, sprintf('<ul id=":ul_id" class=":ul"><li class=":li">%s</li></ul>', implode('</li><li class=":li">', (array) $array))); return str_replace(array('id=""', 'class=""'), '', String::insert($base, $class)); }
function _installDeps() { $this->formattedOut(__d('plugin', ' -> Verificando a existencia de dependencias...', true), false); if (empty($this->deps)) { $this->formattedOut(__d('plugin', '[fg=black][bg=green] OK [/bg][/fg]'), false); $this->_stop(); } $this->formattedOut("\n", false); foreach ($this->deps as $name => $url) { if ($this->Installer->install($url, $name)) { $this->formattedOut(String::insert(__d('plugin', " [fg=green][u]:plugin[/u][/fg] instalado com sucesso!\n", true), array('plugin' => $name))); } else { $this->formattedOut(String::insert(__d('plugin', " Nao foi possivel instalar [fg=red][u]:plugin[/u][/fg]\n", true), array('plugin' => $name))); } } }
/** * Detect Upload and map data * * @access public * @param Model $model * @return boolean * @todo Recursive directory creating */ public function _initUpload(Model &$model) { //check if a new file has been uploaded $__uploadField = $this->settings[$model->alias]['uploadFields']['file']; $__uploadTitle = $this->settings[$model->alias]['uploadFields']['title']; if (!isset($model->data[$model->alias][$__uploadField])) { return false; } //upload $upload = $model->data[$model->alias][$__uploadField]; unset($model->data[$model->alias][$__uploadField]); //uploadTitle if (isset($model->data[$model->alias][$__uploadTitle])) { $uploadTitle = $model->data[$model->alias][$__uploadTitle]; unset($model->data[$model->alias][$__uploadTitle]); } else { $uploadTitle = $upload['name']; } //refId $uploadRefId = isset($model->data[$model->alias]['ref_id']) ? $model->data[$model->alias]['ref_id'] : null; //ext $uploadExt = strrpos($upload['name'], ".") > 0 ? substr($upload['name'], strrpos($upload['name'], ".") + 1) : null; //path $uploadPath = String::insert($this->settings[$model->alias]['path'], array('model' => $this->settings[$model->alias]['model'])); //data mapping $model->data[$model->alias]['model'] = $this->settings[$model->alias]['model']; $model->data[$model->alias]['ref_id'] = $uploadRefId; $model->data[$model->alias]['title'] = strlen($uploadTitle) > 0 ? $uploadTitle : $upload['name']; $model->data[$model->alias]['basename'] = $upload['name']; $model->data[$model->alias]['mime'] = $upload['type']; $model->data[$model->alias]['ext'] = $uploadExt; $model->data[$model->alias]['size'] = $upload['size']; $model->data[$model->alias]['error'] = $upload['error']; $model->data[$model->alias]['tmp_name'] = $upload['tmp_name']; $model->data[$model->alias]['path'] = $uploadPath; unset($upload); //cleanup //upload error $uploadErrors = array(UPLOAD_ERR_OK => __d('media', "There is no error, the file uploaded successfully"), UPLOAD_ERR_INI_SIZE => __d('media', "The uploaded file exceeds the upload_max_filesize directive in php.ini"), UPLOAD_ERR_FORM_SIZE => __d('media', "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"), UPLOAD_ERR_PARTIAL => __d('media', "The uploaded file was only partially uploaded"), UPLOAD_ERR_NO_FILE => __d('media', "No file was uploaded"), UPLOAD_ERR_NO_TMP_DIR => __d('media', "Missing a temporary folder"), UPLOAD_ERR_CANT_WRITE => __d('media', "Can not write to disk"), UPLOAD_ERR_EXTENSION => __d('media', "File upload stopped by extension")); if ($model->data[$model->alias]['error'] > 0) { $model->invalidate($__uploadField, $uploadErrors[$model->data[$model->alias]['error']]); return false; } return true; }
function admin_edit($role_id) { $role = $this->Role->find('first', array('conditions' => array('Role.id' => $role_id))); if ($role == null) { $this->Session->setFlash(String::insert(__('Role doesn\'t exists.', true), $this->data['Role'])); $this->redirect(array('action' => 'index')); } if (!empty($this->data['Role'])) { $this->data['Role']['id'] = $role_id; if ($this->Role->save($this->data['Role'])) { $this->Session->setFlash(String::insert(__('Role :name updated.', true), $this->data['Role'])); $this->redirect(array('action' => 'index')); } } else { $this->data = $role; } $this->set(compact('role')); }
/** * @author Reed Dadoune * distanceQuery * A genral case distance query builder * Pass a number of options to this function and recieve a query * you can pass to either the find or paginate functions to get * objects back by distance * * Example: * $query = $this->Model->distanceQuery(array( * 'lat' => 34.2746405, * 'lng' => -119.2290053 * )); * $query['conditions']['published'] = true; * $results = $this->Model->find('all', $query); * * @param array $opts Options * - lat The latitude coordinate of the center point * - lng The longitude coordinate of the center point * - alias The model name of the query this is for * defaults to the current model alias * - radius The distance to at which to find objects at * defaults to false in which case distance is calculated * only for the sort order * @return array A query that can be modified and passed to find or paginate */ public function distanceQuery($opts = array()) { $defaults = array('lat' => 0, 'lng' => 0, 'alias' => $this->alias, 'radius' => false); $opts = Set::merge($defaults, $opts); $query = array('fields' => array(CakeText::insert('3956 * 2 * ASIN(SQRT( POWER(SIN((:lat - ABS(:alias.lat)) * PI() / 180 / 2), 2) + COS(:lat * PI() / 180) * COS(ABS(:alias.lat) * PI() / 180) * POWER(SIN((:lng - :alias.lng) * PI() / 180 / 2), 2) )) AS distance', array('alias' => $opts['alias'], 'lat' => $opts['lat'], 'lng' => $opts['lng']))), 'order' => array('distance' => 'ASC')); if ($opts['radius']) { $longitudeLower = $opts['lng'] - $opts['radius'] / abs(cos(deg2rad($opts['lat'])) * 69); $longitudeUpper = $opts['lng'] + $opts['radius'] / abs(cos(deg2rad($opts['lat'])) * 69); $latitudeLower = $opts['lat'] - $opts['radius'] / 69; $latitudeUpper = $opts['lat'] + $opts['radius'] / 69; $query['conditions'] = array(String::insert(':alias.lat BETWEEN ? AND ?', array('alias' => $opts['alias'])) => array($latitudeLower, $latitudeUpper), String::insert(':alias.lng BETWEEN ? AND ?', array('alias' => $opts['alias'])) => array($longitudeLower, $longitudeUpper)); $query['group'] = sprintf('%s.id HAVING distance < %f', $opts['alias'], $opts['radius']); } return $query; }
/** * Make the export query * * @param string $type * @param array $params Query strings * @return array Result * @throws CakeException */ protected function _call($type, $params) { $url = 'http://:dc.api.mailchimp.com/export/1.0/'; $apiKey = Configure::read('Mailchimp.apiKey'); $dc = substr($apiKey, strpos($apiKey, '-') + 1); $url = String::insert($url, ['dc' => $dc]); $params += ['apikey' => $apiKey, 'id' => Configure::read('Mailchimp.defaultListId')]; $url .= $type . '/'; $response = $this->_get($url, $params); if ($response) { $result = []; $lines = explode("\n", trim($response)); foreach ($lines as $line) { $result[] = json_decode($line, true); } if (!empty($result[0]['error'])) { throw new MailchimpException('Error ' . $result[0]['code'] . ': ' . $result[0]['error']); } return $result; } return []; }
/** * Formata uma entrada de log gerada pelo AuditableBehavior para fácil * visualização na view, baseada nas configurações do helper. * * @param array $data * @param int $type * * @return string */ public function format($data, $type) { $func = 'unserialize'; if (is_callable(AuditableConfig::$unserialize)) { $func = AuditableConfig::$unserialize; } $data = call_user_func($func, $data); $placeHolders = array(); $prepend = __d('auditable', $this->settings['formats']['prepend']) . ' '; $pospend = ' ' . __d('auditable', $this->settings['formats']['pospend']); $humanDiff = ''; $action = $this->typesEnum[$type]; $actionMsg = __d('auditable', $this->settings['formats'][$action]); switch ($type) { case 2: $placeHolders['action'] = __d('auditable', 'modified'); foreach ($data as $field => $changes) { $humanDiff .= $prepend . String::insert($actionMsg, array('field' => $field, 'old' => $changes['old'], 'new' => $changes['new'])) . $pospend; } break; case 1: $placeHolders['action'] = __d('auditable', 'created'); case 3: if (!isset($placeHolders['action'])) { $placeHolders['action'] = __d('auditable', 'deleted'); } foreach ($data as $field => $value) { $humanDiff .= $prepend . String::insert($actionMsg, compact('field', 'value')) . $pospend; } break; default: $placeHolders['action'] = __d('auditable', 'undefined'); $humanDiff .= __d('auditable', 'nothing changed'); break; } $placeHolders['data'] = $humanDiff; $msg = String::insert(__d('auditable', $this->settings['formats']['general']), $placeHolders); return $msg; }
/** * Extracts a Model.field identifier and an SQL condition operator from a string, formats * and inserts values, and composes them into an SQL snippet. * * @param Model $model Model object initiating the query * @param string $key An SQL key snippet containing a field and optional SQL operator * @param mixed $value The value(s) to be inserted in the string * @return string * @access private */ function __parseKey(&$model, $key, $value) { $operatorMatch = '/^((' . implode(')|(', $this->__sqlOps); $operatorMatch .= '\\x20)|<[>=]?(?![^>]+>)\\x20?|[>=!]{1,3}(?!<)\\x20?)/is'; $bound = strpos($key, '?') !== false || is_array($value) && strpos($key, ':') !== false; if (!strpos($key, ' ')) { $operator = '='; } else { list($key, $operator) = explode(' ', trim($key), 2); if (!preg_match($operatorMatch, trim($operator)) && strpos($operator, ' ') !== false) { $key = $key . ' ' . $operator; $split = strrpos($key, ' '); $operator = substr($key, $split); $key = substr($key, 0, $split); } } $virtual = false; if (is_object($model) && $model->isVirtualField($key)) { $key = $this->__quoteFields($model->getVirtualField($key)); $virtual = true; } $type = is_object($model) ? $model->getColumnType($key) : null; $null = $value === null || is_array($value) && empty($value); if (strtolower($operator) === 'not') { $data = $this->conditionKeysToString(array($operator => array($key => $value)), true, $model); return $data[0]; } $value = $this->value($value, $type); if (!$virtual && $key !== '?') { $isKey = strpos($key, '(') !== false || strpos($key, ')') !== false; $key = $isKey ? $this->__quoteFields($key) : $this->name($key); } if ($bound) { return String::insert($key . ' ' . trim($operator), $value); } if (!preg_match($operatorMatch, trim($operator))) { $operator .= ' ='; } $operator = trim($operator); if (is_array($value)) { $value = implode(', ', $value); switch ($operator) { case '=': $operator = 'IN'; break; case '!=': case '<>': $operator = 'NOT IN'; break; } $value = "({$value})"; } elseif ($null) { switch ($operator) { case '=': $operator = 'IS'; break; case '!=': case '<>': $operator = 'IS NOT'; break; } } if ($virtual) { return "({$key}) {$operator} {$value}"; } return "{$key} {$operator} {$value}"; }
/** * Takes a processed array of data from an error and displays it in the chosen format. * * @param string $data * @return void */ public function outputError($data) { $defaults = array('level' => 0, 'error' => 0, 'code' => 0, 'description' => '', 'file' => '', 'line' => 0, 'context' => array(), 'start' => 2); $data += $defaults; $files = $this->trace(array('start' => $data['start'], 'format' => 'points')); $code = ''; $file = null; if (isset($files[0]['file'])) { $file = $files[0]; } elseif (isset($files[1]['file'])) { $file = $files[1]; } if ($file) { $code = $this->excerpt($file['file'], $file['line'] - 1, 1); } $trace = $this->trace(array('start' => $data['start'], 'depth' => '20')); $insertOpts = array('before' => '{:', 'after' => '}'); $context = array(); $links = array(); $info = ''; foreach ((array) $data['context'] as $var => $value) { $context[] = "\${$var} = " . $this->exportVar($value, 3); } switch ($this->_outputFormat) { case false: $this->_data[] = compact('context', 'trace') + $data; return; case 'log': $this->log(compact('context', 'trace') + $data); return; } $data['trace'] = $trace; $data['id'] = 'cakeErr' . uniqid(); $tpl = array_merge($this->_templates['base'], $this->_templates[$this->_outputFormat]); if (isset($tpl['links'])) { foreach ($tpl['links'] as $key => $val) { $links[$key] = String::insert($val, $data, $insertOpts); } } if (!empty($tpl['escapeContext'])) { $context = h($context); } $infoData = compact('code', 'context', 'trace'); foreach ($infoData as $key => $value) { if (empty($value) || !isset($tpl[$key])) { continue; } if (is_array($value)) { $value = implode("\n", $value); } $info .= String::insert($tpl[$key], array($key => $value) + $data, $insertOpts); } $links = implode(' ', $links); if (isset($tpl['callback']) && is_callable($tpl['callback'])) { return call_user_func($tpl['callback'], $data, compact('links', 'info')); } echo String::insert($tpl['error'], compact('links', 'info') + $data, $insertOpts); }
/** * Transfer an object to the S3 storage bucket. * * @access public * @param string $path * @return string */ public function transfer($path) { if ($this->s3 === null) { return $path; } $host = empty($this->s3->host) ? self::AS3_DOMAIN : $this->s3->host; $name = basename($path); $bucket = $this->s3->bucket; if (!empty($this->s3->path)) { $name = $this->s3->path . '/' . $name; } if ($this->s3->putObjectFile($this->uploader->formatPath($path), $bucket, $name, S3::ACL_PUBLIC_READ)) { $this->s3->uploads[] = $path; return String::insert($this->s3->format, array('bucket' => $bucket, 'path' => $name, 'host' => $host), array('before' => '{', 'after' => '}')); } return $path; }
public function testReplaceWithQuestionMarkInString() { $string = ':a, :b and :c?'; $expected = '2 and 3?'; $result = String::insert($string, array('b' => 2, 'c' => 3), array('clean' => true)); $this->assertEquals($expected, $result); }
/** * Callback used to display actions being performed * * @param CakeMigration &$Migration Migration being performed * @param string $type Type of action. i.e: create_table, drop_table, etc. * @param array $data Data to send to the callback * @return void */ public function beforeAction(&$Migration, $type, $data) { if (isset($this->_messages[$type])) { $message = String::insert($this->_messages[$type], $data); $this->out(' > ' . $message); } }
/** * logQuery method * * Set timers, errors and refer to the parent * If there are arguments passed - inject them into the query * Show MongoIds in a copy-and-paste-into-mongo format * * * @param mixed $query * @param array $args array() * @return void * @access public */ public function logQuery($query, $args = array()) { if ($args) { $this->_stringify($args); $query = String::insert($query, $args); } $this->took = round((microtime(true) - $this->_startTime) * 1000, 0); $this->affected = null; if (empty($this->error['err'])) { $this->error = $this->_db->lastError(); if (!is_scalar($this->error)) { $this->error = json_encode($this->error); } } $this->numRows = !empty($args['count']) ? $args['count'] : null; $query = preg_replace('@"ObjectId\((.*?)\)"@', 'ObjectId ("\1")', $query); return parent::logQuery($query); }