<?php
/* Include ARC2 classes. */
include_once("arc/ARC2.php");

/* Configure the app to use DBPedia. */
$dbpconfig = array(
  "remote_store_endpoint" => "http://dbpedia.org/sparql",
);

/* Create the 'remote store' */
$dbpedia = ARC2::getRemoteStore($dbpconfig);

/* Configure the app to use DBTune. */
$dbtconfig = array(
  "remote_store_endpoint" => "http://dbtune.org/musicbrainz/sparql",
);

/* Create the 'remote store' */
$dbtune = ARC2::getRemoteStore($dbtconfig);

/* Let's start with some genre (Art rock). */
$genre = "Art_rock";
if ($_GET['genre']) {
  $genre = $_GET['genre'];
}
$uri = "http://dbpedia.org/resource/$genre";

if ($_GET['offset']) {
  $offset = $_GET['offset']

/* Here we grab artists. */
$q = "
PREFIX dbpedia-owl-artist: <http://dbpedia.org/ontology/Artist/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX dbpprop: <http://dbpedia.org/property/>
SELECT DISTINCT ?artist ?artisturi ?yearsActive
WHERE
 { ?artisturi dbpedia-owl-artist:genre <$uri> ;
              rdfs:label ?artist .
   OPTIONAL { ?artisturi dbpprop:yearsActive ?yearsActive . }
   FILTER ( langMatches(lang(?artist), \"EN\") ) }

";
$artists = $dbpedia->query($q, 'rows');

/* But we need to do some legwork to get the number of albums, since
 we don't have a sameAs link back to DBTune. We use sameAs.org to go
 backwards. */
$newArtists = array();
foreach ($artists as $key => $artist) {
  $sameAsURI = "http://sameas.org/rdf?uri=" . urlencode($artist['artisturi']);
  $parser = ARC2::getRDFXMLParser();
  $parser->parse($sameAsURI);
  $triples = $parser->getTriples();
  $dbturi = '';
  foreach ($triples as $triple) {
    if (substr($triple['o'], 0, 46) == 'http://dbtune.org/musicbrainz/resource/artist/') {
      $dbturi = $triple['o'];
      break;
    }
  }
  $newArtists[$key] = $artist;
  $newArtists[$key]['artisturi'] = $dbturi;
  print_r($newArtists[$key]);
  if ($dbturi != '') {
    /* Now that we have the DBTune URI, we can query it for the number
     of albums. */
    $q = "
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX mo: <http://purl.org/ontology/mo/>
SELECT ?album
WHERE
 { ?album a mo:Record ;
          foaf:maker <$dbturi> . }";
    $dbtArtist = $dbtune->query($q, 'rows');
    $newArtists[$key]['albums'] = count($dbtArtist);
  } else {
    $newArtists[$key]['artisturi'] = '';
    $newArtists[$key]['albums'] = '';
  }
}
$artists = $newArtists;

