<?php

/* EAMPLE FOR LOCAL WORKING 
$queryurl="http://samscam.local/happier/example.json";
$tweets=fetchjson($queryurl);
$tweets=$tweets->results;
*/
 
if ($_REQUEST['q']){
    
$querystr=urlencode($_REQUEST['q']);
} else {
    
$querystr=urlencode("#dev8d");
}

if (
$_REQUEST['format']){
    
$format=$_REQUEST['format'];
} else {
    
$format="html";
}

//Here is t'query lad 
$queryurl="http://search.twitter.com/search.json?rpp=100&page=1&q=$querystr";
$tweetsone=fetchjson($queryurl);

//SAME AGAIN - SECOND PAGE
$queryurl="http://search.twitter.com/search.json?rpp=100&page=2&q=$querystr";
$tweetstwo=fetchjson($queryurl);

//SAME AGAIN - THIRD PAGE
$queryurl="http://search.twitter.com/search.json?rpp=100&page=3&q=$querystr";
$tweetsthree=fetchjson($queryurl);

$tweets=array_merge($tweetsone->results,$tweetstwo->results,$tweetsthree->results);


function 
fetchjson($url){
    
/* Curl it... */
    
    
$ch=curl_init($url);
    
curl_setopt($chCURLOPT_HEADER0);
    
curl_setopt($chCURLOPT_RETURNTRANSFER1);
    
$res curl_exec($ch);   
    
curl_close($ch);
    
    
    
/* Decode the json */
    
$res=json_decode($res);
    return 
$res;
}

$totalhappyness=0;



$users=array();

if (
is_array($tweets)){
    foreach(
$tweets as $tweet){
    
        
$content=$tweet->text;
        
$user=$tweet->from_user;
        
        if (
preg_match("/([0-9|\.]+)\/([0-9|\.]+)/",$content,$matches)){
            
//print_r($matches);
            
$thishappy=$matches[1];
            
$thishappyoutof=$matches[2];
            if (
is_numeric($thishappy)){
                if (
is_numeric($thishappyoutof) and $thishappyoutof>0){
                    
$userhappy=($thishappy/$thishappyoutof)*10;
                } else {
                    
$userhappy=$thishappy;
                }
                
                if (
$userhappy>10){$userhappy=10;}
                if (
$userhappy<0){$userhappy=0;}
                if (!
array_key_exists($user,$users)){
                    
$users[$user]=$userhappy;
                }
            }
        }
    }
} else {

$errormsg="The happier pipe is rather sad at the moment :-(";

}


$totalhappyness=array_sum($users);
$usercount=count($users);
if (
$usercount>0){
    
$meanhappyness=$totalhappyness/$usercount;
} else {
    
$meanhappyness=0;
}

$colourdegs=round(($meanhappyness/10)*120);

switch (
$format){
    case 
"json":
        
$output=array("timestamp"=>date(DATE_ATOM),"totalpeople"=>$usercount,"averagerating"=>$meanhappyness,"totalrating"=>$totalhappyness);
        print 
json_encode($output);
        exit;
    break;
    case 
"xml":
    
    break;
    default:
        
?><html>
        <head>
        <meta http-equiv="refresh" content="60"/>
        <title>Happier Pipe</title>
        
        <script type="text/javascript">
        
        var sadShown=0;
        
        document.getElementsByClassName = function(cl) {
            var retnode = [];
            var myclass = new RegExp('\\b'+cl+'\\b');
            var elem = this.getElementsByTagName('*');
            for (var i = 0; i < elem.length; i++) {
                var classes = elem[i].className;
                if (myclass.test(classes)){ retnode.push(elem[i]);}
            }
            return retnode;
        };
         
        function showSadTweets(){
            var sadTweets=document.getElementsByClassName("sad");
            for (var tw in sadTweets){
                if (sadShown==0){
                sadTweets[tw].style.display="block";
                } else {
                sadTweets[tw].style.display="none";
                }
            }
            if (sadShown==0){
                sadShown=1;
                document.getElementById('sadtoggler').innerHTML="Hide SAD tweets";
            } else {
                sadShown=0;
                document.getElementById('sadtoggler').innerHTML="Show SAD tweets";
            }
        }
        
        </script></head>
        <?php
        
print "<body style='background-color: hsl(".$colourdegs.",100%,50%); text-align:center;'>";
        
?>
        
        <h1>Happier Pipe</h1>
        
        <p>This tool directly measures developer-happiness.<br/>Tweet something with the <b>#dev8d</b> hashtag including your happiness rating in the form <b>n/z</b> somewhere in the tweet.<br/>You can update it as much as you like. Get happy!</p>
        
        <p><b>New for 2010:</b> <a href="http://samscam.co.uk/happier/?format=json">JSON output</a> (in progress!)</p>
        
        <table style="width:100%; border:0;">
        <tr><td style="vertical-align:top; text-align:center; width:300px;">
        
        <?php
        
if ($errormsg){
        print 
$errormsg;
        } else {

        
        print 
"<div style='margin-top:30px;'>AVERAGE happiness is:</div>";
        print 
"<div style='font-size:58px;' id='meanhappy'>".round($meanhappyness,2)."</div>";
        print 
"<div style='margin-top:0px; font-size:12px;'>out of 10<div>";
        
        print 
"<div style='margin-top:30px;'>Happy people:</div>";
        print 
"<div style='font-size:58px;' id='peoplehappy'>".count($users)."</div>";
        
        print 
"<div style='margin-top:30px;'>TOTAL happiness is:</div>";
        print 
"<div style='font-size:24px;' id='totalhappy'>".round($totalhappyness,2)."</div>";
        
        
        
?>
        
        
        <p style="margin-top:30px;">Tell everyone to get happy!<br/><a href="http://is.gd/j95V" style="font-size:30px;">http://is.gd/j95V</a><br/>
        <a href="source.phps">Dirty old source code</a></p>
        
        <td><td style="vertical-align:top; text-align:left; width:auto;">
        <p><a href="javascript:null(0)" onclick="showSadTweets();" id="sadtoggler">Show SAD tweets</a></p>
        <?php
        
        
foreach ($tweets as $tweet){
            if (
array_key_exists($tweet->from_user,$users)){
                
$happy=$users[$tweet->from_user];
                
$colourdegs=round(($happy/10)*120);
            } else {
                
$happy=false;
            }
            print 
"<div id='tweet-".$tweet->id."'";
            
            if (
$happy){
            print 
"class='tweet' ";
            } else {
            print 
"class='tweet,sad'";
            }
            print 
"style='margin-bottom:5px; padding: 2px 2px 2px 52px; min-height:52px; position:relative;";
            if (
$happy){
                print 
"background-color: hsl(".$colourdegs.",100%,70%); ";
                print 
"border-color: hsl(".$colourdegs.",100%,30%); border-width:1px; border-style:solid;";
            } else {
                print 
"display:none; ";
                print 
"background-color: hsl(0,0%,90%); ";
                print 
"border-color: hsl(0,0%,70%);  border-width:1px; border-style:solid; ";
            }
            print 
"'>";
            print 
"<img src='".$tweet->profile_image_url."' style='width:48px; height:48px; position:absolute; left:2px;'/>";
            print 
"<b>".$tweet->from_user."</b> ";
            if (
$happy){
                print 
" is <b>".round($happy,2)."/10</b> happy";
            } else {
                print 
" is <b>SAD :(</b>";
            }
                print 
"<div class='text' style='font-size:1.3em; font-style:italic;'>";
                print 
$tweet->text;
                print 
"</div>";
            print 
"</div>";
        }
        
        }
        
?></td></tr></table>
        
        </body></html>
        <?php
    
break;
}