[ Index ]

PHP Cross Reference of Drupal 6 (yi-drupal)

title

Body

[close]

/sites/all/modules/data/data_taxonomy/ -> data_taxonomy.module (source)

   1  <?php
   2  
   3  /**
   4   * @file
   5   * Hooks and API functions for Data Node module.
   6   */
   7  
   8  /**
   9   * Implementation of hook_views_api().
  10   */
  11  function data_taxonomy_views_api() {
  12    return array(
  13      'api' => '2.0',
  14      'path' => drupal_get_path('module', 'data_taxonomy') .'/views',
  15    );
  16  }
  17  
  18  /**
  19   * Implementation of hook_menu().
  20   */
  21  function data_taxonomy_menu() {
  22    $items = array();
  23    $items['data-taxonomy/ajax-save'] = array(
  24      'page callback' => 'data_taxonomy_ajax_save',
  25      'page arguments' => array(),
  26      'access arguments' => array('edit data taxonomy relations'),
  27      'type' => MENU_CALLBACK,
  28    );
  29    $items['admin/build/data/edit/%data_ui_table/taxonomy'] = array(
  30      'title' => 'Relate to taxonomy',
  31      'description' => 'Administer data tables.',
  32      'page callback' => 'drupal_get_form',
  33      'page arguments' => array('data_taxonomy_settings_form', 4),
  34      'file' => 'data_taxonomy.admin.inc',
  35      'access arguments' => array('administer data tables'),
  36      'type' => MENU_LOCAL_TASK,
  37    );
  38    return $items;
  39  }
  40  
  41  /**
  42   * Implementation of hook_theme().
  43   */
  44  function data_taxonomy_theme() {
  45    return array(
  46      'data_taxonomy_tagging_form' => array(
  47        'arguments' => array('form' => array()),
  48        'path' => drupal_get_path('module', 'data_taxonomy') . '/theme',
  49        'template' => 'data-taxonomy-tagging-form',
  50      ),
  51    );
  52  }
  53  
  54  /**
  55   * Implementation of hook_perm().
  56   */
  57  function data_taxonomy_perm() {
  58    return array('edit data taxonomy relations');
  59  }
  60  
  61  /**
  62   * Implementation of hook_feeds_data_processor_targets_alter().
  63   */
  64  function data_taxonomy_feeds_data_processor_targets_alter(&$fields, $table_name) {
  65    if ($info = data_taxonomy_get_info($table_name)) {
  66      foreach ($info['vocabularies'] as $vid) {
  67        $vocabulary = data_taxonomy_get_vocabulary($vid);
  68        $fields['data_taxonomy:'. $vid] = array(
  69          'name' => t('Taxonomy: @vocabulary', array("@vocabulary" => $vocabulary->name)),
  70          'description' => t('Map to taxonomy terms of @vocabulary vocabulary.', array("@vocabulary" => $vocabulary->name)),
  71        );
  72      }
  73    }
  74  }
  75  
  76  /**
  77   * Implementation of hook_data_insert().
  78   */
  79  function data_taxonomy_data_insert($record, $table_name) {
  80    if ($info = data_taxonomy_get_info($table_name)) {
  81      $id = $record[$info['id']];
  82      foreach ($info['vocabularies'] as $vid) {
  83        if (isset($record['data_taxonomy:'. $vid])) {
  84          _data_taxonomy_save_terms($table_name, $id, $record['data_taxonomy:'. $vid], data_taxonomy_get_vocabulary($vid));
  85        }
  86      }
  87    }
  88  }
  89  
  90  /**
  91   * Implementation of hook_data_update().
  92   */
  93  function data_taxonomy_data_update($record, $table_name) {
  94    if ($info = data_taxonomy_get_info($table_name)) {
  95      $id = $record[$info['id']];
  96      foreach ($info['vocabularies'] as $vid) {
  97        if (isset($record['data_taxonomy:'. $vid])) {
  98          $vocabulary = data_taxonomy_get_vocabulary($vid);
  99          _data_taxonomy_save_terms($table_name, $id, $record['data_taxonomy:'. $vid], $vocabulary);
 100        }
 101      }
 102    }
 103  }
 104  
 105  /**
 106   * Implementation of hook_taxonomy().
 107   */
 108  function data_taxonomy_taxonomy($op = NULL, $type = NULL, $term = NULL) {
 109    if ($type =='term' && $term['tid'] && $op == 'delete') {
 110      db_query("DELETE FROM {data_taxonomy} WHERE tid = %d", $term['tid']);
 111    }
 112  }
 113  
 114  /**
 115   * Helper function, saves a series of taxonomy terms for a record.
 116   *
 117   * Creates new taxonomy terms on the fly for vocabularies that are tags.
 118   *
 119   * @param $table_name
 120   *   Table name of the record.
 121   * @param $id
 122   *   Record identifier.
 123   * @param $terms
 124   *   An array of terms. Can be an array of tids, term names, term arrays or
 125   *   objects that can be casted into a term array. If the target vocabulary is
 126   *   a tag vocabulary, non-existing terms will be created on the fly.
 127   * @param $vocabulary
 128   *   A vocuabulary object.
 129   */
 130  function _data_taxonomy_save_terms($table_name, $id, $terms, $vocabulary) {
 131    if (!is_array($terms)) {
 132      $terms = array($terms);
 133    }
 134    $tids = array();
 135    foreach ($terms as $term) {
 136      if (is_string($term)) {
 137        $term = data_taxonomy_sanitize($term, $vocabulary->vid);
 138        $term = data_taxonomy_save_term_name($term, $vocabulary->vid, $vocabulary->tags);
 139      }
 140      else {
 141        if (is_object($term)) {
 142          $term = (array)$term;
 143        }
 144        if (is_array($term)) {
 145          $term['name'] = data_taxonomy_sanitize($term['name'], $vocabulary->vid);
 146          $term = data_taxonomy_save_term_array($term, $vocabulary->vid, $vocabulary->tags);
 147        }
 148      }
 149      if (is_array($term)) {
 150        $term = isset($term['tid']) ? $term['tid'] : FALSE;
 151      }
 152      if (is_numeric($term) && !isset($tids[$term])) {
 153        $tids[$term] = $term;
 154      }
 155    }
 156    _data_taxonomy_save_relations($vocabulary->vid, $id, $table_name, $tids);
 157  }
 158  
 159  /**
 160   * Implementation of hook_data_delete_query_alter().
 161   */
 162  function data_taxonomy_data_delete_query_alter($query, $table_name) {
 163    if ($info = data_taxonomy_get_info($table_name)) {
 164      $table_name = db_escape_table($table_name);
 165      $query->addSubject('data_taxonomy');
 166      $query->addJoin('data_taxonomy', "$table_name.{$info['id']} = data_taxonomy.id AND data_taxonomy.data_table_name = '$table_name'", 'LEFT JOIN');
 167    }
 168  }
 169  
 170  /**
 171   * Get data_taxonomy information for a given data table.
 172   */
 173  function data_taxonomy_get_info($table_name) {
 174    static $info = array();
 175    if (!isset($info[$table_name])) {
 176      $info[$table_name] = FALSE;
 177      $meta = data_get_table($table_name)->get('meta');
 178      if (is_array($meta['data_taxonomy'])) {
 179        $info[$table_name] = $meta['data_taxonomy'];
 180      }
 181    }
 182    return $info[$table_name];
 183  }
 184  
 185  /**
 186   * Form callback for tagging.
 187   */
 188  function data_taxonomy_tagging_form(&$form_state, $vid, $id, $table_name, $path, $args) {
 189    $access = user_access('edit data taxonomy relations');
 190    $form = array('#theme' => 'data_taxonomy_tagging_form');
 191    $form['vid'] = array(
 192      '#type' => 'hidden',
 193      '#value' => $vid,
 194      '#access' => $access,
 195    );
 196    $form['id'] = array(
 197      '#type' => 'hidden',
 198      '#value' => $id,
 199      '#access' => $access,
 200    );
 201    $form['table_name'] = array(
 202      '#type' => 'hidden',
 203      '#value' => $table_name,
 204      '#access' => $access,
 205    );
 206    $form['path'] = array(
 207      '#type' => 'hidden',
 208      '#value' => $path,
 209      '#access' => $access,
 210    );
 211    $form['args'] = array(
 212      '#type' => 'hidden',
 213      '#value' => implode('&', $args),
 214      '#access' => $access,
 215    );
 216    $result = db_query('SELECT td.tid, td.name, td.vid FROM {term_data} td JOIN {data_taxonomy} dt ON td.tid = dt.tid WHERE dt.data_table_name = "%s" AND dt.id = %d AND td.vid = %d', $table_name, $id, $vid);
 217    $tags = $terms = array();
 218    while ($term = db_fetch_object($result)) {
 219      $tags[$term->tid] = $term->name;
 220      $terms[$term->tid] = $term;
 221    }
 222    $form['tags'] = array(
 223      '#type' => 'textfield',
 224      '#default_value' => implode(', ', $tags),
 225      '#autocomplete_path' => 'taxonomy/autocomplete/'. $vid,
 226      '#id' => "edit-tags-data-taxonomy-{$vid}-{$id}",
 227      '#access' => $access,
 228    );
 229  
 230    // Ensure our path gets rewritten. We don't use url() here because we're
 231    // not interested in rewrites to parts of the request other than $_GET['q'].
 232    $ajax_path = 'data-taxonomy/ajax-save';
 233    if (function_exists('custom_url_rewrite_outbound')) {
 234      $original_path = $ajax_path;
 235      $options = array();
 236      custom_url_rewrite_outbound($ajax_path, $options, $original_path);
 237    }
 238    $form['submit'] = array(
 239      '#type' => 'submit',
 240      '#value' => t('Save'),
 241      '#access' => $access,
 242  
 243      // AHAH stack: We need to assign our submit button its own ID as auto
 244      // assignment will quickly lead to a situation where our AJAX form button
 245      // has a different ID from the original.
 246      '#id' => "edit-submit-data-taxonomy-{$vid}-{$id}",
 247      '#ahah' => array(
 248        'path' => $ajax_path,
 249        'wrapper' => "data-taxonomy-tags-{$vid}-{$id}",
 250        'method' => 'replace',
 251        'effect' => 'none',
 252      ),
 253    );
 254  
 255    // Pass on key elements for theming.
 256    $form['#terms'] = $terms;
 257    $form['#path'] = $path;
 258    $form['#args'] = $args;
 259    if ($access) {
 260      $form['#edit'] = l(t('Edit'), $_GET['q'], array('fragment' => 'data-taxonomy-edit', 'attributes' => array('class' => 'data-taxonomy-edit')));
 261    }
 262    $form['#vocab'] = taxonomy_vocabulary_load($vid);
 263    return $form;
 264  }
 265  
 266  /**
 267   * Submit handler.
 268   */
 269  function data_taxonomy_tagging_form_submit($form, &$form_state) {
 270    // Using clicked_button allows us to use more than one of the same form on
 271    // a screen.
 272    $post = $form_state['clicked_button']['#post'];
 273    $tids = data_taxonomy_save_tags($form_state['values']['tags'], $post['vid']);
 274    _data_taxonomy_save_relations($post['vid'], $post['id'], $post['table_name'], $tids);
 275  }
 276  
 277  /**
 278   * Save term_data - data table relationships in data_taxonomy table.
 279   */
 280  function _data_taxonomy_save_relations($vid, $id, $table_name, $tids) {
 281    db_query("DELETE dt FROM {data_taxonomy} dt JOIN {term_data} td ON dt.tid = td.tid WHERE dt.id = %d AND dt.data_table_name = '%s' AND td.vid = %d", $id, $table_name, $vid);
 282    foreach ($tids as $tid) {
 283      db_query('INSERT INTO {data_taxonomy} (id, data_table_name, tid) VALUES (%d, "%s", %d)', $id, $table_name, $tid);
 284    }
 285  }
 286  
 287  /**
 288   * Save a term, create a new one if it does not exist yet.
 289   *
 290   * @param $name
 291   *   A taxonomy term name to look up and save.
 292   * @param $vid
 293   *   A <em>numeric</em> vocabulary id (vid).
 294   *
 295   * @return
 296   *   A taxonomy term array.
 297   */
 298  function data_taxonomy_save_term_name($name, $vid) {
 299    if ($term = data_taxonomy_lookup_term($name, $vid)) {
 300      return $term;
 301    }
 302    $term = array(
 303      'vid' => $vid,
 304      'name' => $name,
 305    );
 306    taxonomy_save_term($term);
 307    return $term;
 308  }
 309  
 310  /**
 311   * Save a term array, create a new one if it does not exist yet.
 312   *
 313   * @param $term
 314   *   A taxonomy term array to look up and save.
 315   * @param $vid
 316   *   A <em>numeric</em> vocabulary id (vid).
 317   *
 318   * @return
 319   *   A taxonomy term array.
 320   */
 321  function data_taxonomy_save_term_array($term, $vid) {
 322    if (!isset($term[$vid])) {
 323      $term['vid'] = $vid;
 324    }
 325    if (!isset($term['tid']) || $term['vid'] != $vid) {
 326      if ($lookup = data_taxonomy_lookup_term($term['name'], $vid)) {
 327        $term = $term + $lookup;
 328      }
 329    }
 330    taxonomy_save_term($term);
 331    return $term;
 332  }
 333  
 334  /**
 335   * Sanitize a term name depending on its vocabulary settings.
 336   */
 337  function data_taxonomy_sanitize($name, $vid) {
 338    $vocabulary = taxonomy_vocabulary_load($vid);
 339    if ($vocabulary->tags) {
 340      // Make sure there aren't any terms with a comma (=tag delimiter) in it.
 341      return preg_replace('/\s*,\s*/', ' ', $name);
 342    }
 343    return $name;
 344  }
 345  
 346  /**
 347   * Look up a term by name and vid.
 348   *
 349   * @param $name
 350   *   Term name.
 351   * @param $vid
 352   *   A <em>numeric</em> vocabulary id (vid).
 353   *
 354   * @return
 355   *   A taxonomy term array if there is a term for $name/$vid, NULL otherwise.
 356   */
 357  function data_taxonomy_lookup_term($name, $vid) {
 358    static $terms;
 359    if (!isset($terms[$vid][$name])) {
 360      foreach (data_taxonomy_get_term_by_name_vid($name, $vid) as $term) {
 361        if ($term->vid == $vid) {
 362          $terms[$vid][$name] = (array)$term;
 363        }
 364      }
 365    }
 366    return isset($terms[$vid][$name]) ? $terms[$vid][$name] : NULL;
 367  }
 368  
 369  /**
 370   * Look up a term by name and vocabulary id.
 371   *
 372   * @see taxonomy_get_term_by_name().
 373   */
 374  function data_taxonomy_get_term_by_name_vid($name, $vid) {
 375    $db_result = db_query(db_rewrite_sql("SELECT t.tid, t.* FROM {term_data} t WHERE t.vid = %d AND LOWER(t.name) = LOWER('%s')", 't', 'tid'), $vid, trim($name));
 376    $result = array();
 377    while ($term = db_fetch_object($db_result)) {
 378      $result[] = $term;
 379    }
 380    return $result;
 381  }
 382  
 383  /**
 384   * Explode terms from typed input, create new terms.
 385   *
 386   * @param $typed_input
 387   *   A comma separated list of terms.
 388   * @param $vid
 389   *   A <em>numeric</em> vocabulary id (vid).
 390   *
 391   * @todo: This should actually live in taxonomy module.
 392   *
 393   * @return
 394   *   Array of tids corresponding to the terms in typed_input.
 395   */
 396  function data_taxonomy_save_tags($typed_input, $vid) {
 397    $tids = array();
 398    foreach (drupal_explode_tags($typed_input) as $typed_term) {
 399      $term = data_taxonomy_save_term_name($typed_term, $vid);
 400      // Cast the edit as an object as though it were retrieved from the DB.
 401      $tids[$term['tid']] = (object) $term;
 402    }
 403    return $tids;
 404  }
 405  
 406  /**
 407   * AHAH callback for saving terms.
 408   *
 409   * @todo: Verify form token.
 410   */
 411  function data_taxonomy_ajax_save() {
 412    $cached_form_state = array();
 413    $files = array();
 414    $cached_form = form_get_cache($_POST['form_build_id'], $cached_form_state);
 415    if ($cached_form['form_token']['#default_value'] == $_POST['form_token']) {
 416      // Rebuild $form_state['values'].
 417      $form_state = array('values' => $_POST);
 418      foreach (element_children($cached_form) as $elem) {
 419        if ($cached_form[$elem]['#type'] === 'value' && isset($cached_form[$elem]['#value'])) {
 420          $form_state['values'][$elem] = $cached_form[$elem]['#value'];
 421        }
 422      }
 423  
 424      // Process and save terms & relations.
 425      $values = $form_state['values'];
 426      $terms = data_taxonomy_save_tags($values['tags'], $values['vid']);
 427      _data_taxonomy_save_relations($values['vid'], $values['id'], $values['table_name'], array_keys($terms));
 428      drupal_json(array('status' => 1, 'data' => theme('links', data_taxonomy_tag_links($terms, $_POST['path'], explode('&', $_POST['args'])), array('class' => 'links data-taxonomy-tags'))));
 429      exit;
 430    }
 431    drupal_json(array('status' => 1, 'data' => 'Error submitting form'));
 432    exit;
 433  }
 434  
 435  /**
 436   * Generate a links array suitable for use with theme('links') from an array of
 437   * taxonomy terms.
 438   *
 439   * @param $terms
 440   *   An array of terms.
 441   * @param $path
 442   *   The path template to use (e. g. path/%/!tid/%)
 443   * @param $args
 444   *   The arguments to use in the path template, used to replace %'s in $path.
 445   */
 446  function data_taxonomy_tag_links($terms, $path, $args) {
 447    $tags = array();
 448    $path = _data_taxonomy_replace_tokens($path, $args);
 449    foreach ($terms as $tid => $term) {
 450      $tags[] = array(
 451        'title' => $term->name,
 452        'href' => str_replace('!term', $term->name, str_replace('!tid', $term->tid, $path)),
 453      );
 454    }
 455    return $tags;
 456  }
 457  
 458  /**
 459   * Replaces % in $path with arguments.
 460   *
 461   * @todo: Replace missing % not with 'all' but with value depending on argument
 462   * setting.
 463   *
 464   * @param $path
 465   *   A path template like path/%/!tid/%
 466   * @param $args
 467   *   An array of arguments used to replace % characters in path.
 468   * @return
 469   *   A path with replaced tokens like path/arg1/!tid/arg2
 470   */
 471  function _data_taxonomy_replace_tokens($path, $args) {
 472    if (is_array($args)) {
 473      $args = array_filter($args);
 474      $pos = strpos($path, '%');
 475      while ($pos !== FALSE && count($args)) {
 476        $path = substr_replace($path, array_shift($args), $pos, 1);
 477        $pos = strpos($path, '%');
 478      }
 479    }
 480    $path = str_replace('%', 'all', $path);
 481    return $path;
 482  }
 483  
 484  /**
 485   * Preprocessor for theme('data_taxonomy_tagging_form').
 486   */
 487  function template_preprocess_data_taxonomy_tagging_form(&$vars) {
 488    drupal_add_js(drupal_get_path('module', 'data_taxonomy') .'/theme/data_taxonomy.js');
 489    drupal_add_css(drupal_get_path('module', 'data_taxonomy') .'/theme/data_taxonomy.css');
 490    $vars['label'] = $vars['form']['#vocab']->name;
 491    if ($vars['form']['#edit']) {
 492      $vars['edit'] = $vars['form']['#edit'];
 493    }
 494    $vars['tags'] = theme('links', data_taxonomy_tag_links($vars['form']['#terms'], $vars['form']['#path'], $vars['form']['#args']), array('class' => 'links data-taxonomy-tags'));
 495  }
 496  
 497  /**
 498   * Get a vocabulary by vid or module name.
 499   *
 500   * @param $id
 501   *   A module name or a numeric vocabulary id.
 502   *
 503   * @return
 504   *   An object of type stdClass that represents a vocabulary.
 505   */
 506  function data_taxonomy_get_vocabulary($id) {
 507    static $vocabularies;
 508    if (!isset($vocabularies[$id])) {
 509      foreach (taxonomy_get_vocabularies() as $vocabulary) {
 510        if ($vocabulary->vid == $id) {
 511          $vocabularies[$id] = $vocabulary;
 512          break;
 513        }
 514        elseif ($vocabulary->module == $id) {
 515          $vocabularies[$id] = $vocabulary;
 516          break;
 517        }
 518      }
 519    }
 520    return $vocabularies[$id];
 521  }
 522  
 523  /**
 524   * Return the vocabulary identifier, the vocabulary's vid or module.
 525   *
 526   * @return
 527   *   Vocabulary's module name if it is a features vocabulary (= exportable),
 528   *   vocabulary's vid otherwise.
 529   */
 530  function data_taxonomy_vocabulary_id($vocabulary) {
 531    if (strpos($vocabulary->module, 'features_') === 0) {
 532      return $vocabulary->module;
 533    }
 534    return $vocabulary->vid;
 535  }


Generated: Mon Jul 9 18:01:44 2012 Cross-referenced by PHPXref 0.7