/** * utf8::str_pad * * @package Core * @author Kohana Team * @copyright (c) 2007 Kohana Team * @copyright (c) 2005 Harry Fuecks * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt */ function _str_pad($str, $final_str_length, $pad_str = ' ', $pad_type = STR_PAD_RIGHT) { if (utf8::is_ascii($str) and utf8::is_ascii($pad_str)) { return str_pad($str, $final_str_length, $pad_str, $pad_type); } $str_length = utf8::strlen($str); if ($final_str_length <= 0 or $final_str_length <= $str_length) { return $str; } $pad_str_length = utf8::strlen($pad_str); $pad_length = $final_str_length - $str_length; if ($pad_type == STR_PAD_RIGHT) { $repeat = ceil($pad_length / $pad_str_length); return utf8::substr($str . str_repeat($pad_str, $repeat), 0, $final_str_length); } if ($pad_type == STR_PAD_LEFT) { $repeat = ceil($pad_length / $pad_str_length); return utf8::substr(str_repeat($pad_str, $repeat), 0, floor($pad_length)) . $str; } if ($pad_type == STR_PAD_BOTH) { $pad_length /= 2; $pad_length_left = floor($pad_length); $pad_length_right = ceil($pad_length); $repeat_left = ceil($pad_length_left / $pad_str_length); $repeat_right = ceil($pad_length_right / $pad_str_length); $pad_left = utf8::substr(str_repeat($pad_str, $repeat_left), 0, $pad_length_left); $pad_right = utf8::substr(str_repeat($pad_str, $repeat_right), 0, $pad_length_left); return $pad_left . $str . $pad_right; } trigger_error('utf8::str_pad: Unknown padding type (' . $type . ')', E_USER_ERROR); }
/** * 2Moons * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @package 2Moons * @author Jan Kröpke <*****@*****.**> * @copyright 2012 Jan Kröpke <*****@*****.**> * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License * @version 1.7.3 (2013-05-19) * @info $Id: CreateOnePlanetRecord.php 2640 2013-03-23 19:23:26Z slaver7 $ * @link http://2moons.cc/ */ function CreateOnePlanetRecord($Galaxy, $System, $Position, $Universe, $PlanetOwnerID, $PlanetName, $HomeWorld = false, $AuthLevel = 0, $Iron, $Gold, $Crystal, $Elyrium, $iPlanetCount) { global $LNG; $CONF = Config::getAll(NULL, $Universe); if (Config::get('max_galaxy') < $Galaxy || 1 > $Galaxy) { throw new Exception("Access denied for CreateOnePlanetRecord.php.<br>Try to create a planet at position:" . $Galaxy . ":" . $System . ":" . $Position); } if (Config::get('max_system') < $System || 1 > $System) { throw new Exception("Access denied for CreateOnePlanetRecord.php.<br>Try to create a planet at position:" . $Galaxy . ":" . $System . ":" . $Position); } if (Config::get('max_planets') < $Position || 1 > $Position) { throw new Exception("Access denied for CreateOnePlanetRecord.php.<br>Try to create a planet at position:" . $Galaxy . ":" . $System . ":" . $Position); } if (CheckPlanetIfExist($Galaxy, $System, $Position, $Universe)) { return false; } $tp = 0; if ($iPlanetCount >= 3) { $tp = 1; } $FieldFactor = Config::get('planet_factor'); require 'includes/PlanetData.php'; $Pos = ceil($Position / (Config::get('max_planets') / count($PlanetData))); $TMax = $PlanetData[$Pos]['temp']; $TMin = $TMax - 40; $Fields = $PlanetData[$Pos]['fields'] * Config::get('planet_factor'); $Types = $PlanetData[$Pos]['image']; $Name = !empty($PlanetName) ? $GLOBALS['DATABASE']->sql_escape($PlanetName) : $LNG['type_planet'][1]; $GLOBALS['DATABASE']->query("INSERT INTO " . PLANETS . " SET\n\t\t\t\tname = '" . $Name . "',\n\t\t\t\tuniverse = " . $Universe . ",\n\t\t\t\tid_owner = " . $PlanetOwnerID . ",\n\t\t\t\tgalaxy = " . $Galaxy . ",\n\t\t\t\tsystem = " . $System . ",\n\t\t\t\tplanet = " . $Position . ",\n\t\t\t\tlast_update = " . TIMESTAMP . ",\n\t\t\t\tplanet_type = '1',\n\t\t\t\tcolo_metal = " . $Iron . ",\n\t\t\t\tcolo_crystal = " . $Gold . ",\n\t\t\t\tcolo_deut = " . $Crystal . ",\n\t\t\t\tcolo_elyrium = " . $Elyrium . ",\n\t\t\t\tteleport_portal = " . $tp . ",\n\t\t\t\timage = '" . $Types . "',\n\t\t\t\tdiameter = " . floor(1000 * sqrt($Fields)) . ",\n\t\t\t\tfield_max = " . ($HomeWorld ? Config::get('initial_fields') : floor($Fields)) . ",\n\t\t\t\ttemp_min = " . $TMin . ",\n\t\t\t\ttemp_max = " . $TMax . ",\n\t\t\t\tmetal = " . Config::get('metal_start') . ",\n\t\t\t\tmetal_perhour = " . Config::get('metal_basic_income') . ",\n\t\t\t\tcrystal = " . Config::get('crystal_start') . ",\n\t\t\t\tcrystal_perhour = " . Config::get('crystal_basic_income') . ",\n\t\t\t\tdeuterium = " . Config::get('deuterium_start') . ",\n\t\t\t\tdeuterium_perhour = " . Config::get('deuterium_basic_income') . ",\n\t\t\t\telyrium = " . Config::get('deuterium_start') . ",\n\t\t\t\telyrium_perhour = " . Config::get('deuterium_basic_income') . ";"); return $GLOBALS['DATABASE']->GetInsertID(); }
public static function getAge($unix_timestamp) { $t = time(); $age = $unix_timestamp < 0 ? $t + $unix_timestamp * -1 : $t - $unix_timestamp; $year = 60 * 60 * 24 * 365; return floor($age / $year); }
function page_navi($before = '', $after = '') { global $wpdb, $wp_query; $request = $wp_query->request; $posts_per_page = intval(get_query_var('posts_per_page')); $paged = intval(get_query_var('paged')); $numposts = $wp_query->found_posts; $max_page = $wp_query->max_num_pages; if ($numposts <= $posts_per_page) { return; } if (empty($paged) || $paged == 0) { $paged = 1; } $pages_to_show = 3; $pages_to_show_minus_1 = $pages_to_show - 1; $half_page_start = floor($pages_to_show_minus_1 / 2); $half_page_end = ceil($pages_to_show_minus_1 / 2); $start_page = $paged - $half_page_start; if ($start_page <= 0) { $start_page = 1; } $end_page = $paged + $half_page_end; if ($end_page - $start_page != $pages_to_show_minus_1) { $end_page = $start_page + $pages_to_show_minus_1; } if ($end_page > $max_page) { $start_page = $max_page - $pages_to_show_minus_1; $end_page = $max_page; } if ($start_page <= 0) { $start_page = 1; } echo $before . '<div class="pagination_wrapper"><ul class="pagination">' . ""; if ($paged > 1) { $first_page_text = "First"; echo '<li class="prev"><a href="' . get_pagenum_link() . '" title="First">' . $first_page_text . '</a></li>'; } $prevposts = get_previous_posts_link('Prev'); if ($prevposts) { echo '<li>' . $prevposts . '</li>'; } else { echo '<li class="disabled"><a href="#">Prev</a></li>'; } for ($i = $start_page; $i <= $end_page; $i++) { if ($i == $paged) { echo '<li class="active"><a href="#">' . $i . '</a></li>'; } else { echo '<li><a href="' . get_pagenum_link($i) . '">' . $i . '</a></li>'; } } if ($end_page < $max_page) { $last_page_text = $max_page; echo '<li class="next"><a href="' . get_pagenum_link($max_page) . '" title="Last">' . $last_page_text . '</a></li>'; } echo '<li class="">'; next_posts_link('Next'); echo '</li>'; echo '</ul></div>' . $after . ""; }
/** * ログを出力する * * @access public * @param int $level ログレベル(LOG_DEBUG, LOG_NOTICE...) * @param string $message ログメッセージ(+引数) */ function log($level, $message) { if ($this->fp == null) { return; } $microtime = microtime(true); $sec = floor($microtime); $msec = floor(($microtime - $sec) * 1000); $prefix = sprintf('%s.%03d %s ', strftime('%Y/%m/%dT%H:%M:%S', $sec), $msec, $this->ident); if (array_key_exists("pid", $this->option)) { $prefix .= sprintf('[%d]', getmypid()); } $prefix .= sprintf('(mem:%s)', number_format(memory_get_usage())); $prefix .= sprintf('(%s): ', $this->_getLogLevelName($level)); if (array_key_exists("function", $this->option) || array_key_exists("pos", $this->option)) { $tmp = ""; $bt = $this->_getBacktrace(); if ($bt && array_key_exists("function", $this->option) && $bt['function']) { $tmp .= $bt['function']; } if ($bt && array_key_exists("pos", $this->option) && $bt['pos']) { $tmp .= $tmp ? sprintf('(%s)', $bt['pos']) : $bt['pos']; } if ($tmp) { $prefix .= $tmp . ": "; } } fwrite($this->fp, $prefix . $message . "\n"); return $prefix . $message; }
/** * Convert a millisecond (or finer) timestamp to a UNIX timestamp * This crude method will work until 2037 * * @param int $time * * @return int */ public static function toSeconds($time) { while ($time > 2147483647) { $time = floor($time / 1000); } return (int) $time; }
/** * Currently, PHP date() function always returns zeros for milliseconds (u) * on Windows. This is a replacement function for date() which correctly * displays milliseconds on all platforms. * * It is slower than PHP date() so it should only be used if necessary. */ private function date($format, $utimestamp) { $timestamp = floor($utimestamp); $ms = floor(($utimestamp - $timestamp) * 1000); $ms = str_pad($ms, 3, '0', STR_PAD_LEFT); return date(preg_replace('`(?<!\\\\)u`', $ms, $format), $timestamp); }
/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $loggingIn = $request->is('api/v1/login') || $request->is('api/v1/register') || $request->is('api/v1/oauth_login'); $headers = Utils::getApiHeaders(); $hasApiSecret = false; if ($secret = env(API_SECRET)) { $requestSecret = Request::header('X-Ninja-Secret') ?: ($request->api_secret ?: ''); $hasApiSecret = hash_equals($requestSecret, $secret); } if ($loggingIn) { // check API secret if (!$hasApiSecret) { sleep(ERROR_DELAY); return Response::json('Invalid value for API_SECRET', 403, $headers); } } else { // check for a valid token $token = AccountToken::where('token', '=', Request::header('X-Ninja-Token'))->first(['id', 'user_id']); // check if user is archived if ($token && $token->user) { Auth::onceUsingId($token->user_id); Session::set('token_id', $token->id); } else { sleep(ERROR_DELAY); return Response::json('Invalid token', 403, $headers); } } if (!Utils::isNinja() && !$loggingIn) { return $next($request); } if (!Utils::hasFeature(FEATURE_API) && !$hasApiSecret) { return Response::json('API requires pro plan', 403, $headers); } else { $key = Auth::check() ? Auth::user()->account->id : $request->getClientIp(); // http://stackoverflow.com/questions/1375501/how-do-i-throttle-my-sites-api-users $hour = 60 * 60; $hour_limit = 100; # users are limited to 100 requests/hour $hour_throttle = Cache::get("hour_throttle:{$key}", null); $last_api_request = Cache::get("last_api_request:{$key}", 0); $last_api_diff = time() - $last_api_request; if (is_null($hour_throttle)) { $new_hour_throttle = 0; } else { $new_hour_throttle = $hour_throttle - $last_api_diff; $new_hour_throttle = $new_hour_throttle < 0 ? 0 : $new_hour_throttle; $new_hour_throttle += $hour / $hour_limit; $hour_hits_remaining = floor(($hour - $new_hour_throttle) * $hour_limit / $hour); $hour_hits_remaining = $hour_hits_remaining >= 0 ? $hour_hits_remaining : 0; } if ($new_hour_throttle > $hour) { $wait = ceil($new_hour_throttle - $hour); sleep(1); return Response::json("Please wait {$wait} second(s)", 403, $headers); } Cache::put("hour_throttle:{$key}", $new_hour_throttle, 10); Cache::put("last_api_request:{$key}", time(), 10); } return $next($request); }
function add_pagination_vars(&$page, $total, $curPage, $perPage, $append = '') { $pgs = array(); $p_min = 0; $p_max = $lastPage = floor($total / $perPage); if ($curPage == 0) { $p_max = min($lastPage, $curPage + 4); } else { if ($curPage == 1) { $p_max = min($lastPage, $curPage + 3); } else { $p_max = min($lastPage, $curPage + 2); } } if ($curPage == $lastPage) { $p_min = max(0, $curPage - 4); } else { if ($curPage == $lastPage - 1) { $p_min = max(0, $curPage - 3); } else { $p_min = max(0, $curPage - 2); } } for ($p = $p_min; $p <= $p_max; $p++) { $pgs[] = $p; } $page['pager'] = array('pages' => $pgs, 'first' => 0, 'current' => $curPage, 'last' => floor($total / $perPage), 'append' => $append); }
/** * Defined by Zend_Validate_Interface * * Returns true if and only if $value follows the Luhn algorithm (mod-10 checksum) * * @param string $value * @return boolean */ public function isValid($value) { $this->_setValue($value); if (null === self::$_filter) { /** * @see Zend_Filter_Digits */ // require_once 'Zend/Filter/Digits.php'; self::$_filter = new Zend_Filter_Digits(); } $valueFiltered = self::$_filter->filter($value); $length = strlen($valueFiltered); if ($length < 13 || $length > 19) { $this->_error(self::LENGTH); return false; } $sum = 0; $weight = 2; for ($i = $length - 2; $i >= 0; $i--) { $digit = $weight * $valueFiltered[$i]; $sum += floor($digit / 10) + $digit % 10; $weight = $weight % 2 + 1; } if ((10 - $sum % 10) % 10 != $valueFiltered[$length - 1]) { $this->_error(self::CHECKSUM, $valueFiltered); return false; } return true; }
public static function from(Moment $moment) { $seconds = floor($moment->ms() / 1000); $milliseconds = $moment->ms() - $seconds * 1000; $microseconds = $milliseconds * 1000; return new \MongoDate($seconds, $microseconds); }
/** * Encode the coordinate via the 10:10 algorithm. * * @param CoordinateInterface $coordinate The coordinate to encode. * @return string */ public function encode(CoordinateInterface $coordinate) { $latitude = floor(($coordinate->getLatitude() + 90.0) * 10000.0); $longitude = floor(($coordinate->getLongitude() + 180.0) * 10000.0); $position = $latitude * 3600000.0 + $longitude; $ttNumber = $position * self::BASE; $checkDigit = 0; for ($i = 1; $i < 10; ++$i) { $checkDigit += $position % self::BASE * $i; $position = floor($position / self::BASE); } $checkDigit %= self::BASE; $ttNumber += $checkDigit; $ttNumber = floor($ttNumber); $tt = ''; for ($i = 0; $i < 10; ++$i) { $digit = $ttNumber % self::BASE; if ($i === 4 || $i === 7) { $tt = ' ' . $tt; } $tt = $this->alphabet[$digit] . $tt; $ttNumber = floor($ttNumber / self::BASE); } return $tt; }
public function createdAgo(\DateTime $dateTime) { $delta = time() - $dateTime->getTimestamp(); if ($delta < 0) { throw new \InvalidArgumentException("createdAgo is unable to handle dates in the future"); } $duration = ""; if ($delta < 60) { // Seconds $time = $delta; $duration = $time . " second" . ($time === 0 || $time > 1 ? "s" : "") . " ago"; } else { if ($delta < 3600) { // Mins $time = floor($delta / 60); $duration = $time . " minute" . ($time > 1 ? "s" : "") . " ago"; } else { if ($delta < 86400) { // Hours $time = floor($delta / 3600); $duration = $time . " hour" . ($time > 1 ? "s" : "") . " ago"; } else { // Days $time = floor($delta / 86400); $duration = $time . " day" . ($time > 1 ? "s" : "") . " ago"; } } } return $duration; }
/** * Constructs HTML for progress bars * * @param int $goal number of signatures we hope to collect * @param int $signatures number of signatures collected so far * @param int $max_width width of the outer progress bar div in pixels * @return HTML string */ public static function progress_bar($goal, $signatures, $max_width) { // determine how wide the internal progress bar should be $multiplier = $max_width / 100; $percent_complete = $goal != 0 ? floor($signatures / $goal * 100) : 0; $progressbar_width = $percent_complete > 100 ? $max_width : floor($percent_complete * $multiplier); $progressbar = ''; // set progress bar color via CSS class if ($percent_complete < 25) { $color_class = 'dk-speakout-progressbar-low'; } elseif ($percent_complete < 75) { $color_class = 'dk-speakout-progressbar-medium'; } elseif ($percent_complete < 100) { $color_class = 'dk-speakout-progressbar-high'; } else { $color_class = 'dk-speakout-progressbar-complete'; } // create HTML for progress bar display if ($goal > 0) { $progressbar = '<div class="dk-speakout-progress" style="width: ' . $max_width . 'px;"> <div class="dk-speakout-progressbar ' . $color_class . '" style="width: ' . $progressbar_width . 'px;"></div> </div>'; } return $progressbar; }
public static function getPopularTags($max = 30) { $connection = Propel::getConnection(); $query = 'SELECT %s as query, COUNT(*) as count FROM %s INNER JOIN %s ON %s = %s INNER JOIN %s ON %s = %s WHERE %s = %s GROUP BY query ORDER BY count DESC'; $query = sprintf($query, QueryPeer::QUERY, QueryPeer::TABLE_NAME, ReportQueryPeer::TABLE_NAME, QueryPeer::ID, ReportQueryPeer::QUERY_ID, ReportPeer::TABLE_NAME, ReportQueryPeer::REPORT_ID, ReportPeer::ID, ReportPeer::PUBLIC_RECORD, true); $statement = $connection->prepareStatement($query); $statement->setLimit($max); $resultset = $statement->executeQuery(); $tags = array(); $max_count = 0; while ($resultset->next()) { if (!$max_count) { $max_count = $resultset->getInt('count'); } $queries[] = array('query' => $resultset->getString('query'), 'rank' => floor($resultset->getInt('count') / $max_count * 9 + 1), 'count' => $resultset->getInt('count')); } ksort($queries); return $queries; }
/** * Customises the backup progress bar * * @global moodle_page $PAGE * @return array */ public function get_progress_bar() { global $PAGE; $stage = self::STAGE_COMPLETE; $currentstage = $this->stage->get_stage(); $items = array(); while ($stage > 0) { $classes = array('backup_stage'); if (floor($stage / 2) == $currentstage) { $classes[] = 'backup_stage_next'; } else { if ($stage == $currentstage) { $classes[] = 'backup_stage_current'; } else { if ($stage < $currentstage) { $classes[] = 'backup_stage_complete'; } } } $item = array('text' => strlen(decbin($stage * 2)) . '. ' . get_string('importcurrentstage' . $stage, 'backup'), 'class' => join(' ', $classes)); if ($stage < $currentstage && $currentstage < self::STAGE_COMPLETE && (!self::$skipcurrentstage || $stage * 2 != $currentstage)) { $item['link'] = new moodle_url($PAGE->url, $this->stage->get_params() + array('backup' => $this->get_backupid(), 'stage' => $stage)); } array_unshift($items, $item); $stage = floor($stage / 2); } $selectorlink = new moodle_url($PAGE->url, $this->stage->get_params()); $selectorlink->remove_params('importid'); array_unshift($items, array('text' => '1. ' . get_string('importcurrentstage0', 'backup'), 'class' => join(' ', $classes), 'link' => $selectorlink)); return $items; }
public function action_index($options = array("max" => 10, "current" => 1, "count" => 5)) { $model = array(); $pages = array(); $max_page = $options["max"]; // Максимальное количество страниц $current_page = $options["current"]; // Текущая страница $pages_length = $options["count"]; // Количество номеров страниц (нечётное число) $next_prev_pages = floor($pages_length / 2); // Количество доп. страниц $pages[] = array("href" => "#", "active" => "active", "num" => $current_page); // Создание доп. страниц for ($i = 1; $i <= $next_prev_pages; $i++) { if ($current_page - $i > 1) { array_unshift($pages, array("href" => URL::query(array("page" => $current_page - $i)), "num" => $current_page - $i)); } if ($current_page + $i < $max_page) { array_push($pages, array("href" => URL::query(array("page" => $current_page + $i)), "num" => $current_page + $i)); } } if ($current_page > 1) { $model["min_page"] = array("num" => 1, "href" => URL::query(array("page" => 1))); $model["prev_href"] = URL::query(array("page" => $current_page - 1)); } if ($current_page < $max_page) { $model["max_page"] = array("num" => $max_page, "href" => URL::query(array("page" => $max_page))); $model["next_href"] = URL::query(array("page" => $current_page + 1)); } $model["pages"] = $pages; $this->set_template("/widgets/twig_pagination.php", "twig")->render($model)->body(); }
function FormatTimeLeft($diff) { global $MSG; $days_difference = floor($diff / 86400); $difference = $diff % 86400; $hours_difference = floor($difference / 3600); $difference = $difference % 3600; $minutes_difference = floor($difference / 60); $seconds_difference = $difference % 60; $secshow = false; $timeleft = ''; if ($days_difference > 0) { $timeleft = $days_difference . 'd '; } if ($hours_difference > 0) { $timeleft .= $hours_difference . 'h '; } else { $secshow = true; } if ($diff > 60) { $timeleft .= $minutes_difference . 'm '; } elseif ($diff > 60 && !$seconds) { $timeleft = '<1m'; } if ($secshow) { $timeleft .= $seconds_difference . 's '; } if ($diff < 0) { $timeleft = $MSG['911']; } if ($diff * 60 < 15) { $timeleft = '<span style="color:#FF0000;">' . $timeleft . '</span>'; } return $timeleft; }
function diffDate($d1, $d2, $type = '', $sep = '-') { $d1 = explode($sep, $d1); $d2 = explode($sep, $d2); switch ($type) { case 'A': $X = 31536000; break; case 'M': $X = 2592000; break; case 'D': $X = 86400; break; case 'H': $X = 3600; break; case 'MI': $X = 60; break; default: $X = 1; } echo $d2[1]; echo $d2[2]; echo $d2[0]; return floor((mktime(0, 0, 0, $d2[1], $d2[2], $d2[0]) - mktime(0, 0, 0, $d1[1], $d1[2], $d1[0])) / $X); }
function Zend_Locale_Math_Sub($op1, $op2, $op3 = null) { if (empty($op1)) { $op1 = 0; } $result = $op1 - $op2; if ((string) ($result + $op2) != (string) $op1) { /** * @see Zend_Locale_Math_Exception */ require_once 'Zend/Locale/Math/Exception.php'; throw new Zend_Locale_Math_Exception("subtraction overflow: {$op1} - {$op2} != {$result}", $op1, $op2, $result); } if ($op3 != 0) { $result = round($result, $op3); } else { if ($result > 0) { $result = floor($result); } else { $result = ceil($result); } } if ($op3 > 0) { if ((string) $result == "0") { $result = "0."; } if (strlen($result) < $op3 + 2) { $result = str_pad($result, $op3 + 2, "0", STR_PAD_RIGHT); } } return $result; }
function _secs_to_minsecs($s) { $s = (int) $s; $m = floor($s / 60); $s = $s - $m * 60; return $m . ':' . str_pad($s, 2, '0', STR_PAD_LEFT); }
function pretty_number($n, $floor = true) { if ($floor) { $n = floor($n); } return number_format($n, 0, ",", "."); }
public static function Jaro($string1, $string2) { $str1_len = strlen($string1); $str2_len = strlen($string2); // theoretical distance $distance = (int) floor(min($str1_len, $str2_len) / 2.0); // get common characters $commons1 = self::getCommonCharacters($string1, $string2, $distance); $commons2 = self::getCommonCharacters($string2, $string1, $distance); if (($commons1_len = strlen($commons1)) == 0) { return 0; } if (($commons2_len = strlen($commons2)) == 0) { return 0; } // calculate transpositions $transpositions = 0; $upperBound = min($commons1_len, $commons2_len); for ($i = 0; $i < $upperBound; $i++) { if ($commons1[$i] != $commons2[$i]) { $transpositions++; } } $transpositions /= 2.0; // return the Jaro distance return ($commons1_len / $str1_len + $commons2_len / $str2_len + ($commons1_len - $transpositions) / $commons1_len) / 3.0; }
function twitter_time($time) { // Get the number of seconds elapsed since this date $delta = time() - strtotime($time); if ($delta < 60) { return 'minder dan een minuut geleden'; } else { if ($delta < 120) { return 'ongeveer een minuut geleden'; } else { if ($delta < 60 * 60) { return floor($delta / 60) . ' minuten geleden'; } else { if ($delta < 120 * 60) { return 'ongeveer een uur geleden'; } else { if ($delta < 24 * 60 * 60) { return floor($delta / 3600) . ' uren geleden'; } else { if ($delta < 48 * 60 * 60) { return 'gisteren'; } else { return number_format(floor($delta / 86400)) . ' dagen geleden'; } } } } } } }
function nuage_tags($limit = 30, $id_cat = 0) { $list_tags = array(); $count_tags = array(); $limit_sql = $limit != 0 ? ' LIMIT ' . intval($limit) : ''; $where_cat = $id_cat != 0 ? ' AND n_id_cat = ' . intval($id_cat) : ''; $rqt_tags = Nw::$DB->query('SELECT c_id, c_couleur, c_nom, t_id_news, t_tag, COUNT(t_tag) AS nbr_tags, n_id_cat FROM ' . Nw::$prefix_table . 'tags LEFT JOIN ' . Nw::$prefix_table . 'news ON t_id_news = n_id LEFT JOIN ' . Nw::$prefix_table . 'categories ON c_id = n_id_cat WHERE n_etat = 3' . $where_cat . ' GROUP BY t_tag ORDER BY t_tag ASC ' . $limit_sql) or Nw::$DB->trigger(__LINE__, __FILE__); while ($donnees = $rqt_tags->fetch_assoc()) { $list_tags[$donnees['t_tag']] = $donnees; $count_tags[$donnees['t_tag']] = $donnees['nbr_tags']; } $max_size = 200; $min_size = 100; $max_qty = 0; $min_qty = 0; if (count($count_tags) > 0) { $max_qty = max(array_values($count_tags)); $min_qty = min(array_values($count_tags)); } $spread = $max_qty - $min_qty; if (0 == $spread) { $spread = 1; } $step = ($max_size - $min_size) / $spread; foreach ($list_tags as $tags) { $list_tags[$tags['t_tag']]['size'] = floor($min_size + ($tags['nbr_tags'] - $min_qty) * $step); } return $list_tags; }
/** * _getUserLocation * * das aktuelle Herkunftsland des angemeldeten Benutzers wird ermittelt * * @static * @access private * @param string $ip * @return string $return */ private static function _getUserLocation($ip) { $return = 'eu'; // Datei einlesen $countrydb = file(dirname(__FILE__) . '/../ip-to-country.csv'); // IP umformen $ip_number = sprintf('%u', ip2long($ip)); // Binärsuche starten $low = 0; $high = count($countrydb) - 1; $count = 0; while ($low <= $high) { $count++; $mid = floor(($low + $high) / 2); $num1 = substr($countrydb[$mid], 1, 10); $num2 = substr($countrydb[$mid], 14, 10); if ($num1 <= $ip_number && $ip_number <= $num2) { // Länderkennung ermitteln $return = substr($countrydb[$mid], 27, 2); // Schleife beenden, sobald das Land ermittelt wurde break; } else { if ($ip_number < $num1) { $high = $mid - 1; } else { $low = $mid + 1; } } } // die Länderkennung wird 2-stellig zurückgegeben return strtolower($return); }
public function __get($strName) { switch ($strName) { // BEHAVIOR case "ItemsPerPage": return $this->intItemsPerPage; case "PageNumber": return $this->intPageNumber; case "TotalItemCount": return $this->intTotalItemCount; case "UseAjax": return $this->blnUseAjax; case "PageCount": return floor($this->intTotalItemCount / $this->intItemsPerPage) + ($this->intTotalItemCount % $this->intItemsPerPage != 0 ? 1 : 0); case "PaginatedControl": return $this->objPaginatedControl; default: try { return parent::__get($strName); } catch (QCallerException $objExc) { $objExc->IncrementOffset(); throw $objExc; } } }
function neat_r($arr, $return = false) { $out = array(); $oldtab = " "; $newtab = " "; $lines = explode("\n", print_r($arr, true)); foreach ($lines as $line) { if (substr($line, -5) != "Array") { $line = preg_replace("/^(\\s*)\\[[0-9]+\\] => /", "\$1", $line, 1); } foreach (array("Array" => "", "[" => "", "]" => "", " =>" => ":") as $old => $new) { $out = str_replace($old, $new, $out); } if (in_array(trim($line), array("Array", "(", ")", ""))) { continue; } $indent = "\n"; $indents = floor((substr_count($line, $oldtab) - 1) / 2); if ($indents > 0) { for ($i = 0; $i < $indents; $i++) { $indent .= $newtab; } } $out[] = $indent . trim($line); } $out = implode("<br/>", $out) . "\n"; if ($return == true) { return $out; } echo $out; }
/** * Displays a list of groups * * @return void */ public function displayTask() { $this->view->filters = array('limit' => 'all', 'fields' => array('COUNT(*)'), 'authorized' => 'admin', 'type' => array(Request::getState($this->_option . '.browse.type', 'type', 'all')), 'search' => urldecode(Request::getState($this->_option . '.browse.search', 'search', '')), 'discoverability' => Request::getState($this->_option . '.browse.discoverability', 'discoverability', ''), 'policy' => Request::getState($this->_option . '.browse.policy', 'policy', ''), 'sort' => Request::getState($this->_option . '.browse.sort', 'filter_order', 'cn'), 'sort_Dir' => Request::getState($this->_option . '.browse.sortdir', 'filter_order_Dir', 'ASC'), 'approved' => Request::getVar('approved'), 'created' => Request::getVar('created', '')); $this->view->filters['sortby'] = $this->view->filters['sort'] . ' ' . $this->view->filters['sort_Dir']; $canDo = \Components\Groups\Helpers\Permissions::getActions('group'); if (!$canDo->get('core.admin')) { if ($this->view->filters['type'][0] == 'system' || $this->view->filters['type'][0] == "0" || $this->view->filters['type'][0] == NULL) { $this->view->filters['type'] = array('all'); } if ($this->view->filters['type'][0] == 'all') { $this->view->filters['type'] = array(1, 2, 3); } } // Get a record count $this->view->total = Group::find($this->view->filters); // Filters for returning results $this->view->filters['limit'] = Request::getState($this->_option . '.browse.limit', 'limit', Config::get('list_limit'), 'int'); $this->view->filters['start'] = Request::getState($this->_option . '.browse.limitstart', 'limitstart', 0, 'int'); // In case limit has been changed, adjust limitstart accordingly $this->view->filters['start'] = $this->view->filters['limit'] != 0 ? floor($this->view->filters['start'] / $this->view->filters['limit']) * $this->view->filters['limit'] : 0; $this->view->filters['fields'] = array('cn', 'description', 'published', 'gidNumber', 'type'); // Get a list of all groups $this->view->rows = null; if ($this->view->total > 0) { $this->view->rows = Group::find($this->view->filters); } // Set any errors foreach ($this->getErrors() as $error) { $this->view->setError($error); } // pass config to view $this->view->config = $this->config; // Output the HTML $this->view->display(); }
function carrier($addr = null) { if (!$addr) { $addr = $this->addr(); } $ip = (double) sprintf('%u', ip2long($addr)); $ranges = $this->ranges; $min = -1; $max = count($ranges); while (true) { $center = (int) floor(($min + $max) / 2); if ($center === $min) { return 'pc'; } $range =& $ranges[$center]; if ($ip < $range['network']) { $max = $center; } else { if ($range['network'] <= $ip && $ip <= $range['broadcast']) { return $range['carrier']; } else { $min = $center; } } } }