<?php echo('<?xml version="1.0" encoding="utf-8" ?>'); ?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"
 "http://www.w3.org/TR/REC-html40/strict.dtd">

<html>
<head>
<title>muzzac</title>
<style type="text/css">
.artist {
  font-weight: normal;
}
</style>
</head>
<body>

<h1>muzzac</h1>

<form method="get">
Last.fm brukernavn: 
<input type="text" name="bruker" value="<?php echo($_GET['bruker']); ?>" />
<input type="submit" value="Vis" />
</form>
<form method="get">
Artist: 
<input type="text" name="artist" value="<?php echo($_GET['artist']); ?>" />
Use: 
<select name="use">
<option value="">Velg...</option>
<option value="1">1 Personal name</option>
<option value="2">2 Institution</option>
<option value="1003">1003 Author</option>
<option value="1004">1004 Personal Author</option>
<option value="1016">1016 Any</option>
</select>
<input type="submit" value="Vis" />
</form>
<hr />

<?php

/*

Burde kanskje brukt denne? http://www.matto1990.com/lastfm_protocol/

TODO: 
Bedre søkeuttrykk! Avgrens til "forfatter" og format? 

*/

// Config

// Number of related artists to show
$limit_artists 10;

// Number of Z39.50-results to show
$limit_zresults 10;

// Should we do a Z39.50 search for each related artist from Last.fm? 
// Set this to "false" if the value of $limit_artists is large  
$do_zsearch_for_each_artist true;

// Display the RPN search-expression
$display_rpn true;

// Display the number of hits from the Z39.50 searches
// Only $limit_zresults will actually be shown 
$display_hit_count true;

// Include the PEAR module File_MARC, for handling MARC-data
require 'File/MARC.php';

// Get the API key from http://last.fm/ 
$api_key    'xxx';
$api_root 'http://ws.audioscrobbler.com/2.0/';

// What library should we search
// $host = 'z3950.deich.folkebibl.no:210/data';
$host 'aleph.stavanger.kommune.no:2100/NOR01';
// $host = 'z3950.public.demo.kohalibrary.com:210/koha_public_bilbio';
// $host = 'kohanor.collib.info:9999/biblios';

// End config

// bruker or artist must be set, if not we do nothing
if (!empty($_GET['bruker']) || !empty($_GET['artist'])) { 

  
$url "";
    
$artists "";
    
  if (!empty(
$_GET['bruker'])) { 
    
        
// We are looking for a user:
        
        // API docs: http://www.last.fm/api/show?service=300
        
$url "{$api_root}?method=user.gettopartists&user={$_GET['bruker']}&api_key={$api_key}&format=json";
        
$data json_decode(file_get_contents($url));
        
$artists $data->topartists->artist;
        echo(
"<h2>Bruker: {$_GET['bruker']}</h2>");
    
    } elseif (!empty(
$_GET['artist'])) {
      
        
// We are looking for an artist:
        
        // Get similar artists
        // API docshttp://www.last.fm/api/show?service=119
        // The JSON format for artist.getSimilar is broken, use XML instead... 
      
$url "{$api_root}?method=artist.getsimilar&artist=" urlencode($_GET['artist']) . "&api_key={$api_key}";
        
$data simplexml_load_string(file_get_contents($url));
        
$artists $data->similarartists->artist;
        echo(
"<h2>Artist: {$_GET['artist']}</h2>\n\n");
        echo(
'<div style="float: right;"><iframe id="flickrFrame" src="http://www.flickr.com/slideShow/index.gne?text=' $_GET['artist'] . ' live concert" frameborder="0" width="300" height="300" scrolling="no"></iframe></div>');
        echo(
"<p>Treff fra katalogen:</p>\n");
        
get_bib($_GET['artist']);
        
        
// Events, from Last.fm
        // API docs: http://www.last.fm/api/show?service=117
        
$event_url "{$api_root}?method=artist.getevents&artist=" urlencode($_GET['artist']) . "&api_key={$api_key}&format=json";
        
$event_data json_decode(file_get_contents($event_url));
        
// print_r($event_data);
        
if ($event_data->events->event) {
        echo(
"<p>Kommende konserter (fra Last.fm)</p><ul>");
        foreach(
$event_data->events->event as $e) {
          if (
$e->venue->location->country == 'Norway' 
                 
|| $e->venue->location->country == 'Sweden' 
                 
|| $e->venue->location->country == 'Denmarc') {
            echo(
"<li><a href=\"{$e->url}\">Sted: {$e->venue->name}, {$e->venue->location->city}, {$e->venue->location->country}</a> Tid: {$e->startDate}<br />
                      </li>"
);
          }
        }
        }
      echo(
"</ul>");
        
        echo(
"<h2>Lignende artister</h2>\n");
    }
  
  echo(
"<ul>\n");
  
  
$count 1;
  
    if (
$artists) {
    
    foreach (
$artists as $artist) {
    
        
$artist_name $artist->name;
      echo(
"<li><a href=\"?artist=" urlencode($artist_name) . "\" class=\"artist\" title=\"Klikk for å se lignende artister\">$artist_name</a></li>\n");
          
          if (
$do_zsearch_for_each_artist) { 
        
get_bib($artist_name);
            }
    
      
$count++;
    
      if (
$count $limit_artists) { exit; }
    
    }
    
    }
  
  echo(
"</ul>\n");

}

// Do the actual Z39.50 searches:
function get_bib($q) {

  global 
$limit_zresults$display_rpn$display_hit_count$host;

  
$id yaz_connect($host);

  
yaz_element($id"F");
  
yaz_syntax($id"USMARC");
  
yaz_range($id110);
    
    
// CREATE THE RPN SEARCH EXPRESSION
    // http://www.loc.gov/z3950/agency/defns/bib1.html
    // http://www.loc.gov/z3950/agency/bib1.html
    // Attributes supported by Deichman catalogue: 
    // http://www.bibsyst.no/produkter/bibliofil/z/carl.xml
    // Candidates: 
    // 1    Personal name - Works for artist's names, not band names
    // 2    Institution (= Korporasjon?) - Works for band names, not artist's names
    // 1003 Author - Works for artist's names, not band names
    // 1004 Personal Author
    // 1016 Any - Works for both artist's names and band names, but search is a bit too broad? 
    // Solution:
    // 1 OR 2 should do the trick
    
  // Set the default use-attribute to 1 if none is given in $_GET['use'] 
    
$use $_GET['use'] ? $_GET['use'] : 1
    
    
$rpn "@attr 1=$use \"$q\"";
    
// Is there a space in $q? If so, we need to search for names in inverted form too
    // This will search for e.g. "Purple, Deep", but that should not be much of a problem
    
    /*
    if (substr_count($q, " ") > 0) {
        // Add the inverted form to the actual search string
        $rpn = "@or $rpn @attr 1=$use \"" . invert($q) . '"';
        // If $_GET['use'] is not specified, add a second use-attribute
        if (empty($_GET['use'])) {
        $rpn = "@or $rpn @or @attr 1=2 \"$q\" @attr 1=2 \"" . invert($q) . '"';
      }
    } else {
      if (empty($_GET['use'])) {
        $rpn = "@or " . $rpn . " @attr 1=2 \"$q\"";
      }
    }
    */
    
    
yaz_search($id"rpn"$rpn);

  
yaz_wait();

  
$error yaz_error($id);

  if (!empty(
$error)) {

    echo 
"$rpn - Error: $error \nError number: " yaz_errno($id) . "\n";

  } else {

    
$hits yaz_hits($id);
    echo 
"  <ul>\n";
        if (
$display_rpn) {
        echo(
"<li>S&oslash;k etter: <em>$q</em> = <strong>$rpn</strong></li>");
      }
        if (
$display_hit_count) {
      echo 
"  <li>Antall treff i biblioteket: $hits</li>\n";
        }
    for (
$p 1$p <= $limit_zresults$p++) {
      
$rec yaz_record($id$p"raw");
      if (empty(
$rec)) continue;
      echo 
"  <li>";
            
// DEBUG echo("<pre>" . nl2br($rec) . "</pre>");
            // Use File_MARC to pick out interesting stuff
            
$marc_file = new File_MARC($recFile_MARC::SOURCE_STRING);
      while (
$marc_record $marc_file->next()) {
              
// Title
                
$title clean_field($marc_record->getField('245')->getSubfield('a'));
                if (
$marc_record->getField('245')->getSubfield('b')) {
                  
$title $title " : " clean_field($marc_record->getField('245')->getSubfield('b'));
                }
                
$title htmlentities($title);
                
// URL
                
$url clean_field($marc_record->getField('996')->getSubfield('u'));
                
// Output
                
echo("<a href=\"$url\">$title</a>"); 
                echo(
"\n<!--\n");
                echo(
nl2br($marc_record->__toString()));
                echo(
"\n-->\n");
        echo 
"</li>\n";
      }
    }
    echo 
"  </ul>\n";
  }
}

function 
invert($s) {

  
// Split on whitespace and turn into array
  
$pieces explode(" "$s);
  
// Get the last element and append comma
  
$last array_pop($pieces) . ",";
  
// Put the last element at the top of the array
  
array_unshift($pieces$last);
  
// Turn the array into a string, with elements separated by whitespace
  
return implode(" "$pieces);

}

function 
clean_field($s) {

  
// For some reason this: 
    // $marc_record->getField('245')->getSubfield('a')
    // returns this: 
    // "[a]: Wuthering heights"

  
return substr($s5);

}

?>

<hr />

<p>
Kilder: <a href="http://www.last.fm/api">Last.fm API</a> + Z39.50. 
Byggeklosser: <a href="http://www.indexdata.dk/phpyaz/">PHP/YAZ</a> og <a href="http://pear.php.net/package/File_MARC/">File_MARC</a>. 
<a href="lastfm.txt">Kildekode</a></p>

</body>
</html>