<?php
/*
 * 'zonSearch v0.2
 * Written by Peter Beckman <beckman@purplecow.com>
 * http://purplecow.com/
 * Created: January 7, 2002
 * Updated: February 10, 2004
 * This script is covered and released under the GNU General Public License (GPL)
 * Read the license before use: http://www.gnu.org/copyleft/gpl.html
 *
 * I wrote this because Amazon Web Services doesn't have a feature to search titles 
 * of songs.  CDNOW did, but then Amazon took CDNOW and threw out the great search
 * feature.  'zonSearch mimics the CDNOW Song Title search.
 *
 * I'd appreciate it if would keep the above lines in tact, 
 * as well as the hidden credit and link to my site.
 *
 * Change Log
 * v0.2 2/10/2004: Fixed offset for artist from 6 to 7; added hidden link to purplecow.com
 * v0.1 1/7/2002: Original Release
 */

# this is the referal code that you want so you get your precious 5% baby!
$amazon_referer "purplecowbook";

### NOTHING ELSE BELOW NEEDS EDITING ###

set_time_limit(300);
?>
<style> BODY { font-family:Arial,Verdana; font-size:13px} 
      td { font-size:12px; border-color: #000000; border-style: solid solid none none; border-width: 1px; padding: 0px 5px 0px 5px;
      vertical-align:top; } 
      tr { font-size:12px; } 
      table { border-color:#000000; border-style:none none solid solid; border-width:1px; margin:0px; padding:0px; border-collapse:collapse; }
      table.modify {  border-style:none none none none; border-width:0px; margin:9px; padding:9px; }
      .noborder { border-style:none none none none; padding:0px 30px 0px 0px; }
      tr.a { background-color:#dddddd; }
      tr.b { background-color:#eeeeee; }
      font.name { font-size:25px; }
      .small { font-size:9px; }
      .smaller { font-size:8px; }
      font.title { font-size:25px; }
      font.subtitle { font-size:15px; }
      .credit { color:#ffffff; }
      .top { vertical-align:top; }
      a { color:#0000ff; text-decoration: none; }
      a:hover { color:#ff9900; }
   </style>
<?
echo "<font class='title'>'ZonSearch</font>  <font class='subtitle'>The better way to find CD Tracks at Amazon</font><br>";
echo 
"<a class='small' href='index.phps'>Get the Source Code for your site</a><br/>";
echo 
"<font class='small credit'>by peter beckman  &lt;beckman SHIFT-2 purplecow.com&gt; <a href='http://purplecow.com/zonsearch/' class='small credit'>zonsearch
home</a></font><br/>"
;
echo 
"<form action='".$_SERVER['PHP_SELF']."' method='POST'>";
echo 
"Search Track: <input type='textbox' name='q' value=\"".htmlentities(stripslashes($_REQUEST['q']))."\"><input type='submit' value='Go!'><br/>";
echo 
"<font class='small'><b>NOTE:</b> It may take up to 60 seconds for this form to return results.</font></form>";

if (!empty(
$_REQUEST['q'])) {
    
$start time();
    
$x 1;
    
$output getresults($_REQUEST['q']);
    if (
$output === FALSE) {
        echo 
"Crap -- Cannot get results from Amazon.  Exiting.";
        exit();
    }

    
$ret amazon_parse_track_search_results($output);

    while ((
$ret['total']-(25*$x))>0) {
        
$x++;
        
$output getresults($_REQUEST['q'],$x);
        if (
$output === FALSE) {
            echo 
"Crap -- Cannot get results from Amazon.  Exiting.";
            exit();
        }
        
$ret2 amazon_parse_track_search_results($output);
        if (
is_array($ret2)) $ret $ret $ret2;
        if (
$x>6) break;
    }

    if (!
is_array($ret)) { print "Could not find that one ($artist - $title)\n"; }
    else {
        
$ttime time()-$start;
        
$fp fopen("./logresults.txt","a"); fwrite($fp,stripslashes($_REQUEST['q'])."|".$ret['total']."|".$ttime."|".time()."\n"); fclose($fp);
        echo 
" Query took {$ttime} seconds. <br/>";
        if (
$ret['total']>150) echo "Found the first 150 out of {$ret['total']} matches.";
        else echo 
"Found {$ret['total']} matches.";
        echo 
"<table class='noborder'><tr><th>Artist</th><th>Album</th><th>Track</th></tr>";
        while (list(
$x,$y)=each($ret)) {
            if (!
is_numeric($x)) continue;
            if (
$x%2==0$ab "a"; else $ab "b";
            echo 
"<tr class='{$ab}'><td class='noborder'>{$y['artist']}</td><td class='noborder'>{$y['album']}</td><td class='noborder'><a
            target='_blank' href='http://www.amazon.com/exec/obidos/ASIN/{$y['asin']}/ref%3Dnosim/{$amazon_referer}'>{$y['track']}</td></tr>"
;
        }
        echo 
"</table>";
        echo 
"<pre>";
        
#reset($ret);
        #print_r($ret);
        
echo "</pre>";

    }

}
echo 
"<hr/>";
#print "\n\nend\n\n";

function amazon_parse_track_search_results($html) {
    
$debug 0;  // 1 for basic, 2 for full
    
$output nl2br($html);
    
$outarray preg_split("/\<br \/\>/",$output);
    
$next 0;
    
$x 0$y 0$match 0;
    while(list(
$k,$row) = each($outarray)) {
        
$row trim($row);
        if (
$debug$prow htmlentities($row);

        if (
preg_match("/All (\d{1,6}) results for/",$row,$matches)) {
            if (
$debug) echo "Total Found: {$matches[1]}<br/>";
            
$results['total'] = $matches[1];
            continue;
        }
        if (
preg_match("/\<b\>(\d{1,6})\.\<\/b\>/",$row,$matches)) {
            
$next 1;
            
$mynum $matches[1];
            if (
$debug) print "START:: ".$prow." ($mynum)<br/>";
            
$x 0;
            continue;
        }
        if (
$next) {
            if (
$debug==2) print "$x: $prow<br/>";
            if (
$x==1) {
                if (
preg_match("/music-no-image/",$row)) $offset 1;
                elseif (
$y>=10$offset 5;
                else 
$offset 0;
            } elseif (
$x==(4+$offset)) { // the track name
                
$track strip_tags($row);
                if (
$debug) echo "$x: Track: {$track}<br/>";
                
$results[$mynum]['track'] = $track;
            } elseif (
$x==(5+$offset)) { // album
                
preg_match_all("{B0........}x"$row$matches);
                
$albumurl $matches[0][0];
                
$album trim(strip_tags($row));
                if (
$debug) echo "$x: Album: {$album} ($albumurl)<br/>";
                
$results[$mynum]['album'] = $album;
                
$results[$mynum]['asin'] = $albumurl;
            } elseif (
$x==(7+$offset)) { // artist
                
$artist trim(preg_replace("/~/","",strip_tags($row)));
                if (
$debug) echo "$x: Artist: {$artist}<br/>";
                
$results[$mynum]['artist'] = $artist;
            } else {
                
#echo "$x: $prow<br/>";
            
}
            
$x++;
            if (
$x>=15) { $y++; $x 0$match 0$next 0;}
        }
    }
    return 
$results;  // none found
}

function 
getresults($q,$pg=1,$sz=25) {

/**
 * http://www.amazon.com/exec/obidos/search-handle-url/?url=index%3Dmusic-tracks&search-type=quick-search&field-keywords=".urlencode($q)."&sz=".$sz."&pg=".$pg."Go.x=11&Go.y=8&Go=Go
 *
 * Old URL:
 * "http://www.amazon.com/exec/obidos/search-handle-url/ix=music-tracks&rank=%2Btitlerank&fqp=keywords%01".urlencode($q)."&nsp=Go%01Go%21&sz=".$sz."&pg=".$pg."/ref=s_m_np/002-1120767-9079251";
 */

    
$url =
    
"http://www.amazon.com/exec/obidos/search-handle-url/?url=index%3Dmusic-tracks&search-type=quick-search&field-keywords=".urlencode($q)."&sz=".$sz."&pg=".$pg."Go.x=11&Go.y=8&Go=Go";
    print 
"<a target='_blank' href='$url'>Page $pg</a> | ";
    
$fp fopen($url"r") or print("can't open $url");

    if (
$fp !== FALSE) {
        while(!
feof($fp)) { 
            
$s fgets($fp,4096);
            
$output .= $s;
        }
        
fclose($fp);
    } else {
        return 
FALSE;
    }

    
#echo "<pre>";
    #echo htmlentities($output);
    #echo "</pre>";
    
return $output;
}