/** * Return a locomotive * * @since Version 3.9.1 * @return \Railpage\Locos\Locomotive * * @param int|bool $id * @param string|bool $class * @param string|bool $number */ public static function CreateLocomotive($id = false, $class = false, $number = false) { $Redis = AppCore::getRedis(); $Registry = Registry::getInstance(); if (!filter_var($id, FILTER_VALIDATE_INT)) { $id = Utility\LocomotiveUtility::getLocoId($class, $number); } if ($id = filter_var($id, FILTER_VALIDATE_INT)) { $regkey = sprintf(Locomotive::REGISTRY_KEY, $id); try { $Loco = $Registry->get($regkey); } catch (Exception $e) { $cachekey = sprintf(Locomotive::CACHE_KEY, $id); if (!self::USE_REDIS || !($Loco = $Redis->fetch($cachekey))) { $Loco = new Locomotive($id); if (self::USE_REDIS) { $Redis->save($cachekey, $Loco); } } $Registry->set($regkey, $Loco); } return $Loco; } return false; }
/** * Return an event * @since Version 3.9.1 * @return \Railpage\Organisations\Organisation * @param int|string $id */ public static function CreateOrganisation($id = false) { $Memcached = AppCore::getMemcached(); $Redis = AppCore::getRedis(); $Registry = Registry::getInstance(); if (!filter_var($id, FILTER_VALIDATE_INT)) { $slugkey = sprintf(Organisation::REGISTRY_KEY, $id); try { $id = $Registry->get($slugkey); } catch (Exception $e) { $Database = (new AppCore())->getDatabaseConnection(); $id = $Database->fetchOne("SELECT organisation_id FROM organisation WHERE organisation_slug = ?", $id); $Registry->set($slugkey, $id); } } $regkey = sprintf(Organisation::REGISTRY_KEY, $id); try { $Organisation = $Registry->get($regkey); } catch (Exception $e) { $cachekey = sprintf(Organisation::CACHE_KEY, $id); if (!self::USE_REDIS || !($Organisation = $Redis->fetch($cachekey))) { $Organisation = new Organisation($id); if (self::USE_REDIS) { $Redis->save($cachekey, $Organisation); } } $Registry->set($regkey, $Organisation); } return $Organisation; }
/** * Return a user * @since Version 3.9.1 * @return \Railpage\Users\User * @param int|string $id */ public static function CreateUser($id = null) { $Redis = AppCore::getRedis(); $Registry = Registry::getInstance(); $regkey = sprintf(User::REGISTRY_KEY, $id); try { $User = $Registry->get($regkey); } catch (Exception $e) { if (!($User = $Redis->fetch(sprintf("railpage:users.user=%d", $id)))) { $User = new User($id); $Redis->save(sprintf("railpage:users.user=%d", $id), $User, 60 * 60 * 2); } $Registry->set($regkey, $User); } return $User; }
/** * Return an instance of EventCategory * @since Version 3.9.1 * @return \Railpage\Events\EventCategory * @param int|string $id */ public static function CreateEventCategory($id = null) { $CacheDriver = AppCore::getRedis(); $Registry = Registry::getInstance(); $regkey = sprintf(EventCategory::REGISTRY_KEY, $id); try { $EventCategory = $Registry->get($regkey); } catch (Exception $e) { $cachekey = sprintf(EventCategory::CACHE_KEY, $id); if (!self::USE_REDIS || !($EventCategory = $CacheDriver->fetch($cachekey))) { $EventCategory = new EventCategory($id); if (self::USE_REDIS) { $CacheDriver->save($cachekey, $EventCategory); } } $Registry->set($regkey, $EventCategory); } return $EventCategory; }
/** * Return a news article * @since Version 3.9.1 * @return \Railpage\News\Article * @param int|string $id */ public static function CreateArticle($id) { $Redis = AppCore::getRedis(); $Memcached = AppCore::getMemcached(); $Registry = Registry::getInstance(); /** * Lookup article slug-to-ID first */ if (!filter_var($id, FILTER_VALIDATE_INT)) { $mckey = sprintf("railpage:news.article_slug=%s", $id); if (!($article_id = $Memcached->fetch($mckey))) { $Database = AppCore::getDatabase(); $article_id = $Database->fetchOne("SELECT sid FROM nuke_stories WHERE slug = ?", $id); } if (!filter_var($article_id, FILTER_VALIDATE_INT)) { throw new Exception("Could not find an article ID matching URL slug " . $id); } $id = $article_id; } /** * We have an integer article ID, so go ahead and load it */ $regkey = sprintf(Article::REGISTRY_KEY, $id); try { $Article = $Registry->get($regkey); } catch (Exception $e) { if ($Article = $Redis->fetch($regkey)) { $Article->Memcached = $Memcached; $Article->Redis = $Redis; $Database = AppCore::getDatabase(); $Article->setDatabaseConnection($Database)->setDatabaseReadOnlyConnection($Database); } else { $Article = new Article($id); $Redis->save($regkey, $Article); } $Registry->set($regkey, $Article); } return $Article; }
/** * Create a photo competition object from an ID or URL slug * @since Version 3.10.0 * @param string|int $id * @return \Railpage\Images\Competition */ public static function CreatePhotoComp($id) { //$Database = AppCore::GetDatabase(); $cacheHandler = AppCore::getRedis(); $Registry = Registry::getInstance(); if (!filter_var($id, FILTER_VALIDATE_INT)) { $lookup = Utility\CompetitionUtility::getIDFromSlug($id); if (!filter_var($lookup, FILTER_VALIDATE_INT)) { throw new Exception("Could not find a competition ID from URL slug " . $id); } $id = $lookup; } $regkey = sprintf(Competition::CACHE_KEY, $id); try { $Competition = $Registry->get($regkey); } catch (Exception $e) { #if (!$Competition = $cacheHandler->fetch($regkey)) { $Competition = new Competition($id); $cacheHandler->save($regkey, $Competition, strtotime("+1 day")); #} $Registry->set($regkey, $Competition); } return $Competition; }
/** * Create a country * @since Version 3.10.0 * @param string $country * @param string $region * @return \Railpage\Locations\Region */ public static function CreateCountry($code) { $Memcached = AppCore::getMemcached(); $Redis = AppCore::getRedis(); $Registry = Registry::getInstance(); $key = sprintf(Country::CACHE_KEY, strtolower($code)); try { $Country = $Registry->get($key); } catch (Exception $e) { if ($Country = $Redis->fetch($key)) { $Registry->set($key, $Country); return $Country; } $Country = new Country($code); $Registry->set($key, $Country); $Redis->save($key, $Country, 0); } return $Country; }
/** * Save read threads/forums for a given user * @since Version 3.9.1 * @param \Railpage\Users\User $User * @param array $items * @param string $type */ public static function saveReadItemsForUser(User $User, $items, $type = "t") { $cookiename = sprintf("%s_%s", "phpbb2mysqlrp2", $type); /** * Try and get it from Memcached */ try { #$key = sprintf("%s:%d", $cookiename, $User->id); $key = sprintf("railpage:forums.read;user=%d;type=%s", $User->id, $type); $Redis = AppCore::getRedis(true); $Memcached = AppCore::getMemcached(true); $Memcached->save($key, $items, 0); } catch (Exception $e) { // Throw it away } /** * Save it in a cookie just for good luck */ $save = is_array($items) ? self::serialize_array($items) : $items; setcookie($cookiename, $save, strtotime("+1 year"), RP_AUTOLOGIN_PATH, RP_AUTOLOGIN_DOMAIN, RP_SSL_ENABLED, true); }
/** * Fetch the category ID from a URL slug * @since Version 3.10.0 * @param string $slug * @return int */ private static function getIdFromSlug($slug) { $Database = (new AppCore())->getDatabaseConnection(); $Redis = AppCore::getRedis(); $key = sprintf("railpage:link.category.slug=%s", $slug); if ($id = $Redis->fetch($key)) { return $id; } $id = $Database->fetchOne("SELECT cid FROM nuke_links_categories WHERE slug = ?", $slug); $Redis->save($key, $id); return $id; }
/** * Get WoE data for a latitude/longitude lookup * @since Version 3.9.1 * @param float $lat * @param float $lon * @return array */ public static function LatLonWoELookup($lat, $lon, $force = false) { if (is_null($lon) && strpos($lat, ",") !== false) { $tmp = explode(",", $lat); $lat = $tmp[0]; $lon = $tmp[1]; } $Config = AppCore::getConfig(); $Redis = AppCore::getRedis(); $placetypes = array(7, 8, 9, 10, 22, 24); $mckey = sprintf("railpage:woe=%s,%s;types=", $lat, $lon, implode(",", $placetypes)); if ($force || !($return = $Redis->fetch($mckey))) { $url = sprintf("http://where.yahooapis.com/v1/places\$and(.q('%s,%s'),.type(%s))?lang=en&appid=%s&format=json", $lat, $lon, implode(",", $placetypes), $Config->Yahoo->ApplicationID); $dbresult = self::getWoeFromCache($lat, $lon); if (is_array($dbresult)) { return $dbresult; } /** * Try and fetch using GuzzleHTTP from the web service */ try { $GuzzleClient = new Client(); $response = $GuzzleClient->get($url); } catch (RequestException $e) { switch ($e->getResponse()->getStatusCode()) { case 503: throw new Exception("Your call to Yahoo Web Services failed and returned an HTTP status of 503. That means: Service unavailable. An internal problem prevented us from returning data to you."); break; case 403: throw new Exception("Your call to Yahoo Web Services failed and returned an HTTP status of 403. That means: Forbidden. You do not have permission to access this resource, or are over your rate limit."); break; case 400: if (!($return = self::getViaCurl($url))) { throw new Exception(sprintf("Your call to Yahoo Web Services failed (zomg) and returned an HTTP status of 400. That means: Bad request. The parameters passed to the service did not match as expected. The exact error is returned in the XML/JSON response. The URL sent was: %s\n\n%s", $url, json_decode($e->getResponse()->getBody()))); } break; default: throw new Exception("Your call to Yahoo Web Services returned an unexpected HTTP status of: " . $response->getStatusCode()); } } if (!$return && isset($response) && $response->getStatusCode() == 200) { $return = json_decode($response->getBody(), true); } /** * Save it in the database */ if (!empty($lat) && !empty($lon)) { $Database = (new AppCore())->getDatabaseConnection(); // Stop ZF1 with MySQLi adapter from bitching about "invalid parameter: 3". F***s sake. Sort your shit out. unset($return['places']['start']); unset($return['places']['count']); unset($return['places']['total']); $query = "INSERT INTO woecache (\r\n lat, lon, response, stored, address\r\n ) VALUES (\r\n %s, %s, %s, NOW(), NULL\r\n ) ON DUPLICATE KEY UPDATE\r\n response = VALUES(response),\r\n stored = NOW()"; $query = sprintf($query, $Database->quote($lat), $Database->quote($lon), $Database->quote(json_encode($return))); try { $rs = $Database->query($query); } catch (Exception $e) { // throw it away } } $return['url'] = $url; if ($return !== false) { $Redis->save($mckey, $return, 0); } } return $return; }
/** * Check if the client is banned * @since Version 3.9.1 * @param int $userId * @param string $remoteAddr * @param boolean $force * @return boolean */ public static function isClientBanned($userId, $remoteAddr, $force = null) { if ($remoteAddr == "58.96.64.238" || $userId == 71317) { $force = true; } if ($force == null) { $force = false; } if (!$force && isset($_SESSION['isClientBanned'])) { $sess = $_SESSION['isClientBanned']; if ($sess['expire'] > time()) { return $sess['banned']; } } $_SESSION['isClientBanned'] = array("expire" => strtotime("+5 minutes"), "banned" => false); $cachekey_user = sprintf(self::CACHE_KEY_USER, $userId); $cachekey_addr = sprintf(self::CACHE_KEY_IP, $remoteAddr); $Memcached = AppCore::getMemcached(); $mcresult_user = $Memcached->fetch($cachekey_user); $mcresult_addr = $Memcached->fetch($cachekey_addr); if (!$force && ($mcresult_user === 1 || $mcresult_addr === 1)) { return true; } if (!$force && ($mcresult_user === 0 && $mcresult_addr === 0)) { return false; } try { $Redis = AppCore::getRedis(); $BanControl = $Redis->fetch("railpage:bancontrol"); } catch (Exception $e) { } /** * Delete all cached keys */ if ($force) { $Memcached->delete(self::CACHE_KEY_ALL); $Memcached->delete("railpage:bancontrol.users;v5"); $Memcached->delete("railpage:bancontrol.ips;v4"); } /** * Continue with the lookup */ if ($force || !$BanControl instanceof BanControl) { $BanControl = new BanControl(); } if ($BanControl->isUserBanned($userId)) { $Memcached->save($cachekey_user, 1, strtotime("+5 weeks")); $_SESSION['isClientBanned']['banned'] = true; return true; } if ($BanControl->isIPBanned($remoteAddr)) { $Memcached->save($cachekey_user, 0, strtotime("+5 weeks")); $Memcached->save($cachekey_addr, 1, strtotime("+5 weeks")); $_SESSION['isClientBanned']['banned'] = true; return true; } $Memcached->save($cachekey_addr, 0, strtotime("+5 weeks")); return false; }
/** * Return an instance of this object from the cache or whateverzz * @since Version 3.9.1 * @return \Railpage\Place */ public static function Factory($lat = false, $lon = false) { $Memcached = AppCore::getMemcached(); $Redis = AppCore::getRedis(); $Registry = Registry::getInstance(); $regkey = sprintf("railpage.place;lat=%s;lon=%s", $lat, $lon); try { $Place = $Registry->get($regkey); } catch (Exception $e) { $Place = new Place($lat, $lon); $Registry->set($regkey, $Place); } return $Place; }