You are here

function media_browser_plus_load_tag_terms in Media Browser Plus 7

Same name and namespace in other branches
  1. 7.2 media_browser_plus.module \media_browser_plus_load_tag_terms()

@todo Document what this funciont does.

Parameters

string $tags:

boolean $tids_only:

boolean $auto_create:

Return value

array

File

./media_browser_plus.module, line 1690
Adds fields to the media browser forms for better UX

Code

function media_browser_plus_load_tag_terms($tags, $tids_only = TRUE, $auto_create = FALSE) {
  $vocabulary = taxonomy_vocabulary_machine_name_load('tags');
  $select = $tids_only ? 'tid, name' : '*';
  $all_tags = array();
  $found_tags = array();
  $found_terms = array();
  $terms = explode(',', $tags);
  foreach ($terms as $tag) {

    // Check if tag exists.
    // @todo Would an EntityFieldQuery be appropriate?
    // http://drupal.org/node/916776
    $results = db_query('SELECT ' . $select . ' FROM {taxonomy_term_data} ttd WHERE ttd.name = :name AND ttd.vid = :vocabulary', array(
      'name' => check_plain(trim($tag)),
      'vocabulary' => $vocabulary->vid,
    ));
    foreach ($results as $result) {
      $term = taxonomy_term_load($result->tid);
      if ($tids_only) {
        $found_terms[] = array(
          'tid' => $term->tid,
        );
      }
      else {
        $found_terms[] = get_object_vars($term);
      }
      $found_tags[] = trim($tag);
    }
    $all_tags[] = trim($tag);
  }
  if ($auto_create) {
    foreach (array_diff($all_tags, $found_tags) as $id => $tag) {
      $term = new stdClass();
      $term->name = $tag;
      $term->vid = $vocabulary->vid;
      if (strlen(trim($term->name))) {
        taxonomy_term_save($term);
        if ($tids_only) {
          $found_terms[] = array(
            'tid' => $term->tid,
          );
        }
        else {
          $found_terms[] = get_object_vars($term);
        }
      }
    }
  }
  return $found_terms;
}