<?php
include_once("inc_apikey"); //format - $api_key = "key";
$base "http://www.flickr.com/services/rest/?api_key=$api_key&";

$size $_REQUEST["picsize"];
$string $_REQUEST["string"];
$nsid $_REQUEST["nsid"];
$height $_REQUEST["height"];

$string preg_replace("/[^A-Za-z0-9 \?\.!\-,&\*]/"""$string);
if (!
preg_match("/^[st]$/"$size)) 
    
$size "s";

if (
$size == "s") {
    
$height = ($height) ? "width=\"$height\" height=\"$height\"" "";
}

/* Functions to parse xml - not ideal */
/* Function to handle <(HERE)>.</tag> */
function startTag($parser$name$attrs) {
    global 
$tags$doc;
    
$name strtolower($name);
    if (
$name == "rsp") {
        
$doc "";
        
$tags = Array();
    }
    
array_push($tags$name);
    
$attrs array_change_key_case($attrs);
    
$tt join("\"][\""$tags);
    eval(
"\$doc[\"$tt\"][]=\$attrs;");
}
/* Function to handle <tag>.</(HERE)> */
function endTag($parser$name) {
    global 
$tags;
    
array_pop($tags);
}
/* Function to handle <tag>(HERE)</tag> */
function cdata($parser$cdata) {
    global 
$tags$doc;
    
$tt join("\"][\""$tags);
    if (
trim($cdata))
        eval(
"\$doc[\"$tt\"][count(\$doc[\"$tt\"])-1]['cdata']=\$cdata;");
}
/* / xml */

/* Send headers */
header("Pragma: no-cache");
header("Cache-Control: no-cache, must-revalidate");
header("Last-Modified: " gmdate("D, d M Y H:i:s") . " GMT");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 

foreach (
preg_split("//"strtolower(preg_replace("/\/words\//"""$string))) as $letter) {
    
$img "";
    if (
strlen($letter) == 1) {     // if ($letter) fails on "0"
        
$id_spot++;
        
$group_id "";
        switch (
$letter) {
            case 
"a":
                
$tag "aa";
                
$group_id='27034531@N00';           // Letter group
                
break;
            case 
"i":
                
$tag "ii";
                
$group_id='27034531@N00';           // Letter Group
                
break;
            case (
preg_match("/[b-z]/"$letter) ? $letter: !$letter):
                
$tag $letter;
                
$group_id='27034531@N00';           // Letter Group
                
break;
            case 
"?":
                
$tag "Question Mark";
                
$tag "questionmark";              // Not sure which to use
                
$group_id='34231816@N00';           // Puncuation group
                
break;
            case 
"+":
                
$tag "plus";
                
$group_id='34231816@N00';           // Puncuation group
                
break;
            case 
"&":
                
$tag "ampersand";
                
$group_id='34231816@N00';           // Puncuation group
                
break;
            case 
"!":
                
$tag "exclamation";
                
$group_id='34231816@N00';           // Puncuation group
                
break;
            case 
".":
                
$tag "period";
                
$group_id='34231816@N00';           // Puncuation group
                
break;
            case 
"0":
                
$tag "00";
                
$group_id='54718308@N00';           // Number Group
                
break;
            case (
preg_match("/[1-9]/"$letter) ? $letter : !$letter):
                
$tag $letter;
                
$group_id='54718308@N00';           // Number Group
                
break;
            default:
                
$group_id "";
                break;
        }
        if (
$group_id) {
            if (!
$letters[$tag]) {

                
$method "flickr.groups.pools.getPhotos";
                
$limit "&per_page=100";
                
$extra "&group_id=$group_id";
                
$extra .= "&tags=$tag";

                
$method "method=$method";

                
$tags = Array();
                
/* Check the filesystem first - rudimentary caching */
                
$get_new 1;
                
$get_new_reason "initial";
                
$cache_name "./cache/{$method}_" str_replace("@""-"$group_id) . "_{$tag}.xml";
                
$cache_name str_replace(".."""$cache_name);
                
$cache_name preg_replace("/;\@\*/"""$cache_name);
                if (
file_exists($cache_name)) {
                    
//if (time() - (filemtime($cache_name)) <= (8 * (60 * 60))) {         //hours to cache for
                    
if (time() - (filemtime($cache_name)) <= (140 * (60 60))) {         // cache extension for 2013-07-25 outage
                        
$xml_conts file_get_contents($cache_name);
                        
$get_new 0;
                    } else {
                        
$get_new_reason "file is too old - " . (time() - (filemtime($cache_name)));
                    }
                } else {
                    
$get_new_reason "file doesn't exist";
                }
                
/* request the xml */
                
if ($get_new) {
                    
#echo "SKIPPED CACHE!!! - $letter<br />";    #hopefuly to figure out why I slammed the api :/
                    
$fi fopen("cache-misses.txt""a") or die("can't pen cache-misses.txt");
                    
fwrite($fi"JS Cache miss at " date("D M j G:i:s T Y") . " with letter $letter and string $string $get_new_reason \n");
                    
fclose($fi);
                    
$xml_conts file_get_contents("$base$method$limit$email$extra");
                    if (
preg_match("/stat=\"fail/"$xml_conts) || strlen($xml_conts) == 0) {
                        
$fi fopen("cache-misses.txt""a") or die("can't pen cache-misses.txt");
                        
fwrite($fi"    JS PROBLEM-+-+ Failure\n");
                        
fclose($fi);
                        continue;
                    }
                    else {
                        
$hand fopen($cache_name'w');
                        
fwrite($hand$xml_conts);
                        
fclose($hand);
                    }
                }

                
/* for some reason, I must re-initialze each time :( */
                
$xml_parser xml_parser_create();
                
xml_set_element_handler($xml_parser"startTag""endTag");
                
xml_set_character_data_handler($xml_parser"cdata");
                
xml_parse($xml_parser$xml_contstrue) or die(sprintf("XML error: %s at line %d\n\n%s"xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser), $xml_conts));
                
xml_parser_free($xml_parser);
                
/* done parsing xml */
                
$letters[$tag] = $doc;      //Cache letters
            
}

            if (
$letters[$tag]["rsp"][0]["stat"] == "ok") {
                
$photo "";
                
$i 0;
                
/* make sure we fill it with something, this was for an early bug, it might not be an issue any longer */
                
while (!$photo["id"] and $i++<10) {
                    
$photo $letters[$tag]["rsp"]["photos"]["photo"][rand(1,count($letters[$tag]["rsp"]["photos"]["photo"]))];
                }
                
$title addslashes($photo["title"]);
                
#document.write('<a href="http://www.flickr.com/photos/$photo[owner]/$photo[id]/"><img src="http://photos$photo[server].flickr.com/$photo[id]_$photo[secret]_$size.jpg" class="flickrImg" title="$title"></a>');
                
echo <<<HTML
document.write('<a href="http://www.flickr.com/photos/$photo[owner]/$photo[id]/"><img src="http://static.flickr.com/$photo[server]/$photo[id]_$photo[secret]_$size.jpg" $height class="flickrImg" title="$title"></a>');

HTML;

            }
            else {
                echo 
"Error - {$letters[$tag][rsp][err][0][code]}{$letters[$tag][rsp][err][0][msg]}<br />";
            }
        }
    }
}
if (
$_REQUEST["no_link"] != 1) {
    echo <<<HTML
    document.write(' <a class="spell_link" href="http://metaatem.net/words">spell</a>');

HTML;
}