/** * Constructor * @param string $slug */ public function __construct($slug) { $Database = AppCore::GetDatabase(); $Cache = AppCore::GetMemcached(); $mckey = "railpage:news.article_slug=" . $slug; $loaded = false; if ($story_id = $Cache->fetch($mckey)) { try { parent::__construct($story_id); $loaded = true; } catch (Exception $e) { } } /** * Fall back to a database query if we can't load the news article from Memcached */ if (!$loaded) { $story_id = $Database->fetchOne("SELECT sid FROM nuke_stories WHERE slug = ?", $slug); if (filter_var($story_id, FILTER_VALIDATE_INT)) { $Cache->save($mckey, $story_id, strtotime("+6 months")); parent::__construct($story_id); } else { throw new Exception("Could not find a story matching URL slug " . $slug); return false; } } }
/** * Constructor * @since Version 3.10.0 * @return \Railpage\Railcams\Storage */ public function __construct($id = null) { $this->db = AppCore::GetDatabase(); if (filter_var($id, FILTER_VALIDATE_INT)) { $this->id = $id; $this->getConfig(); } }
/** * Constructor * @since Version 3.10.0 * @param \Railpage\Railcams\Camera $cameraObject * @param int|null $id */ public function __construct(Camera $cameraObject, $id = null) { $this->setCamera($cameraObject); $this->db = AppCore::GetDatabase(); if (filter_var($id, FILTER_VALIDATE_INT)) { $this->id = $id; $this->getFootage(); } }
/** * Get read news articles for the given user * @since Version 3.10.0 * @param \Railpage\Users\User $User * @return array */ public static function getReadArticlesForUser($User) { if (!$User instanceof User || $User->id == 0 || $User->guest) { return array(); } $Database = AppCore::GetDatabase(); $query = "SELECT v.story_id, s.title AS story_title FROM nuke_stories_view AS v LEFT JOIN nuke_stories AS s ON s.sid = v.story_id WHERE v.user_id = ?"; return $Database->fetchAll($query, intval($User->id)); }
/** * Get most recent push notification for a given user * @since Version 3.10.0 * @param \Railpage\Users\User|int $User * @return array */ public static function getCurrentNotification($User) { if ($User instanceof User) { $User = $User->id; } $query = "SELECT n.* FROM notifications AS n LEFT JOIN notifications_recipients AS nr ON n.id = nr.notification_id WHERE nr.user_id = ? AND n.transport = ? ORDER BY n.date_sent DESC LIMIT 1"; $params = [$User, Notifications::TRANSPORT_PUSH]; $result = AppCore::GetDatabase()->FetchRow($query, $params); $result['meta'] = json_decode($result['meta'], true); return $result; }
/** * Get a phpBB config item * @since Version 3.10.0 * @param string $key * @return mixed */ public static function getPhpBB($key = null) { $Memcached = AppCore::GetMemcached(); $cachekey = sprintf("railpage:config_phpbb:%s", $key); if ($rs = $Memcached->fetch($cachekey)) { return $rs; } $Database = AppCore::GetDatabase(); $query = "SELECT config_value FROM nuke_bbconfig WHERE config_name = 'allow_html_tags'"; $rs = $Database->fetchOne($query); $Memcached->save($cachekey, $rs, strtotime("+1 month")); return $rs; }
/** * Update the user regdate if required * @since Version 3.10.0 * @param array $data * @return array */ public static function checkUserRegdate($data) { if (!empty($data['user_regdate_nice']) && $data['user_regdate_nice'] != "0000-00-00") { return $data; } if ($data['user_regdate'] == 0) { $data['user_regdate'] = date("Y-m-d"); } $datetime = new DateTime($data['user_regdate']); $data['user_regdate_nice'] = $datetime->format("Y-m-d"); $update['user_regdate_nice'] = $data['user_regdate_nice']; AppCore::GetDatabase()->update("nuke_users", $update, array("user_id = ?" => $data['user_id'])); return $data; }
/** * Create a camera object from an ID or URL slug * @since Version 3.10.0 * @param string|int $id * @return \Railpage\Images\Camera */ public static function CreateCamera($id) { $Database = AppCore::GetDatabase(); $Memcached = AppCore::GetMemcached(); $Redis = AppCore::getRedis(); $Registry = Registry::getInstance(); if (!filter_var($id, FILTER_VALIDATE_INT)) { $cachekey = sprintf("railpage:images.camera.id=%s", $id); if (!($lookup = $Memcached->fetch($cachekey))) { $lookup = $Database->fetchOne("SELECT id FROM image_camera WHERE url_slug = ?", $id); if ($lookup) { $Memcached->save($cachekey, $lookup); } } if (!filter_var($lookup, FILTER_VALIDATE_INT)) { throw new Exception("Could not find a camera ID from URL slug " . $id); } $id = $lookup; } $regkey = sprintf(Camera::CACHE_KEY, $id); try { $Camera = $Registry->get($regkey); } catch (Exception $e) { if (!($Camera = $Redis->fetch($regkey))) { $Camera = new Camera($id); $Redis->save($regkey, $Camera, strtotime("+1 day")); } $Registry->set($regkey, $Camera); } return $Camera; }
/** * @depends test_newUser */ public function test_getNumRegistrationsByMonth($User) { $User->setUserAccountStatus(User::STATUS_ACTIVE); $Base = new Base(); $Database = AppCore::GetDatabase(); $From = new DateTime("today"); $To = new DateTime(); $Base->getNumRegistrationsByMonth($From, $To); }
/** * Get liveries tagged in photos of a locomotive or loco class * @since Version 3.9.1 * @param array $params * @return array */ private static function getLiveriesFromObject($params) { $Database = AppCore::GetDatabase(); $query = "SELECT DISTINCT l.livery_id, l.livery AS name, l.photo_id AS livery_photo_id\n FROM loco_livery AS l\n LEFT JOIN image_link AS il ON il.namespace_key = l.livery_id\n WHERE il.namespace = 'railpage.locos.liveries.livery'\n AND il.image_id IN (\n SELECT image_id FROM image_link WHERE namespace = '" . $params['namespace'] . "' AND namespace_key = ?\n )\n ORDER BY l.livery"; $return = array(); foreach ($Database->fetchAll($query, $params['namespace_key']) as $row) { $return[$row['livery_id']] = array("id" => $row['livery_id'], "name" => $row['name'], "photo" => array("id" => $row['livery_photo_id'], "provider" => "flickr")); } return $return; }
/** * Set some default values for the user data array * @since Version 3.10.0 * @param array $data * @param \Railpage\Users\User $ThisUser * @return array */ public static function setDefaults($data, User $userObject) { $defaults = ["provider" => "railpage", "rank_title" => null, "timezone" => "Australia/Melbourne", "theme" => User::DEFAULT_THEME, "meta" => [], "user_id" => $userObject->id]; $data = array_merge($defaults, $data); $data['user_lastvisit_nice'] = date($data['user_dateformat'], $data['user_lastvisit']); // Fix a dodgy timezone if ($data['timezone'] == "America/Kentucky") { $data['timezone'] = "America/Kentucky/Louisville"; $update['timezone'] = $data['timezone']; AppCore::GetDatabase()->update("nuke_users", $update, array("user_id = ?" => $data['user_id'])); } // Backwards compatibility if ($data['timezone']) { $timezone = new DateTime(null, new DateTimeZone($data['timezone'])); $data['user_timezone'] = str_pad($timezone->getOffset() / 60 / 60, 5, ".00"); } return $data; }
/** * Get the subscription statuses for a given user * @since Version 3.10.0 * @param \Railpage\Users\User $User * @return array */ public static function getSubscriptionFlags(User $User) { $Database = AppCore::GetDatabase(); $query = "SELECT COALESCE(newsletter_daily, 1) AS newsletter_daily,\n COALESCE(newsletter_weekly, 1) AS newsletter_weekly,\n COALESCE(newsletter_monthly, 1) AS newsletter_monthly,\n COALESCE(notify_photocomp, 1) AS notify_photocomp,\n COALESCE(notify_pm, 1) AS notify_pm,\n COALESCE(notify_forums, 1) AS notify_forums\n FROM nuke_users_flags\n WHERE user_id = ?"; return $Database->fetchRow($query, $User->id); }
/** * Fetch the latest information on an album from the relevant provider * @since Version 3.10.0 * @param array $album * @return void */ public static function ScrapeAlbum($album) { Debug::LogCLI("Scraping album ID " . $album['album_id'] . " from provider " . $album['provider']); set_time_limit(30); $Database = AppCore::GetDatabase(); $Provider = ImageUtility::CreateImageProvider($album['provider']); // Assume Flickr for now, we can update the internal code later $params = ["photoset_id" => $album['album_id']]; $albumdata = $Provider->execute("flickr.photosets.getInfo", $params); // Insert this shit into the database $data = ["scraped" => new Zend_Db_Expr("NOW()"), "meta" => json_encode($albumdata['photoset'])]; $where = ["id = ?" => $album['id']]; $Database->update("image_scrape_album", $data, $where); // Fetch the photos $params['user_id'] = $albumdata['photoset']['owner']; $photos = $Provider->execute("flickr.photosets.getPhotos", $params); foreach ($photos['photoset']['photo'] as $photo) { Debug::LogCLI("Scraping photo ID " . $photo['id']); set_time_limit(10); ImageFactory::CreateImage($photo['id'], $album['provider']); Debug::LogCLI("Sleeping for 2 seconds..."); sleep(2); } }
/** * Suggest locos to tag * Ported from \Railpage\Images\Image * @since Version 3.10.0 * @param \Railpage\Images\Image $imageObject * @param bool|null $skipTagged * @return array */ public static function suggestLocos(Image $imageObject, $skipTagged = null) { $locolookup = array(); $locos = array(); $title = self::getCleanedTitleOrDesc($imageObject->title); $desc = self::getCleanedTitleOrDesc($imageObject->description); /** * Loop through all our possible regexes and search */ $regexes = array("[a-zA-Z0-9\\w+]{4,6}", "[0-9\\w+]{3,5}", "[a-zA-Z0-9\\w+]{2}", "[a-zA-Z0-9\\s\\w+]{4,6}"); foreach ($regexes as $regex) { $regex = "/\\b(" . $regex . ")\\b/"; preg_match_all($regex, $title, $matches['title']); preg_match_all($regex, $desc, $matches['description']); if (isset($imageObject->meta['tags']) && count($imageObject->meta['tags'])) { foreach ($imageObject->meta['tags'] as $tag) { // strip the tags #$tag = trim(preg_replace($stripetc, "", $tag)); $tag = self::getCleanedTitleOrDesc($tag); if (empty($tag)) { continue; } preg_match_all($regex, $tag, $matches[]); } } foreach ($matches as $matched) { foreach ($matched as $array) { foreach ($array as $v) { if (empty($v) || !preg_match("/([0-9])/", $v) || preg_match("/(and|to|or|for)/", $v)) { continue; } if (in_array(trim($v), $locolookup)) { continue; } $locolookup[] = trim($v); /* if (!empty( $v ) && preg_match("/([0-9])/", $v) && !preg_match("/(and|to|or|for)/", $v)) { if (!in_array(trim($v), $locolookup)) { $locolookup[] = trim($v); } } */ } } } } /** * Try to include loco numbers with spaces (eg RT 40 vs RT40) in the lookup */ foreach ($locolookup as $num) { if (preg_match("/(\\s)/", $num)) { preg_match("/([a-zA-Z0-9]+)(\\s)([a-zA-Z0-9]+)/", $num, $matches); if (isset($matches[3])) { $prop = sprintf("%s%s", $matches[1], $matches[3]); if (!in_array($prop, $locolookup)) { $locolookup[] = $prop; } } } elseif (strlen($num) == 5) { preg_match("/([a-zA-Z0-9]{2})([0-9]{3})/", $num, $matches); if (isset($matches[2])) { $prop = sprintf("%s %s", $matches[1], $matches[2]); if (!in_array($prop, $locolookup)) { $locolookup[] = $prop; } } } } $locolookup = array_unique($locolookup); /** * Prepare the SQL query */ $query = "SELECT l.loco_id, l.loco_num, l.class_id, c.name AS class_name, s.name AS status_name, s.id AS status_id, t.id AS type_id, t.title AS type_name, g.gauge_id, CONCAT(g.gauge_name, ' ', g.gauge_imperial) AS gauge_formatted, o.operator_id, o.operator_name\r\n FROM loco_unit AS l \r\n LEFT JOIN loco_class AS c ON l.class_id = c.id \r\n LEFT JOIN loco_type AS t ON c.loco_type_id = t.id\r\n LEFT JOIN loco_status AS s ON l.loco_status_id = s.id\r\n LEFT JOIN loco_gauge AS g ON g.gauge_id = l.loco_gauge_id\r\n LEFT JOIN operators AS o ON l.operator_id = o.operator_id\r\n WHERE l.loco_num IN ('" . implode("','", $locolookup) . "') \r\n AND l.loco_status_id NOT IN (2)"; /** * Remove existing tags from our DB query */ if ($skipTagged === true) { $tags = $imageObject->getObjects("railpage.locos.loco"); if (count($tags)) { $ids = array(); foreach ($tags as $tag) { $ids[] = $tag['namespace_key']; } $query .= " AND l.loco_id NOT IN (" . implode(",", $ids) . ")"; } $query .= " ORDER BY CHAR_LENGTH(l.loco_num) DESC"; } /** * Loop through the DB results */ $i = 0; foreach (AppCore::GetDatabase()->fetchAll($query) as $row) { $row['object'] = "Railpage\\Locos\\Locomotive"; $locos[$row['loco_id']] = $row; $i++; if ($i == 5) { break; } } return $locos; }
/** * Get screeners who haven't done any work in the last seven days * @since Version 3.10.0 * @return array */ public static function getLazyScreeners() { $Database = AppCore::GetDatabase(); $query = "SELECT * FROM ( \r\n SELECT u.user_id, u.username, u.user_email, MAX(s.screened_on) AS last_screen \r\n FROM image_flags AS s \r\n LEFT JOIN nuke_users AS u ON u.user_id = s.screened_by \r\n GROUP BY u.user_id \r\n ) AS screeners \r\n WHERE user_id NOT IN (2) \r\n AND last_screen < DATE_SUB(NOW(), INTERVAL 7 DAY)"; return $Database->fetchAll($query); }
/** * Get the push subscription(s) for a user * @since Version 3.10.0 * @param \Railpage\Users\User $User * @return array */ public static function getPushSubscriptions(User $User) { $Database = AppCore::GetDatabase(); $rs = $Database->fetchAll("SELECT * FROM nuke_user_push WHERE user_id = ?", $User->id); foreach ($rs as $key => $val) { if ($val['endpoint'] == "https://android.googleapis.com/gcm/send/") { $rs[$key]['endpoint'] = "https://android.googleapis.com/gcm/send"; } } return $rs; }
/** * List locomotive groupings * Ported from \Railpage\Locos\Locos * @since Version 3.5 * @return array */ public static function getGroupings() { $query = "SELECT * FROM loco_groups ORDER BY group_name"; $return = array("stat" => "ok"); foreach (AppCore::GetDatabase()->fetchAll($query) as $row) { $return['groups'][$row['group_id']] = $row; } return $return; }