1));
user_external_login($u);
echo "Bootstrap sucessfull\n\n";
$return = menu_execute_active_handler();
  
copy_to_taxonomy_parents("dbo_DisciplineTree1", $system_vid, 'disciplinetree1id', 'parentdisciplinetree1id'); 
copy_to_taxonomy_parents("dbo_DisciplineTree2", $spatial_vid, 'disciplinetree2id', 'parentdisciplinetree2id'); 
copy_to_taxonomy("dbo_MediaType", $mediatype_vid); 
copy_to_taxonomy_parents("dbo_Material", $material_vid, 'materialid', 'parentmaterialid'); 
copy_to_taxonomy("dbo_Group", $group_vid); 
copy_to_taxonomy("dbo_StorageLocation", $storagelocation_vid); 
copy_to_taxonomy("dbo_LocationType", $locationtype_vid); // Creation location type vocabulary
copy_to_taxonomy("dbo_ClimaticZone", $climaticzone_vid); // Creation climatic zone vocabulary
copy_to_taxonomy("dbo_DevelopmentLevel", $developmentlevel_vid); // Creation development level vocabulary
copy_to_taxonomy("dbo_Culture", $culture_vid); // Creation culture vocabulary
copy_to_taxonomy("dbo_sysconstraints", $style_vid); 
copy_to_taxonomy("dbo_Discipline", $discipline_vid); 
copy_to_taxonomy("dbo_Role", $role_vid); 
copy_to_taxonomy_parents("dbo_WorkType", $worktype_vid, 'worktypeid', 'parentworktypeid'); 
print "imported basic taxonomies
";
$res = db_query("SELECT * FROM {dbo_RightsInformation}");
while($r = db_fetch_object($res)) {
  $node = new StdClass();
  node_object_prepare($node);
  $node->is_new = true;
  $node->title = $r->name;
  $node->type = 'rights';
  
  $node->field_rights_rightsinformationid[0]['value'] = $r->rightsinformationid;
  $node->field_rights_use1[0]['value'] = $r->use1;
  $node->field_rights_use2[0]['value'] = $r->use2;
  $node->field_rights_use3[0]['value'] = $r->use3;
  
  node_save($node);  
  
  db_query("update {dbo_RightsInformation} set import_special = '%s' where rightsinformationid = '%s'", $node->nid, $r->rightsinformationid);
}
print "imported rights information
";
// Creation of courses
$res = db_query("SELECT * FROM {dbo_Course}");
while($r = db_fetch_object($res)) {
  $node = new StdClass();
  node_object_prepare($node);
  $node->is_new = true;
  $node->title = $r->name;
  $node->type = 'course';
  
  $node->field_course_courseid[0]['value'] = $r->courseid;
  
  $tid = db_result(db_query("select import_special from {dbo_Discipline} where disciplineid = '%s'", $r->disciplineid));
  $node->field_course_disciplineid[0]['value'] = $tid;
  
  $node->field_course_coursenumber[0]['value'] = $r->coursenumber;
  
  node_save($node);  
  
  db_query("update {dbo_Course} set import_special = '%s' where courseid = '%s'", $node->nid, $r->courseid);
}
print "imported courses
";
// Creation of periods
$res = db_query("SELECT * FROM {dbo_Period} where periodid>1");
while($r = db_fetch_object($res)) {
  $node = new StdClass();
  node_object_prepare($node);
  $node->is_new = true;
  $node->title = $r->name;
  $node->type = 'period';
  
  $node->field_period_periodid[0]['value'] = $r->periodid;
  $node->field_period_fromyear[0]['value'] = $r->fromyear;
  $node->field_period_toyear[0]['value'] = $r->toyear;
  
  node_save($node);  
  
  db_query("update {dbo_Period} set import_special = '%s' where periodid = '%s'", $node->nid, $r->periodid);
}
set_taxonomy_node_parent( 'dbo_Period', "periodid", "parentperiodid" );
print "imported periods
";
// Creation of locations
$res = db_query("SELECT * FROM {dbo_Location} where locationid>1");
while($r = db_fetch_object($res)) {
  $node = new StdClass();
  node_object_prepare($node);
  $node->is_new = true;
  $node->title = $r->name;
  $node->type = 'location';
  
  $node->field_location_locationid[0]['value'] = $r->locationid;
  $node->field_location_address1[0]['value'] = $r->address1;
  $node->field_location_address2[0]['value'] = $r->address2;
  $node->field_location_postalcode[0]['value'] = $r->postalcode;
  $node->field_location_longeast[0]['value'] = $r->longeast;
  $node->field_location_longwest[0]['value'] = $r->longwest;
  $node->field_location_latnorth[0]['value'] = $r->latnorth;
  $node->field_location_latsouth[0]['value'] = $r->latsouth;
  
  $tid = db_result(db_query("SELECT import_special FROM {dbo_ClimaticZone} WHERE climaticzoneid = '%s'", $r->climaticzoneid));
  $node->field_location_climaticzone[0]['value'] = $tid;
  
  $tid = db_result(db_query("SELECT import_special FROM {dbo_DevelopmentLevel} WHERE developmentlevelid = '%s'", $r->developmentlevelid));
  $node->field_location_developmentlevel[0]['value'] = $tid;
  
  $tid = db_result(db_query("SELECT import_special FROM {dbo_LocationType} WHERE locationtypeid = '%s'", $r->locationtypeid));
  $node->field_location_locationtype[0]['value'] = $tid;
  node_save($node);  
  
  db_query("update {dbo_Location} set import_special = '%s' where locationid = '%s'", $node->nid, $r->locationid);
}
set_taxonomy_node_parent( 'dbo_Location', "locationid", "parentlocationid" );
print "imported locations
";
// Creation of creators
$res = db_query("SELECT * FROM {dbo_Creator}");
while($r = db_fetch_object($res)) {
  if ( $r->lastname . $r->firstname != '' ) {
    $node = new StdClass();
    node_object_prepare($node);
    $node->is_new = true;
    $node->title = $r->lastname . ', ' . $r->firstname;
    $node->type = 'creator';
    
    $node->field_creator_creatorid[0]['value'] = $r->creatorid;
    $node->field_creator_lastname[0]['value'] = $r->lastname;
    $node->field_creator_firstname[0]['value'] = $r->firstname;
    $node->field_creator_middlename[0]['value'] = $r->middlename;
    $node->field_creator_pseudonym[0]['value'] = $r->pseudonym;
    $node->field_creator_dateofbirth[0]['value'] = $r->dateofbirth;
    $node->field_creator_dateofdeath[0]['value'] = $r->dateofdeath;
    $node->field_creator_source[0]['value'] = $r->source;
    $node->field_creator_comment[0]['value'] = $r->comment;
    
    
    $nid = db_result(db_query("select import_special from {dbo_Location} where locationid = '%s'", $r->locationid));
    $tid = _taxonomynode_get_tid_from_nid($nid);
    $node->field_creator_locationid[0]['value'] = $tid;
    
    $nid = db_result(db_query("select import_special from {dbo_Period} where periodid = '%s'", $r->periodid));
    $tid = _taxonomynode_get_tid_from_nid($nid);
    $node->field_creator_periodid[0]['value'] = $tid;
    
    $tid = db_result(db_query("select import_special from {dbo_Culture} where cultureid = '%s'", $r->cultureid));
    $node->field_creator_cultureid[0]['value'] = $tid;
    
    node_save($node);  
    
    db_query("update {dbo_Creator} set import_special = '%s' where creatorid = '%s'", $node->nid, $r->creatorid);
  }
}
print "imported creators
";
// Creation of organizations
$res = db_query("SELECT * FROM {dbo_Organization}");
while($r = db_fetch_object($res)) {
  $node = new StdClass();
  node_object_prepare($node);
  $node->is_new = true;
  $node->title = $r->organizationname;
  $node->type = 'org';
  
  $node->field_org_department[0]['value'] = $r->department;
  $node->field_org_address1[0]['value'] = $r->address1;
  $node->field_org_address2[0]['value'] = $r->address2;
  $node->field_org_city[0]['value'] = $r->city;
  $node->field_org_state[0]['value'] = $r->state;
  $node->field_org_country[0]['value'] = $r->country;
  $node->field_org_postalcode[0]['value'] = $r->postalcode;
  $node->field_org_userid[0]['value'] = $r->userid;
  $node->field_org_emailaddress[0]['value'] = $r->emailaddress;
  $node->field_org_phonenumber[0]['value'] = $r->phonenumber;
  $node->field_org_url[0]['value'] = $r->url;
  $node->field_org_source[0]['value'] = $r->source;
  $node->field_org_comment[0]['value'] = $r->comment;
  
  node_save($node);  
  
  db_query("update {dbo_Organization} set import_special = '%s' where organizationid = '%s'", $node->nid, $r->organizationid);
}
print "imported organizations
";
// Creation of works
$res = db_query("SELECT * FROM {dbo_Work}");
while($r = db_fetch_object($res)) {
  $node = new StdClass();
  node_object_prepare($node);
  $node->is_new = true;
  $node->title = $r->title;
  $node->type = 'work';
  
  $node->field_work_workid[0]['value'] = $r->workid;
  $node->field_work_url[0]['value'] = $r->url;
  $node->field_work_catalognumber[0]['value'] = $r->catalognumber;
  $node->field_work_subject[0]['value'] = $r->subject;
  $node->field_work_desc[0]['value'] = $r->objectdescriptionsummary;
  $node->field_work_crossreference[0]['value'] = $r->crossreference;
  $node->field_work_comment[0]['value'] = $r->comment;
  $node->field_work_height[0]['value'] = $r->height;
  $node->field_work_width[0]['value'] = $r->width;
  $node->field_work_length[0]['value'] = $r->length;
  $node->field_work_diameter[0]['value'] = $r->diameter;
  $node->field_work_dimensionunit[0]['value'] = $r->dimensionunit;
  $node->field_work_volume[0]['value'] = $r->volume;
  $node->field_work_volumeunit[0]['value'] = $r->volumeunit;
  $node->field_work_area[0]['value'] = $r->area;
  $node->field_work_areaunit[0]['value'] = $r->areaunit;
  $node->field_work_dimensionflags[0]['value'] = $r->dimensionflags;
  $node->field_work_scalesmall[0]['value'] = $r->scalesmall;
  $node->field_work_scalesmallunit[0]['value'] = $r->scalesmallunit;
  $node->field_work_scalelarge[0]['value'] = $r->scalelarge;
  $node->field_work_scalelargeunit[0]['value'] = $r->scalelargeunit;
  $node->field_work_dimensioncomment[0]['value'] = $r->dimensioncomment;
  $node->field_work_exactyear[0]['value'] = $r->exactyear;
  $node->field_work_datecomment[0]['value'] = $r->datecomment;
  $node->field_work_publicationcomment[0]['value'] = $r->publicationcomment;
 
  
  $nid = db_result(db_query("select import_special from {dbo_Location} where locationid = '%s'", $r->locationidwork));
  $tid = _taxonomynode_get_tid_from_nid($nid);
  $node->field_work_locationidwork[0]['value'] = $tid;
  
  $tid = db_result(db_query("select import_special from {dbo_Culture} where cultureid = '%s'", $r->cultureid));
  $node->field_work_cultureid[0]['value'] = $tid;
  
  
  $tid = db_result(db_query("
    select dt1.import_special
    from {dbo_DisciplineTree1} as dt1, {dbo_WorkDisciplineTree1} as wdt1
    where wdt1.disciplinetree1id = dt1.disciplinetree1id and wdt1.workid = '%s'", $r->workid));
  $node->field_work_system[0]['value'] = $tid;
  
  $tid = db_result(db_query("
    select dt1.import_special
    from {dbo_DisciplineTree2} as dt1, {dbo_WorkDisciplineTree2} as wdt1
    where wdt1.disciplinetree2id = dt1.disciplinetree2id and wdt1.workid = '%s'", $r->workid));
  $node->field_work_spatial[0]['value'] = $tid;
  
  $tid = db_result(db_query("
    select dt1.import_special
    from {dbo_Group} as dt1, {dbo_WorkGroup} as wdt1
    where wdt1.groupid = dt1.groupid and wdt1.workid = '%s'", $r->workid));
  $node->field_work_group[0]['value'] = $tid;
  
  $tid = db_result(db_query("
    select dt1.import_special
    from {dbo_Material} as dt1, {dbo_WorkMaterial} as wdt1
    where wdt1.materialid = dt1.materialid and wdt1.workid = '%s'", $r->workid));
  $node->field_work_material[0]['value'] = $tid;
  
  $nid = db_result(db_query("
    select dt1.import_special
    from {dbo_Period} as dt1, {dbo_WorkPeriod} as wdt1
    where wdt1.periodid = dt1.periodid and wdt1.workid = '%s'", $r->workid));
  $tid = _taxonomynode_get_tid_from_nid($nid);
  $node->field_work_period[0]['value'] = $tid;
  
  $tid = db_result(db_query("
    select dt1.import_special
    from {dbo_sysconstraints} as dt1, {dbo_WorkStyle} as wdt1
    where wdt1.styleid = dt1.styleid and wdt1.workid = '%s'", $r->workid));
  $node->field_work_style[0]['value'] = $tid;
  
  $wwts = db_query("
    select dt1.import_special as tid
    from {dbo_WorkType} as dt1, {dbo_WorkWorkType} as wdt1
    where wdt1.worktypeid = dt1.worktypeid and wdt1.workid = '%s'", $r->workid);
  while($wwt = db_fetch_object($wwts)) {
    $node->field_work_type[] = array( 'value' => $wwt->tid );
  }
  // Add people by role
  $roles = db_query("SELECT * FROM {dbo_WorkRole} where workid = '%s'", $r->workid);
  while($role = db_fetch_object($roles)) {
    $role_tid = db_result(db_query("SELECT import_special FROM {dbo_Role} WHERE roleid = '%s'", $role->roleid));
    $creator_nid = db_result(db_query("SELECT import_special FROM {dbo_Creator} WHERE creatorid = '%s'", $role->creatorid));
    $creator_tid = _taxonomynode_get_tid_from_nid($creator_nid);
    $org_nid = db_result(db_query("SELECT import_special FROM {dbo_Organization} WHERE organizationid = '%s'", $role->organizationid));
    $org_tid = _taxonomynode_get_tid_from_nid($org_nid);
    $node->field_work_people[] = array(
        'type' => 'people',
        'value' => array(
            'field_people_creatorid' => array(array('value' => $creator_tid)),
            'field_people_organizationid' => array(array('value' => $org_tid)),
            'field_people_role' => array(array('value' => $role_tid)),
        ),
    );
  }
  
  // Import data from related MediaAsset row
  $m = db_fetch_object(db_query("SELECT * FROM {dbo_MediaAsset} WHERE workid = '%s'", $r->workid));
  $node->field_work_accessnumber[0]['value'] = $m->accessnumber;
  $node->field_work_originalmedianumber[0]['value'] = $m->originalmedianumber;
  $node->field_work_mediaassetyear[0]['value'] = $m->mediaassetyear;
  $node->field_work_mediadatecomment[0]['value'] = $m->datecomment;
  $node->field_work_mimetype[0]['value'] = $m->mimetype;
  $node->field_work_fileextension[0]['value'] = $m->fileextension;
  $node->field_work_pathhint[0]['value'] = $m->pathhint;
  $tid = db_result(db_query("select import_special from {dbo_MediaType} where mediatypeid = '%s'", $m->mediatypeid));
  $node->field_work_mediatypeid[0]['value'] = $tid;
  $tid = db_result(db_query("select import_special from {dbo_StorageLocation} where storagelocationid = '%s'", $m->storagelocationid));
  $node->field_work_storagelocationid[0]['value'] = $tid;
  $nid = db_result(db_query("select import_special from {dbo_RightsInformation} where rightsinformationid = '%s'", $m->rightsinformationid));
  $tid = _taxonomynode_get_tid_from_nid($nid);
  $node->field_work_rightsinformationid[0]['value'] = $tid;
  $nid = db_result(db_query("select import_special from {dbo_Course} where courseid = '%s'", $m->courseid));
  $tid = _taxonomynode_get_tid_from_nid($nid);
  $node->field_work_courseid[0]['value'] = $tid;
  
  $tid = db_result(db_query("
    select dt1.import_special
    from {dbo_Discipline} as dt1, {dbo_MediaAssetDiscipline} as wdt1
    where wdt1.disciplineid = dt1.disciplineid and wdt1.workid = '%s'", $r->workid));
  $node->field_work_disciplineid[0]['value'] = $tid;
  $url = 'http://localhost/files/'.$m->accessnumber.'.jpeg';
  drupal_set_message( $url );
  $file=remote_file_get_url( $url );
  if (is_object($file)) {
    remote_file_cck_attach_file($node, $file->filepath, 'field_work_image', 0);
  }
  node_save($node);
  db_query("update {dbo_Work} set import_special = '%s' where workid = '%s'", $node->nid, $r->workid);
}
function set_taxonomy_node_parent ( $table, $field, $parent ) {
  // Set hierarchy for all terms
  $res = db_query("SELECT * FROM {%s} where %s>1", $table, $field);
  while($r = db_fetch_object($res)) {
    if ( $r->$parent > 1 ) {
      $tid = _taxonomynode_get_tid_from_nid($r->import_special);
      $term = taxonomy_get_term($tid);
      
      $sql = "select import_special from {%s} where %s = '%s' limit 1";
      $pid = db_result(db_query($sql, $table, $field, $r->$parent));
      
        
      if ($pid > 0) { 
        $pid = _taxonomynode_get_tid_from_nid($pid);
        $term->parent = $pid; 
        $term_array = (array) $term;
        taxonomy_save_term( $term_array );
      }
    }
  }  
}
function copy_to_taxonomy($table, $vid, $name = "name") {
  $res = db_query("SELECT * FROM {%s}", $table);
  while($r = db_fetch_object($res)) {
    if ( $r->$name != '' ) {
      db_query(
        "UPDATE {%s} set import_special = '%s' WHERE record_id = %d",
        $table,
        create_term(
          $r->$name,
          $vid
        ),
        $r->record_id
      );
    }
  }
}
function copy_to_taxonomy_parents($table, $vid, $child, $parent, $name = "name") {
  copy_to_taxonomy($table, $vid, $name);
  
  $res = db_query("SELECT * FROM {%s}", $table);
  while($r = db_fetch_object($res)) {
    if ( $r->$parent > 1 ) {
      $tid = $r->import_special;
      $ptid = db_result(db_query("select import_special from {%s} where %s = '%s'", $table, $child, $r->$parent));
      if ( $ptid > 0 ) {
        $term = taxonomy_get_term($tid);
        $term_array = (array) $term;
        $term_array['parent'] = $ptid;
        taxonomy_save_term($term_array);
      }
    }
  }
}
function create_term($name, $vid, $desc = '') {
  $edit = array(
    'name' => $name,
    'vid'  => $vid,
    'description' => $desc,
  );
  
  taxonomy_save_term( $edit );
  
  return $edit['tid'];
}
/**
 * Attach the given file object to the given CCK field
 *
 * @param $node
 * @param $filepath
 *   Path to the file to attach
 * @param $fieldname
 *   CCK fieldname to attach to
 * @param $index
 *   Index to multiple values
 *
 * @see http://drupal.org/node/328232 for a drupal_execute example
 */
function remote_file_cck_attach_file($node, $filepath, $fieldname, $index=0) {
  $field = content_fields($fieldname, $node->type);
  //TODO: I'm not sure why we need the filefield validators too
  $validators = array_merge(filefield_widget_upload_validators($field), imagefield_widget_upload_validators($field));
  $files_path = filefield_widget_file_path($field);
  // This path does not have to exists already.
  _remote_file_recursive_file_create_path($files_path);
  $file = field_file_save_file($filepath, $validators, $files_path);
  if (!is_array($node->$fieldname)) {
    // Make CCK array structure
    $node->$fieldname=array();
  }
  $node->{$fieldname}[$index]=$file;
}
/**
 * Create the path ourselves recursively
 */
function _remote_file_recursive_file_create_path($path) {
  if (!file_check_directory($path, FILE_CREATE_DIRECTORY)) {
    // Support DOS style
    $root=str_replace('\\','/',file_directory_path());
    $path=str_replace('\\','/',$path);
    // We only do our work from the file system root
    $roots=explode('/',$root);
    $paths=explode('/',$path);
    while (count($roots)) {
      array_shift($roots);
      array_shift($paths);
    }
    foreach ($paths as $dir) {
      $root.= '/' . $dir;
      file_check_directory($root, FILE_CREATE_DIRECTORY);
    }
  }
}
/**
 * Gets the file given by the url
 *
 * @param $url
 *   The given url
 * @return
 *   FALSE or file object for further processing
 */
function remote_file_get_url($url, $temp=TRUE) {
  $md5_url=md5($url);
  $error = 'No error';
  static $urls;
  if (!isset($urls)) {
    $urls=array();
  }
  if (isset($urls[$md5_url])) {
    return $urls[$md5_url];
  }
  // TODO: Check for appropriate providers like wikipedia.org
  //$result=parse_url($url);
  //===
  //TODO: Only do the request if the file is not already on our server
  $result=drupal_http_request($url);
  if (isset($result->error)) {
    unset($result->data);
    $error=print_r($result, TRUE);
    return $error;
  }
  $info=array();
  $info['filemime']=$result->headers['Content-Type'];
  $info['filesize']=$result->headers['Content-Length'];
  $info['data']=$result->data;
  list($dummy, $ext)=explode('/', $info['filemime']);
  $file_name = $md5_url . '.' . $ext;
  $info['filepath']=remote_file_basepath() . '/' . $file_name;
  $info['filename']=$file_name;
  $file=remote_file_write_file($info, $temp);
  if (!is_object($file)) {
    $error=print_r($info,TRUE);
    return $error;
  }
  $urls[$md5_url]=$file;
  return $urls[$md5_url];
}
/**
 * Writes the given data to the file system and drupals files table
 *
 * Existing files are overriden.
 *
 * @param array $info
 *   Info for the file to create
 * @param $temp
 *   Indicated whether the file should be temporary saved of permanent
 *
 * @return
 *   File object or FALSE
 *
 * @see remote_file_basepath()
 */
function remote_file_write_file( $info, $temp=FALSE) {
  $exists = is_file($info['filepath']);
  if (!$exists) {
    file_save_data( $info['data'], $info['filepath'], FILE_EXISTS_REPLACE);
    global $user;
    $file = (object) array();
    $file->uid = $user->uid;
    $file->filename=$info['filename'];
    $file->filepath=$info['filepath'];
    $file->filemime=$info['filemime'];
    $file->filesize=$info['filesize'];
    if ($temp) {
      $file->status = FILE_STATUS_TEMPORARY;
    }
    else {
      $file->status = FILE_STATUS_PERMANENT;
    }
    $result=drupal_write_record('files', $file);
    if ($result!==FALSE) {
      return $file;
    }
    return FALSE;
  }
  else {
    $sql="SELECT * FROM {files} WHERE filepath='%s'";
    return db_fetch_object(db_query($sql, $info['filepath']));
  }
}
/**
 * base path for the file location
 *
 * @return
 *   path to file location
 */
function remote_file_basepath() {
  $path='remote';
  $path = file_create_path($path);
  file_check_directory($path, FILE_CREATE_DIRECTORY);
  return $path;
}