/** * Get the query log as an array. * * @param boolean $sorted Get the queries sorted by time taken, defaults to false. * @return array Array of queries run as an array * @access public */ function getLog($sorted = false, $clear = true) { if ($sorted) { $log = sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC); } else { $log = $this->_queriesLog; } if ($clear) { $this->_queriesLog = array(); } return array('log' => $log, 'count' => $this->_queriesCnt, 'time' => $this->_queriesTime); }
/** * sortImageArray will sort an array of Images based on the given key. The * key must be one of (filename, title, sort_order) at the moment. * * @param array $images The array of filenames to be sorted. * @param string $sorttype optional sort type * @param string $sortdirection optional sort direction * @param bool $mine set to true/false to override ownership clause * @return array */ protected function sortImageArray($images, $sorttype, $sortdirection, $mine = NULL) { if (is_null($mine)) { $mine = $this->isMyItem(LIST_RIGHTS | MANAGE_ALL_ALBUM_RIGHTS); } if ($mine && !($mine & MANAGE_ALL_ALBUM_RIGHTS)) { // check for managed album view unpublished image rights $mine = $this->albumSubRights() & (MANAGED_OBJECT_RIGHTS_EDIT | MANAGED_OBJECT_RIGHTS_VIEW); } $sortkey = $this->getImageSortKey($sorttype); if ($sortkey == '`sort_order`' || $sortkey == 'RAND()') { // manual sort is always ascending $order = false; } else { if (!is_null($sortdirection)) { $order = strtoupper($sortdirection) == 'DESC'; } else { $order = $this->getSortDirection('image'); } } $result = query($sql = "SELECT * FROM " . prefix("images") . " WHERE `albumid`= " . $this->getID() . ' ORDER BY ' . $sortkey . ' ' . $sortdirection); $results = array(); while ($row = db_fetch_assoc($result)) { $filename = $row['filename']; if (($key = array_search($filename, $images)) !== false) { // the image exists in the filesystem $results[] = $row; unset($images[$key]); } else { // the image no longer exists $id = $row['id']; query("DELETE FROM " . prefix('images') . " WHERE `id`={$id}"); // delete the record query("DELETE FROM " . prefix('comments') . " WHERE `type` ='images' AND `ownerid`= '{$id}'"); // remove image comments } } db_free_result($result); foreach ($images as $filename) { // these images are not in the database $imageobj = newImage($this, $filename); $results[] = $imageobj->getData(); } // now put the results into the right order $results = sortByKey($results, str_replace('`', '', $sortkey), $order); // the results are now in the correct order $images_ordered = array(); foreach ($results as $key => $row) { // check for visible switch (checkPublishDates($row)) { case 1: $imageobj = newImage($this, $row['filename']); $imageobj->setShow(0); $imageobj->save(); case 2: $row['show'] = 0; break; } if ($row['show'] || $mine) { // don't display it $images_ordered[] = $row['filename']; } } return $images_ordered; }
/** * Outputs the contents of the queries log. If in a non-CLI environment the sql_log element * will be rendered and output. If in a CLI environment, a plain text log is generated. * * @param boolean $sorted Get the queries sorted by time taken, defaults to false. * @return void */ function showLog($sorted = false) { if ($sorted) { $log = sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC); } else { $log = $this->_queriesLog; } if ($this->_queriesCnt > 1) { $text = 'queries'; } else { $text = 'query'; } if (PHP_SAPI != 'cli') { $summary = "{$this->_queriesCnt} {$text} took {$this->_queriesTime} ms"; $body = array(); $body[] = array("Nr", "Query", "Error", "Affected", "Num. rows", "Took (ms)"); foreach ($log as $k => $i) { $body[] = array($k + 1, $i['query'], $i['error'], $i['affected'], $i['numRows'], $i['took']); } fb(array($summary, $body), FirePHP::TABLE); } else { foreach ($log as $k => $i) { print $k + 1 . ". {$i['query']} {$i['error']}\n"; } } }
/** * Get the query log as an array. * * @param boolean $sorted Get the queries sorted by time taken, defaults to false. * @param boolean $clear Clear after return logs * @return array Array of queries run as an array */ public function getLog($sorted = false, $clear = true) { if ($sorted) { $log = sortByKey($this->_requestsLog, 'took', 'desc', SORT_NUMERIC); } else { $log = $this->_requestsLog; } if ($clear) { $this->_requestsLog = array(); } return array('log' => $log, 'count' => count($log), 'time' => array_sum(Set::extract('{n}.took', $log))); }
/** * Outputs the contents of the queries log. * * @param boolean $sorted */ function showLog($sorted = false) { if ($sorted) { $log = sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC); } else { $log = $this->_queriesLog; } if ($this->_queriesCnt > 1) { $text = 'queries'; } else { $text = 'query'; } if (php_sapi_name() != 'cli') { print ("<table id=\"cakeSqlLog\" cellspacing=\"0\" border = \"0\">\n<caption>{$this->_queriesCnt} {$text} took {$this->_queriesTime} ms</caption>\n"); print ("<thead>\n<tr><th>Nr</th><th>Query</th><th>Error</th><th>Affected</th><th>Num. rows</th><th>Took (ms)</th></tr>\n</thead>\n<tbody>\n"); foreach ($log as $k => $i) { print ("<tr><td>" . ($k +1) . "</td><td>{$i['query']}</td><td>{$i['error']}</td><td style = \"text-align: right\">{$i['affected']}</td><td style = \"text-align: right\">{$i['numRows']}</td><td style = \"text-align: right\">{$i['took']}</td></tr>\n"); } print ("</table>\n"); } else { foreach ($log as $k => $i) { print (($k +1) . ". {$i['query']} {$i['error']}\n"); } } }
/** * Outputs the contents of the queries log. * * @param boolean $sorted */ function showLog($sorted = false) { if ($sorted) { $log = sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC); } else { $log = $this->_queriesLog; } if ($this->_queriesCnt > 1) { $text = 'queries'; } else { $text = 'query'; } if (php_sapi_name() != 'cli') { print "<table class=\"cakeSqlLog\" id=\"cakeSqlLog_" . preg_replace('/[^A-Za-z0-9_]/', '_', uniqid(time(), true)) . "\" summary=\"Cake SQL Log\" cellspacing=\"0\" border = \"0\">\n<caption>{$this->_queriesCnt} {$text} took {$this->_queriesTime} ms</caption>\n"; print "<thead>\n<tr><th>Nr</th><th>Query</th><th>Error</th><th>Affected</th><th>Num. rows</th><th>Took (ms)</th></tr>\n</thead>\n<tbody>\n"; foreach ($log as $k => $i) { print "<tr><td>" . ($k + 1) . "</td><td>" . h($i['query']) . "</td><td>{$i['error']}</td><td style = \"text-align: right\">{$i['affected']}</td><td style = \"text-align: right\">{$i['numRows']}</td><td style = \"text-align: right\">{$i['took']}</td></tr>\n"; } print "</tbody></table>\n"; } else { foreach ($log as $k => $i) { print $k + 1 . ". {$i['query']} {$i['error']}\n"; } } }
/** * Returns a of a slice of the images for this album. They will * also be sorted according to the sort type of this album, or by filename if none * has been set. * * @param string $page Which page of images should be returned. If zero, all images are returned. * @param int $firstPageCount count of images that go on the album/image transition page * @param string $sorttype optional sort type * @param string $sortdirection optional sort direction * @param bool $care set to false if the order of the images does not matter * @param bool $mine set true/false to override ownership * * @return array */ function getImages($page = 0, $firstPageCount = 0, $sorttype = null, $sortdirection = null, $care = true, $mine = NULL) { if ($mine || is_null($this->images) || $care && $sorttype . $sortdirection !== $this->lastimagesort) { $this->images = NULL; $images = array(); $result = query('SELECT * FROM ' . prefix('plugin_storage') . ' WHERE `type`="favorites" AND `aux`=' . db_quote($this->getInstance()) . ' AND `data` LIKE "%s:4:\\"type\\";s:6:\\"images\\";%"'); if ($result) { while ($row = db_fetch_assoc($result)) { $id = $row['id']; $data = getSerializedArray($row['data']); $imageObj = newImage(NULL, array('folder' => dirname($data['id']), 'filename' => basename($data['id'])), true); if ($imageObj->exists) { $images[] = array_merge(array('folder' => dirname($data['id']), 'filename' => basename($data['id'])), $imageObj->getData()); } else { query("DELETE FROM " . prefix('plugin_storage') . ' WHERE `id`=' . $row['id']); } } db_free_result($result); if (is_null($sorttype)) { $sorttype = $this->getSortType(); } $sortkey = str_replace('` ', ' ', $this->getImageSortKey($sorttype)); if ($sortkey == 'sort_order' || $sortkey == 'RAND()') { // manual sort is always ascending $order = false; } else { if (!is_null($sortdirection)) { $order = strtoupper($sortdirection) == 'DESC'; } else { $order = $this->getSortDirection('image'); } } $images = sortByKey($images, $sortkey, $order); $this->images = array(); foreach ($images as $data) { $this->images[] = array('folder' => $data['folder'], 'filename' => $data['filename']); } $this->lastimagesort = $sorttype . $sortdirection; } } return parent::getImages($page, $firstPageCount); }
/** * Get the query log as an array. * * @param boolean $sorted Get the queries sorted by time taken, defaults to false. * @return array Array of queries run as an array */ public function getLog($sorted = false) { if ($sorted) { $log = sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC); } else { $log = $this->_queriesLog; } return $log; }
/** * Sort the album array based on either according to the sort key. * Default is to sort on the `sort_order` field. * * Returns an array with the albums in the desired sort order * * @param array $albums array of album names * @param string $sortkey the sorting scheme * @param string $sortdirection * @param bool $mine set true/false to override ownership * @return array * * @author Todd Papaioannou (lucky@luckyspin.org) * @since 1.0.0 */ function sortAlbumArray($parentalbum, $albums, $sortkey = 'sort_order', $sortdirection = NULL, $mine = NULL) { if (count($albums) == 0) { return array(); } if (is_null($mine) && zp_loggedin(MANAGE_ALL_ALBUM_RIGHTS)) { $mine = true; } if (is_null($parentalbum)) { $albumid = ' IS NULL'; $obj = $this; $viewUnpublished = $mine; } else { $albumid = '=' . $parentalbum->getID(); $obj = $parentalbum; $viewUnpublished = zp_loggedin() && $obj->subRights() & (MANAGED_OBJECT_RIGHTS_EDIT | MANAGED_OBJECT_RIGHTS_VIEW); } if (trim($sortkey . '`') != 'sort_order' || $sortkey == 'RAND()') { // manual sort is always ascending $order = false; } else { if (is_null($sortdirection)) { $sortdirection = $this->getSortDirection('album'); } $order = $sortdirection && strtolower($sortdirection) != 'asc'; } $sql = 'SELECT * FROM ' . prefix("albums") . ' WHERE `parentid`' . $albumid . ' ORDER BY ' . db_escape($sortkey); if ($order) { $sql .= ' DESC'; } $result = query($sql); $results = array(); // check database aganist file system while ($row = db_fetch_assoc($result)) { $folder = $row['folder']; if (($key = array_search($folder, $albums)) !== false) { // album exists in filesystem $results[$row['folder']] = $row; unset($albums[$key]); } else { // album no longer exists $id = $row['id']; query("DELETE FROM " . prefix('albums') . " WHERE `id`={$id}"); // delete the record query("DELETE FROM " . prefix('comments') . " WHERE `type` ='images' AND `ownerid`= '{$id}'"); // remove image comments query("DELETE FROM " . prefix('obj_to_tag') . "WHERE `type`='albums' AND `objectid`=" . $id); query("DELETE FROM " . prefix('albums') . " WHERE `id` = " . $id); } } db_free_result($result); foreach ($albums as $folder) { // these albums are not in the database $albumobj = newAlbum($folder); if ($albumobj->exists) { // fail to instantiate? $results[$folder] = $albumobj->getData(); } } // now put the results in the right order $results = sortByKey($results, $sortkey, $order); // albums are now in the correct order $albums_ordered = array(); foreach ($results as $row) { // check for visible $folder = $row['folder']; $album = newAlbum($folder); $subrights = $album->subrights(); if ($mine || ($row['show'] || $viewUnpublished) || $subrights && is_null($album->getParent()) || $subrights && $subrights & MANAGED_OBJECT_RIGHTS_VIEW) { $albums_ordered[] = $folder; } } return $albums_ordered; }
/** * Sort the album array based on either according to the sort key. * Default is to sort on the `sort_order` field. * * Returns an array with the albums in the desired sort order * * @param array $albums array of album names * @param string $sortkey the sorting scheme * @param string $sortdirection * @param bool $mine set true/false to override ownership * @return array * * @author Todd Papaioannou (lucky@luckyspin.org) * @since 1.0.0 */ function sortAlbumArray($parentalbum, $albums, $sortkey = '`sort_order`', $sortdirection = NULL, $mine = NULL) { if (is_null($parentalbum)) { $albumid = ' IS NULL'; $obj = $this; } else { $albumid = '=' . $parentalbum->id; $obj = $parentalbum; } if ($sortkey == '`sort_order`' || $sortkey == 'RAND()') { // manual sort is always ascending $order = false; } else { if (!is_null($sortdirection)) { $order = strtoupper($sortdirection) == 'DESC'; } else { $order = $obj->getSortDirection('album'); } } if (count($albums) == 0) { return array(); } $sql = 'SELECT * FROM ' . prefix("albums") . ' WHERE `parentid`' . $albumid; $result = query($sql); $results = array(); while ($row = db_fetch_assoc($result)) { $results[$row['folder']] = $row; } // check database aganist file system foreach ($results as $dbrow => $row) { $folder = $row['folder']; if (($key = array_search($folder, $albums)) !== false) { // album exists in filesystem unset($albums[$key]); } else { // album no longer exists $id = $row['id']; query("DELETE FROM " . prefix('albums') . " WHERE `id`={$id}"); // delete the record query("DELETE FROM " . prefix('comments') . " WHERE `type` ='images' AND `ownerid`= '{$id}'"); // remove image comments query("DELETE FROM " . prefix('obj_to_tag') . "WHERE `type`='albums' AND `objectid`=" . $id); query("DELETE FROM " . prefix('albums') . " WHERE `id` = " . $id); unset($results[$dbrow]); } } foreach ($albums as $folder) { // these albums are not in the database $albumobj = new Album($this, $folder); if ($albumobj->exists) { // fail to instantiate? $results[$folder] = $albumobj->data; } } // now put the results in the right order $results = sortByKey($results, $sortkey, $order); // albums are now in the correct order $albums_ordered = array(); foreach ($results as $row) { // check for visible $folder = $row['folder']; $album = new Album($this, $folder); if ($row['show'] || $mine || is_null($mine) && $album->isMyItem(LIST_RIGHTS)) { $albums_ordered[] = $folder; } } return $albums_ordered; }
function excerpt_matches($text, $words, $length = 100, $prefix = "...", $suffix = null, $options = array()) { // Set default score modifiers [tweak away...] $options = am(array('exact_case_bonus' => 2, 'exact_word_bonus' => 3, 'abs_length_weight' => 0.0, 'rel_length_weight' => 1.0, 'debug' => false), $options); // Null suffix defaults to same as prefix if (is_null($suffix)) { $suffix = $prefix; } // Not enough to work with? if (strlen($text) <= $length) { return $text; } // Just in case if (!is_array($words)) { $words = array($words); } // Build the event list // [also calculate maximum word length for relative weight bonus] $events = array(); $maxWordLength = 0; foreach ($words as $word) { if (strlen($word) > $maxWordLength) { $maxWordLength = strlen($word); } $i = -1; while (($i = stripos($text, $word, $i + 1)) !== false) { // Basic score for a match is always 1 $score = 1; // Apply modifiers if (substr($text, $i, strlen($word)) == $word) { // Case matches exactly $score += $options['exact_case_bonus']; } if ($options['abs_length_weight'] != 0.0) { // Absolute length weight (longer words count for more) $score += strlen($word) * $options['abs_length_weight']; } if ($options['rel_length_weight'] != 0.0) { // Relative length weight (longer words count for more) $score += strlen($word) / $maxWordLength * $options['rel_length_weight']; } if (preg_match('/\\W/', substr($text, $i - 1, 1))) { // The start of the word matches exactly $score += $options['exact_word_bonus']; } if (preg_match('/\\W/', substr($text, $i + strlen($word), 1))) { // The end of the word matches exactly $score += $options['exact_word_bonus']; } // Push event occurs when the word comes into range $events[] = array('type' => 'push', 'word' => $word, 'pos' => max(0, $i + strlen($word) - $length), 'score' => $score); // Pop event occurs when the word goes out of range $events[] = array('type' => 'pop', 'word' => $word, 'pos' => $i + 1, 'score' => $score); // Bump event makes it more attractive for words to be in the // middle of the excerpt [@todo: this needs work] $events[] = array('type' => 'bump', 'word' => $word, 'pos' => max(0, $i + floor(strlen($word) / 2) - floor($length / 2)), 'score' => 0.5); } } // If nothing is found then just truncate from the beginning if (empty($events)) { return ''; } // We want to handle each event in the order it occurs in // $events = sortByKey($events, 'pos'); $scores = array(); $score = 0; $current_words = array(); // Process each event in turn foreach ($events as $idx => $event) { $thisPos = floor($event['pos']); $word = strtolower($event['word']); switch ($event['type']) { case 'push': if (empty($current_words[$word])) { // First occurence of a word gets full value $current_words[$word] = 1; $score += $event['score']; } else { // Subsequent occurrences mean less and less $current_words[$word]++; $score += $event['score'] / sizeof($current_words[$word]); } break; case 'pop': if ($current_words[$word] == 1) { unset($current_words[$word]); $score -= $event['score']; } else { $current_words[$word]--; $score -= $event['score'] / sizeof($current_words[$word]); } break; case 'bump': if (!empty($event['score'])) { $score += $event['score']; } break; default: } // Close enough for government work... $score = round($score, 2); // Store the position/score entry $scores[$thisPos] = $score; // For use with debugging $debugWords[$thisPos] = $current_words; // Remove score bump if ($event['type'] == 'bump') { $score -= $event['score']; } } // Calculate the best score // Yeah, could have done this in the main event loop // but it's better here $bestScore = 0; foreach ($scores as $pos => $score) { if ($score > $bestScore) { $bestScore = $score; } } if ($options['debug']) { // This is really quick, really tatty debug information // (but it works) echo "<table border>"; echo "<caption>Events</caption>"; echo "<tr><th>Pos</th><th>Type</th><th>Word</th><th>Score</th>"; foreach ($events as $event) { echo "<tr>"; echo "<td>{$event['pos']}</td><td>{$event['type']}</td><td>{$event['word']}</td><td>{$event['score']}</td>"; echo "</tr>"; } echo "</table>"; echo "<table border>"; echo "<caption>Positions and their scores</caption>"; $idx = 0; foreach ($scores as $pos => $score) { $excerpt = substr($text, $pos, $length); $style = $score == $bestScore ? 'background: #ff7;' : ''; //$score = floor($score + 0.5); echo "<tr>"; echo "<th style=\"{$style}\">" . $idx . "</th>"; echo "<td style=\"{$style}\">" . $pos . "</td>"; echo "<td style=\"{$style}\"><div style=\"float: left; width: 2em; margin-right: 1em; text-align right; background: #ddd\">" . $score . "</div><code>" . str_repeat('*', $score) . "</code></td>"; echo "<td style=\"{$style}\"><table border>"; foreach ($debugWords[$pos] as $word => $count) { echo "<tr><td>{$word}</td><td>{$count}</td></tr>"; } echo "</table></td>"; echo "<td style=\"{$style}\">" . preg_replace('/(' . implode('|', $words) . ')/i', '<b style="border: 1px solid red;">\\1</b>', htmlentities($excerpt)) . "</td>"; echo "</tr>"; $idx++; } echo "</table>"; } // Find all positions that correspond to the best score $positions = array(); foreach ($scores as $pos => $score) { if ($score == $bestScore) { $positions[] = $pos; } } if (sizeof($positions) > 1) { // Scores are tied => do something clever to choose one // @todo: Actually do something clever here $pos = $positions[0]; } else { $pos = $positions[0]; } // Extract the excerpt from the position, (pre|ap)pend the (pre|suf)fix $excerpt = substr($text, $pos, $length); $beginPos = strpos($excerpt, ' ') + 1; $endPos = strrpos($excerpt, ' '); $excerpt = substr($excerpt, $beginPos, $endPos - $beginPos); if ($pos > 0) { $excerpt = $prefix . $excerpt; } if ($pos + $length < strlen($text)) { $excerpt .= $suffix; } return $excerpt; }
function sortKeyAscending($array) { echo "<br/>sortKeyAscending<br/>"; return sortByKey($array); }
/** * Browse repository * * @param Revision $revision * @param string $path * @return array */ function browse($revision, $path = '', $peg_revision = null) { if (intval($revision) !== intval($peg_revision)) { $peg = !is_null($peg_revision) ? "@" . $peg_revision : ''; } else { $peg = ''; } // if $string = 'list -r ' . $revision . ' --xml ' . $this->getRealPath($path) . $peg; $this->execute($string); $list_data = xml2array(implode("\n", $this->output), 1, array('entry')); $list['current_dir'] = $list_data['lists']['list']['attr']['path']; $entries = array(); $dirs = array(); $files = array(); $i = 0; foreach ($list_data['lists']['list']['entry'] as $entry) { // put dirs and files into separate arrays if ($entry['attr']['kind'] == 'dir') { $dirs[$i]['kind'] = $entry['attr']['kind']; $dirs[$i]['name'] = $entry['name']['value']; $dirs[$i]['size'] = $entry['size']['value']; $dirs[$i]['revision'] = $entry['commit']['attr']['revision']; $dirs[$i]['author'] = $entry['commit']['author']['value']; $dirs[$i]['date'] = new DateTimeValue($entry['commit']['date']['value']); } else { $files[$i]['kind'] = $entry['attr']['kind']; $files[$i]['name'] = $entry['name']['value']; $files[$i]['size'] = format_file_size($entry['size']['value']); $files[$i]['revision'] = $entry['commit']['attr']['revision']; $files[$i]['author'] = $entry['commit']['author']['value']; $files[$i]['date'] = new DateTimeValue($entry['commit']['date']['value']); } $i++; } // merge dirs and files array into one array with each of them sorted by name, but // directories go first $list['entries'] = array_merge(sortByKey($dirs, 'name'), sortByKey($files, 'name')); return $list; }