<?php
/*
Template Name: NEW Blogroll TEST
 */

/*
   * get html from linkpage blog
   * for each blog save url, title, last post url, last post title, timestamp as transient, key is ????
   * for leicaphilia and oren grad, get last post title and url with special function
 */

$pdo = new PDO(
    'sqlite::memory:',
    null,
    null,
    array(PDO::ATTR_PERSISTENT => false)
); 

function scratch99_fromthisblog() {
    $ref = $_SERVER['HTTP_REFERER'];
    $host = $_SERVER['HTTP_HOST'];
    /* echo "<p style='color:green!important;'>Referer: $ref <br>Host: $host</p>"; */
    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 blogs_i_read() {
    $url = "http://spring2life-links.blogspot.de";
    //$html = file_get_contents('/tmp/spring2life-links.html');
    $html = curlDownload($url);
    set_transient( $url, $html, 1800 );
    if ( false === ( $html = get_transient( $url ) ) ) {
        $html = curlDownload($url);
        if ( ! $html )
            echo "<h2>There is a problem with the http request!</h2>";
        else
            set_transient( $url, $html, 1800 );
    }
    if ( ! preg_match('/(<ul id=\'BlogList1_blogs.*?<\/ul>)/is', $html, $matches)) {
        echo $html;
        echo "Error: could not retrieve spring2life-links blogroll";
        return;
    }
    $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) {
        /* if ( preg_match("/orengrad.com/ism", $chunk) ) {
           $result = curlDownload('http://orengrad.com/thingsseen/index.html');
           $result = preg_replace('/</ism', '&lt;', $result);
           $result = preg_replace('/>/ism', '&gt;', $result);
           echo "<br><tt>Orengrad: $chunk</tt><br><pre>$result</pre><br>";
           } */
        if ( preg_match("/vor\s+\d+\s+(Minute|Stunde)/ism", $chunk) )
            if (! $stundenflag) {
                $chunk = "<li class='linkhead'>Hot from the Sphere</li>\n\n" . $chunk; $stundenflag = true;
            }
        if ( preg_match("/vor\s+\d+\s+(Tag)/ism", $chunk) )
            if (! $tagflag) {
                $chunk = "<li class='linkhead'>A day and older</li>\n\n" . $chunk; $tagflag = true;
            }
        if ( preg_match("/vor\s+\d+\s+Woche/ism", $chunk) )
            if (! $wochenflag) {
                $chunk = "<li class='linkhead'>Less than a month old</li>\n\n" . $chunk; $wochenflag = true;
            }
        if ( preg_match("/vor\s+\d+\s+(Monat)/ism", $chunk) )
            if (! $monatflag) {
                $chunk = "<li class='linkhead'>Older</li>\n\n" . $chunk; $monatflag = true;
            }
        if ( preg_match("/vor\s+\d+\s+(Jahr)/ism", $chunk) )
            if (! $pleistoflag) {
                $chunk = "<li class='linkhead'>From the Pleistozaen</li>\n\n" . $chunk; $pleistoflag = true;
            }
        /* if (! preg_match("/<li>/ism", $chunk) )
           $chunk = "<li>" . $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);
        $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);
            /*             print_r($newest_only); die; */
        }
        /* $chunk = preg_replace( '/<\/li>[\s\r\n]*<\/ul>/ism', '', $chunk ); */
        /* $newest_only .= $chunk . "</div></li>\n"; */
    }
    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, "http://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">
  <div id="inner-content" class="wrap group">
    <?php get_sidebar(); ?>
    <div id="main" class="col-4-5 group" role="main">
      <ul class="blogroll">
        <?php
        if (scratch99_fromthisblog()) {
            /* echo "<p style='color:ping!important;'>Referer: $ref POSITIV</p>"; */
            scratch99_last_post_thumbnail_link();
        }
        ?>
        <?php echo blogs_i_read(); ?>
      </ul>
    </div> <!-- #main -->
  </div> <!-- #inner-content -->  
</div> <!-- #content -->  
<?php get_footer(); ?>
