public function TripalEntityController::setAlias

3.x TripalEntityController.inc public TripalEntityController::setAlias($entity, $alias = NULL)

Sets the URL alias for an entity.

1 call to TripalEntityController::setAlias()
TripalEntityController::save in tripal/includes/TripalEntityController.inc
Saves a new entity.

File

tripal/includes/TripalEntityController.inc, line 140

Class

TripalEntityController
TripalEntityController extends DrupalDefaultEntityController.

Code

public function setAlias($entity, $alias = NULL) {
  $source_url = "bio_data/$entity->id";

  // If no alias was supplied then we should try to generate one using the
  // default format set by admins.
  if (!$alias) {

    // Load the TripalBundle entity for this TripalEntity.
    $bundle_entity = tripal_load_bundle_entity(array('name' => $entity->bundle));

    // First get the format for the url alias based on the bundle of the entity.
    $alias = tripal_get_bundle_variable('url_format', $bundle_entity->id);

    // And then replace all the tokens with values from the entity fields.
    $alias = tripal_replace_entity_tokens($alias, $entity, $bundle_entity);
  }

  // If there is still no alias supplied then we should generate one using
  // the term name and entity id.
  if (!$alias) {

    // Load the term for this TripalEntity.
    $term = entity_load('TripalTerm', array('id' => $entity->term_id));
    $term = reset($term);

    // Set a default based on the term name and entity id.
    $alias = str_replace(' ', '', $term->name) . '/[TripalEntity__entity_id]';

    // And then replace all the tokens with values from the entity fields.
    $alias = tripal_replace_entity_tokens($alias, $entity, $bundle_entity);
  }
  // Check if the passed alias has tokens.
  if ($alias && (preg_match_all("/\[[^\]]*\]/", $alias, $bundle_tokens))) {

    // Load the TripalBundle entity for this TripalEntity.
    $bundle_entity = tripal_load_bundle_entity(array('name' => $entity->bundle));

    // And then replace all the tokens with values from the entity fields.
    $alias = tripal_replace_entity_tokens($alias, $entity, $bundle_entity);
  }

  // Make sure the alias doesn't contain spaces.
  $alias = preg_replace('/\s+/', '-', $alias);
  // Or any non alpha numeric characters.
  $alias = preg_replace('/[^a-zA-Z0-9\-\/]/', '', $alias);
  $alias = preg_replace('/_/', '-', $alias);

  if ($alias) {
    // Determine if this alias has already been used.
    $sql = '
        SELECT count(*) as num_alias
        FROM {url_alias}
        WHERE alias=:alias
      ';
    $num_aliases = db_query($sql, array(':alias' => $alias))->fetchField();

    // Either there isn't an alias yet so we just create one.
    // OR an Alias already exists but we would like to add a new one.
    if ($num_aliases == 0) {
      // First delete any previous alias' for this entity.
      // Then save the new one.

      // TODO: publishing an entity can be very slow if there are lots of
      // entries in the url_alias table, due to this type of
      // SQL statement that gets called somewhere by Drupal:
      // SELECT DISTINCT SUBSTRING_INDEX(source, '/', 1) AS path FROM url_alias.
      // Perhaps we should write our own SQL to avoid this issue.
      $values = array(
        'source' => $source_url,
        'alias' => $alias,
        'language' => 'und',
      );

      //        path_delete(array('source' => $source_url));
      //        $path = array('source' => $source_url, 'alias' => $alias);
      //        path_save($path);
      //Now check if an entry with the source url for this entity already
      // exists. This is an issue when updating existing url aliases. To avoid
      // creating 404s existing aliases need to be updated and a redirect
      // created to handle the old alias.
      $existing_aliases = db_select('url_alias', 'ua')
        ->fields('ua')
        ->condition('source', $source_url, '=')
        ->execute()->fetchAll();
      $num_aliases = count($existing_aliases);
      if ($num_aliases) {
        // For each existing entry create a redirect.
        foreach ($existing_aliases as $ea) {
          $path =[
          'source' $ea->source
            'alias' $alias
            'pid' $ea->pid
            'original'[
            'alias' $ea->alias
              'pid' $ea->pid
              'language' $ea->language
              ]
            ];
          module_load_include('module', 'redirect', 'redirect');
          redirect_path_update($path);

          //After redirects created now update the url_aliases table.
          db_update('url_alias')
            ->fields([
            'alias' $alias
            ])
            ->condition('source', $source_url, '=')
            ->condition('pid', $ea->pid, '=')
            ->execute();

        }
      }
      else {
        drupal_write_record('url_alias', $values);
      }
    }
    // If there is only one alias matching then it might just be that we already
    // assigned this alias to this entity in a previous save.
    elseif ($num_aliases == 1) {

      $bundle_entity = tripal_load_bundle_entity(array('name' => $entity->bundle));

      // Check to see if the single alias is for the same entity and if not
      // warn the admin that the alias is already used (ie: not unique?)
      $sql = "
          SELECT count(*) as num_alias
          FROM {url_alias}
          WHERE alias=:alias AND source=:source
        ";
      $replace = array(':alias' => $alias, ':source' => $source_url);
      $same_alias = db_query($sql, $replace)->fetchField();
      if (!$same_alias) {
        $msg = 'The URL alias, %alias, already exists for another page. ' .
          'Please ensure the pattern supplied on the <a href="!link" ' .
          'target="_blank">%type Edit Page</a> under URL Path options is ' .
          'unique.';
        $msg_var = array(
          '%alias' => $alias,
          '!link' => url("admin/structure/bio_data/manage/$entity->bundle"),
          '%type' => $bundle_entity->label
        );
        tripal_report_error('trpentity', TRIPAL_WARNING, $msg, $msg_var);
        drupal_set_message(t($msg, $msg_var), 'warning');
      }
    }
    // If there are more then one alias' matching what we generated then there's
    // a real problem and we need to warn the administrator.
    else {
      $bundle_entity = tripal_load_bundle_entity(array('name' => $entity->bundle));

      $aliases = db_query('SELECT source FROM {url_alias} WHERE alias=:alias', 
      array(':alias' => $alias))->fetchAll();
      $pages = array();
      foreach ($aliases as $a) {
        $pages[] = $a->source;
      }

      $msg = 'The URL alias, %alias, already exists for multiple pages! ' .
        'Please ensure the pattern supplied on the <a href="!link" ' .
        'target="_blank">%type Edit Page</a> under URL Path options is ' .
        'unique.';
      $msg_var = array(
        '%alias' => $alias,
        '!link' => url("admin/structure/bio_data/manage/$entity->bundle"),
        '%type' => $bundle_entity->label
      );
      drupal_set_message(t($msg, $msg_var), 'error');

      $msg .= ' This url alias has already been used for the following pages: %pages.
          You can manually delete alias\' using a combination of path_load() and path_delete().';
      $msg_var['%pages'] = implode(', ', $pages);
      tripal_report_error('trpentity', TRIPAL_ERROR, $msg, $msg_var);
    }
  }
}