view ISMIBioFilter/ISMIBioFilter.module @ 10:2a786f0d46a7

more comments in the code.
author casties
date Fri, 26 Jun 2015 10:59:53 +0200
parents 124ef8f3b22d
children
line wrap: on
line source

<?php

/**
 * @file
 * Provides a Markdown input filter.
 */




function ISMIBioFilter_menu(){
  $items['showBio/%'] = array(
      'title'              => 'View',
      'description' => 'show an object.',
      'page callback' => 'ISMIBioFilter_showBio_page',
      'access arguments'   => array('access content'),
      'page arguments'     => array(1),

      'access arguments'   => array('access content'),
      'type' => MENU_LOCAL_TASK,

  );

  $items['showEntity/%'] = array(
      'title'              => 'View',
      'description' => 'show an object.',
      'page callback' => 'ISMIBioFilter_showEntity_page',
      'access arguments'   => array('access content'),
      'page arguments'     => array(1),

      'access arguments'   => array('access content'),
      'type' => MENU_LOCAL_TASK,

  );


  return $items;


}


function ISMIBioFilter_showEntity_page($keys){
  #$results = db_query("SELECT * FROM {field_data_field_id} n where field_id_value  ='" . $keys . "'  and bundle = 'openmind_entity' ");
  #$results = db_query("SELECT * FROM {field_data_field_id} n where field_id_value  ='" . $keys . "' ");

  $query = new EntityFieldQuery;
  $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'openmind_entity')
  ->fieldCondition('field_id', 'value',$value = $keys);
  $results = $query->execute();

  if (isset($results['node'])){
    $nids = array_keys($results['node']);

    foreach ($nids as $nid){

      drupal_goto("node/" . $nid);
    }
  } else {
    drupal_goto("/unknownEntity");
  }

}

function ISMIBioFilter_showBio_page($keys){
  ##$results = db_query("SELECT * FROM {field_data_field_original_url} n where field_original_url_value  ='" . $keys . "'");

  # zerlege den string
  $paths = explode("/",$keys);
  #gebraucht wird nur der letzte teil

  $fn = $paths[sizeof(paths)-1];
  dpm($fn);
  dpm($keys);
  drupal_goto($fn);
  #foreach ($results as $result){
  #	drupal_goto("node/" . $result->entity_id);
  #}
}
/**
 * Implements hook_help().
 */
function ISMIBioFilter_help($path, $arg) {
  switch ($path) {
    case 'admin/help#ISMIBioFilter':
      return t('<p> Filters the original biographies to make the Drupal compatible.</p>');
  }
}

/**
 * Implements hook_filter_info().
 */
function ISMIBioFilter_filter_info() {
  $filters['filter_ISMIBioFilter'] = array(
      'title' => t('ISMIBioFilter'),
      'description' => t('Filter for the Biographies from the Springer Website'),
      'process callback' => '_filter_ISMIBioFilter',
      'settings callback' => '_filter_ISMIBioFilter_settings',
      'tips callback'  => '_filter_ISMIBioFilter_tips',
  );

  return $filters;
}


function _ISMIBioFilter_getSources($rel){
  $vals = array();
  $relNode = relation_load($rel->rid);
  $eps = relation_get_endpoints($relNode);
  foreach($eps as $ep){

    $vals[]=array_shift(array_values($ep));

  }

  return $vals;
}

function _ISMIBioFilter_getTargets($rel){
  $vals = array();
  $relNode = relation_load($rel->rid);
  $eps = relation_get_endpoints($relNode);
  foreach($eps as $ep){

    $ar = array_values($ep);
    array_shift($ar);
    $vals[]=array_shift($ar);
  }

  return $vals;
}


/**
 * Returns the ISMIBioFilter input filter tips.
 * @TODO: make it easier for translators.
 */
function _filter_ISMIBioFilter_tips($format, $long = FALSE) {
  if ($long) {
    return t('no tip');
  }
  else {
    return t('no tip');
  }
}

/**
 * Implements hook_block_view().
 */
function ISMIBioFilter_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'ISMIBioFilter_help':
      $block['title'] = t('ISMIBio filter tips');
      $block['content'] = _ISMIBioFilter_help_block();
      break;


    case 'ISMIObjects_main':
      // main info for an object

      $node = menu_get_object();

      //node hat keine objektype dann mache nichts
      if (!isset($node->field_oc)){
        break;
      }

      $tid = $node->field_oc[LANGUAGE_NONE][0]['tid'];
      $taxonomy = taxonomy_term_load($tid)->name;

      switch($taxonomy){

        case 'PERSON':
          $ov = $node->field_ov[LANGUAGE_NONE][0]['value'];
          $nov = $node->field_nov[LANGUAGE_NONE][0]['value'];
          $block['title'] =  t('Person');
          //$block['content']= theme('ISMIPersons_main',array('node' => $node));

          $rows[] = array("Name",$ov);
          $rows[] = array("Normalisiert",$nov);

          $block['content']=theme('table', array('header' => null, 'rows' => $rows));


          //is_prime_alias_name_of,invOf_is_prime_alias_name_of, invOf_is_alias_name_of ,is_alias_name_of
          $rels = relation_query("node",$node->nid)->execute();
          $prime_alias = "";
          $aliases = array();

          foreach($rels as $rel){

            switch($rel->relation_type){
              case "is_prime_alias_name_of":
                $prime_alias = _ISMIBioFilter_getSources($rel);
                break;

              case "is_alias_name_of":
                $aliases = _ISMIBioFilter_getSources($rel);
                break;
            }
          }

          $block['content'] .= theme("ISMIObject_aliases",array("prime_alias"=>$prime_alias,"aliases"=>$aliases));
          break;

        case  'TEXT':
          $ov = $node->field_ov[LANGUAGE_NONE][0]['value'];
          $nov = $node->field_nov[LANGUAGE_NONE][0]['value'];
          $block['title'] =  t('Text');
          //$block['content']= theme('ISMIPersons_main',array('node' => $node));

          $rows[] = array("Title",$ov);
          $rows[] = array("Normalisiert",$nov);

          $block['content']=theme('table', array('header' => null, 'rows' => $rows));
          $rels = relation_query("node",$node->nid)->execute();
          $prime_alias = "";
          $aliases = array();

          foreach($rels as $rel){

            switch($rel->relation_type){
              case "is_prime_alias_name_of":
                $prime_alias = _ISMIBioFilter_getSources($rel);
                break;

              case "is_alias_name_of":
                $aliases = array_merge($aliases,_ISMIBioFilter_getSources($rel));
                break;
            }
          }

          $block['content'] .= theme("ISMIObject_aliases",array("prime_alias"=>$prime_alias,"aliases"=>$aliases));

      }

      break;

    case 'ISMIObjects_titles':

      $node = menu_get_object();
      //node hat keine objektype dann mache nichts
      if (!isset($node->field_oc)){
        break;
      }


      $tid = $node->field_oc[LANGUAGE_NONE][0]['tid'];
      $taxonomy = taxonomy_term_load($tid)->name;

      switch($taxonomy){

        case 'PERSON':
          $rels = relation_query("node",$node->nid)->execute();

          foreach($rels as $rel){

            if ($rel->relation_type=="was_created_by"){
              $relNode = relation_load($rel->rid);
              $targets = relation_get_endpoints($relNode);
              foreach($targets as $target){

                $titles[]=array_shift(array_values($target));




              }
            }
          }

          $block['title'] = t('Titles');
          $block['content']= theme('ISMIPersons_titles',array('titles' => $titles));

      }
      break;

    case 'ISMIText_witnesses':
      $node = menu_get_object();
      //node hat keine objektype dann mache nichts
      if (!isset($node->field_oc)){
        break;
      }


      $tid = $node->field_oc[LANGUAGE_NONE][0]['tid'];
      $taxonomy = taxonomy_term_load($tid)->name;

      switch($taxonomy){

        case 'TEXT':
          $rels = relation_query("node",$node->nid)->execute();
          $titles=array();
          foreach($rels as $rel){

            if ($rel->relation_type=="is_exemplar_of"){
              $titles = array_merge($titles,_ISMIBioFilter_getSources($rel));

            }
          }

          _ISMIBioFilter_enrich($titles);

          $block['title'] = t('Witnesses');
          //$block['content']= theme('ISMIWitnesses_list',array('witnesses' => $titles));

          // create table
          $rows=array();

          foreach ($titles as $witness){

          $rows[]=array(
          l($witness->field_nov[LANGUAGE_NONE][0]['value'],$witness->nid),
          l($witness->codex->field_nov[LANGUAGE_NONE][0]['value'],$witness->codex->nid),
          l($witness->collection->field_nov[LANGUAGE_NONE][0]['value'],$witness->collection->nid),
          l($witness->repository->field_nov[LANGUAGE_NONE][0]['value'],$witness->repository->nid),
          l($witness->place->field_nov[LANGUAGE_NONE][0]['value'],$witness->place->nid)
          );
          }

          $header = array("witness","codex","collection","repository","place");
          $block['content'] = array(
              '#theme' => 'table',
              '#header' => $header,
              '#rows' => $rows,
          );
          #$block['content'] = theme("table",array('header'=>null,'rows'=>$rows));
      }
      break;


    case 'ISMIPersons_bea':
      $node = menu_get_object();
      //node hat keine objektype dann mache nichts
      if (!isset($node->field_oc)){
        break;
      }

      $tid = $node->field_oc[LANGUAGE_NONE][0]['tid'];
      $taxonomy = taxonomy_term_load($tid)->name;
      switch($taxonomy){

        case 'PERSON':



          $author_id = $node->field_id[LANGUAGE_NONE][0]['value'];


          $query = new EntityFieldQuery;
          $query->entityCondition('entity_type', 'node')
          ->entityCondition('bundle', 'biography')
          ->fieldCondition('field_id', 'value',$value = $author_id);
          $results = $query->execute();

          if (isset($results['node'])){
            $nids = array_keys($results['node']);

            foreach ($nids as $nid){

              $body = entity_load_single("node", $nid)->body[LANGUAGE_NONE][0]['value'];

              $block['title'] = t('BEA');
              $block['content']= $body;
            }
          }
      }
      break;


    case  'ISMIObjects_relations':
      $node = menu_get_object();
      $author_id = $node->field_id[LANGUAGE_NONE][0]['value'];


      $rels = relation_query("node",$node->nid)->execute();

      $block['content'] = ISMIBioFilter_RelationsFormat("node",$node,$rels);

      break;
  }

  return $block;
}

/**
 * Implements hook_block_info().
 */
function ISMIBioFilter_block_info() {
  $blocks = array();
  $blocks['ISMIBioFilter_help'] = array(
      'info' => t('ISMI Bio filter tips'),
  );
  $blocks['ISMIObjects_main'] = array(
      'info' => t('ISMI Main information of an object'),
  );

  $blocks['ISMIObjects_titles'] = array(
      'info' => t('ISMI Titles related to an object'),
  );

  $blocks['ISMIPersons_bea'] = array(
      'info' => t('ISMI Bea Entry of Person'),
  );

  $blocks['ISMIObjects_relations'] = array(
      'info' => t('ISMI all relations'),
  );

  $blocks['ISMIText_witnesses'] = array(
      'info' => t('ISMI witnesses'),
  );

  return $blocks;
}

/**
 * Provides content for the ISMIBioFilter help block.
 */
function _ISMIBioFilter_help_block() {
  return '<pre>' . t('Replaces external links to authors in the text to links to nodes in this website. ') . '</pre>';
}

/**
 *
 * Filter process callback.
 */
function _filter_ISMIBioFilter($text, $format) {
  if (!empty($text)) {

    $params = drupal_get_query_parameters();

    $text=preg_replace('/href="([^>]+?_BEA.htm)"\>/', 'href="$1">', $text);

    $text=preg_replace('#</span>\n#',"</span>",$text); #remove returns nach span otherwise this gives an extra space

    $text=preg_replace('#style="[^"]+#',"",$text); #remove all style information


  }

  return $text;
}

/**
 * Filter settings callback. Just provides a version overview.
 */
function _filter_ISMIBioFilter_settings($form, &$form_state, $filter, $format, $defaults) {
  module_load_include('php', 'ISMIBioFilter', 'ISMIBioFilter');

  $settings['ISMIBioFilter_wrapper'] = array(
      '#type' => 'fieldset',
      '#title' => t('ISMIBioFilter'),
  );
  $links = array('NO LINK',
      /*'Markdown PHP Version: <a href="http://michelf.com/projects/php-ISMIBioFilter/">' . MARKDOWN_VERSION . '</a>',
       'Markdown Extra Version: <a href="http://michelf.com/projects/php-ISMIBioFilter/">' . MARKDOWNEXTRA_VERSION . '</a>',*/
  );
  $settings['ISMIBioFilter_wrapper']['ISMIBioFilter_status'] = array(
      '#title' => t('Versions'),
      '#type' => 'item',
      '#markup' => theme('item_list', array('items' => $links)),
  );

  return $settings;
}


/* add id to url */

function ISMIBioFilter_addIDs(){
  $txt = file_get_contents(drupal_get_path("module", "ISMIBioFilter") . "/bio2ismi.txt");
  $lines = explode("\n",$txt);
  foreach ($lines as $line){
    $content = explode(" ",$line);
    $id = $content[0];
	$origPath=$content[sizeof($content)-1];
    $path = explode("/",$origPath);
    $url = $path[sizeof($path)-1];


    $nodePath = explode("/",drupal_lookup_path("source",$url));
    #$nodePath = explode("/",drupal_lookup_path("source",str_replace(".htm","",$url)));

    $nodeId = $nodePath[sizeof($nodePath)-1];

    if ($nodeId != ""){
      $node = node_load($nodeId);

      $node->field_id[LANGUAGE_NONE][0]['value']=$id;
      dpm($node);

      node_save($node);
    }
  }


}


function ISMIBioFilter_field_formatter_info(){
  return array(
      // This formatter shows the obejct with fullmetadata
      'ISMIBioFilter_entityLink' => array(
          'label' => t('Entity Link Formatter'),
          'field types' => array('text'),
      ),
  );
}

function ISMIBioFilter_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  #TODO make this configurable
  $text ="Show data entry";

  switch ($instance['label']){
    case 'author_id':
      $text = "More about the author";
  }

  switch ($display['type']) {
    // This formatter simply outputs the field as text and with a color.
    case 'ISMIBioFilter_entityLink':
      foreach ($items as $delta => $item) {
        if ($item['value']!=""){

          $element[$delta]['#markup'] = l($text,"showEntity/" . $item['value']);

        }
      }
      break;

  }
  return $element;
}



function ISMIBioFilter_theme(){

  return array(
      'ISMIObject_aliases'  => array(
          'variables' => array($prime_alias=null,$aliases=null),
          'template' => 'ISMIObject-aliases',
      ),

      'ISMIPersons_titles'  => array(
          'variables' => array('titles' => NULL),
          'template' => 'ISMITitlesOfPerson',
      ),

      'ISMIWitnesses_list'  => array(
          'variables' => array('witnesses' => NULL),
          'template' => 'ISMIWitnesses-list',
      ),
  );
}

function ISMIBioFilter_RelationsFormat($entity_type,$entity,$rels){
  $ret ="";
  $sentences = array();


  foreach ($rels as $item) {
    list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
    $relation = (object) relation_load($item->rid);

    $relation_type = relation_type_load($relation->relation_type);

    $subject = entity_label($entity_type, $entity) . ' '; // Subject of the sentence.
    $subject_is_source = ($relation->endpoints[LANGUAGE_NONE]['0']['entity_id']) == $id ? TRUE : FALSE;
    $count = 0; // For comma separation of objects.
    $duplicate = FALSE; // To make sure duplicates of $entity get included in object list.
    $objects = ''; // Comma separated list of entities that are the object of the sentence.
    // Gramatical predicate of teh sentence.
    $predicate = $relation_type->directional ? $relation_type->reverse_label : $relation_type->label;

    foreach ($relation->endpoints[LANGUAGE_NONE] as $endpoint) {
      // Add all entities that aren't this entity to the sentence $objects.
      // Check for duplicates of the $subject first.
      if ($endpoint['entity_type'] == $entity_type && $endpoint['entity_id'] == $id && $duplicate == FALSE) {
        $duplicate = TRUE;
        // Use the forward label as sentence predicate if r_index == 0.
        // (only makes a difference if relation is directional).
        if ($endpoint['r_index'] == 0) {
          $predicate = ' ' . $relation_type->label;
        }
      }
      else {
        // If the relation is directional and the subject isn't the source,
        // we want to list the source without any siblings. If it is
        // directional and the subject is a source, list all targets.
        // If non-directional, list everything as normal.
        if (!$relation_type->directional || $subject_is_source || $endpoint['r_index'] == 0) {
          $object_entities = entity_load($endpoint['entity_type'], array($endpoint['entity_id']));
          $object_entity = reset($object_entities);
          $object_label = entity_label($endpoint['entity_type'], $object_entity);
          $object_uri = entity_uri($endpoint['entity_type'], $object_entity);
          // Just add a space before the first element, comma and space before further ones.
          $objects .= $count ? ', ' : ' ';
          $count += 1;
          $objects .= l($object_label, $object_uri['path']);

          $ret .=theme('item_list',array('items' => array(".." . $predicate . $objects)));
        }
      }


    }




  }

  return $ret;
}

function _ISMIBioFilter_non_indentical($tars,$nid){
  $ret=array();
  foreach($tars as $tar){
    if($tar->nid!=$nid){
      $ret[]=$tar;
    }
  }
  return $ret;
}
function _ISMIBioFilter_enrich(&$titles){
  foreach($titles as $title){
  $title->codex=_ISMIBioFilter_find_unique_entity("is_part_of",$title->nid);
  $title->collection=_ISMIBioFilter_find_unique_entity("is_part_of",$title->codex->nid);
  $title->repository=_ISMIBioFilter_find_unique_entity("is_part_of",$title->collection->nid);
  $title->place=_ISMIBioFilter_find_unique_entity("is_in",$title->repository->nid);

  }
}





function _ISMIBioFilter_find_unique_entity($rel_type,$nid){
  $rels = relation_query("node",$nid)->execute();
  $is_in_place=array();
  foreach($rels as $rel){
    if ($rel->relation_type==$rel_type){
      $reps = _ISMIBioFilter_getTargets($rel);
      $is_in_place = array_merge($is_in_place,_ISMIBioFilter_non_indentical($reps,$nid));
    }

  }
  return $is_in_place[0];
}