static function drawProgressBar($percent) { static $i = 0; if ($percent == 'reset') { $i = 0; return; } $max = 80; // draw up to percent $ret = ''; $new = (int) (clamp(round($percent, 1), 0.0, 1.0) * 80); while ($i <= $new) { if ($i == 0) { $ret .= '['; } elseif ($i == $max) { $ret .= "]\n"; } elseif ($i % ($max / 4) == $max / 4 - 1) { $ret .= '|'; } else { $ret .= '='; } $i++; } return $ret; }
function randombg($s, $w, $h, $bounds) { $w *= $s; $h *= $s; $im = imagecreatetruecolor($w, $h); imagecolorallocate($im, 0, 0, 0); foreach (range(0, $h, $s) as $y) { foreach (range(0, $w, $s) as $x) { $color = imagecolorallocate($im, clamp(rand(0, 255), $bounds['r']), clamp(rand(0, 255), $bounds['g']), clamp(rand(0, 255), $bounds['b'])); imagefilledrectangle($im, $x, $y, $x + $s, $y + $s, $color); } } header('Content-type: image/gif'); imagegif($im); imagedestroy($im); }
/** * Normalizes the given value between 0 and 1, based on the ratio between the given value and expected maximum value * @param int|float $value * @param int|float $upperBound * @return int|float */ function normalize($value, $upperBound) { return clamp($value / $upperBound, 0, 1); }
function yt_lib_lighten($args) { list($color, $delta) = yt_colorArgs($args); $hsl = toHSL($color); $hsl[3] = clamp($hsl[3] + $delta, 100); return toRGB($hsl); }
/** * HERE WE GET THE LIST OF POOLS. * * @param \Page $page * @param int $pageNumber */ private function list_pools(Page $page, $pageNumber) { global $config, $database; $pageNumber = clamp($pageNumber, 1, null) - 1; $poolsPerPage = $config->get_int("poolsListsPerPage"); $order_by = ""; $order = $page->get_cookie("ui-order-pool"); if ($order == "created" || is_null($order)) { $order_by = "ORDER BY p.date DESC"; } elseif ($order == "updated") { $order_by = "ORDER BY p.lastupdated DESC"; } elseif ($order == "name") { $order_by = "ORDER BY p.title ASC"; } elseif ($order == "count") { $order_by = "ORDER BY p.posts DESC"; } $pools = $database->get_all("\n\t\t\tSELECT p.id, p.user_id, p.public, p.title, p.description,\n\t\t\t p.posts, u.name as user_name\n\t\t\tFROM pools AS p\n\t\t\tINNER JOIN users AS u\n\t\t\tON p.user_id = u.id\n\t\t\t{$order_by}\n\t\t\tLIMIT :l OFFSET :o\n\t\t", array("l" => $poolsPerPage, "o" => $pageNumber * $poolsPerPage)); $totalPages = ceil($database->get_one("SELECT COUNT(*) FROM pools") / $poolsPerPage); $this->theme->list_pools($page, $pools, $pageNumber + 1, $totalPages); }
/** * @param int $current_page */ private function build_page($current_page) { global $database, $user; $where = SPEED_HAX ? "WHERE posted > now() - interval '24 hours'" : ""; $total_pages = $database->cache->get("comment_pages"); if (empty($total_pages)) { $total_pages = (int) ($database->get_one("\n\t\t\t\tSELECT COUNT(c1)\n\t\t\t\tFROM (SELECT COUNT(image_id) AS c1 FROM comments {$where} GROUP BY image_id) AS s1\n\t\t\t") / 10); $database->cache->set("comment_pages", $total_pages, 600); } $total_pages = max($total_pages, 1); $current_page = clamp($current_page, 1, $total_pages); $threads_per_page = 10; $start = $threads_per_page * ($current_page - 1); $result = $database->Execute("\n\t\t\tSELECT image_id,MAX(posted) AS latest\n\t\t\tFROM comments\n\t\t\t{$where}\n\t\t\tGROUP BY image_id\n\t\t\tORDER BY latest DESC\n\t\t\tLIMIT :limit OFFSET :offset\n\t\t", array("limit" => $threads_per_page, "offset" => $start)); $user_ratings = ext_is_live("Ratings") ? Ratings::get_user_privs($user) : ""; $images = array(); while ($row = $result->fetch()) { $image = Image::by_id($row["image_id"]); if (ext_is_live("Ratings") && !is_null($image) && strpos($user_ratings, $image->rating) === FALSE) { $image = null; // this is "clever", I may live to regret it } if (!is_null($image)) { $comments = $this->get_comments($image->id); $images[] = array($image, $comments); } } $this->theme->display_comment_list($images, $current_page, $total_pages, $user->can("create_comment")); }
function blc_latest_comments($num_posts = 5, $num_comments = 6, $hide_pingbacks_and_trackbacks = true, $prefix = "<li class='alternate'>", $postfix = "</li>", $fade_old = true, $range_in_days = 10, $new_col = "#444444", $old_col = "#cccccc") { global $wpdb; function clamp($min, $max, $val) { return max($min, min($max, $val)); } $usetimesince = function_exists('time_since'); // Work nicely with Dunstan's Time Since plugin (adapted by Michael Heilemann) // This is compensating for the lack of subqueries in mysql 3.x // The approach used in previous versions needed the user to // have database lock and create tmp table priviledges. // This uses more queries and manual DISTINCT code, but it works with just select privs. if (!$hide_pingbacks_and_trackbacks) { $ping = ""; } else { $ping = "AND comment_type<>'pingback' AND comment_type<>'trackback'"; } $posts = $wpdb->get_results("SELECT \r\n\t\tcomment_post_ID, post_title \r\n\t\tFROM ({$wpdb->comments} LEFT JOIN {$wpdb->posts} ON (comment_post_ID = ID))\r\n\t\tWHERE comment_approved = '1' \r\n\t\tAND {$wpdb->posts}.post_status='publish'\r\n\t\t{$ping}\r\n\t\tORDER BY comment_date DESC;"); $seen = array(); $num = 0; if ($fade_old) { $max_time = $range_in_days * 24 * 60 * 60; $r_new = hexdec(substr($new_col, 1, 2)); $r_old = hexdec(substr($old_col, 1, 2)); //$r_min = min($min, $max); //$r_max = max($min, $max); $r_range = $r_old - $r_new; $g_new = hexdec(substr($new_col, 3, 2)); $g_old = hexdec(substr($old_col, 3, 2)); //$g_min = min($min, $max); //$g_max = max($min, $max); $g_range = $g_old - $g_new; $b_new = hexdec(substr($new_col, 5, 2)); $b_old = hexdec(substr($old_col, 5, 2)); //$b_min = min($min, $max); //$b_max = max($min, $max); $b_range = $b_old - $b_new; } // print "ranges: $r_range, $g_range, $b_range<br>"; // print "r: ".(0.5*$r_range+$r_new)."<br>"; foreach ($posts as $post) { // The following 5 lines is a manual DISTINCT and LIMIT, // since mysql 3.x doesn't allow you to control which way a DISTINCT // select merges multiple entries. if (array_key_exists($post->comment_post_ID, $seen)) { continue; } $seen[$post->comment_post_ID] = true; if ($num++ > $num_posts) { break; } $commenters = $wpdb->get_results("SELECT *, UNIX_TIMESTAMP(comment_date) AS unixdate FROM {$wpdb->comments}\r\n\t \t\t\tWHERE comment_approved = '1'\r\n\t\t\t\tAND comment_post_ID = '" . $post->comment_post_ID . "'\r\n\t\t\t\t{$ping}\r\n\t\t\t\tORDER BY comment_date DESC\r\n\t\t\t\tLIMIT {$num_comments};"); $count = $wpdb->get_var("SELECT COUNT(comment_ID) AS c FROM {$wpdb->comments} WHERE comment_post_ID = {$post->comment_post_ID} AND comment_approved = '1' " . $ping); $i = 0; $link = get_permalink($post->comment_post_ID); if ($usetimesince) { $title = " title=\"Last comment was " . time_since($comment->unixdate) . " ago\""; } else { $title = ""; } echo $prefix . "<a href=\"" . $link . "\"{$title} class=\"activityentry\">" . stripslashes($post->post_title) . "</a> <a href=\"{$link}#comments\" title=\"Go to the comments of this entry\">" . $count . "</a><br />\n<small>"; foreach ($commenters as $commenter) { if ($usetimesince) { $title = " title=\"Posted " . time_since($commenter->unixdate) . " ago\""; } if ($fade_old) { $diff = time() - $commenter->unixdate; $r = round($diff / $max_time * $r_range) + $r_new; $r = clamp(min($r_new, $r_old), max($r_new, $r_old), $r); $g = round($diff / $max_time * $g_range) + $g_new; $g = clamp(min($g_new, $g_old), max($g_new, $g_old), $g); $b = round($diff / $max_time * $b_range) + $b_new; $b = clamp(min($b_new, $b_old), max($b_new, $b_old), $b); $r_hex = str_pad(dechex($r), 2, '0', STR_PAD_LEFT); $g_hex = str_pad(dechex($g), 2, '0', STR_PAD_LEFT); $b_hex = str_pad(dechex($r), 2, '0', STR_PAD_LEFT); $colstr = " style=\"color: #" . $r_hex . $g_hex . $b_hex . ";\""; } if ($i++ > 0) { echo ", "; } echo "<a{$colstr} href=\"" . $link . "#comment-" . $commenter->comment_ID . "\"{$title}>" . stripslashes($commenter->comment_author) . "</a>"; } if ($count > $num_comments) { echo " <a href=\"{$link}#comments\" title=\"Go to the comments of this entry\">[...]</a>"; } echo "</small>" . $postfix . "\n"; } }
/** * Get Nonce * * @since 2.03 * @author tankmiche * @uses $USR * @uses $SALT * * @param string $action Id of current page * @param string $file Optional, default is empty string * @param bool $last * @return string */ function get_nonce($action, $file = "", $last = false) { global $USR; global $SALT; // set nonce_timeout default and clamps include_once GSADMININCPATH . 'configuration.php'; clamp($nonce_timeout, 60, 86400, 3600); // min, max, default in seconds // $nonce_timeout = 10; if ($file == "") { $file = getScriptFile(); } // using user agent since ip can change on proxys $uid = $_SERVER['HTTP_USER_AGENT']; // set nonce time domain to $nonce_timeout or $nonce_timeout x 2 when last is $true $time = $last ? time() - $nonce_timeout : time(); $time = floor($time / $nonce_timeout); // Mix with a little salt $hash = sha1($action . $file . $uid . $USR . $SALT . $time); return $hash; }
private function get_listing(Page $page, PageRequestEvent $event) { global $config, $database; $pageNumber = clamp($event->get_arg(1), 1, null) - 1; $artistsPerPage = $config->get_int("artistsPerPage"); $listing = $database->get_all("\n (\n SELECT a.id, a.user_id, a.name, u.name AS user_name, COALESCE(t.count, 0) AS posts\n , 'artist' as type, a.id AS artist_id, a.name AS artist_name, a.updated\n FROM artists AS a\n INNER JOIN users AS u\n ON a.user_id = u.id\n LEFT OUTER JOIN tags AS t\n ON a.name = t.tag\n GROUP BY a.id, a.user_id, a.name, u.name\n ORDER BY a.updated DESC\n )\n\n UNION\n\n (\n SELECT aa.id, aa.user_id, aa.alias AS name, u.name AS user_name, COALESCE(t.count, 0) AS posts\n , 'alias' as type, a.id AS artist_id, a.name AS artist_name, aa.updated\n FROM artist_alias AS aa\n INNER JOIN users AS u\n ON aa.user_id = u.id\n INNER JOIN artists AS a\n ON aa.artist_id = a.id\n LEFT OUTER JOIN tags AS t\n ON aa.alias = t.tag\n GROUP BY aa.id, a.user_id, aa.alias, u.name, a.id, a.name\n ORDER BY aa.updated DESC\n )\n\n UNION\n\n (\n SELECT m.id, m.user_id, m.name AS name, u.name AS user_name, COALESCE(t.count, 0) AS posts\n , 'member' AS type, a.id AS artist_id, a.name AS artist_name, m.updated\n FROM artist_members AS m\n INNER JOIN users AS u\n ON m.user_id = u.id\n INNER JOIN artists AS a\n ON m.artist_id = a.id\n LEFT OUTER JOIN tags AS t\n ON m.name = t.tag\n GROUP BY m.id, m.user_id, m.name, u.name, a.id, a.name\n ORDER BY m.updated DESC\n )\n ORDER BY updated DESC\n LIMIT ?, ?\n ", array($pageNumber * $artistsPerPage, $artistsPerPage)); $number_of_listings = count($listing); for ($i = 0; $i < $number_of_listings; $i++) { $listing[$i]["name"] = stripslashes($listing[$i]["name"]); $listing[$i]["user_name"] = stripslashes($listing[$i]["user_name"]); $listing[$i]["artist_name"] = stripslashes($listing[$i]["artist_name"]); } $count = $database->get_one("\n SELECT COUNT(1)\n FROM artists AS a\n LEFT OUTER JOIN artist_members AS am\n ON a.id = am.artist_id\n LEFT OUTER JOIN artist_alias AS aa\n ON a.id = aa.artist_id\n "); $totalPages = ceil($count / $artistsPerPage); $this->theme->list_artists($listing, $pageNumber + 1, $totalPages); }
public function call() { // The Slim application $app = $this->app; // // Respond based on ACCEPT request header // Add EventSource middeware: http://en.wikipedia.org/wiki/Server-sent_events | http://www.html5rocks.com/en/tutorials/eventsource/basics/ // if ($app->request->headers->get('ACCEPT') == 'text/event-stream' || $app->request->getMethod() == 'GET' && preg_match('/^\\/channels/', $app->request->getResourceUri())) { // Workaround for Internet Explorer, which can't send custom request headers on CORS requests. ini_set('zlib.output_compression', 0); ini_set('implicit_flush', 1); // Start buffering ob_start(); $pool_start = $app->request->headers->get('X-Time') ?: time(); // stream timing configs $stream_config = $app->request->get('stream'); $refresh_timeout = isset($stream_config['refresh']) ? intval($stream_config['refresh']) : self::MIN_REFRESH_TIMEOUT; $refresh_timeout = clamp($refresh_timeout, self::MIN_REFRESH_TIMEOUT, self::MAX_REFRESH_TIMEOUT); $retry_timeout = isset($stream_config['retry']) ? intval($stream_config['retry']) : self::MIN_POOLING_RETRY; $retry_timeout = clamp($retry_timeout, self::MIN_POOLING_RETRY, self::MAX_POOLING_RETRY) * 1000; $last_event_id = $app->request->headers->get('Last-Event-ID') ?: $app->request->get('lastEventId'); // Set response headers $app->response->headers->set('Content-type', 'text/event-stream'); $app->response->headers->set('Cache-Control', 'no-cache'); foreach ($app->response->headers as $header => $content) { header("{$header}: {$content}"); } echo 'retry: ' . $retry_timeout . PHP_EOL . PHP_EOL; do { // Close EventSource connection after 15 seconds // let the client re-open it if necessary if (time() - $pool_start > 15) { die; } // Append last-event-id to filtering options if ($last_event_id) { $query_data = AppMiddleware::decode_query_string(); if (!isset($query_data['q'])) { $query_data['q'] = array(); } if ($last_event_id) { array_push($query_data['q'], array('_id', '>', $last_event_id)); } $app->environment->offsetSet('slim.request.query_hash', $query_data); } try { // Call current request $this->next->call(); $response = $app->response->getBody(); } catch (Exception $e) { $response = $this->handleErrorResponse($e, $app); } // Multiple results if (method_exists($response, 'each')) { $self = $this; $response->each(function ($data) use($app, &$last_event_id, &$self) { echo 'id: ' . $data->_id . PHP_EOL . PHP_EOL; echo 'data: ' . to_json($data) . PHP_EOL . PHP_EOL; ob_flush(); flush(); $last_event_id = $data->_id; }); } else { // Single result if ($response instanceof stdClass) { echo 'id: ' . $response->_id . PHP_EOL . PHP_EOL; $last_event_id = $data->content->_id; } echo 'data: ' . to_json($response) . PHP_EOL . PHP_EOL; ob_flush(); flush(); } sleep($refresh_timeout); } while (true); } else { return $this->next->call(); } }
public function onPageRequest(PageRequestEvent $event) { global $config, $database, $user, $page; if ($event->page_matches("numeric_score_votes")) { $image_id = int_escape($event->get_arg(0)); $x = $database->get_all("SELECT users.name as username, user_id, score \n\t\t\t\tFROM numeric_score_votes \n\t\t\t\tJOIN users ON numeric_score_votes.user_id=users.id\n\t\t\t\tWHERE image_id=?", array($image_id)); $html = "<table style='width: 100%;'>"; foreach ($x as $vote) { $html .= "<tr><td>"; $html .= "<a href='" . make_link("user/{$vote['username']}") . "'>{$vote['username']}</a>"; $html .= "</td><td width='10'>"; $html .= $vote['score']; $html .= "</td></tr>"; } die($html); } else { if ($event->page_matches("numeric_score_vote") && $user->check_auth_token()) { if (!$user->is_anonymous()) { $image_id = int_escape($_POST['image_id']); $char = $_POST['vote']; $score = null; if ($char == "up") { $score = 1; } else { if ($char == "null") { $score = 0; } else { if ($char == "down") { $score = -1; } } } if (!is_null($score) && $image_id > 0) { send_event(new NumericScoreSetEvent($image_id, $user, $score)); } $page->set_mode("redirect"); $page->set_redirect(make_link("post/view/{$image_id}")); } } else { if ($event->page_matches("numeric_score/remove_votes_on") && $user->check_auth_token()) { if ($user->can("edit_other_vote")) { $image_id = int_escape($_POST['image_id']); $database->execute("DELETE FROM numeric_score_votes WHERE image_id=?", array($image_id)); $database->execute("UPDATE images SET numeric_score=0 WHERE id=?", array($image_id)); $page->set_mode("redirect"); $page->set_redirect(make_link("post/view/{$image_id}")); } } else { if ($event->page_matches("numeric_score/remove_votes_by") && $user->check_auth_token()) { if ($user->can("edit_other_vote")) { $this->delete_votes_by(int_escape($_POST['user_id'])); $page->set_mode("redirect"); $page->set_redirect(make_link()); } } else { if ($event->page_matches("popular_by_day") || $event->page_matches("popular_by_month") || $event->page_matches("popular_by_year")) { //FIXME: popular_by isn't linked from anywhere list($day, $month, $year) = array(date("d"), date("m"), date("Y")); if (!empty($_GET['day'])) { $D = (int) $_GET['day']; $day = clamp($D, 1, 31); } if (!empty($_GET['month'])) { $M = (int) $_GET['month']; $month = clamp($M, 1, 12); } if (!empty($_GET['year'])) { $Y = (int) $_GET['year']; $year = clamp($Y, 1970, 2100); } $totaldate = $year . "/" . $month . "/" . $day; $sql = "SELECT id FROM images\n\t\t\t WHERE EXTRACT(YEAR FROM posted) = :year\n\t\t\t\t\t"; $args = array("limit" => $config->get_int("index_images"), "year" => $year); if ($event->page_matches("popular_by_day")) { $sql .= "AND EXTRACT(MONTH FROM posted) = :month\n\t\t\t\t\tAND EXTRACT(DAY FROM posted) = :day"; $args = array_merge($args, array("month" => $month, "day" => $day)); $dte = array($totaldate, date("F jS, Y", strtotime($totaldate)), "\\y\\e\\a\\r\\=Y\\&\\m\\o\\n\\t\\h\\=m\\&\\d\\a\\y\\=d", "day"); } else { if ($event->page_matches("popular_by_month")) { $sql .= "AND EXTRACT(MONTH FROM posted) = :month"; $args = array_merge($args, array("month" => $month)); $dte = array($totaldate, date("F Y", strtotime($totaldate)), "\\y\\e\\a\\r\\=Y\\&\\m\\o\\n\\t\\h\\=m", "month"); } else { if ($event->page_matches("popular_by_year")) { $dte = array($totaldate, $year, "\\y\\e\\a\\r\\=Y", "year"); } else { // this should never happen due to the fact that the page event is already matched against earlier. throw new UnexpectedValueException("Error: Invalid page event."); } } } $sql .= " AND NOT numeric_score=0 ORDER BY numeric_score DESC LIMIT :limit OFFSET 0"; //filter images by score != 0 + date > limit to max images on one page > order from highest to lowest score $result = $database->get_col($sql, $args); $images = array(); foreach ($result as $id) { $images[] = Image::by_id($id); } $this->theme->view_popular($images, $dte); } } } } } }
/** * Add generic hook wrapper * FOR INTERNAL USE * @since 3.4 * @param array $hook_array array for hooks * @param array $hook_hash_array array for hooks hash * @param string $hook_name if of hook action * @param string $hook_function callable function * @param array $args arguments to pass to $hook_function * @param int $priority order of execution of hook, lower numbers execute earlier */ function add_hook(&$hook_array, &$hook_hash_array, $hook_name, $hook_function, $args = array(), $priority = null, $expectedargs = 0) { if (isset($priority) && !is_int($priority)) { debugLog(__FUNCTION__ . ': invalid priority'); $priority = null; } if ($priority === 0) { $priority = 1; } # fixup 0 clamp($priority, 1, 10, 10); # clamp priority, min:1, max:10, default:10 $hook = array('hook' => $hook_name, 'function' => $hook_function, 'args' => (array) $args, 'priority' => $priority, 'numargs' => $expectedargs); addPlugindebugging($hook); # add debug info , file, line, core $hook_array[] = $hook; # add to global plugins $hook_hash_array[$hook_name][$priority][] =& $hook_array[count($hook_array) - 1]; # add ref to global plugin hook hash array }
function conceive($id) { // get number of segments $segments = 0; $stmt = $this->source_db->prepare(SQL_SELECT_NUM_SEGMENTS); $stmt->bind_param("i", $id); $stmt->execute(); $stmt->bind_result($segments); $stmt->fetch(); $stmt->close(); // select parents $parents = Array(); $total_points = $this->num_parents * $segments; $stmt = $this->source_db->prepare(SQL_SELECT_MOST_FIT); $stmt->bind_param("ii", $id, $total_points); $stmt->execute(); $stmt->bind_result($kid_id, $px, $py, $psz, $po); while($stmt->fetch()) { // messy I know $_SESSION['parent_ids'][$id][$kid_id] = $kid_id; // not messy, :) $parents[$po][] = Array ( 'x' => $px, 'y' => $py, 'sz' => $psz); } $_SESSION['parent_ids'][$id] = array_values($_SESSION['parent_ids'][$id]); /*echo "<pre>"; var_dump($parents); echo "</pre>";*/ $stmt->close(); // create new genomes // Science! She blinded me with Science! $ch_prep = $this->source_db->prepare(SQL_INSERT_CHILD); $ch_prep->bind_param("i", $id); $pt_prep = $this->sink_db->prepare(SQL_INSERT_POINT); $pt_prep->bind_param("idddi", $cid, $cx, $cy, $csz, $co); for($i = 0; $i < GFE_DEATH_RATE; $i++) { $ch_prep->execute(); $cid = $ch_prep->insert_id; $_SESSION['offspring_ids'][$id][] = $cid; // populate the points for($j = 0; $j < $segments; $j++) { $idx = mt_rand(0, GFE_NUM_PARENTS - 1); $cx = clamp($parents[$j][$idx]['x'] + random_val(-GFE_MUTATION_JITTER, GFE_MUTATION_JITTER), GFE_MAX_X, GFE_MIN_X); $cy = clamp($parents[$j][$idx]['y'] + random_val(-GFE_MUTATION_JITTER, GFE_MUTATION_JITTER), GFE_MAX_Y, GFE_MIN_Y); $csz = clamp($parents[$j][$idx]['sz'] + random_val(-GFE_MUTATION_JITTER, GFE_MUTATION_JITTER), GFE_MAX_SIZE, GFE_MIN_SIZE); $co = $j; //$this->display_parents($parents[$j], $idx, "item: " . $j . " index: " . $idx); $pt_prep->execute(); } // birth the child $this->source_db->query(sprintf(SQL_UPDATE_CHILD_BIRTH, $cid)); } $pt_prep->close(); $ch_prep->close(); // create event $stmt = $this->sink_db->prepare(SQL_INSERT_EVENT); $stmt->bind_param("is",$id, $this->birth); $stmt->execute(); $stmt->close(); }