<?
/*
BETA BETA BETA BETA BETA BETA BETA BETA BETA BETA BETA BETA BETA BETA BETA BETA BETA BETA BETA BETA 

FOAFmake BETA 1- Joel De Gan
http://peoplesdns.com

This file is to be used to generate a FOAF file via PHP.
It uses pre-digested ontologies to generate the pages for what to add. 

It can also be used in conjunction with MeNowDocument variables to "auto" update your foaf
though other programs just by simply posting to this file.

For instance, in this example, calling the URL:
http://peoplesdns.com/make/?auto=1&menow:MeNowDocument[1][listeningTo]=Someband-song.mp3&password=testing
will update your MeNowDocument "listeningTo" setting to "Someband-song.mp3" and write your new foaf.rdf with
the changes made.
Currently this only works with the MeNowDocument but could be easily changed for doing updates via remote on
any of your FOAF data (i.e. knows).

BETA BETA BETA BETA BETA BETA BETA BETA BETA BETA BETA BETA BETA BETA BETA BETA BETA BETA BETA BETA 
*/

$dir getcwd();
define("PASSWORD""testing");            // password for updates.
define("REQPASSWORD"1);            // require a password for updates.
define("HIDEEMAILS"1);            // never place actual emails in the created foaf file, use sha1
define("FOAFFILE""foaf.rdf");         // the foaf
define("FOAFDATA""foaf.dat");         // stored foaf structure (what we build the foaf from)
define("FOAFBASE""$dir");             // where do the above files live?
define("NSBASE""$dir/ns/");             // where are our ontology structures?
define("STEPS"7);                 // basic, additional, knows+rel, wot, bio, geo, menow

if($left) {$step $poststep -1; }
if(
$update) {$step $poststep; }

$stepsdata = array(
    array(
"Basics of your profile""Insert your settings for your FOAF profile here, these are the basic settings. <i>Please note that not every variable needs to be added. sha1 values will be auto generated if left blank.</i>","foaf"),
    array(
"Additional profile""Additional portions of your FOAF that you can add parts to.","foaf"),
    array(
"Who you know and how you know them""Add users who you know, these are people you currently 'know' and how you know them","foaf"),
    array(
"Encryption settings (testing)""If you chose to add in encryption settings (the generated values of this section may not validate correctly)","wot"),
    array(
"Biographical values (testing)""Any biographical events that are important about you. (the generated values of this section generally validate correctly, but full testing has not been done)","bio"),
    array(
"Geographical values (testing)""Where you are currently located, your latitude and longitude. (the generated values of this section may not validate correctly)","geo"),
    array(
"Current 'MeNow' values""Values of your current often changing variables. Once set up, this file can be posted to with a password and you can auto-update these items through programs.","menow")
);

######### OPTIONS FOR EACH STEP #########
/*
    main options = array[step][list of options]
    list of options is item or array
    item is just a property, an array treats it as a class or subclass
    for multiple properties with the same name use #_{property name} (pound and underscore then name)
    see topic_interest below.
    don't list mutliple classes on a page, user can go back and add another.
*/
// main foaf
$options[] = array("title","name""firstName""family_name""phone""mbox""mbox_sha1sum""homepage""weblog""img","workplaceHomepage","schoolHomepage","nick","icqChatID","yahooChatID","aimChatID","msnChatID","jabberID");
$options[] = array("geekcode","workInfoHomepage"
    array(
"currentProject""logo","page","fundedBy"), 
    
"interest""topic_interest","1_topic_interest""2_topic_interest","3_topic_interest""4_topic_interest","5_topic_interest");
#"logo","page","fundedBy"

//knows
$options[] = array(
    array(
"knows""name""firstName""family_name""phone""mbox""mbox_sha1sum""weblog""img""nick","icqChatID","yahooChatID","aimChatID","msnChatID","jabberID""thumbnail")
);

//wot
$options[] = array(
    array(
"PubKey","hex_id""length""fingerprint""identity"),
    array(
"SigEvent","signed"),
    array(
"User","sigdate","signerLongHexID"),
    
"pubkeyAddress","assurance");

//bio
$options[] = array(
    
"olb",
    
"keywords",
    array(
"Birth""date","place"),
    array(
"Marriage""date","place"),
    array(
"Event""Event","date","place")
);
//geo
$options[] = array(
    array(
"foaf:based_near""Point""lat_long""alt")
);

//menow from http://schema.peoplesdns.com/menow/
$options[] = array(
    array(
"MeNowDocument",
    
"isWith",
    
"listeningTo",
    
"game""gamingAt","gameNick",
    
"thinking",
    
"mood","moodIcon",
    
"liking","chatting",
    
"browsing","reading",
    
"vacation","moblogging","moImage",
    
"camImage","status","statusIcon",
    
"workingOn","writing","planning",
    
"watching"
    
)
);
######### OPTIONS FOR EACH STEP ABOVE #########

// the ontology list. remove all #'s
// "name of ontology file"    "xmlns common name"    "common URI for ontology"
$ontology = array(
        
"22-rdf-syntax-ns"      => array("rdf",     "http://www.w3.org/1999/02/22-rdf-syntax-ns#"),
        
"bio"                   => array("bio",     "http://purl.org/vocab/bio/0.1/"),
        
"cc"                    => array("cc",         "http://web.resource.org/cc/"),
        
"dc"                    => array("dc",         "http://purl.org/dc/elements/1.1/"),
        
"dcterms"               => array("dcterms",     "http://purl.org/dc/terms/"),
        
"foaf"                  => array("foaf",     "http://xmlns.com/foaf/0.1/"),
        
"ns"                    => array("vs",         "http://www.w3.org/2003/06/sw-vocab-status/ns"),
        
"owl"                   => array("owl",     "http://www.w3.org/2002/07/owl"),
        
"rdf-schema"            => array("rdfs",     "http://www.w3.org/2000/01/rdf-schema#"),
        
"rel"                   => array("rel",     "http://purl.org/vocab/relationship/"),
        
"wgs84_pos"             => array("geo",     "http://www.w3.org/2003/01/geo/wgs84_pos"),
        
"wot"                   => array("wot",     "http://xmlns.com/wot/0.1/"),
    
"menow"            => array("menow",    "http://schema.peoplesdns.com/menow/")
);
// list of ontologies the user can choose from
$avail = array("foaf""menow""bio""wot""rel");

// list of ontologies to always use in the foaf.. mostly internal
$usealways = array("foaf""22-rdf-syntax-ns""rdf-schema""dc");

if(
$step==""){$step=1;}

function 
debugarr($arr){
    echo 
"<pre>\n";
    
print_r($arr);
    echo 
"</pre>\n";
}

// returns key based on val
function _array_search($s$a) {
  for(
$i=0$i <= count($a); $i++) {
   if (
in_array($s, array($a[$i]))) {
     return(
$i);
     break;
   }
  }
  return(
FALSE);
}
function 
xmlns($arr){
    global 
$ontology;
    while(list(
$key,$val)=each($arr)){
        
$ret .= "    xmlns:"$ontology[$val][0]."=\"".$ontology[$val][1]."\"\n";
    }
    
$ret .= "    xmlns:admin=\"http://webns.net/mvcb/\"\n";
   return 
$ret;
}
function 
foafwrap($data$arr){
    
sort($arr);
    
$arr array_unique($arr);
    
$ns xmlns($arr);
    
$ret "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<rdf:RDF\n$ns>\n";
    
$ret .= "   <foaf:PersonalProfileDocument rdf:about=\"\">\n    <admin:generatorAgent rdf:resource=\"http://peoplesdns.com\"/>\n";
      
$ret .= "    <admin:errorReportsTo rdf:resource=\"mailto:joel@tagword.com\"/>\n   </foaf:PersonalProfileDocument>\n";

    
$ret .= "\n<foaf:Person>\n";
    
$ret .= $data;
    
$ret .= "\n</foaf:Person>\n</rdf:RDF>\n";
    return 
$ret;
}

function 
findns($name){
    global 
$ontology;
    
reset($ontology);
    while(list(
$key,$val)=each($ontology)){
        if(
$val[0] == $name){
            return 
$key;
        }
    }
}

function 
genfoaf($data){
    global 
$usealways;
    
$ns $usealways;
    while(list(
$key,$val)=each($data)){
        if(!
is_array($val)){
            
$aparts explode(":"$key);
            
$bparts explode("_"$aparts[1]);
            if(
HIDEEMAILS && $aparts[1] == "mbox"){
                
//do nothing
            
}else{
            if(
is_numeric($bparts[0])){
                
array_shift($bparts);
                
$key $aparts[0] .":"implode("_"$bparts);
                
$ret .= "    <$key>$val</$key>\n";
            }else{
                
$ret .= "    <$key>$val</$key>\n";
            }
            if(
$nns findns($aparts[0])){
                
$ns[] = $nns;
            }
            }
        }else{
            
#if($key <> "menow:MeNowDocument"){
            #    $ret .= "    <$key>\n";
            #}
            
$parts explode(":"$key);
            
$begin $parts[0];
            while(list(
$kk,$vv)=each($val)){
            
#echo "<!-- $key -->\n";
            
if($key <> "menow:MeNowDocument"){
                if(
$key == "bio:Birth" || $key == "bio:Marriage"){$ret .= "  <bio:Event>\n";}
                
$ret .= "    <$key>\n";
            }            
                if(
$key == "foaf:knows"){$ret .= "        <foaf:Person>\n";}
                while(list(
$kkk,$vvv)=each($vv)){
                    if(
HIDEEMAILS && $kkk == "mbox"){
                        
//do nothing
                    
}else{        
                     if(
substr_count(":"$kkk)>0){
                        
$ret .= "            <$kkk>$vvv</$kkk>\n";
                     }else{
                        
$ret .= "            <$begin:$kkk rdf:value=\"$vvv\" />\n";
                     }
                    }
                }
                if(
$key == "foaf:knows"){$ret .= "        </foaf:Person>\n";}
            if(
$key <> "menow:MeNowDocument"){
                
$ret .= "    </$key>\n";
                if(
$key == "bio:Birth" || $key == "bio:Marriage"){$ret .= "  </bio:Event>\n";}
            }
                
            }
            
#if($key <> "menow:MeNowDocument"){
            #    $ret .= "    </$key>\n";
            #}
            
$ns[] = findns($parts[0]);
        }
    }
    return 
foafwrap($ret$ns);
}

// save an array to file on disk
    
function datasave($array$filename) {
        
$serialised serialize($array);

        
$f fopen($filename"w+");
        if (!
$f)  {
            echo 
"\nCould not open $filename!";
            return;
        } 
    
        
$size fwrite($f$serialised);
        
fclose($f);
    }
    function 
savefile($data$filename){
        
$f fopen($filename"w+");
        if (!
$f)  {
            echo 
"\nCould not open $filename!";
            return;
        } 
        
$size fwrite($f$data);
        
fclose($f);
    }
// load an array from file on disk
    
function &dataload($filename) {
        if (
file_exists($filename) ) {
            
$f fopen($filename"r");
            
$serialised fread($ffilesize($filename) );
            
fclose($f);

            if (
$serialised 0) {
                return 
null;
            }
            return 
unserialize($serialised);
        }
        return 
null;
    }

function 
class_select($class){
    global 
$ont;
    
$ret "<select name=add_$class>\n";
    
$classes $ont[$class]['classes'];
    while(list(
$k,$v)=each($classes['rdfs:class'])){
        
$ret .= "<option value='$v'>$v</option>\n";
    }
    
$ret.= "</select>\n";
    return 
$ret;
}

function 
showstep($step){
    global 
$password;
    if(
$step>1){
        
$d $step-2;
        
$ret .= "<input type=submit value='<<' name=left><input type=hidden name=step and value=$d> | ";
    }
    for(
$a=1;$a<STEPS+1;$a++){
        if(
$step == $a){
            
$ret .= " $a ";
        }else{
            
$ret .= " <a href='?step=$a&password=$password'>$a</a> ";
        }
    }    

    if((
$step)<STEPS){
        
$d $step+1;
        
$ret .= " | <input type=submit value='>>' name=right><input type=hidden name=step and value=$d>";
    }    
    return 
$ret;
}

// this loads all the ontologies into memory for easy use.
while(list($key,$val)=each($ontology)){
    
$ont[$val[0]] = dataload(NSBASE.$key);
}

// load the current foafdata
$userfoaf = @dataload($dir."/".FOAFDATA);
// if we have a post, we need to add the data...
if($_POST || $auto){
    if(
$_POST){ $proc $_POST; }else{  $proc $_GET; }
    while(list(
$key,$val)=each($proc)){
        if(
$key <> "poststep" && $key <> "step" && $key <> "password" && $key <> "left" && $key <> "right" && $key <> "update" && $key <> "auto"){
          if(
is_array($val)){
          
/////////////////////////////////////////////
            
$aval "";
            
$blank true;
            while(list(
$kk,$vv) = each($val)){
            
$blank true;
                if(!
is_array($vv)){
                    if(
trim($vv) <> ""){
                        
$blank false;
                        
$aval[$kk] = $vv;
                    }
                }else{
                    while(list(
$kkk,$vvv)=each($vv)){
                        if(
trim($vvv) <> ""){
                            
$blank false;
                            
$aval[$kkk]=$vvv;
                        }
                    }
                    if(
$blank == false){
                        
#$userfoaf[$key][] = $aval;
                    
}
                }
            }
            if(
$blank == false){
                if(
$aval['mbox'] <> "") {$aval['mbox_sha1sum'] = sha1($aval['mbox']);}
                if(
$key "menow:MeNowDocument"){
                    
$akey array_keys($aval);
                    if(
is_array($userfoaf['menow:MeNowDocument'])){
                      while(list(
$key,$val)=each($userfoaf['menow:MeNowDocument'])){
                        while(list(
$k,$v)=each($val)){
                            if(
$k == $akey[0]){
                                
$userfoaf['menow:MeNowDocument'][$key][$k] = $aval[$akey[0]];
                            }
                        }
                      }
                    }else{
                        
$userfoaf[$key][] = $aval;
                    }
                }else{
                    
$userfoaf[$key][] = $aval;
                }
            }
          
/////////////////////////////////////////////
          
}else{
            if(
trim($val)<>""){
                
$userfoaf[$key] = $val;
            }
          }
          if(
$key == "foaf:mbox") { $userfoaf['foaf:mbox_sha1sum'] = sha1($val); }
        }
//fi
    
}
    if(
REQPASSWORD == 1){
        if(
$password == PASSWORD){
            @
datasave($userfoaf$dir."/".FOAFDATA);
            
savefile(genfoaf($userfoaf), FOAFFILE);
        }else{
            
$ERR[] = "You must provide a valid password to update your foaf";
            
$userfoaf = @dataload($dir."/".FOAFDATA);
        }
    }else{
        @
datasave($userfoaf$dir."/".FOAFDATA);
        
savefile(genfoaf($userfoaf), FOAFFILE);
    }
}
#extract($userfoaf[$step]);

###########################################################################
## output header here
if($auto == ""){
?>
<style type="text/css">
body {
  padding: 2em 1em 2em 35px;
  margin: 0;
  font-family: sans-serif;
  color: black;
  background: white;
}
.list {
    background-color: #ddf;
    border: 1px solid black;
    margin: 0.3em 1%; 
}
pre {
    border: 1px dotted black;
        background-color: #D9E3E9;
        padding: 5px;
}
</style>
<!-- #########  HEADER  ######### -->
<table width=90% border=1>
<tr><td>
<form method=post action="<?= $PHP_SELF ?>">
<input type=hidden name=poststep and value=<?= $step ?>>
<table width=100%>
    <tr>
        <td colspan=2><h2><?= $stepsdata[$step-1][0?></h2><i><?= $stepsdata[$step-1][1?></i></td>
    </tr>
    <tr>
        <td align=right colspan=2>Password: <input type=password size=5 name=password value="<?= $password ?>"><br><?= showstep($step?></td>
    </tr>
    
<!-- #########  DONE HEADER  ######### -->

<?
########################################################################################################

$count 1;
while(list(
$key,$val)=@each($options[$step-1])){
    
$pre $stepsdata[$step-1][2] .":";
    
$tmp _array_search($val$ont[$stepsdata[$step-1][2]]['properties']['rdfs:class']);
    
$comment $ont[$stepsdata[$step-1][2]]['properties']['rdfs:comment'][$tmp];
    if(!
is_array($val)){
    
///////////////////////////////////
    
$bits explode("_",$val);
    if(
is_numeric($bits[0])){
        
$comment "See above";
        
$part array_shift($bits);
        
$showval implode("_",$bits);
    }else{
        
$showval $val;
    }
    if(
substr_count($showval,"#")>0){
        
$aaa explode("#"$showval);
        
$showval $aaa[1];
    }
?>
    <tr>
        <td valign=top><?= $showval ?></td>
        <td><input type=text name="<?= $pre $val ?>" value="<?= $userfoaf[$pre $val?>" size=25><br>
        <small><?= $comment ?></small>
        </td>
    </tr>
<?
    
///////////////////////////////////
    
}else{
    
///////////////////////////////////
        
$classname array_shift($val);
?>
    <tr>
        <td colspan=2 bgcolor="#D9E3E9"><b><?= $classname ?> (add new)</b></td>
    </tr>
<?
        
while(list($k,$v)=each($val)){
        
$tmp _array_search($v$ont[$stepsdata[$step-1][2]]['properties']['rdfs:class']);
        
$comment $ont[$stepsdata[$step-1][2]]['properties']['rdfs:comment'][$tmp];    
        
$cn $pre $classname;
        if(
substr_count($v"#")>0){
            
$aaa explode("#"$v);
            
$v $aaa[1];
        }
        
?>
    <tr>
        <td valign=top><?= $v ?></td>
        <!-- value="<?= $userfoaf[$v][0][$count?>" -->
        <td><input type=text name="<?= $cn ?>[<?= $count ?>][<?= $v ?>]" size=25><br>
        <small><?= $comment ?></small>
        </td>
    </tr>
<?
        
}
?>
    <tr>
        <td colspan=2 bgcolor="#D9E3E9"><input type=submit value=" add this and insert another " name=update>&nbsp;</td>
    </tr>
<?
            
    
///////////////////////////////////
    
}
    
$count++;

}
//wend
?>
    <tr>
    <tr>
        <td>&nbsp;</td>
        <td align=right><?= showstep($step?></td>
    </tr>
<?

########################################################################################################
?>
<!-- #########  FOOTER  ######### -->
<tr><td colspan=2>
<?
###########################################################################
?>
</form>
</td></tr></table>
</td></tr></table>

<!-- #########  DONE FOOTER  ######### -->

<pre>
############################## CURRENT RDF BELOW ##############################
<?
echo htmlspecialchars(genfoaf($userfoaf));

#print_r($userfoaf);
?>
</pre>
<a href="make.phps">source</a> | <a href="make.tar.gz">download all</a>
<?
}
?>