From 8c5a65bab34da63270e6a4bc8a97df5cc5df7b3f Mon Sep 17 00:00:00 2001 From: Andreas Baumann Date: Fri, 19 Mar 2021 08:03:43 +0100 Subject: index.php: add get_news functions to avoid code duplication --- lib/helper.php | 47 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) (limited to 'lib') diff --git a/lib/helper.php b/lib/helper.php index a81eedf..ad089bf 100644 --- a/lib/helper.php +++ b/lib/helper.php @@ -143,7 +143,7 @@ function if_unset($array, $index, $default) { }; function site_is_reachable($url) { - $stream_context = stream_context_create(array('timeout' => 10)); + $stream_context = stream_context_create(array('http' => array('timeout' => 10))); $headers = get_headers($url, 0, $stream_context); if (is_array($headers)) foreach ($headers as $header) { @@ -156,6 +156,51 @@ function site_is_reachable($url) { return false; } +function get_news($name, $url, $ttl) { + // clear cache if you have to push out new news fast, otherwise wait for $ttl seconds + //apcu_clear_cache(); + + $news = apcu_fetch($name, $apcu_success); + if( $apcu_success == false ) { + $news_reachable = apcu_fetch($name."_reachable", $apcu_success); + if ($apcu_success == false) { + if (site_is_reachable($url)) { + $news_reachable = 'YES'; + } else { + $news_reachable = 'NO'; + } + apcu_store($name."_reachable", $news_reachable, $ttl); + } + if ($news_reachable == 'YES') { + $ch = curl_init($url); + if( $ch != null && $ch != false ) { + curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); + curl_setopt($ch, CURLOPT_VERBOSE,1); + $news = curl_exec($ch); + $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + curl_close($ch); + if( $httpcode >= 200 && $httpcode < 300 ) { + apcu_store($name, $news, $ttl); + } else { + $news = false; + } + } else { + $news = false; + } + } else { + $news = false; + } + } + if ($news != false) { + $news = simplexml_load_string($news); + } + return $news; +} + function add_fancy_unit($value, $unit) { $suffixes = array("z", "y", "a", "f", "p", "n", "ยต", "m", "", "k", "M", "G", "T", "P", "Y", "Z"); if ($value==0) -- cgit v1.2.3-54-g00ecf