/** * Constructor * * @param \Cake\ORM\Entity $entity Entity * @param int $code code to report to client */ public function __construct(Entity $entity, $code = 422) { $this->_validationErrors = array_filter((array) $entity->errors()); $flat = Hash::flatten($this->_validationErrors); $errorCount = $this->_validationErrorCount = count($flat); $this->message = __dn('crud', 'A validation error occurred', '{0} validation errors occurred', $errorCount, [$errorCount]); parent::__construct($this->message, $code); }
/** * Constructor * * @param array $error list of validation errors * @param integer $code code to report to client * @return void */ public function __construct($errors, $code = 412) { $this->_validationErrors = array_filter($errors); $flat = Hash::flatten($this->_validationErrors); $errorCount = $this->_validationErrorCount = count($flat); $this->message = __dn('crud', 'A validation error occurred', '%d validation errors occurred', $errorCount, array($errorCount)); if ($errorCount === 1) { $code = $this->_deriveRuleSpecific($this->_validationErrors, $code); } parent::__construct($this->message, $code); }
public function toReadableSize($size) { switch (true) { case $size < 1000: return __dn('cake', '{0,number,integer}', '{0,number,integer}', $size, $size); case round($size / 1000) < 1000: return __d('cake', '{0,number,#,###.##}k', $size / 1000); case round($size / 1000 / 1000, 2) < 1000: return __d('cake', '{0,number,#,###.##}m', $size / 1000 / 1000); case round($size / 1000 / 1000 / 1000, 2) < 1000: return __d('cake', '{0,number,#,###.##}b', $size / 1000 / 1000 / 1000); default: return __d('cake', '{0,number,#,###.##}t', $size / 1000 / 1000 / 1000 / 1000); } }
/** * Returns a formatted-for-humans file size. * * @param int $size Size in bytes * @return string Human readable size * @link http://book.cakephp.org/3.0/en/core-libraries/number.html#interacting-with-human-readable-values */ public static function toReadableSize($size) { switch (true) { case $size < 1024: return __dn('cake', '{0,number,integer} Byte', '{0,number,integer} Bytes', $size, $size); case round($size / 1024) < 1024: return __d('cake', '{0,number,#,###.##} KB', $size / 1024); case round($size / 1024 / 1024, 2) < 1024: return __d('cake', '{0,number,#,###.##} MB', $size / 1024 / 1024); case round($size / 1024 / 1024 / 1024, 2) < 1024: return __d('cake', '{0,number,#,###.##} GB', $size / 1024 / 1024 / 1024); default: return __d('cake', '{0,number,#,###.##} TB', $size / 1024 / 1024 / 1024 / 1024); } }
/** * Returns a formatted-for-humans file size. * * @param integer $size Size in bytes * @return string Human readable size * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toReadableSize */ public static function toReadableSize($size) { switch (true) { case $size < 1024: return __dn('cake', '%d Byte', '%d Bytes', $size, $size); case round($size / 1024) < 1024: return __d('cake', '%d KB', self::precision($size / 1024, 0)); case round($size / 1024 / 1024, 2) < 1024: return __d('cake', '%.2f MB', self::precision($size / 1024 / 1024, 2)); case round($size / 1024 / 1024 / 1024, 2) < 1024: return __d('cake', '%.2f GB', self::precision($size / 1024 / 1024 / 1024, 2)); default: return __d('cake', '%.2f TB', self::precision($size / 1024 / 1024 / 1024 / 1024, 2)); } }
/** * Returns a formatted-for-humans file size. * * @param integer $size Size in bytes * @return string Human readable size * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toReadableSize */ public function toReadableSize($size) { switch (true) { case $size < 1024: return __dn('cake', '%d Byte', '%d Bytes', $size, $size); case round($size / 1024) < 1024: return __d('cake', '%s KB', $this->precision($size / 1024, 0)); case round($size / 1024 / 1024, 2) < 1024: return __d('cake', '%s MB', $this->precision($size / 1024 / 1024, 2)); case round($size / 1024 / 1024 / 1024, 2) < 1024: return __d('cake', '%s GB', $this->precision($size / 1024 / 1024 / 1024, 2)); default: return __d('cake', '%s TB', $this->precision($size / 1024 / 1024 / 1024 / 1024, 2)); } }
public function display($likes, $userKey = 'username') { $n = count($likes); if ($n > 0) { if ($n == 1) { $like = $likes[0]; $text = $this->Html->link($like['User'][$userKey], array('controller' => 'users', 'action' => 'view', $like['User']['id'])); } else { if ($n > 1) { $users = array(); foreach ($likes as $like) { $users[] = $like['User'][$userKey]; } $text = $this->Html->link(__n('%s people', '%s people', $n, $n), '#', array('title' => $this->Text->toList($users, __('and')))); } } echo __dn('like', '%s liked this.', '%s liked this.', $n, $text); } }
/** * Re-builds the table * * @return void */ public function clean() { // $done = []; $errors = 0; if ($this->request->is('POST')) { // Get connection: $connection = ConnectionManager::get('default'); $truncate = $connection->query('truncate acts;'); $models = ['Files', 'Posts', 'Projects', 'Notes', 'Albums']; foreach ($models as $model) { // $done[$model]=['add'=>0, 'edit'=>0]; $query = $this->{$model}->find('all', ['conditions' => ['status' => 1]]); foreach ($query as $item) { // Add $act = $this->Acts->patchEntity($this->Acts->newEntity(), ['fkid' => $item->id, 'model' => $model, 'type' => 'add', 'created' => $item->created]); //, 'user_id' => $uid]); if (!$this->Acts->save($act)) { $errors++; } // $done[$model]['add']++; // Edit if ($item->created != $item->modified) { // $done[$model]['edit']++; $act = $this->Acts->patchEntity($this->Acts->newEntity(), ['fkid' => $item->id, 'model' => $model, 'type' => 'edit', 'created' => $item->modified]); //, 'user_id' => $uid]); if (!$this->Acts->save($act)) { $errors++; } } } } // debug($done);die; if ($errors > 0) { $this->Flash->error(__dn('elabs', 'An error occured during the cleanup. Please, try again.', '{0,number} errors occured during the cleanup. Please, try again.', $errors, $errors)); } else { $this->Flash->success(__d('elabs', 'Acts table has been rebuilt.')); } $this->redirect($this->request->referer()); } else { throw new \Cake\Network\Exception\MethodNotAllowedException(__d('elabs', 'Use the menu to access this functionality')); } }
public function load() { $this->Product->clearCart(); $products = array(); foreach ($this->request->query as $parameter => $value) { if (strpos($parameter, 'product-') !== 0) { continue; } $products[(int) substr($parameter, 8)] = (int) $value; } $existingProducts = $this->Product->find('list', array('conditions' => array('Product.id' => array_keys($products)))); foreach ($existingProducts as $productId => $name) { $this->Product->addToCart($productId, $products[$productId]); } if (empty($missingProducts)) { $this->Session->setFlash(__d('webshop_shopping_cart', 'The shopping cart has been imported')); } else { $this->Session->setFlash(__dn('webshop_shopping_cart', 'The shopping cart has been imported, the products with the following ids\'s did not exist however: %1$s', 'The shopping cart has been imported, the product with the following id did not exist however: %1$s', count($missingProducts), implode(', ', array_diff(array_keys($products), array_keys($existingProducts))))); } $this->redirect(array('action' => 'index')); }
/** * Format a into a relative date string. * * @param \DatetimeInterface $date The date to format. * @param array $options Array of options. * @return string Relative date string. * @see \Cake\I18n\Date::timeAgoInWords() */ public function dateAgoInWords(DatetimeInterface $date, array $options = []) { $options = $this->_options($options, FrozenDate::class); if ($options['timezone']) { $date = $date->timezone($options['timezone']); } $now = $options['from']->format('U'); $inSeconds = $date->format('U'); $backwards = $inSeconds > $now; $futureTime = $now; $pastTime = $inSeconds; if ($backwards) { $futureTime = $inSeconds; $pastTime = $now; } $diff = $futureTime - $pastTime; if (!$diff) { return __d('cake', 'today'); } if ($diff > abs($now - (new FrozenDate($options['end']))->format('U'))) { return sprintf($options['absoluteString'], $date->i18nFormat($options['format'])); } $diffData = $this->_diffData($futureTime, $pastTime, $backwards, $options); list($fNum, $fWord, $years, $months, $weeks, $days, $hours, $minutes, $seconds) = array_values($diffData); $relativeDate = []; if ($fNum >= 1 && $years > 0) { $relativeDate[] = __dn('cake', '{0} year', '{0} years', $years, $years); } if ($fNum >= 2 && $months > 0) { $relativeDate[] = __dn('cake', '{0} month', '{0} months', $months, $months); } if ($fNum >= 3 && $weeks > 0) { $relativeDate[] = __dn('cake', '{0} week', '{0} weeks', $weeks, $weeks); } if ($fNum >= 4 && $days > 0) { $relativeDate[] = __dn('cake', '{0} day', '{0} days', $days, $days); } $relativeDate = implode(', ', $relativeDate); // When time has passed if (!$backwards) { $aboutAgo = ['day' => __d('cake', 'about a day ago'), 'week' => __d('cake', 'about a week ago'), 'month' => __d('cake', 'about a month ago'), 'year' => __d('cake', 'about a year ago')]; return $relativeDate ? sprintf($options['relativeString'], $relativeDate) : $aboutAgo[$fWord]; } // When time is to come if ($relativeDate) { return $relativeDate; } $aboutIn = ['day' => __d('cake', 'in about a day'), 'week' => __d('cake', 'in about a week'), 'month' => __d('cake', 'in about a month'), 'year' => __d('cake', 'in about a year')]; return $aboutIn[$fWord]; }
/** * Removes expired registrations * * @return void */ public function removeExpired() { $count = $this->UserTable->removeExpiredRegistrations(); $this->out(__dn('user_tools', 'Removed {0,number,integer} expired registration.', 'Removed {0,number,integer} expired registrations.', $count, $count)); }
/** * testSubstitutionPluralDomain * * @return void */ public function testSubstitutionPluralDomain() { $return = __dn('testing', 'single', 'plural {number}', 1); $this->assertSame('single', $return); $return = __dn('testing', 'single', 'plural {number}', 0); $this->assertSame('plural 0', $return); $return = __dn('testing', 'single', 'plural {number}', 2); $this->assertSame('plural 2', $return); $return = __dn('testing', 'single {color}', 'plural {number} {color}', 1, array('color' => 'blue')); $this->assertSame('single blue', $return); $return = __dn('testing', 'single {color}', 'plural {number} {color}', 0, array('color' => 'blue')); $this->assertSame('plural 0 blue', $return); $return = __dn('testing', 'single {color}', 'plural {number} {color}', 2, array('color' => 'blue')); $this->assertSame('plural 2 blue', $return); }
/** * Returns either a relative or a formatted absolute date depending * on the difference between the current time and given datetime. * $datetime should be in a *strtotime* - parsable format, like MySQL's datetime datatype. * * ### Options: * * - `format` => a fall back format if the relative time is longer than the duration specified by end * - `accuracy` => Specifies how accurate the date should be described (array) * - year => The format if years > 0 (default "day") * - month => The format if months > 0 (default "day") * - week => The format if weeks > 0 (default "day") * - day => The format if weeks > 0 (default "hour") * - hour => The format if hours > 0 (default "minute") * - minute => The format if minutes > 0 (default "minute") * - second => The format if seconds > 0 (default "second") * - `end` => The end of relative time telling * - `relativeString` => The printf compatible string when outputting past relative time * - `relativeStringFuture` => The printf compatible string when outputting future relative time * - `absoluteString` => The printf compatible string when outputting absolute time * - `userOffset` => Users offset from GMT (in hours) *Deprecated* use timezone instead. * - `timezone` => The user timezone the timestamp should be formatted in. * * Relative dates look something like this: * * - 3 weeks, 4 days ago * - 15 seconds ago * * Default date formatting is d/m/yy e.g: on 18/2/09 * * The returned string includes 'ago' or 'on' and assumes you'll properly add a word * like 'Posted ' before the function output. * * NOTE: If the difference is one week or more, the lowest level of accuracy is day * * @param int|string|DateTime $dateTime Datetime UNIX timestamp, strtotime() valid string or DateTime object * @param array $options Default format if timestamp is used in $dateString * * @return string Relative time string. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::timeAgoInWords */ public static function timeAgoInWords($dateTime, $options = array()) { $timezone = NULL; $accuracies = static::$wordAccuracy; $format = static::$wordFormat; $relativeEnd = static::$wordEnd; $relativeStringPast = __d('cake', '%s ago'); $relativeStringFuture = __d('cake', 'in %s'); $absoluteString = __d('cake', 'on %s'); if (is_string($options)) { $format = $options; } elseif (!empty($options)) { if (isset($options['timezone'])) { $timezone = $options['timezone']; } elseif (isset($options['userOffset'])) { $timezone = $options['userOffset']; } if (isset($options['accuracy'])) { if (is_array($options['accuracy'])) { $accuracies = array_merge($accuracies, $options['accuracy']); } else { foreach ($accuracies as $key => $level) { $accuracies[$key] = $options['accuracy']; } } } if (isset($options['format'])) { $format = $options['format']; } if (isset($options['end'])) { $relativeEnd = $options['end']; } if (isset($options['relativeString'])) { $relativeStringPast = $options['relativeString']; unset($options['relativeString']); } if (isset($options['relativeStringFuture'])) { $relativeStringFuture = $options['relativeStringFuture']; unset($options['relativeStringFuture']); } if (isset($options['absoluteString'])) { $absoluteString = $options['absoluteString']; unset($options['absoluteString']); } unset($options['end'], $options['format']); } $now = static::fromString(time(), $timezone); $inSeconds = static::fromString($dateTime, $timezone); $isFuture = $inSeconds > $now; if ($isFuture) { $startTime = $now; $endTime = $inSeconds; } else { $startTime = $inSeconds; $endTime = $now; } $diff = $endTime - $startTime; if ($diff === 0) { return __d('cake', 'just now', 'just now'); } $isAbsoluteDate = $diff > abs($now - static::fromString($relativeEnd)); if ($isAbsoluteDate) { if (strpos($format, '%') === FALSE) { $date = date($format, $inSeconds); } else { $date = static::_strftime($format, $inSeconds); } return sprintf($absoluteString, $date); } $years = $months = $weeks = $days = $hours = $minutes = $seconds = 0; // If more than a week, then take into account the length of months if ($diff >= 604800) { list($future['H'], $future['i'], $future['s'], $future['d'], $future['m'], $future['Y']) = explode('/', date('H/i/s/d/m/Y', $endTime)); list($past['H'], $past['i'], $past['s'], $past['d'], $past['m'], $past['Y']) = explode('/', date('H/i/s/d/m/Y', $startTime)); $years = $future['Y'] - $past['Y']; $months = $future['m'] + (12 * $years - $past['m']); if ($months >= 12) { $years = floor($months / 12); $months = $months - $years * 12; } if ($future['m'] < $past['m'] && $future['Y'] - $past['Y'] === 1) { $years--; } if ($future['d'] >= $past['d']) { $days = $future['d'] - $past['d']; } else { $daysInPastMonth = date('t', $startTime); $daysInFutureMonth = date('t', mktime(0, 0, 0, $future['m'] - 1, 1, $future['Y'])); if ($isFuture) { $days = $daysInFutureMonth - $past['d'] + $future['d']; } else { $days = $daysInPastMonth - $past['d'] + $future['d']; } if ($future['m'] != $past['m']) { $months--; } } if (!$months && $years >= 1 && $diff < $years * 31536000) { $months = 11; $years--; } if ($months >= 12) { $years = $years + 1; $months = $months - 12; } if ($days >= 7) { $weeks = floor($days / 7); $days = $days - $weeks * 7; } } else { $days = floor($diff / 86400); $diff = $diff - $days * 86400; $hours = floor($diff / 3600); $diff = $diff - $hours * 3600; $minutes = floor($diff / 60); $diff = $diff - $minutes * 60; $seconds = $diff; } $accuracy = $accuracies['second']; if ($years > 0) { $accuracy = $accuracies['year']; } elseif (abs($months) > 0) { $accuracy = $accuracies['month']; } elseif (abs($weeks) > 0) { $accuracy = $accuracies['week']; } elseif (abs($days) > 0) { $accuracy = $accuracies['day']; } elseif (abs($hours) > 0) { $accuracy = $accuracies['hour']; } elseif (abs($minutes) > 0) { $accuracy = $accuracies['minute']; } $accuracyNum = str_replace(array('year', 'month', 'week', 'day', 'hour', 'minute', 'second'), array(1, 2, 3, 4, 5, 6, 7), $accuracy); $relativeDate = array(); if ($accuracyNum >= 1 && $years > 0) { $relativeDate[] = __dn('cake', '%d year', '%d years', $years, $years); } if ($accuracyNum >= 2 && $months > 0) { $relativeDate[] = __dn('cake', '%d month', '%d months', $months, $months); } if ($accuracyNum >= 3 && $weeks > 0) { $relativeDate[] = __dn('cake', '%d week', '%d weeks', $weeks, $weeks); } if ($accuracyNum >= 4 && $days > 0) { $relativeDate[] = __dn('cake', '%d day', '%d days', $days, $days); } if ($accuracyNum >= 5 && $hours > 0) { $relativeDate[] = __dn('cake', '%d hour', '%d hours', $hours, $hours); } if ($accuracyNum >= 6 && $minutes > 0) { $relativeDate[] = __dn('cake', '%d minute', '%d minutes', $minutes, $minutes); } if ($accuracyNum >= 7 && $seconds > 0) { $relativeDate[] = __dn('cake', '%d second', '%d seconds', $seconds, $seconds); } $relativeDate = implode(', ', $relativeDate); if ($relativeDate) { $relativeString = $isFuture ? $relativeStringFuture : $relativeStringPast; return sprintf($relativeString, $relativeDate); } if ($isFuture) { $strings = array('second' => __d('cake', 'in about a second'), 'minute' => __d('cake', 'in about a minute'), 'hour' => __d('cake', 'in about an hour'), 'day' => __d('cake', 'in about a day'), 'week' => __d('cake', 'in about a week'), 'year' => __d('cake', 'in about a year')); } else { $strings = array('second' => __d('cake', 'about a second ago'), 'minute' => __d('cake', 'about a minute ago'), 'hour' => __d('cake', 'about an hour ago'), 'day' => __d('cake', 'about a day ago'), 'week' => __d('cake', 'about a week ago'), 'year' => __d('cake', 'about a year ago')); } return $strings[$accuracy]; }
/** * Tests the __dn() function * * @return void */ public function testBasicDomainPluralFunction() { I18n::translator('custom', 'en_US', function () { $package = new Package('default'); $package->setMessages(['Cow' => 'Le Moo', 'Cows' => ['Le Moo', 'Les Moos']]); return $package; }); $this->assertEquals('Le Moo', __dn('custom', 'Cow', 'Cows', 1)); $this->assertEquals('Les Moos', __dn('custom', 'Cow', 'Cows', 2)); }
/** * Plural method * * @access private * @return void */ function __domainPlural($domain = 'test_plugin') { $plurals = array(); for ($number = 0; $number <= 25; $number++) { $plurals[] = sprintf(__dn($domain, '%d = 1', '%d = 0 or > 1', (float)$number, true), (float)$number ); } return $plurals; }
/** * Translates different type of strings depending on the number of arguments it is passed and their types. Supports: * * - all of `__()`, `__n()`, `__d()`, `__dn()` * - placeholders for `String::insert()` * * Examples: * * - __t('Hello world!') * - __t('Hello :name!', array('name' => 'world')) * - __t('Hello mate!', 'Hello mates!', 2) * - __t(':salutation mate!', ':salutation mates!', 2, array('salutation' => 'Hello')) * - __t('myapp', 'Hello world!') * - __t('myapp', 'Hello :name!', array('name' => 'world')) * - __t('myapp', 'Hello mate!', 'Hello mates!', 2) * - __t('myapp', ':salutation mate!', ':salutation mates!', 2, array('salutation' => 'Hello')) * * @return string */ function __t() { $args = func_get_args(); $data = $options = array(); switch (count($args)) { case 1: return __($args[0]); break; case 2: if (is_array($args[1])) { $result = __($args[0]); $data = $args[1]; } else { if (is_string($args[1])) { return __d($args[0], $args[1]); } } break; case 3: if (is_array($args[2])) { $result = __d($args[0], $args[1]); $data = $args[2]; } else { if (is_numeric($args[2])) { return __n($args[0], $args[1], $args[2]); } } break; case 4: if (is_array($args[2]) && is_array($args[3])) { $result = __d($args[0], $args[1]); $data = $args[2]; $options = $args[3]; } else { if (is_numeric($args[2]) && is_array($args[3])) { $result = __n($args[0], $args[1], $args[2]); $data = $args[3]; } else { if (is_string($args[2]) && is_numeric($args[3])) { return __dn($args[0], $args[1], $args[2], $args[3]); } } } break; } if (empty($data)) { return $result; } return String::insert($result, $data, $options); }
/** * Display usefull stats about the workers. * * Note: The workers status is conveniently stored by ResqueStatus. * * @return void * @see ResqueStatus\ResqueStatus::isSchedulerWorker() * @see ResqueStatus\ResqueStatus::getPausedWorker() */ public function stats() { $ResqueStatus = $this->ResqueStatus; $workers = CakeResque::getWorkers(); // List of all queues $queues = array_unique(CakeResque::getQueues()); // List of queues monitored by a worker $activeQueues = []; foreach ($workers as $worker) { $workerParams = explode(':', $worker); $activeQueues = array_merge($activeQueues, explode(',', array_pop($workerParams))); } $this->out("\n"); $this->out('<info>' . __d('cake_resque', 'Resque Statistics') . '</info>'); $this->hr(); $this->out("\n"); $this->out('<info>' . __d('cake_resque', 'Jobs Stats') . '</info>'); $this->out(' ' . __d('cake_resque', 'Processed Jobs : {0}', number_format(Resque_Stat::get('processed')))); $this->out(' <warning>' . __d('cake_resque', 'Failed Jobs : {0}', number_format(Resque_Stat::get('failed'))) . '</warning>'); if (Configure::read('CakeResque.Scheduler.enabled') === true) { $this->out(' ' . __d('cake_resque', 'Scheduled Jobs : {0}', number_format(Stat::get()))); } $this->out("\n"); $count = []; $this->out('<info>' . __d('cake_resque', 'Queues Stats') . '</info>'); for ($i = count($queues) - 1; $i >= 0; --$i) { $count[$queues[$i]] = CakeResque::getQueueSize($queues[$i]); if (!in_array($queues[$i], $activeQueues) && $count[$queues[$i]] == 0) { unset($queues[$i]); } } $this->out(' ' . __d('cake_resque', 'Queues count : {0}', count($queues))); foreach ($queues as $queue) { $this->out(sprintf("\t- %-15s : %12s %s", $queue, number_format($count[$queue]), __dn('cake_resque', 'pending job', 'pending jobs', $count[$queue]) . (!in_array($queue, $activeQueues) ? " <error>(unmonitored queue)</error>" : ''))); } $this->out("\n"); $this->out('<info>' . __d('cake_resque', 'Workers Stats') . '</info>'); $this->out(' ' . __d('cake_resque', 'Workers count : {0}', count($workers))); $pausedWorkers = $ResqueStatus->getPausedWorker(); $schedulerWorkers = []; if (!empty($workers)) { $this->out("\t<info>" . strtoupper(__d('cake_resque', 'regular workers')) . "</info>"); foreach ($workers as $worker) { if (Configure::read('CakeResque.Scheduler.enabled') === true && $ResqueStatus->isSchedulerWorker($worker)) { $schedulerWorkers[] = $worker; continue; } $this->out("\t* <bold>" . (string) $worker . '</bold>' . (in_array((string) $worker, $pausedWorkers) ? ' <warning>(' . __d('cake_resque', 'paused') . ')</warning>' : '')); $this->out("\t - " . __d('cake_resque', 'Started on') . " : " . CakeResque::getWorkerStartDate($worker)); $this->out("\t - " . __d('cake_resque', 'Processed Jobs') . " : " . $worker->getStat('processed')); $worker->getStat('failed') == 0 ? $this->out("\t - " . __d('cake_resque', 'Failed Jobs') . " : " . $worker->getStat('failed')) : $this->out("\t - <warning>" . __d('cake_resque', 'Failed Jobs') . " : " . $worker->getStat('failed') . "</warning>"); } } $this->out("\n"); if (!empty($schedulerWorkers)) { $this->out("\t<info>" . strtoupper(__d('cake_resque', 'scheduler worker')) . "</info>" . (in_array((string) $schedulerWorkers[0], $pausedWorkers) ? ' <warning>(' . __d('cake_resque', 'paused') . ')</warning>' : '')); foreach ($schedulerWorkers as $worker) { $schedulerWorker = new ResqueScheduler(); $delayedJobCount = $schedulerWorker->getDelayedQueueScheduleSize(); $this->out("\t - " . __d('cake_resque', 'Started on') . " : " . CakeResque::getWorkerStartDate($worker)); $this->out("\t - " . __d('cake_resque', 'Delayed Jobs') . " : " . $delayedJobCount); if ($delayedJobCount > 0) { $this->out("\t - " . __d('cake_resque', 'Next Job on') . " : " . strftime('%a %b %d %H:%M:%S %Z %Y', $schedulerWorker->nextDelayedTimestamp())); } } $this->out("\n"); } elseif (Configure::read('CakeResque.Scheduler.enabled') === true) { $jobsCount = ResqueScheduler::getDelayedQueueScheduleSize(); if ($jobsCount > 0) { $this->out("\t<error>************ " . __d('cake_resque', 'Alert') . " ************</error>"); $this->out("\t<bold>" . __d('cake_resque', 'The Scheduler Worker is not running') . "</bold>"); $this->out("\t" . __d('cake_resque', 'But there is still <bold>{0}</bold> scheduled jobs left in its queue', $jobsCount)); $this->out("\t<error>********************************</error>"); $this->out("\n"); } } }
/** * Returns either a relative date or a formatted date depending * on the difference between the current time and given datetime. * $datetime should be in a *strtotime* - parsable format, like MySQL's datetime datatype. * * ### Options: * * - `format` => a fall back format if the relative time is longer than the duration specified by end * - `accuracy` => Specifies how accurate the date should be described (array) * - year => The format if years > 0 (default "day") * - month => The format if months > 0 (default "day") * - week => The format if weeks > 0 (default "day") * - day => The format if weeks > 0 (default "hour") * - hour => The format if hours > 0 (default "minute") * - minute => The format if minutes > 0 (default "minute") * - second => The format if seconds > 0 (default "second") * - `end` => The end of relative time telling * - `userOffset` => Users offset from GMT (in hours) *Deprecated* use timezone intead. * - `timezone` => The user timezone the timestamp should be formatted in. * * Relative dates look something like this: * * - 3 weeks, 4 days ago * - 15 seconds ago * * Default date formatting is d/m/yy e.g: on 18/2/09 * * The returned string includes 'ago' or 'on' and assumes you'll properly add a word * like 'Posted ' before the function output. * * NOTE: If the difference is one week or more, the lowest level of accuracy is day * * @param integer|string|DateTime $dateTime Datetime UNIX timestamp, strtotime() valid string or DateTime object * @param array $options Default format if timestamp is used in $dateString * @return string Relative time string. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting */ public static function timeAgoInWords($dateTime, $options = array()) { $timezone = null; $format = self::$wordFormat; $end = self::$wordEnd; $accuracy = self::$wordAccuracy; if (is_array($options)) { if (isset($options['timezone'])) { $timezone = $options['timezone']; } elseif (isset($options['userOffset'])) { $timezone = $options['userOffset']; } if (isset($options['accuracy'])) { if (is_array($options['accuracy'])) { $accuracy = array_merge($accuracy, $options['accuracy']); } else { foreach ($accuracy as $key => $level) { $accuracy[$key] = $options['accuracy']; } } } if (isset($options['format'])) { $format = $options['format']; } if (isset($options['end'])) { $end = $options['end']; } unset($options['end'], $options['format']); } else { $format = $options; } $now = self::fromString(time(), $timezone); $inSeconds = self::fromString($dateTime, $timezone); $backwards = $inSeconds > $now; $futureTime = $now; $pastTime = $inSeconds; if ($backwards) { $futureTime = $inSeconds; $pastTime = $now; } $diff = $futureTime - $pastTime; // If more than a week, then take into account the length of months if ($diff >= 604800) { list($future['H'], $future['i'], $future['s'], $future['d'], $future['m'], $future['Y']) = explode('/', date('H/i/s/d/m/Y', $futureTime)); list($past['H'], $past['i'], $past['s'], $past['d'], $past['m'], $past['Y']) = explode('/', date('H/i/s/d/m/Y', $pastTime)); $years = $months = $weeks = $days = $hours = $minutes = $seconds = 0; $years = $future['Y'] - $past['Y']; $months = $future['m'] + (12 * $years - $past['m']); if ($months >= 12) { $years = floor($months / 12); $months = $months - $years * 12; } if ($future['m'] < $past['m'] && $future['Y'] - $past['Y'] === 1) { $years--; } if ($future['d'] >= $past['d']) { $days = $future['d'] - $past['d']; } else { $daysInPastMonth = date('t', $pastTime); $daysInFutureMonth = date('t', mktime(0, 0, 0, $future['m'] - 1, 1, $future['Y'])); if (!$backwards) { $days = $daysInPastMonth - $past['d'] + $future['d']; } else { $days = $daysInFutureMonth - $past['d'] + $future['d']; } if ($future['m'] != $past['m']) { $months--; } } if (!$months && $years >= 1 && $diff < $years * 31536000) { $months = 11; $years--; } if ($months >= 12) { $years = $years + 1; $months = $months - 12; } if ($days >= 7) { $weeks = floor($days / 7); $days = $days - $weeks * 7; } } else { $years = $months = $weeks = 0; $days = floor($diff / 86400); $diff = $diff - $days * 86400; $hours = floor($diff / 3600); $diff = $diff - $hours * 3600; $minutes = floor($diff / 60); $diff = $diff - $minutes * 60; $seconds = $diff; } $diff = $futureTime - $pastTime; if (!$diff) { return __d('cake', 'just now', 'just now'); } if ($diff > abs($now - self::fromString($end))) { return __d('cake', 'on %s', date($format, $inSeconds)); } $fWord = $accuracy['second']; if ($years > 0) { $fWord = $accuracy['year']; } elseif (abs($months) > 0) { $fWord = $accuracy['month']; } elseif (abs($weeks) > 0) { $fWord = $accuracy['week']; } elseif (abs($days) > 0) { $fWord = $accuracy['day']; } elseif (abs($hours) > 0) { $fWord = $accuracy['hour']; } elseif (abs($minutes) > 0) { $fWord = $accuracy['minute']; } $fNum = str_replace(array('year', 'month', 'week', 'day', 'hour', 'minute', 'second'), array(1, 2, 3, 4, 5, 6, 7), $fWord); $relativeDate = ''; if ($fNum >= 1 && $years > 0) { $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d year', '%d years', $years, $years); } if ($fNum >= 2 && $months > 0) { $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d month', '%d months', $months, $months); } if ($fNum >= 3 && $weeks > 0) { $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d week', '%d weeks', $weeks, $weeks); } if ($fNum >= 4 && $days > 0) { $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d day', '%d days', $days, $days); } if ($fNum >= 5 && $hours > 0) { $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d hour', '%d hours', $hours, $hours); } if ($fNum >= 6 && $minutes > 0) { $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d minute', '%d minutes', $minutes, $minutes); } if ($fNum >= 7 && $seconds > 0) { $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d second', '%d seconds', $seconds, $seconds); } $aboutAgo = array('second' => __d('cake', 'about a second ago'), 'minute' => __d('cake', 'about a minute ago'), 'hour' => __d('cake', 'about an hour ago'), 'day' => __d('cake', 'about a day ago'), 'week' => __d('cake', 'about a week ago'), 'year' => __d('cake', 'about a year ago')); $aboutIn = array('second' => __d('cake', 'in about a second'), 'minute' => __d('cake', 'in about a minute'), 'hour' => __d('cake', 'in about an hour'), 'day' => __d('cake', 'in about a day'), 'week' => __d('cake', 'in about a week'), 'year' => __d('cake', 'in about a year')); // When time has passed if (!$backwards) { if ($relativeDate) { return __d('cake', '%s ago', $relativeDate); } return $aboutAgo[$fWord]; } // When time is to come if (!$relativeDate) { return $aboutIn[$fWord]; } return $relativeDate; }
* @modifiedby $LastChangedBy: phpnut $ * @lastmodified $Date: 2007-05-25 05:54:16 $ * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ /** * Only used when -debug option */ return null; $singularReturn = __('Singular string return __()', true); $singularEcho = __('Singular string echo __()'); $pluralReturn = __n('% apple in the bowl (plural string return __n())', '% apples in the blowl (plural string 2 return __n())', 3, true); $pluralEcho = __n('% apple in the bowl (plural string 2 echo __n())', '% apples in the blowl (plural string 2 echo __n()', 3); $singularDomainReturn = __d('controllers', 'Singular string domain lookup return __d()', true); $singularDomainEcho = __d('controllers', 'Singular string domain lookup echo __d()'); $pluralDomainReturn = __dn('controllers', '% pears in the bowl (plural string domain lookup return __dn())', '% pears in the blowl (plural string domain lookup return __dn())', 3, true); $pluralDomainEcho = __dn('controllers', '% pears in the bowl (plural string domain lookup echo __dn())', '% pears in the blowl (plural string domain lookup echo __dn())', 3); $singularDomainCategoryReturn = __dc('controllers', 'Singular string domain and category lookup return __dc()', 5, true); $singularDomainCategoryEcho = __dc('controllers', 'Singular string domain and category lookup echo __dc()', 5); $pluralDomainCategoryReturn = __dcn('controllers', '% apple in the bowl (plural string 1 domain and category lookup return __dcn())', '% apples in the blowl (plural string 2 domain and category lookup return __dcn())', 3, 5, true); $pluralDomainCategoryEcho = __dcn('controllers', '% apple in the bowl (plural string 1 domain and category lookup echo __dcn())', '% apples in the blowl (plural string 2 domain and category lookup echo __dcn())', 3, 5); $categoryReturn = __c('Category string lookup line return __c()', 5, true); $categoryEcho = __c('Category string lookup line echo __c()', 5); /** * Language string extractor * * @package cake * @subpackage cake.cake.console.libs */ class ExtractShell extends Shell { var $path = null;
/** * test __dn() * * @access public * @return void */ function test__dn() { Configure::write('Config.language', 'rule_1_po'); $result = __dn('default', '%d = 1', '%d = 0 or > 1', 0, true); $expected = '%d = 0 or > 1 (translated)'; $this->assertEqual($result, $expected); $result = __dn('core', '%d = 1', '%d = 0 or > 1', 0, true); $expected = '%d = 0 or > 1'; $this->assertEqual($result, $expected); $result = __dn('core', '%d = 1 (from core)', '%d = 0 or > 1 (from core)', 0, true); $expected = '%d = 0 or > 1 (from core translated)'; $this->assertEqual($result, $expected); $result = __dn('default', '%d = 1', '%d = 0 or > 1', 1, true); $expected = '%d = 1 (translated)'; $this->assertEqual($result, $expected); ob_start(); __dn('core', '%d = 1 (from core)', '%d = 0 or > 1 (from core)', 2); $result = ob_get_clean(); $expected = '%d = 0 or > 1 (from core translated)'; $this->assertEqual($result, $expected); }
/** * test __dn() * * @return void */ public function testTranslateDomainPlural() { Configure::write('Config.language', 'rule_1_po'); $result = __dn('default', '%d = 1', '%d = 0 or > 1', 0); $expected = '%d = 0 or > 1 (translated)'; $this->assertEquals($expected, $result); $result = __dn('core', '%d = 1', '%d = 0 or > 1', 0); $expected = '%d = 0 or > 1'; $this->assertEquals($expected, $result); $result = __dn('core', '%d = 1 (from core)', '%d = 0 or > 1 (from core)', 0); $expected = '%d = 0 or > 1 (from core translated)'; $this->assertEquals($expected, $result); $result = __dn('default', '%d = 1', '%d = 0 or > 1', 1); $expected = '%d = 1 (translated)'; $this->assertEquals($expected, $result); $result = __dn('core', '%d item.', '%d items.', 1, 1); $expected = '1 item.'; $this->assertEquals($expected, $result); $result = __dn('core', '%d item for id %s', '%d items for id %s', 2, 2, '1234'); $expected = '2 items for id 1234'; $this->assertEquals($expected, $result); $result = __dn('core', '%d item for id %s', '%d items for id %s', 2, array(2, '1234')); $expected = '2 items for id 1234'; $this->assertEquals($expected, $result); }
/** * Run a queue worker loop. * * Runs a queue worker process which will try to find unassigned tasks in the queue * which it may run and try to fetch and execute them. * * @return void */ public function runworker() { // Enable garbage collector (PHP >= 5.3) if (function_exists('gc_enable')) { gc_enable(); } // Register signal handler(s) if possible if (function_exists('pcntl_signal')) { pcntl_signal(SIGTERM, [$this, 'signalHandler']); pcntl_signal(SIGINT, [$this, 'signalHandler']); } else { $this->err(__d('queue', 'Signal handler(s) could not be registered.')); } $this->__exit = false; $workerStartTime = time(); while (!$this->__exit) { $this->out(__d('queue', 'Looking for a job.'), 1, Shell::VERBOSE); $data = $this->QueuedTask->requestJob($this->_getTaskConf()); if ($this->QueuedTask->exit === true) { $this->__exit = true; } else { if ($data !== false) { $jobId = $data['id']; $taskname = 'Queue' . $data['task']; $this->out(__d('queue', 'Running job of task \'%s\' \'%d\'.', $data['task'], $jobId)); $taskStartTime = time(); $return = $this->{$taskname}->run(unserialize($data['data'])); $took = time() - $taskStartTime; if ($return) { $this->QueuedTask->markJobDone($jobId); $this->out(__d('queue', 'Job \'%d\' finished (took %s).', $jobId, __dn('queue', '%d second', '%d seconds', $took, $took))); } else { $failureMessage = null; if (isset($this->{$taskname}->failureMessage) && !empty($this->{$taskname}->failureMessage)) { $failureMessage = $this->{$taskname}->failureMessage; } $this->QueuedTask->markJobFailed($jobId, $failureMessage); $this->out(__d('queue', 'Job \'%d\' did not finish, requeued.', $jobId)); } } elseif (Configure::read('Queue.exitWhenNothingToDo')) { $this->out(__d('queue', 'Nothing to do, exiting.')); $this->__exit = true; } else { $this->out(__d('queue', 'Nothing to do, sleeping for %d second(s).', Configure::read('Queue.sleepTime')), 1, Shell::VERBOSE); sleep(Configure::read('Queue.sleepTime')); } // Check if we are over the maximum runtime and end processing if so. if (Configure::read('Queue.workerMaxRuntime') != 0 && time() - $workerStartTime >= Configure::read('Queue.workerMaxRuntime')) { $this->__exit = true; $this->out(__d('queue', 'Reached runtime of %s seconds (max. %s), terminating.', time() - $workerStartTime, Configure::read('Queue.workerMaxRuntime'))); } if ($this->__exit || rand(0, 100) > 100 - Configure::read('Queue.gcprop')) { $this->out(__d('queue', 'Performing old job cleanup.')); $this->QueuedTask->cleanOldJobs($this->_getTaskConf()); } } } }
/** * Plural method * * @return void */ protected function _domainPlural($domain = 'test_plugin') { $plurals = array(); for ($number = 0; $number <= 25; $number++) { $plurals[] = sprintf(__dn($domain, '%d = 1', '%d = 0 or > 1', (double) $number), (double) $number); } return $plurals; }
/** * Returns either a relative or a formatted absolute date depending * on the difference between the current time and this object. * * ### Options: * * - `from` => another Time object representing the "now" time * - `format` => a fall back format if the relative time is longer than the duration specified by end * - `accuracy` => Specifies how accurate the date should be described (array) * - year => The format if years > 0 (default "day") * - month => The format if months > 0 (default "day") * - week => The format if weeks > 0 (default "day") * - day => The format if weeks > 0 (default "hour") * - hour => The format if hours > 0 (default "minute") * - minute => The format if minutes > 0 (default "minute") * - second => The format if seconds > 0 (default "second") * - `end` => The end of relative time telling * - `relativeString` => The printf compatible string when outputting relative time * - `absoluteString` => The printf compatible string when outputting absolute time * - `timezone` => The user timezone the timestamp should be formatted in. * * Relative dates look something like this: * * - 3 weeks, 4 days ago * - 15 seconds ago * * Default date formatting is d/M/YY e.g: on 18/2/09. Formatting is done internally using * `i18nFormat`, see the method for the valid formatting strings * * The returned string includes 'ago' or 'on' and assumes you'll properly add a word * like 'Posted ' before the function output. * * NOTE: If the difference is one week or more, the lowest level of accuracy is day * * @param array $options Array of options. * @return string Relative time string. */ public function timeAgoInWords(array $options = []) { $time = $this; $timezone = null; $format = static::$wordFormat; $end = static::$wordEnd; $relativeString = __d('cake', '%s ago'); $absoluteString = __d('cake', 'on %s'); $accuracy = static::$wordAccuracy; $from = static::now(); $opts = ['timezone', 'format', 'end', 'relativeString', 'absoluteString', 'from']; foreach ($opts as $option) { if (isset($options[$option])) { ${$option} = $options[$option]; unset($options[$option]); } } if (isset($options['accuracy'])) { if (is_array($options['accuracy'])) { $accuracy = $options['accuracy'] + $accuracy; } else { foreach ($accuracy as $key => $level) { $accuracy[$key] = $options['accuracy']; } } } if ($timezone) { $time = clone $this; $time->timezone($timezone); } $now = $from->format('U'); $inSeconds = $time->format('U'); $backwards = $inSeconds > $now; $futureTime = $now; $pastTime = $inSeconds; if ($backwards) { $futureTime = $inSeconds; $pastTime = $now; } $diff = $futureTime - $pastTime; if (!$diff) { return __d('cake', 'just now', 'just now'); } if ($diff > abs($now - (new static($end))->format('U'))) { return sprintf($absoluteString, $time->i18nFormat($format)); } // If more than a week, then take into account the length of months if ($diff >= 604800) { list($future['H'], $future['i'], $future['s'], $future['d'], $future['m'], $future['Y']) = explode('/', date('H/i/s/d/m/Y', $futureTime)); list($past['H'], $past['i'], $past['s'], $past['d'], $past['m'], $past['Y']) = explode('/', date('H/i/s/d/m/Y', $pastTime)); $weeks = $days = $hours = $minutes = $seconds = 0; $years = $future['Y'] - $past['Y']; $months = $future['m'] + (12 * $years - $past['m']); if ($months >= 12) { $years = floor($months / 12); $months = $months - $years * 12; } if ($future['m'] < $past['m'] && $future['Y'] - $past['Y'] === 1) { $years--; } if ($future['d'] >= $past['d']) { $days = $future['d'] - $past['d']; } else { $daysInPastMonth = date('t', $pastTime); $daysInFutureMonth = date('t', mktime(0, 0, 0, $future['m'] - 1, 1, $future['Y'])); if (!$backwards) { $days = $daysInPastMonth - $past['d'] + $future['d']; } else { $days = $daysInFutureMonth - $past['d'] + $future['d']; } if ($future['m'] != $past['m']) { $months--; } } if (!$months && $years >= 1 && $diff < $years * 31536000) { $months = 11; $years--; } if ($months >= 12) { $years = $years + 1; $months = $months - 12; } if ($days >= 7) { $weeks = floor($days / 7); $days = $days - $weeks * 7; } } else { $years = $months = $weeks = 0; $days = floor($diff / 86400); $diff = $diff - $days * 86400; $hours = floor($diff / 3600); $diff = $diff - $hours * 3600; $minutes = floor($diff / 60); $diff = $diff - $minutes * 60; $seconds = $diff; } $fWord = $accuracy['second']; if ($years > 0) { $fWord = $accuracy['year']; } elseif (abs($months) > 0) { $fWord = $accuracy['month']; } elseif (abs($weeks) > 0) { $fWord = $accuracy['week']; } elseif (abs($days) > 0) { $fWord = $accuracy['day']; } elseif (abs($hours) > 0) { $fWord = $accuracy['hour']; } elseif (abs($minutes) > 0) { $fWord = $accuracy['minute']; } $fNum = str_replace(['year', 'month', 'week', 'day', 'hour', 'minute', 'second'], [1, 2, 3, 4, 5, 6, 7], $fWord); $relativeDate = ''; if ($fNum >= 1 && $years > 0) { $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '{0} year', '{0} years', $years, $years); } if ($fNum >= 2 && $months > 0) { $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '{0} month', '{0} months', $months, $months); } if ($fNum >= 3 && $weeks > 0) { $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '{0} week', '{0} weeks', $weeks, $weeks); } if ($fNum >= 4 && $days > 0) { $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '{0} day', '{0} days', $days, $days); } if ($fNum >= 5 && $hours > 0) { $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '{0} hour', '{0} hours', $hours, $hours); } if ($fNum >= 6 && $minutes > 0) { $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '{0} minute', '{0} minutes', $minutes, $minutes); } if ($fNum >= 7 && $seconds > 0) { $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '{0} second', '{0} seconds', $seconds, $seconds); } // When time has passed if (!$backwards && $relativeDate) { return sprintf($relativeString, $relativeDate); } if (!$backwards) { $aboutAgo = ['second' => __d('cake', 'about a second ago'), 'minute' => __d('cake', 'about a minute ago'), 'hour' => __d('cake', 'about an hour ago'), 'day' => __d('cake', 'about a day ago'), 'week' => __d('cake', 'about a week ago'), 'year' => __d('cake', 'about a year ago')]; return $aboutAgo[$fWord]; } // When time is to come if (!$relativeDate) { $aboutIn = ['second' => __d('cake', 'in about a second'), 'minute' => __d('cake', 'in about a minute'), 'hour' => __d('cake', 'in about an hour'), 'day' => __d('cake', 'in about a day'), 'week' => __d('cake', 'in about a week'), 'year' => __d('cake', 'in about a year')]; return $aboutIn[$fWord]; } return $relativeDate; }
/** * Returns either a relative date or a formatted date depending * on the difference between the current time and given datetime. * $datetime should be in a <i>strtotime</i> - parsable format, like MySQL's datetime datatype. * * ### Options: * * - `format` => a fall back format if the relative time is longer than the duration specified by end * - `end` => The end of relative time telling * - `userOffset` => Users offset from GMT (in hours) * * Relative dates look something like this: * 3 weeks, 4 days ago * 15 seconds ago * * Default date formatting is d/m/yy e.g: on 18/2/09 * * The returned string includes 'ago' or 'on' and assumes you'll properly add a word * like 'Posted ' before the function output. * * @param string $dateTime Datetime string or Unix timestamp * @param array $options Default format if timestamp is used in $dateString * @return string Relative time string. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting */ public function timeAgoInWords($dateTime, $options = array()) { $userOffset = null; if (is_array($options) && isset($options['userOffset'])) { $userOffset = $options['userOffset']; } $now = time(); if (!is_null($userOffset)) { $now = $this->convert(time(), $userOffset); } $inSeconds = $this->fromString($dateTime, $userOffset); $backwards = $inSeconds > $now; $format = 'j/n/y'; $end = '+1 month'; if (is_array($options)) { if (isset($options['format'])) { $format = $options['format']; unset($options['format']); } if (isset($options['end'])) { $end = $options['end']; unset($options['end']); } } else { $format = $options; } if ($backwards) { $futureTime = $inSeconds; $pastTime = $now; } else { $futureTime = $now; $pastTime = $inSeconds; } $diff = $futureTime - $pastTime; // If more than a week, then take into account the length of months if ($diff >= 604800) { $current = array(); $date = array(); list($future['H'], $future['i'], $future['s'], $future['d'], $future['m'], $future['Y']) = explode('/', date('H/i/s/d/m/Y', $futureTime)); list($past['H'], $past['i'], $past['s'], $past['d'], $past['m'], $past['Y']) = explode('/', date('H/i/s/d/m/Y', $pastTime)); $years = $months = $weeks = $days = $hours = $minutes = $seconds = 0; if ($future['Y'] == $past['Y'] && $future['m'] == $past['m']) { $months = 0; $years = 0; } else { if ($future['Y'] == $past['Y']) { $months = $future['m'] - $past['m']; } else { $years = $future['Y'] - $past['Y']; $months = $future['m'] + (12 * $years - $past['m']); if ($months >= 12) { $years = floor($months / 12); $months = $months - $years * 12; } if ($future['m'] < $past['m'] && $future['Y'] - $past['Y'] == 1) { $years--; } } } if ($future['d'] >= $past['d']) { $days = $future['d'] - $past['d']; } else { $daysInPastMonth = date('t', $pastTime); $daysInFutureMonth = date('t', mktime(0, 0, 0, $future['m'] - 1, 1, $future['Y'])); if (!$backwards) { $days = $daysInPastMonth - $past['d'] + $future['d']; } else { $days = $daysInFutureMonth - $past['d'] + $future['d']; } if ($future['m'] != $past['m']) { $months--; } } if ($months == 0 && $years >= 1 && $diff < $years * 31536000) { $months = 11; $years--; } if ($months >= 12) { $years = $years + 1; $months = $months - 12; } if ($days >= 7) { $weeks = floor($days / 7); $days = $days - $weeks * 7; } } else { $years = $months = $weeks = 0; $days = floor($diff / 86400); $diff = $diff - $days * 86400; $hours = floor($diff / 3600); $diff = $diff - $hours * 3600; $minutes = floor($diff / 60); $diff = $diff - $minutes * 60; $seconds = $diff; } $relativeDate = ''; $diff = $futureTime - $pastTime; if ($diff > abs($now - $this->fromString($end))) { $relativeDate = __d('cake', 'on %s', date($format, $inSeconds)); } else { if ($years > 0) { // years and months and days $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d year', '%d years', $years, $years); $relativeDate .= $months > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d month', '%d months', $months, $months) : ''; $relativeDate .= $weeks > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d week', '%d weeks', $weeks, $weeks) : ''; $relativeDate .= $days > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d day', '%d days', $days, $days) : ''; } elseif (abs($months) > 0) { // months, weeks and days $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d month', '%d months', $months, $months); $relativeDate .= $weeks > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d week', '%d weeks', $weeks, $weeks) : ''; $relativeDate .= $days > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d day', '%d days', $days, $days) : ''; } elseif (abs($weeks) > 0) { // weeks and days $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d week', '%d weeks', $weeks, $weeks); $relativeDate .= $days > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d day', '%d days', $days, $days) : ''; } elseif (abs($days) > 0) { // days and hours $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d day', '%d days', $days, $days); $relativeDate .= $hours > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d hour', '%d hours', $hours, $hours) : ''; } elseif (abs($hours) > 0) { // hours and minutes $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d hour', '%d hours', $hours, $hours); $relativeDate .= $minutes > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d minute', '%d minutes', $minutes, $minutes) : ''; } elseif (abs($minutes) > 0) { // minutes only $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d minute', '%d minutes', $minutes, $minutes); } else { // seconds only $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d second', '%d seconds', $seconds, $seconds); } if (!$backwards) { $relativeDate = __d('cake', '%s ago', $relativeDate); } } return $relativeDate; }
/** * Handle the command. * * @param string $message The message to handle. * * @return array */ protected function _handleCommand($message) { $json = ['hasCmd' => true]; $errorAuthorization = __d('chat', 'You don\'t have the permission to execute this command.'); switch ($this->_parts[0]) { case 'prune': if ($this->Chat->hasPermission(['action' => 'canPrune']) === false) { $json['error'] = true; $json['message'] = $errorAuthorization; return $json; } //Delete all messages. $this->_controller->loadModel('ChatMessages'); $this->_controller->ChatMessages->deleteAll(['1 = 1']); //Create a new message to display who has deleted all the messages. $this->_controller->loadModel('Users'); $user = $this->_controller->Users->find()->contain(['Groups' => function ($q) { return $q->select(['id', 'name', 'css', 'is_staff', 'is_member']); }])->where(['Users.id' => $this->_controller->Auth->user('id')])->select(['Users.id', 'Users.group_id', 'Users.username', 'Users.slug', 'Users.end_subscription'])->first(); $data = ['text' => __d('chat', 'The chat has been cleaned by {0}.', $user->username), 'username' => $user->username, 'user_id' => $user->id, 'group_id' => $user->group_id, 'command' => 'prune', 'css' => $user->group_css, 'slug' => $user->slug]; $message = $this->_controller->ChatMessages->newEntity($data); if ($lastMessage = $this->_controller->ChatMessages->save($message)) { $json['error'] = false; $json['command'] = 'prune'; $json['lastMessageId'] = $lastMessage->id; } else { $json['error'] = true; $json['message'] = __d('chat', 'Error while saving the new message after deleting all messages.'); } break; case 'ban': if ($this->Chat->hasPermission(['action' => 'canBan']) === false) { $json['error'] = true; $json['message'] = $errorAuthorization; return $json; } $this->_controller->loadModel('Users'); $userId = (int) $this->_arguments[0]; //Build the condition to find the User. if ($userId != 0) { $conditions = ['Users.id' => $userId]; } else { $conditions = ['LOWER(Users.username)' => strtolower($this->_arguments[0])]; } //Find the User. $user = $this->_controller->Users->find('all', ['conditions' => [$conditions], 'select' => ['Users.id', 'Users.username']])->first(); if (is_null($user)) { $json['error'] = true; $json['hasCmd'] = true; $json['message'] = __d('chat', 'The user "{0}" doesn\'t exist.', $this->_arguments[0]); return $json; } //Check if the user is not already banned. $this->_controller->loadModel('ChatBans'); $userBanned = $this->_controller->ChatBans->find()->where(['ChatBans.user_id' => $user->id])->first(); if (!is_null($userBanned) && ($userBanned->forever === true || $userBanned->end_date > Time::now())) { $json['error'] = true; $json['hasCmd'] = true; $json['message'] = __d('chat', 'The user "{0}" is already banned.', $user->username); return $json; } elseif (!is_null($userBanned)) { $this->_controller->ChatBans->delete($userBanned); } $data = ['banisher_id' => $this->_controller->Auth->user('id'), 'user_id' => $user->id]; $time = (int) $this->_arguments[1]; //If time == 0 then it's a forever. if ($time === 0) { $data += ['forever' => 1]; } else { $now = Time::now(); if ($time === 1) { $now->addMinute(); } else { $now->addMinutes($time); } $data += ['end_date' => $now]; } $reason = explode(chr(32), $message, 4); if (isset($reason[3])) { $data += ['reason' => $reason[3]]; } $ban = $this->_controller->ChatBans->newEntity($data); if ($this->_controller->ChatBans->save($ban)) { $json['error'] = false; $json['command'] = 'ban'; $json['username'] = $user->username; } else { $json['error'] = true; $json['message'] = __d('chat', 'Error while banning the user "{0}".', $user->username); } if (isset($data['forever'])) { $textTime = __d('chat', 'forever'); } else { $textTime = __dn('chat', 'for {0} minute', 'for {0} minutes', $time, $time); } if (isset($data['reason'])) { $textReason = $textTime . '. ' . __d('chat', 'Reason : {0}', h($data['reason'])); } else { $textReason = $textTime . ' ' . __d('chat', 'without reason.'); } //Select the current user to get his information. $currentUser = $this->_controller->Users->find()->contain(['Groups' => function ($q) { return $q->select(['id', 'name', 'css', 'is_staff', 'is_member']); }])->select(['Users.id', 'Users.end_subscription', 'Users.username', 'Users.slug', 'Users.group_id'])->where(['Users.id' => $this->_controller->Auth->user('id')])->first(); //Build the notification. $notify = ['text' => __('I have banned {0} {1}', $user->username, $textReason), 'username' => $currentUser->username, 'user_id' => $currentUser->id, 'command' => 'ban', 'group_id' => $currentUser->group_id, 'css' => $currentUser->group_css, 'slug' => $currentUser->slug]; $this->_controller->loadModel('ChatMessages'); $message = $this->_controller->ChatMessages->newEntity($notify); $this->_controller->ChatMessages->save($message); break; case 'unban': if ($this->Chat->hasPermission(['action' => 'canUnban']) === false) { $json['error'] = true; $json['message'] = $errorAuthorization; return $json; } $this->_controller->loadModel('Users'); $userId = (int) $this->_arguments[0]; //Build the condition to find the User. if ($userId != 0) { $conditions = ['Users.id' => $userId]; } else { $conditions = ['LOWER(Users.username)' => strtolower($this->_arguments[0])]; } //Find the User. $user = $this->_controller->Users->find('all', ['conditions' => [$conditions], 'select' => ['Users.id', 'Users.username']])->first(); if (is_null($user)) { $json['error'] = true; $json['hasCmd'] = true; $json['message'] = __d('chat', 'The user "{0}" doesn\'t exist.', $this->_arguments[0]); return $json; } //Select the User banned. $this->_controller->loadModel('ChatBans'); $userBanned = $this->_controller->ChatBans->find()->where(['ChatBans.user_id' => $user->id])->first(); //Check if the user is banned. if (is_null($userBanned) || $userBanned->end_date < Time::now() && $userBanned->forever === false) { $json['error'] = true; $json['hasCmd'] = true; $json['message'] = __d('chat', 'The user "{0}" is not banned.', $user->username); //Clean the database. if (!is_null($userBanned) && $userBanned->end_date < Time::now()) { $this->_controller->ChatBans->delete($userBanned); } return $json; } elseif (!is_null($userBanned) && ($userBanned->forever === true || $userBanned->end_date > Time::now())) { //The user is banned, we unban him. if ($this->_controller->ChatBans->delete($userBanned)) { $json['error'] = false; $json['command'] = 'unban'; $json['username'] = $user->username; } else { $json['error'] = true; $json['message'] = __d('chat', 'Error while unbanning the user "{0}".', $user->username); } //Select the current user to get his information. $currentUser = $this->_controller->Users->find()->contain(['Groups' => function ($q) { return $q->select(['id', 'name', 'css', 'is_staff', 'is_member']); }])->select(['Users.id', 'Users.end_subscription', 'Users.username', 'Users.slug', 'Users.group_id'])->where(['Users.id' => $this->_controller->Auth->user('id')])->first(); //Build the notification. $notify = ['text' => __d('chat', 'I have unbanned {0}.', $user->username), 'username' => $currentUser->username, 'user_id' => $currentUser->id, 'command' => 'unban', 'group_id' => $currentUser->group_id, 'css' => $currentUser->group_css, 'slug' => $currentUser->slug]; $this->_controller->loadModel('ChatMessages'); $message = $this->_controller->ChatMessages->newEntity($notify); $this->_controller->ChatMessages->save($message); } break; } return $json; }