Browse Source

adding the bulk update functionality for titles and aliases

Shawna 7 years ago
parent
commit
a930a0c4f1

+ 61 - 40
tripal/includes/TripalBundleUIController.inc

@@ -11,8 +11,6 @@ class TripalBundleUIController extends EntityDefaultUIController {
 
   public function __construct($entity_type, $entity_info) {
      parent::__construct($entity_type, $entity_info);
-     // Set the pager limit to something a bit larger
-     $this->overviewPagerLimit = 100;
   }
 
   /**
@@ -59,43 +57,6 @@ class TripalBundleUIController extends EntityDefaultUIController {
     return $forms;
   }
 
-  /**
-   * Override the EntityDefaultUIController::overviewTable because 
-   * it doesn't sort the content types by name
-   */
-  public function overviewTable($conditions = array()) {
-    $query = new EntityFieldQuery();
-    $query->entityCondition('entity_type', $this->entityType);
-  
-    // Add all conditions to query.
-    foreach ($conditions as $key => $value) {
-      $query->propertyCondition($key, $value);
-    }
-
-    if ($this->overviewPagerLimit) {
-      $query->pager($this->overviewPagerLimit);
-    }
-
-
-    $query->propertyOrderBy('label', 'ASC');
-    $results = $query->execute();
-
-    $ids = isset($results[$this->entityType]) ? array_keys($results[$this->entityType]) : array();
-    $entities = $ids ? entity_load($this->entityType, $ids) : array();
-
-    $rows = array();
-    foreach ($entities as $entity) {
-      $rows[] = $this->overviewTableRow($conditions, entity_id($this->entityType, $entity), $entity);
-    }
-
-    $render = array(
-      '#theme' => 'table', 
-      '#header' => $this->overviewTableHeaders($conditions, $rows), 
-      '#rows' => $rows, 
-      '#empty' => t('None.'),
-    );
-    return $render;
-  }
 }
 
 /**
@@ -281,6 +242,17 @@ function tripal_tripal_bundle_form($form, &$form_state, $entityDataType) {
     '#type' => 'item',
     '#markup' => theme_token_list($tokens),
   );
+  $form['set_titles']['bp_explanation'] = array(
+    '#type' => 'item',
+    '#markup' => t('Retroactively apply the new title pattern to
+        existing content.',
+      array('%type' => $bundle->label)),
+  );
+  $form['set_titles']['bulk_update'] = array(
+    '#type' => 'submit',
+    '#value' => t('Bulk update all titles'),
+    '#submit' => array('tripal_bulk_update_submit'),
+  );
 
   // Set URL Alias Pattern.
   //-------------------------
@@ -316,6 +288,7 @@ function tripal_tripal_bundle_form($form, &$form_state, $entityDataType) {
     '#rows' => 1
   );
 
+
   $tokens = tripal_get_entity_tokens($bundle, array('required only' => TRUE));
   $form['url']['tokens'] = array(
     '#type' => 'hidden',
@@ -334,7 +307,17 @@ function tripal_tripal_bundle_form($form, &$form_state, $entityDataType) {
     '#type' => 'item',
     '#markup' => theme_token_list($tokens),
   );
-
+  $form['url']['bp_explanation'] = array(
+    '#type' => 'item',
+    '#markup' => t('Retroactively apply the new url alias pattern to
+        existing content.',
+      array('%type' => $bundle->label)),
+  );
+  $form['url']['bulk_update'] = array(
+    '#type' => 'submit',
+    '#value' => t('Bulk update all aliases'),
+    '#submit' => array('tripal_bulk_update_submit'),
+  );
   // Submit Buttons
   //-------------------------
 
@@ -777,3 +760,41 @@ function tripal_admin_access($entity) {
   }
   return TRUE;
 }
+
+/**
+ * Process function for the bulk_update field of the bundle form.
+ *
+ * @param $form
+ * @param $form_state
+ *
+ * @return mixed
+ */
+function tripal_bulk_update_submit($form, &$form_state) {
+  $trigger = $form_state['triggering_element']['#value'];
+  $bundle_entity = $form_state['build_info']['args'][0];
+  $bundle_id = $bundle_entity->name;
+
+  //There are two submit buttons for this function, so to keep it DRY we'll
+  // use the triggering_element into to determine $update value.
+  if($trigger == 'Bulk update all titles'){
+    $update = $form_state['input']['set_titles']['title_format'];
+    $type = 'title';
+  }
+  elseif ($trigger == 'Bulk update all aliases'){
+    $update = $form_state['input']['url']['url_pattern'];
+    $type = 'alias';
+  }
+  global $user;
+  $args = array(
+    'bundle_id' => $bundle_id,
+    'update' => $update,
+    'type' => $type
+  );
+  $includes = array(
+    module_load_include('inc', 'tripal', 'includes/tripal.bulk_update'),
+  );
+  tripal_add_job('Update all aliases', 'tripal',
+     'tripal_update_all', $args,
+     $user->uid, 10, $includes);
+  return $form;
+}

+ 58 - 2
tripal/includes/TripalEntityController.inc

@@ -113,6 +113,15 @@ class TripalEntityController extends EntityAPIController {
       $title = tripal_get_title_format($bundle_entity);
       $title = tripal_replace_entity_tokens($title, $entity, $bundle_entity);
     }
+    // Check if the passed alias has tokens.
+    if($title && (preg_match_all("/\[[^\]]*\]/", $title, $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.
+      $title = tripal_replace_entity_tokens($title, $entity, $bundle_entity);
+    }
     // As long as we were able to determine a title, we should update it ;-).
     if ($title) {
       db_update('tripal_entity')
@@ -158,6 +167,15 @@ class TripalEntityController extends EntityAPIController {
       // 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);
@@ -166,7 +184,6 @@ class TripalEntityController extends EntityAPIController {
     $alias = preg_replace('/_/','-',$alias);
 
     if ($alias) {
-
       // Determine if this alias has already been used.
       $sql ='
         SELECT count(*) as num_alias
@@ -191,10 +208,49 @@ class TripalEntityController extends EntityAPIController {
           'alias' => $alias,
           'language' => 'und',
         );
-        drupal_write_record('url_alias', $values);
+
 //        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.

+ 58 - 0
tripal/includes/tripal.bulk_update.inc

@@ -0,0 +1,58 @@
+<?php
+/**
+ * Updates all existing url aliases for an entity.
+ *
+ * @param $bundle_id
+ * @param $update
+ * @param $type
+*/
+function tripal_update_all($bundle_id, $update, $type) {
+  //Load all the entity_ids.
+  $entity_table = 'chado_'.$bundle_id;
+  $entities = db_select($entity_table, 'e')
+  ->fields('e', array('entity_id'))
+  ->execute()->fetchAll();
+  $num_entities = count($entities);
+  //Parse the $update variable for tokens and load those tokens.
+  preg_match_all("/\[[^\]]*\]/", $update, $bundle_tokens);
+  //Get the queue so we can add to it.  Use a
+  //descriptive name. It's ok if it doesn't exist yet.
+  $queue = DrupalQueue::get('entityQueue');
+  //Push all the items into the queue, one at a time.
+  //You can push any data in with (arrays, objects, etc).
+  foreach($entities as $entity) {
+    $queue->createItem($entity);
+  }
+  $i = 0;
+  //Pull items out one at a time.
+  while($entity = $queue->claimItem()) {
+    $arg = tripal_load_entity('TripalEntity', [$entity->data->entity_id], $bundle_tokens);
+    if ($type == 'alias') {
+      if (!empty($arg)) {
+        if(is_array($arg)){
+          $ent = reset($arg);
+        }
+        // Get the entity controller and clear the cache if requested (default).
+        $ec = entity_get_controller('TripalEntity');
+        $ec->setAlias($ent, $update);
+      }
+    }
+    elseif ($type == 'title') {
+      if (!empty($arg)) {
+        if(is_array($arg)){
+          $ent = reset($arg);
+        }
+        $ec = entity_get_controller('TripalEntity');
+        $ec->setTitle($ent, $update);
+      }
+    }
+    $i++;
+    // Check if 50 items have been updated, if so print message.
+    if ($i < $num_entities){
+      print $i."/".$num_entities." entities have been updated.\r";
+    }
+    //Good, we succeeded.  Delete the item as it is no longer needed.
+    $queue->deleteItem($entity);
+  }
+}
+