<?php
/*
Template Name: Blogroll Test
*/

function scratch99_fromthisblog() {
    $ref = $_SERVER['HTTP_REFERER'];
    $host = $_SERVER['HTTP_HOST'];
    if( $ref == "" ) return true;
    if( strpos($host, $ref) !== false ) return false;
    return false;
} 

function scratch99_last_post_thumbnail_link () {
    $recent_posts = wp_get_recent_posts(array(
        'numberposts' => 10, // Number of recent posts thumbnails to display
        'post_status' => 'publish' // Show only the published posts
    ));
    foreach( $recent_posts as $recent ) {
        if ( has_post_thumbnail($recent['ID']) ) { // check if the post has a Post Thumbnail assigned to it.
            echo "<div style='text-align: right;'><a href='" . get_permalink($recent['ID']) . "'>";
            echo "<span style='padding-right: 1em; font-weight: bold;'>New on spring2life</span> ";
            echo get_the_post_thumbnail($recent['ID'],'thumbnail', 'style=float:right;') . "</a></div>";
            break;
        }
    }
}

function debug_echo ( $text ) {
    /* if ( false ) { */
        /* echo 'debug: <![CDATA[ ', str_replace('<', '&lt;', $text), " ]]><br>\n"; */
        echo 'debug: ', $text, "<br>\n";
    /* } */
}

function insert_chunk_before( $before, $newest_only, $chunk ) {
    return preg_replace("/<\/ul>\n<li class='linkhead'><h4>$before<\/h4>/",
                        "<li>$chunk</li>\n</ul>\n<li class='linkhead'><h4>$before</h4>", $newest_only);
}

function process_oren_grad($chunk, $newest_only, $omitflag) {
    $chunk = preg_replace('#<div class=[\'"]item-content[\'"]>.*</div>#s', '', $chunk);
    $chunk = preg_replace('#</div>#s', '', $chunk);
    $now = date_timestamp_get(date_create());
    if ( false === ( $og = get_transient( 'orengrad' ) ) ) { /* no transient could be restored */
        $result = curlDownload('http://orengrad.com/thingsseen/index.html');
        $og[1] = md5($result); 
        $og[0] = $now;
        set_transient('orengrad', $og);
    } else {                            /* there is a transient */
        if ( $now - $og[0] > 1*3600 ) { /* timestamp older than 12h, so compare again */
            $oldhash = $og[1];
            $result = curlDownload('http://orengrad.com/thingsseen/index.html');/* nochmal holen */
            $og[1] = md5($result);
            if ( $og[1] <> $oldhash ) { /* not equal, so save again */
                $og[0] = $now; 
                set_transient('orengrad', $og);/* set transient with new timestamp */
                /* } else {
                   debug_echo('Hashes are equal'); */
            }
        }
    }
    $diff_in_seconds = date_timestamp_get(date_create()) - $og[0];
    echo "<!-- orengrad diff_in_seconds: $diff_in_seconds -->";
    if ( $diff_in_seconds < 24 * 3600 ) {
        $newest_only = insert_chunk_before('A day and older', $newest_only, $chunk);
    } elseif ( $diff_in_seconds < 30 * 24 * 3600 ) {
        $newest_only = insert_chunk_before('Less than a month old', $newest_only, $chunk);
    } else {
        $newest_only = insert_chunk_before('Older', $newest_only, $chunk);
    }
    /* delete_transient('orengrad');  */
    $omitflag = true;
    return array($newest_only, $omitflag);
}

function process_lfi_online($chunk, $newest_only, $omitflag) {
    $chunk = preg_replace('#<div class=[\'"]item-content[\'"]>.*</div>#s', '', $chunk);
    $chunk = preg_replace('#</div>#s', '', $chunk);
    $matches = [];
    if ( false === ( $result = get_transient( 'lfionlinede' ) ) ) {
        $result = curlDownload('https://lfi-online.de/ceemes/en/blog/');
        $chunk = str_replace('<div class=[\'"]blog-title[\'"]>', '', $chunk);
        if ( preg_match('#<div class="titlebox30 cu-pointer" onclick="window.location = \'(.*?)\'">\s*<h1 class="typo-1">(.*?)</h1>\s*<span class="subline">\s*<h2 class="sl typo-26">.*?</h2>\s*<h3 class="sl typo-27">(.*?)</h3>#s', $result, $matches)) {
            $chunk = $chunk . ":&nbsp;<span class=\"item-title\">\n<a href=\"$matches[1]\" target=\"_blank\">\n$matches[2]</a></span>";
            set_transient('lfionlinede', $chunk, 12*3600);
        }
    } else {
        $chunk = $result;
    }
    /* delete_transient('lfionlinede'); */
    /* Assumption: LFI comes in the last section of all entries, because it does not show a date to google.
       Therefore all headlines are already written to $newestonly and we can insert before */
    /* $age_in_days = date_diff(date_create($matches[3]), date_create(date("d.m.Y")))->format('%a'); */
    $age_in_days = date_diff(date_create($matches[3]), date_create(date("d.m.Y")));
    debug_echo($matches[0]);
    /* debug_echo(date_create($matches[3])); */
    /*     debug_echo(date_create(date("d.m.Y"))); */
    #echo "<!-- lfi age in days: ", $age_in_days, " -->";
    if ($age_in_days < 1) {
        $newest_only = insert_chunk_before('A day and older', $newest_only, $chunk);
    } elseif ($age_in_days < 30) {
        $newest_only = insert_chunk_before('Less than a month old', $newest_only, $chunk);
    } else {
        $newest_only = insert_chunk_before('Older', $newest_only, $chunk);
    } 
    $omitflag = true;
    return array($newest_only, $omitflag);
}

function cleanup_chunk ( $chunk ) {
    $chunk = preg_replace("/[\s]*<div class=[\"']item-time[\"']>.*<\/div>/ism", "", $chunk);
    $chunk = preg_replace("/<div class=[\"']item-content[\"']>[\r\n]?/ism", "", $chunk);
    $chunk = preg_replace("/<div class=[\"']blog-title[\"']>[\r\n]?/ism", "<li>", $chunk);
    $chunk = preg_replace("/<\/div>[\r\n]?/ism", ":&nbsp;", $chunk);
    $chunk = preg_replace("/<\/span>/ism", "</span></li>", $chunk);
    return $chunk;
}

function blogs_i_read() {
    $url = "http://spring2life-links.blogspot.de";
    if ( false === ( $html = get_transient( $url ) ) ) {
        $html = curlDownload($url);
        if ( ! $html ) {
            echo "<h2>There is a problem with the http request!</h2>";
        } else {
            if ( ! preg_match('/(<ul id=\'BlogList1_blogs.*?<\/ul>)/is', $html, $matches)) {
                echo "Error: could not retrieve valid spring2life-links blogroll<br>", $html;
                return;
            } else { 
                set_transient( $url, $html, 3600 );
            }
        }
    }
    /* delete_transient($url); */
    $html = preg_replace('/.*<div class=["\']widget BlogList["\'] id=["\']BlogList1["\']>/ism', '', $html);
    $newest_only = "";
    $stundenflag = false;
    $tagflag = false;
    $wochenflag = false;
    $monatflag = false;
    $pleistoflag = false;
    preg_match_all('/<div class=["\']blog-title["\']>.*<div class=["\']item-time["\']>.*<\\/div>/Us', $html, $matches);
    foreach ($matches[0] as $chunk) {
        $omitflag = false;
        if ( preg_match("/orengrad.com/ism", $chunk) ) {
            list ($newest_only, $omitflag) = process_oren_grad($chunk, $newest_only, $omitflag);
        }
        if ( preg_match("#/lfi-online.de/ceemes/#", $chunk) ) {
            list ($newest_only, $omitflag) = process_lfi_online($chunk, $newest_only, $omitflag);
        }
        if ( preg_match("/vor\s+\d+\s+(Minute|Stunde)/ism", $chunk) )
            if (! $stundenflag) {
                $chunk = "<li class='linkhead'><h4>Hot from the Sphere</h4></li>\n\n<ul>\n" . $chunk;
                $stundenflag = true;
            }
        if ( preg_match("/vor\s+\d+\s+(Tag)/ism", $chunk) )
            if (! $tagflag) {
                $chunk = "</ul>\n<li class='linkhead'><h4>A day and older</h4></li>\n<ul>\n" . $chunk;
                $tagflag = true;
            }
        if ( preg_match("/vor\s+\d+\s+Woche/ism", $chunk) )
            if (! $wochenflag) {
                $chunk = "</ul>\n<li class='linkhead'><h4>Less than a month old</h4></li>\n<ul>\n" . $chunk;
                $wochenflag = true;
            }
        if ( preg_match("/vor\s+\d+\s+(Monat)/ism", $chunk) )
            if (! $monatflag) {
                $chunk = "</ul><li class='linkhead'><h4>Older</h4></li>\n<ul>\n" . $chunk; $monatflag = true;
            }
        if ( preg_match("/vor\s+\d+\s+(Jahr)/ism", $chunk) )
            if (! $pleistoflag) {
                $chunk = "</ul><li class='linkhead'><h4>From the Pleistozaen</h4></li>\n<ul>\n" . $chunk; $pleistoflag = true;
            }
        $chunk = cleanup_chunk($chunk);
        if ( $omitflag == false )
            $newest_only .= $chunk;
        if ( preg_match('/href=\'(http:\/\/feedproxy.google.com.*?)\'/', $chunk, $match) ) {
            $proxyurl = $match[1];
            if ( false === ( $cleanurl = get_transient( md5('cleanurlof' . $proxyurl) ) ) ) {
                $cleanurl = resolveUrl($proxyurl);
                $cleanurl = doHardcore($cleanurl);
                set_transient( md5("cleanurlof" . $proxyurl), $cleanurl, 90000 + rand(1,3600) );
            } $chunk = str_replace($match[1], $cleanurl, $chunk);
        }
    }
    return $newest_only;
}

function resolveUrl($url) {
    try {
        $header = doCurlRequest($url); return $header['redirect_url']; } catch (Exception $ex) {
            _log("error freeing url $url: " . $ex->getMessage()); return $url;
        }
}

function curlDownload($Url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $Url);
    curl_setopt($ch, CURLOPT_REFERER, "https://markus-spring.info");
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0");
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

if(!function_exists('_log')) {
    function _log( $message ) {
        if( WP_DEBUG === true ) {
            if( is_array( $message ) || is_object( $message ) ) {
                error_log( print_r( $message, true ) );
            } else {
                error_log( $message );
            }
        }
    }
}

function doCurlRequest($url) {
    $curlSession = curl_init($url);
    curl_setopt($curlSession, CURLOPT_NOBODY, 1);
    $curlResponse = curl_exec($curlSession);
    $header = curl_getinfo($curlSession);
    curl_close($curlSession);
    return $header;
}

function doHardcore($url) {
    try {
        $parts = explode("?", $url);
        $ret = $parts[0];
        _log("do hardcore: [$url] -> [$ret]");
        return $ret;
    } catch (Exception $ex) {
        _log("error in hardcore: " . $ex->getMessage());
        return $url;
    }
}

?>
<?php get_header(); ?>
<div id="content" class="site-content">
  <div id="primary" class="content-area">
    <main id="main" class="site-main" role="main">
      <article id="post--31201" class="post--31201 post type-post status-publish format-image hentry category-vernacular post_format-post-format-image entry">
        <header class="entry-header">
	  <h2 class="entry-title default-max-width">Blogs I read</h2>
	</header><!-- .entry-header -->
        
        <div id="content" class="site-content">
          <div id="primary" class="content-area">
            <main id="main" class="site-main" role="main">
	
	      <div class="entry-content">
                <ul class="linktable">
                  <?php
                  if (scratch99_fromthisblog()) {
                      scratch99_last_post_thumbnail_link();
                  }
                  ?>
                  <?php echo blogs_i_read(); ?>
                </ul>
              </div><!-- .entry-content -->
            </main>
          </div>
        </div>
      </article><!-- #post-31164 -->
    </main><!-- #main -->
  </div><!-- #primary -->
</div><!-- #content -->
<?php get_footer(); ?>
