/** * Process bbcode inside a string * @since Version 3.10.0 * @param string|DOMDocument $string The HTML or text block to process * @return DOMDocument */ public static function Process($string, $doBbcode = true) { if (!$doBbcode) { return $string; } $timer = Debug::getTimer(); /** * Pre-process the string before we send it through the BBCode parser */ $string = self::preProcessBBCodeUIDs($string); $parser = new Decoda($string); $parser->addPath(__DIR__ . DIRECTORY_SEPARATOR . 'BbcodeEtc' . DIRECTORY_SEPARATOR); $emoticonConfig = ['path' => '//static.railpage.com.au/images/smiles/', 'extension' => 'gif']; $engine = new DecodaPhpEngine(); $engine->addPath(__DIR__ . DIRECTORY_SEPARATOR . 'BbcodeEtc' . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR); $parser->setEngine($engine); $parser->defaults(); $parser->setStrict(false); $parser->setLineBreaks(false); $parser->removeHook('Emoticon'); $parser->addFilter(new RailpageImageFilter()); $string = $parser->parse(); $string = html_entity_decode($string); // Fix: if I set escapeHtml in the Decoda options, it fails to auto linkify links //$string = wpautop($string); Debug::LogEvent(__METHOD__, $timer); return $string; }
/** * Process emoticons inside a string * @since Version 3.10.0 * @param string|DOMDocument $string The HTML or text block to process * @param boolean $doEmoticons Boolean flag for processing or skipping emoticons * @return DOMDocument */ public static function Process($string, $doEmoticons = true) { if (!$doEmoticons) { return $string; } $emojiOne = new EmojioneClient(new EmoticonsRuleset()); $emojiOne->ascii = true; $string = $emojiOne->toImage($string); $attr = "data-sceditor-emoticon"; $timer = Debug::getTimer(); if (is_string($string)) { $string = phpQuery::newDocumentHTML($string); } //phpQuery::selectDocument($doc); // Remove #tinymce and .mceContentBody tags foreach (pq('img') as $e) { if (pq($e)->attr($attr)) { $emoticon = pq($e)->attr($attr); if (strlen($emoticon) > 0) { pq($e)->replaceWith(str_replace('\\"', "", $emoticon)); } } } Debug::LogEvent(__METHOD__, $timer); return $string; }
/** * Constructor */ public function __construct() { parent::__construct(); /** * Record this in the debug log */ Debug::recordInstance(); }
/** * Remove an object from the registry * @since Version 3.9.1 * @param string $key Name of the object to remove * @return \Railpage\Registry; */ public function remove($key) { if (isset($this->registry[strtolower($key)])) { unset($this->registry[strtolower($key)]); } Debug::logEvent(__METHOD__ . "(" . $key . ")"); return $this; }
/** * Constructor * @since Version 3.2 * @version 3.2 * @param int $operator_id */ public function __construct($operator_id = false) { $timer = Debug::getTimer(); parent::__construct(); if (filter_var($operator_id, FILTER_VALIDATE_INT)) { $this->fetch($operator_id); } Debug::logEvent(__METHOD__, $timer); }
/** * Constructor */ public function __construct() { parent::__construct(); Debug::RecordInstance(); /** * Load the Module object */ $this->Module = new Module("glossary"); }
/** * Convert plaintext URI to HTML links. * * Converts URI, www and ftp, and email addresses. Finishes by fixing links * within links. * * @since 0.71 * * @param string $text Content to convert URIs. * @return string Content with converted URIs. */ public static function Process($text) { $timer = Debug::GetTimer(); $r = ''; $textarr = preg_split('/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE); // split out HTML tags foreach ($textarr as $piece) { if (empty($piece) || $piece[0] == '<' && !preg_match('|^<\\s*[\\w]{1,20}+://|', $piece)) { $r .= $piece; continue; } // Long strings might contain expensive edge cases ... if (10000 < strlen($piece)) { // ... break it up foreach (self::_split_str_by_whitespace($piece, 2100) as $chunk) { // 2100: Extra room for scheme and leading and trailing paretheses if (2101 < strlen($chunk)) { $r .= $chunk; // Too big, no whitespace: bail. } else { $r .= make_clickable($chunk); } } } else { $ret = " {$piece} "; // Pad with whitespace to simplify the regexes $url_clickable = '~ ([\\s(<.,;:!?]) # 1: Leading whitespace, or punctuation ( # 2: URL [\\w]{1,20}+:// # Scheme and hier-part prefix (?=\\S{1,2000}\\s) # Limit to URLs less than about 2000 characters long [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+ # Non-punctuation URL character (?: # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character [\'.,;:!?)] # Punctuation URL character [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++ # Non-punctuation URL character )* ) (\\)?) # 3: Trailing closing parenthesis (for parethesis balancing post processing) ~xS'; // The regex is a non-anchored pattern and does not have a single fixed starting character. // Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times. $ret = preg_replace_callback($url_clickable, 'self::_make_url_clickable_cb', $ret); $ret = preg_replace_callback('#([\\s>])((www|ftp)\\.[\\w\\x80-\\xff\\#$%&~/.\\-;:=,?@\\[\\]+]+)#is', 'self::_make_web_ftp_clickable_cb', $ret); $ret = preg_replace_callback('#([\\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\\.)+[0-9a-z]{2,})#i', 'self::_make_email_clickable_cb', $ret); $ret = substr($ret, 1, -1); // Remove our whitespace padding. $r .= $ret; } } // Cleanup of accidental links within links $r = preg_replace('#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', "\$1\$3</a>", $r); Debug::LogEvent(__METHOD__, $timer); return $r; }
/** * Constructor * * @param string|null $country * @param string|bool $region */ public function __construct($country = null, $region = false) { Debug::RecordInstance(); $timer = Debug::GetTimer(); if (is_null($country)) { throw new InvalidArgumentException("No country was specified"); } parent::__construct(); $this->load($country, $region); Debug::LogEvent(__METHOD__, $timer); }
/** * Constructor * @since Version 3.6 * @param int $event_id */ public function __construct($event_id = false) { parent::__construct(); /** * Record this in the debug log */ Debug::RecordInstance(); if ($event_id) { $this->id = $event_id; $this->fetch(); } }
public function testAdd() { if (!defined("RP_DEBUG")) { define("RP_DEBUG", true); } $timer = Debug::getTimer(); Debug::logEvent("testing", $timer); Debug::getLog(); Debug::printPretty(); //Debug::SaveError(new Exception("zomg this is shit")); Debug::printArray("asdafd"); }
/** * Constructor * @since Version 3.8.7 * @var int|string $id */ public function __construct($id = NULL) { $timer = Debug::getTimer(); parent::__construct(); if (!is_null($id)) { if (filter_var($id, FILTER_VALIDATE_INT)) { $row = $this->db->fetchRow("SELECT * FROM wheel_arrangements WHERE id = ?", $id); } elseif (is_string($id)) { $row = $this->db->fetchRow("SELECT * FROM wheel_arrangements WHERE slug = ?", $id); } $this->load($row); } Debug::logEvent(__METHOD__, $timer); }
/** * Constructor * @since Version 3.9.1 * @param int|string $id */ public function __construct($id = false) { $timer = Debug::getTimer(); parent::__construct(); $this->Module = new Module("locos"); if (filter_var($id, FILTER_VALIDATE_INT)) { $this->id = $id; } elseif (is_string($id) && !empty($id)) { $query = "SELECT gauge_id FROM loco_gauge WHERE slug = ?"; $this->id = $this->db->fetchOne($query, $id); } $this->populate(); Debug::logEvent(__METHOD__, $timer); }
/** * Constructor * @since Version 3.8.7 * @var int|string $id */ public function __construct($id = NULL) { $timer = Debug::getTimer(); parent::__construct(); if (filter_var($id, FILTER_VALIDATE_INT)) { $row = $this->db->fetchRow("SELECT * FROM loco_type WHERE id = ?", $id); $this->load($row); } $id = filter_var($id, FILTER_SANITIZE_STRING); if (!is_null($id)) { $row = $this->db->fetchRow("SELECT * FROM loco_type WHERE slug = ?", $id); $this->load($row); } Debug::logEvent(__METHOD__, $timer); }
/** * Get $num newest images * @since Version 3.10.0 * @param int $num * @return array * @todo $cacheProvider doesn't seem to bloody work! */ public static function getNewest($num = 5) { $cacheProvider = AppCore::GetMemcached(); $mckey = sprintf("railpage:images.recent=%d;url.cached", $num); if ($newphotos = $cacheProvider->fetch($mckey)) { Debug::LogCLI("Fetched new photos from cache provider using cache key " . $mckey); return $newphotos; } $newphotos = (new Images())->getRecentAdditions(5); shuffle($newphotos); foreach ($newphotos as $id => $data) { $newphotos[$id]['meta']['sizes']['medium']['source'] = ImageCache::cache($newphotos[$id]['meta']['sizes']['medium']['source']); } $rs = $cacheProvider->save($mckey, $newphotos, 900); // save for 15 minutes Debug::LogCLI("Saved new photos in cache provider using cache key " . $mckey); if ($res = $cacheProvider->fetch($mckey)) { Debug::LogCLI("new photos found in cache, success"); } return $newphotos; }
/** * Constructor * * @since Version 3.8.7 * * @param string $default_url */ public function __construct($default_url = false) { Debug::RecordInstance(); $timer = Debug::getTimer(); if ($default_url !== false) { $this->url = $default_url; $fwlink = new fwlink($this->url); $this->short = $fwlink->url_short; /** * Create the canonical link */ $rp_host = defined("RP_HOST") ? RP_HOST : "www.railpage.com.au"; $rp_root = defined("RP_WEB_ROOT") ? RP_WEB_ROOT : ""; if (substr($this->url, 0, 4) == "http") { $this->canonical = $this->url; } else { $this->canonical = sprintf("http://%s%s%s", $rp_host, $rp_root, $this->url); } } Debug::logEvent(__METHOD__, $timer); }
/** * Constructor * * @param int $id */ public function __construct($id = null) { $timer = Debug::getTimer(); parent::__construct(); if ($id = filter_var($id, FILTER_VALIDATE_INT)) { $this->id = $id; $this->populate(); } Debug::logEvent(__METHOD__, $timer); }
/** * @depends test_createPhotos * @depends test_createUser */ public function test_votePhotos($photoComp, $userObject) { $photoComp->SubmissionsDateOpen = (new DateTime())->sub(new DateInterval("P10D")); $photoComp->SubmissionsDateClose = (new DateTime())->sub(new DateInterval("P3D")); $photoComp->VotingDateOpen = (new DateTime())->sub(new DateInterval("P1D")); $photoComp->VotingDateClose = (new DateTime())->add(new DateInterval("P10D")); $this->assertTrue($photoComp->canUserVote($userObject)); $this->assertFalse(empty($photoComp->getPhotosAsArray(true))); foreach ($photoComp->getPhotos() as $Photo) { Debug::LogCLI("Voting for photo ID " . $Photo->Image->id); $this->assertEquals(0, $photoComp->getNumVotesForImage($Photo->Image)); $this->assertTrue($photoComp->canUserVote($userObject, $Photo->Image)); $photoComp->submitVote($userObject, $Photo->Image); $this->assertfalse($photoComp->canUserVote($userObject, $Photo->Image)); $this->assertEquals(1, $photoComp->getNumVotesForImage($Photo->Image)); $this->winning_id = $Photo->Image->id; break; } $photoComp->getNumVotesForUser(new User()); $photoComp->SubmissionsDateOpen->sub(new DateInterval("P10W")); $photoComp->SubmissionsDateClose->sub(new DateInterval("P10W")); $photoComp->VotingDateOpen->sub(new DateInterval("P10W")); $photoComp->VotingDateClose->sub(new DateInterval("P10W")); $photoComp->getVoteCountsPerDay(); $winner = $photoComp->getWinningPhoto(); $this->assertFalse($winner == false); $this->assertEquals($this->winning_id, $winner->Image->id); }
/** * Format an avatar * @since Version 3.9.1 * @return string * @param string $userAvatar * @param int $width * @param width $height */ public static function format($userAvatar = null, $width = 100, $height = 100) { if (is_null($userAvatar)) { return false; } $cacheHandler = AppCore::getMemcached(); $timer = Debug::getTimer(); if ($userAvatar == "http://www.railpage.com.au/modules/Forums/images/avatars/https://static.railpage.com.au/image_resize") { $userAvatar = self::DEFAULT_AVATAR; } if (empty($userAvatar) || stristr($userAvatar, "blank.gif") || stristr($userAvatar, "blank.png")) { $userAvatar = self::DEFAULT_AVATAR; return $userAvatar; } $parts = parse_url($userAvatar); if (isset($parts['host']) && $parts['host'] == "static.railpage.com.au" && isset($parts['query'])) { parse_str($parts['query'], $query); if (isset($query['w']) && isset($query['h']) && isset($query['image'])) { if ($query['w'] == $width && $query['h'] == $height) { return $userAvatar; } return sprintf("http://static.railpage.com.au/image_resize.php?w=%d&h=%d&image=%s", $width, $height, $query['image']); } } if (isset($parts['host']) && $parts['host'] == "www.gravatar.com" && isset($parts['query'])) { parse_str($parts['query'], $query); $query['s'] = $width; $bits = array(); foreach ($query as $key => $val) { $bits[] = sprintf("%s=%s", $key, $val); } $userAvatar = sprintf("%s://%s%s?%s", $parts['scheme'], $parts['host'], $parts['path'], implode("&", $bits)); return self::GravatarHTTPS($userAvatar); } $mckey = sprintf("railpage.user:avatar=%s;width=%s;height=%s", $userAvatar, $width, $height); /** * Check if this shit is in Memcache first */ if ($result = $cacheHandler->fetch($mckey)) { return self::GravatarHTTPS($result); } /** * It's not in Memcached, so let's process and cache it */ parse_str(parse_url($userAvatar, PHP_URL_QUERY), $args); if (isset($args['base64_args'])) { if (!@unserialize(base64_decode($args['base64_args']))) { // Malformed string! $userAvatar = self::DEFAULT_AVATAR; } else { // Do other stuff... $base64 = unserialize(base64_decode($args['base64_args'])); } } if (preg_match("@modules/Forums/images/avatars/(http\\:\\/\\/|https\\:\\/\\/)@", $userAvatar)) { $userAvatar = self::DEFAULT_AVATAR; } if (!preg_match("@(http\\:\\/\\/|https\\:\\/\\/)@", $userAvatar)) { $userAvatar = "http://static.railpage.com.au/modules/Forums/images/avatars/" . $userAvatar; } if (!ContentUtility::url_exists($userAvatar)) { $userAvatar = self::DEFAULT_AVATAR; } if ($width && !$height) { $height = $width; } // Is this an anigif? if (substr($userAvatar, -4, 4) == ".gif") { // Fetch the dimensions $mckey = "railpage:avatar.size=" . md5($userAvatar); if ($dimensions = $cacheHandler->fetch($mckey)) { // Do nothing } else { $dimensions = @getimagesize($userAvatar); $cacheHandler->save($mckey, $dimensions); } if (isset($dimensions['mime']) && $dimensions['mime'] == "image/gif") { // Great, it's a gif if ($width && $height) { if ($dimensions[0] <= $width && $dimensions[1] <= $height) { // It fits within the width and height - return it as-is return self::GravatarHTTPS($userAvatar); } } } } // Assume that all avatars created on dev.railpage.com.au are shit and should be re-directed to static.railpage.com.au $userAvatar = str_replace("dev.railpage.com.au", "static.railpage.com.au", $userAvatar); if ($width && $height) { $args['width'] = $width; $args['height'] = $height; $args['url'] = $userAvatar; if (empty($userAvatar)) { $args['url'] = self::DEFAULT_AVATAR; } #$userAvatar = "https://static.railpage.com.au/image_resize.php?base64_args=".base64_encode(serialize($args)); $userAvatar = sprintf("https://static.railpage.com.au/image_resize.php?w=%d&h=%d&image=%s", $args['width'], $args['height'], $args['url']); if ($width == $height) { $userAvatar .= "&square=true"; } } $cacheHandler->save($mckey, $userAvatar, 0); Debug::logEvent(__METHOD__, $timer); return self::GravatarHTTPS($userAvatar); }
/** * Get latest photo from this railcam * @since Version 3.10.0 * @return \Railpage\Railcams\Photo * @param boolean $update Update cached data if it's stale */ public function getLatest($update = true) { if ($footage = $this->getLatestFootage("image")) { return ["id" => $footage['id'], "title" => "", "description" => "", "dates" => ["taken" => $footage['datestored']], "sizes" => ["original" => ["source" => $footage['url']['original']]]]; } $mckey = sprintf("railpage:railcam=%d;latest=1", $this->id); /** * Shitty, hacky way to handle Memcached expiry bug on Debian */ $mckey_age = $mckey . ";expiry"; $exp = $this->Memcached->fetch($mckey_age); if ($update && (!$exp || $exp < time())) { $this->Memcached->delete($mckey); } /** * Fetch from Memcached, or load from API */ if (!($latest = $this->Memcached->fetch($mckey))) { $latest = $this->getPhotos(1); Debug::LogCLI("Fetched " . count($latest['photo']) . " photo(s)"); foreach ($latest['photo'] as $key => $photo) { Debug::LogCLI("Processing photo..."); $photo['timezone'] = $this->timezone; $Date = new DateTime($photo['datetaken']); $Date->setTimezone(new DateTimeZone($this->timezone)); $photo['datetaken'] = $Date->format("c"); $latest['photo'][$key] = $photo; } Debug::LogCLI("Saving photo in Memcached"); $this->Memcached->save($mckey, $latest, 0); Debug::LogCLI("Saving photo expiry in Memcached"); $this->Memcached->save($mckey_age, strtotime("+5 minutes"), 0); } return $this->getPhoto($latest['photo'][0]['id']); }
/** * Find events where key = x and optionally value = y * @since Version 3.6 * @param mixed $keys * @param mixed $value * @param int $limit * @return array */ public function find($keys = false, $value = false, $limit = 25) { $timer = Debug::getTimer(); if (!$keys) { throw new Exception("Cannot find events - \$keys cannot be empty"); return false; } $clause = array(); $where = array(); if (is_array($keys)) { $clause[] = "`key` IN ('" . implode("','", $keys) . "')"; } elseif (is_string($keys)) { $clause[] = $this->db instanceof sql_db ? " `key` = '" . $this->db->real_escape_string($keys) . "'" : " `key` = ?"; $where[] = $keys; } if ($value) { $clause[] = $this->db instanceof sql_db ? " `value` = '" . $this->db->real_escape_string($value) . "'" : " `value` = ?"; $where[] = $value; } if (count($clause)) { $sql_where = "WHERE " . implode(" AND ", $clause); } $query = "SELECT e.id, e.user_id, u.username, e.timestamp, e.title, e.args, e.key, e.value FROM log_general AS e INNER JOIN nuke_users AS u ON u.user_id = e.user_id " . $sql_where . " ORDER BY e.timestamp DESC LIMIT 0, ?"; $where[] = $limit; $return = array(); foreach ($this->db->fetchAll($query, $where) as $row) { $row['timestamp'] = new DateTime($row['timestamp']); $row['args'] = json_decode($row['args'], true); $return[$row['id']] = $row; } Debug::logEvent(__METHOD__, $timer); return $return; }
/** * Create other sizes * @since Version 3.10.0 * @return void */ public static function createOtherSizes() { $sleep = 2; $sleep = false; $Database = (new AppCore())->getDatabaseConnection(); $query = "SELECT i.id,\r\n square.size AS square, square.source AS square_src, square.width AS square_w, square.height AS square_h,\r\n large_square.size AS large_square, large_square.source AS large_square_src, large_square.width AS large_square_w, large_square.height AS large_square_h,\r\n small.size AS small, small.source AS small_src, small.width AS small_w, small.height AS small_h,\r\n small_320.size AS small_320, small_320.source AS small_320_src, small_320.width AS small_320_w, small_320.height AS small_320_h,\r\n medium.size AS medium, medium.source AS medium_src, medium.width AS medium_w, medium.height AS medium_h,\r\n medium_640.size AS medium_640, medium_640.source AS medium_640_src, medium_640.width AS medium_640_w, medium_640.height AS medium_640_h,\r\n medium_800.size AS medium_800, medium_800.source AS medium_800_src, medium_800.width AS medium_800_w, medium_800.height AS medium_800_h,\r\n original.size AS original, original.source AS original_src, original.width AS original_w, original.height AS original_h\r\n FROM gallery_mig_image AS i\r\n LEFT JOIN gallery_mig_image_sizes AS square ON square.photo_id = i.id AND square.size = 'square'\r\n LEFT JOIN gallery_mig_image_sizes AS large_square ON large_square.photo_id = i.id AND large_square.size = 'large_square'\r\n LEFT JOIN gallery_mig_image_sizes AS small ON small.photo_id = i.id AND small.size = 'small'\r\n LEFT JOIN gallery_mig_image_sizes AS small_320 ON small_320.photo_id = i.id AND small_320.size = 'small_320'\r\n LEFT JOIN gallery_mig_image_sizes AS medium ON medium.photo_id = i.id AND medium.size = 'medium'\r\n LEFT JOIN gallery_mig_image_sizes AS medium_640 ON medium_640.photo_id = i.id AND medium_640.size = 'medium_640'\r\n LEFT JOIN gallery_mig_image_sizes AS medium_800 ON medium_800.photo_id = i.id AND medium_800.size = 'medium_800'\r\n LEFT JOIN gallery_mig_image_sizes AS original ON original.photo_id = i.id AND original.size = 'original'\r\n WHERE i.hidden = 0\r\n AND square.size IS NULL\r\n AND large_square.size IS NULL\r\n AND small.size IS NULL\r\n AND small_320.size IS NULL\r\n AND medium.size IS NULL\r\n AND medium_640.size IS NULL\r\n AND medium_800.size IS NULL\r\n LIMIT 0, 250"; $result = $Database->fetchAll($query); /** * Set our desired sizes */ $sizes = ["square" => ["width" => 75, "height" => 75], "large_square" => ["width" => 150, "height" => 150], "small" => ["width" => 240, "height" => 0], "small_320" => ["width" => 320, "height" => 0], "medium" => ["width" => 500, "height" => 0], "medium_640" => ["width" => 640, "height" => 0], "medium_800" => ["width" => 800, "height" => 0]]; /** * Loop through the results and start building the sizes */ foreach ($result as $row) { /** * Load the original image from disk. If it doesn't exist then continue to the next array item */ $filename = sprintf("%s%s", Album::ALBUMS_DIR, $row['original_src']); if (!file_exists($filename)) { continue; } $ext = pathinfo($filename, PATHINFO_EXTENSION); $allowedtypes = ["jpeg", "jpg", "png", "gif"]; if (!in_array($ext, $allowedtypes)) { continue; } $noext = str_replace("." . $ext, "", $filename); $image = file_get_contents($filename); Debug::LogCLI("Source image " . $filename); /** * Loop through each required size */ foreach ($sizes as $key => $dims) { /** * If the size already exists in DB then proceed to the next size */ if (!is_null($row[$key]) || $key == "original") { continue; } /** * Break out of the loop if the desired size is larger than than the original image */ if ($dims['width'] > $row['original_w']) { continue; } $dstfile = sprintf("%s.%s.%s", $noext, $key, $ext); if (file_exists($dstfile)) { unlink($dstfile); } Debug::LogCLI(" Creating " . $key . " from image " . $filename); Debug::LogCLI(""); $Image = WideImage::loadFromString($image); if ($dims['width'] == $dims['height']) { $size = $Image->resize($dims['width'], $dims['height'], "outside"); $size = $size->crop(0, "middle", $dims['width'], $dims['height']); } if ($dims['width'] != $dims['height']) { $size = $Image->resize($dims['width'], $dims['width'], "inside"); } $quality = $dims['width'] <= 240 ? 80 : 100; file_put_contents($dstfile, $size->asString("jpg", $quality)); if (file_exists($dstfile)) { Debug::LogCLI(" Image created, inserting into DB"); Debug::LogCLI(" " . $dstfile); $data = ["photo_id" => $row['id'], "size" => $key, "source" => $dstfile, "width" => $size->getWidth(), "height" => $size->getHeight()]; $Database->insert("gallery_mig_image_sizes", $data); } Debug::LogCLI(" ---"); } if ($sleep) { Debug::LogCLI("-------------------------------"); Debug::LogCLI(""); Debug::LogCLI("Sleeping for two seconds"); Debug::LogCLI(""); sleep($sleep); } Debug::LogCLI("-------------------------------"); Debug::LogCLI(""); } }
/** * Check SpamCop for the given IP address * @since Version 3.10.0 * @return boolean * @param string $ip */ public static function spamCop($ip) { if (!filter_var($ip, FILTER_VALIDATE_IP)) { $ip = $_SERVER['REMOTE_ADDR']; } $timer = Debug::GetTimer(); $reversedIp = implode(".", array_reverse(explode(".", $ip))); $host = $reversedIp . ".bl.spamcop.net"; $response = gethostbyname($host); if (stristr($response, "127.0.0")) { return true; } Debug::LogEvent(__METHOD__, $timer); return false; }
/** * Build the Forums ACL * @since Version 3.8.7 * @param boolean $force Force an update of the ACL * @todo Finish this shit */ public function buildACL($force = false) { $Registry = Registry::getInstance(); try { $ForumsACL = $Registry->get("forumsacl"); $this->ZendACL = $ForumsACL; return; } catch (Exception $e) { // F**k it } Debug::RecordInstance(__METHOD__); $timer = Debug::getTimer(); $acl = $Registry->get("acl"); if (!$this->User instanceof User) { throw new Exception("A valid user must be set before the ACL can be built"); } $mckey = "railpage.forums.list"; if ($force || !($forums = $this->Memcached->fetch($mckey))) { $query = "SELECT forum_id FROM nuke_bbforums"; $forums = $this->db->fetchAll($query); $this->Memcached->save($mckey, $forums); } $acl_forums = array(); /** * Add all the forums to the ACL */ foreach ($forums as $row) { $acl_forum_name = sprintf("railpage.forums.forum:%d", $row['forum_id']); $acl_forums[$row['forum_id']] = $acl_forum_name; try { $acl->get($acl_forum_name); } catch (Exception $e) { $acl->addResource(new Zend_Acl_Resource($acl_forum_name)); } } /** * Get the forum permissions from the database */ $a_sql = array("auth_view", "auth_read", "auth_post", "auth_reply", "auth_edit", "auth_delete", "auth_sticky", "auth_announce", "auth_vote", "auth_pollcreate"); $auth_fields = array('auth_view', 'auth_read', 'auth_post', 'auth_reply', 'auth_edit', 'auth_delete', 'auth_sticky', 'auth_announce', 'auth_vote', 'auth_pollcreate'); $query = "SELECT forum_id, " . implode(", ", $a_sql) . ", " . self::AUTH_ACL . " AS auth_mod FROM nuke_bbforums"; $db_acl = array(); foreach ($this->db->fetchAll($query) as $row) { $db_acl[$row['forum_id']] = $row; } /** * Get the group permissions for this user */ $query = "SELECT a.* FROM nuke_bbauth_access AS a WHERE a.group_id IN (SELECT group_id FROM nuke_bbuser_group WHERE user_id = ? AND user_pending = 0)"; $gperms = array(); foreach ($this->db->fetchAll($query, $this->User->id) as $perm) { $forum_id = $perm['forum_id']; $group_id = $perm['group_id']; unset($perm['forum_id']); unset($perm['group_id']); $gperms[$forum_id][$group_id] = $perm; } /** * Guest details */ $guestfucknamingthis = [self::AUTH_MOD => $this->User->inGroup(RP_GROUP_MODERATORS), self::AUTH_ADMIN => $this->User->inGroup(RP_GROUP_ADMINS)]; /** * Add the forum permissions to Zend_ACL */ foreach ($db_acl as $forum_id => $permissions) { $allowed = array(); $denied = array(); unset($permissions['forum_id']); $allowed = array_merge($allowed, array_keys($permissions, self::AUTH_ALL)); if (!$this->User->guest) { $allowed = array_merge($allowed, array_keys($permissions, self::AUTH_REG)); } if ($guestfucknamingthis[self::AUTH_MOD]) { $allowed = array_merge($allowed, array_keys($permissions, self::AUTH_MOD)); } if ($guestfucknamingthis[self::AUTH_ADMIN]) { $allowed = array_merge($allowed, array_keys($permissions, self::AUTH_ADMIN)); } $perms_acl = array_keys($permissions, self::AUTH_ACL); if (count($perms_acl)) { if (isset($gperms[$forum_id])) { foreach ($gperms[$forum_id] as $group) { foreach ($group as $gitem => $gval) { $allowed = array_merge($allowed, array_keys($permissions, self::AUTH_REG)); if ($guestfucknamingthis[self::AUTH_MOD]) { $allowed = array_merge($allowed, array_keys($permissions, self::AUTH_MOD)); } if ($guestfucknamingthis[self::AUTH_ADMIN]) { $allowed = array_merge($allowed, array_keys($permissions, self::AUTH_ADMIN)); } } } } } $allowed = array_unique($allowed); #continue; /* foreach ($permissions as $item => $value) { switch ($value) { case self::AUTH_ACL . "zzz" : if (isset($gperms[$forum_id])) { foreach ($gperms[$forum_id] as $group) { foreach ($group as $gitem => $gval) { switch ($gval) { case self::AUTH_REG : $allowed[] = $item; break; case self::AUTH_ACL : // Inception break; case self::AUTH_MOD : if ($this->User->inGroup(RP_GROUP_MODERATORS)) { $allowed[] = $gitem; } break; case self::AUTH_ADMIN : if ($this->User->inGroup(RP_GROUP_ADMINS)) { $allowed[] = $gitem; } break; } } } } break; case self::AUTH_MOD . "zzz": if ($this->User->inGroup(RP_GROUP_MODERATORS)) { $allowed[] = $item; } break; case self::AUTH_ADMIN . "zzz" : if ($this->User->inGroup(RP_GROUP_ADMINS)) { $allowed[] = $item; } break; } } */ foreach ($permissions as $item => $value) { if (!in_array($item, $allowed)) { $denied[] = $item; } } #$allowed = array_unique($allowed); #$denied = array_unique($denied); $acl->allow("forums_viewer", sprintf("railpage.forums.forum:%d", $forum_id), $allowed); $acl->deny("forums_viewer", sprintf("railpage.forums.forum:%d", $forum_id), $denied); } $Registry->set("acl", $acl); $Registry->set("forumsacl", $acl); $this->ZendACL = $acl; Debug::LogEvent(__METHOD__, $timer); return; }
/** * Constructor * @since Version 3.8.7 * * @param int|string $id */ public function __construct($id = NULL) { $timer = Debug::getTimer(); parent::__construct(); if (!is_null($id)) { if (filter_var($id, FILTER_VALIDATE_INT)) { $query = "SELECT * FROM loco_manufacturer WHERE manufacturer_id = ?"; $row = $this->db->fetchRow($query, $id); } elseif (is_string($id)) { $query = "SELECT * FROM loco_manufacturer WHERE slug = ?"; $row = $this->db->fetchRow($query, $id); } if (isset($row) && count($row)) { $this->id = $row['manufacturer_id']; $this->name = $row['manufacturer_name']; $this->desc = $row['manufacturer_desc']; $this->slug = $row['slug']; if (empty($this->slug)) { $proposal = ContentUtility::generateUrlSlug($this->name, 30); $query = "SELECT manufacturer_id FROM loco_manufacturer WHERE slug = ?"; $result = $this->db->fetchAll($query, $proposal); if (count($result)) { $proposal = $proposal . count($result); } $this->slug = $proposal; $this->commit(); } $this->url = new Url(sprintf("/locos/builder/%s", $this->slug)); } } Debug::logEvent(__METHOD__, $timer); }
/** * Find an image by provider and provider image ID * @since Version 3.8.7 * @param string $provider * @param int $photoId * @param mixed $option * @throws \Exception if $provider is null * @throws \Exception if $photoId is null * @param int $option */ public function findImage($provider = null, $photoId = null, $option = null) { if (is_null($provider)) { throw new Exception("Cannot lookup image from image provider - no provider given (hint: Flickr, WestonLangford)"); } if (!preg_match("/([a-zA-Z0-9]+)/", $photoId) || $photoId === 0) { throw new Exception("Cannot lookup image from image provider - no provider image ID given"); } $mckey = sprintf("railpage:image;provider=%s;id=%s", $provider, $photoId); if (defined("NOREDIS") && NOREDIS == true || $option != self::OPT_REFRESH && !($id = $this->Redis->fetch($mckey))) { Debug::LogCLI("Found photo ID " . $photoId . " in database"); $id = $this->db->fetchOne("SELECT id FROM image WHERE provider = ? AND photo_id = ?", array($provider, $photoId)); $this->Redis->save($mckey, $id, strtotime("+1 month")); } if (isset($id) && filter_var($id, FILTER_VALIDATE_INT)) { return new Image($id, $option); } Debug::LogCLI("Photo ID " . $photoId . " not found in local cache"); $Image = new Image(); $Image->provider = $provider; $Image->photo_id = $photoId; $Image->populate(true, $option); return $Image; }
/** * Commit changes to database * @since Version 3.2 * @version 3.8.7 * @return boolean */ public function commit() { $timer = Debug::getTimer(); $this->validate(); $data = Utility\LocomotiveUtility::getSubmitData($this); if (!filter_var($this->id, FILTER_VALIDATE_INT)) { $rs = $this->db->insert("loco_unit", $data); $this->id = $this->db->lastInsertId(); $verb = "Insert"; } else { $this->Memcached->delete($this->mckey); $this->Redis->delete($this->mckey); $where = array("loco_id = ?" => $this->id); $verb = "Update"; $rs = $this->db->update("loco_unit", $data, $where); } // Update the registry $Registry = Registry::getInstance(); $regkey = sprintf(self::REGISTRY_KEY, $this->id); $Registry->remove($regkey)->set($regkey, $this); $this->Memcached->delete(sprintf(self::CACHE_KEY_DESC, $this->id)); Debug::logEvent("Zend_DB: commit loco ID " . $this->id, $timer); $this->makeLinks(); return true; }
/** * Get an instance of Memcache for legacy code * @since Version 3.9.1 * @return object * @param boolean $reload Don't fetch the cache handler from the registry and instead create a new instance */ public static function getMemcache($reload = false) { if (!extension_loaded("memcache") || defined("PHPUNIT_RAILPAGE_TESTSUITE")) { return new NullCacheDriver(); } $Registry = Registry::getInstance(); if ($reload) { $Registry->remove("memcache"); } try { $memcache = $Registry->get("memcache"); } catch (Exception $e) { $memcache = false; Debug::logEvent(__METHOD__ . " -- Looking for memcache.php"); if (file_exists(__DIR__ . DIRECTORY_SEPARATOR . "memcache.php")) { require __DIR__ . DIRECTORY_SEPARATOR . "memcache.php"; } $Registry->set("memcache", $memcache); } return $memcache; }
/** * Populate this object * @since Version 3.9.1 * @return void */ private function populate() { $timer = Debug::getTimer(); $this->mckey = sprintf("railpage:organisations.organisation=%d", $this->id); if (!($row = $this->Memcached->fetch($this->mckey))) { $query = "SELECT o.* FROM organisation AS o WHERE organisation_id = ?"; $row = $this->db->fetchRow($query, $this->id); $this->Memcached->save($this->mckey, $row); } $lookup = ["name" => "organisation_name", "desc" => "organisation_desc", "created" => "organisation_dateadded", "owner" => "organisation_owner", "contact_website" => "organisation_website", "contact_phone" => "organisation_phone", "contact_fax" => "organisation_fax", "contact_email" => "organisation_email", "loco" => "organisation_logo", "flickr_photo_id" => "flickr_photo_id", "slug" => "organisation_slug"]; foreach ($lookup as $var => $val) { $this->{$var} = $row[$val]; } /* $this->name = $row['organisation_name']; $this->desc = $row['organisation_desc']; $this->created = $row['organisation_dateadded']; $this->owner = $row['organisation_owner']; $this->contact_website = $row['organisation_website']; $this->contact_phone = $row['organisation_phone']; $this->contact_fax = $row['organisation_fax']; $this->contact_email = $row['organisation_email']; $this->logo = $row['organisation_logo']; $this->flickr_photo_id = $row['flickr_photo_id']; $this->slug = $row['organisation_slug']; */ if (empty($this->slug)) { $this->slug = parent::createSlug(); } $this->url = parent::makePermaLink($this->slug); $this->loadRoles(); Debug::logEvent(__METHOD__, $timer); }
/** * Constructor * @since Version 3.4 */ public function __construct() { // Placeholder - do nothing for now Debug::RecordInstance(); }
/** * Fetch the users' timeline * @since Version 3.5 * * @param object $dateStart * @param object $dateEnd * * @return array */ public function timeline($dateStart, $dateEnd) { $timer = Debug::GetTimer(); $timezzz = (new Timeline())->setUser($this)->generateTimeline($dateStart, $dateEnd); Debug::LogEvent(__METHOD__, $timer); return $timezzz; #return Timeline::GenerateTimeline($this, $date_start, $date_end); }