SHARE
TWEET

Drupal Migrate module, appending files to migrated nodes

pjerky Jan 19th, 2012 171 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. class ImageAssetNodeAddEPSMigration extends BasicClientMigration {
  3.   public function __construct() {
  4.     parent::__construct();
  5.  
  6.     //This allows us to update the existing record.
  7.     $this->systemOfRecord = Migration::DESTINATION;
  8.    
  9.     $this->description = t('Image Asset Files - Adding the EPS files');
  10.     $this->dependencies = array('ImageAssetNode');
  11.  
  12.     $this->map = new MigrateSQLMap($this->machineName,
  13.       array(
  14.         'destid1' => array(
  15.           'type' => 'int',
  16.           'not null' => TRUE,
  17.           'description' => 'Node ID.',
  18.           'alias' => 'an',
  19.         )
  20.       ),
  21.       MigrateDestinationNode::getKeySchema()
  22.     );
  23.    
  24.     // We get the data from the database for this.
  25.     $query = db_select('migrate_map_imageassetnode', 'an')
  26.         ->fields('an', array('destid1'));
  27.     $query->innerJoin('migrate_client_image_asset_node', 'ta', 'an.sourceid1 = ta.fcid');
  28.     $query->fields('ta', array('eps_psd_filename', 'eps_psd_name', 'eps_psd_uri', 'fcid') );
  29.    
  30.     // Passing the cache_counts option means the source count (shown in
  31.     // drush migrate-status) will be cached - this can be very handy when
  32.     // dealing with a slow source database.
  33.     $this->source = new MigrateSourceSQL($query, array(), NULL,
  34.       array('cache_counts' => TRUE));
  35.    
  36.     // Set up our destination - nodes of type migrate_example_beer
  37.     $this->destination = new MigrateDestinationNodeExtended('media_images');
  38.    
  39.     /*
  40.       Assign mappings TO destination fields FROM source fields. To discover
  41.       the names used in these calls, use the drush commands
  42.       drush migrate-fields-destination ImageAssetNode
  43.       drush migrate-fields-source ImageAssetNode
  44.     */
  45.      
  46.     // Mapped fields
  47.     $this->addFieldMapping('nid', 'destid1')
  48.          ->description(t('The original node id.'));
  49.    
  50.     // Copy an image file, write DB record to files table, and save in Field storage.
  51.     // Note we specify the source query fields that will map to the file alt/title/description
  52.     // values.
  53.    
  54.     $eps_arguments = MigrateFileFieldHandler::arguments(NULL,
  55.       'file_link', FILE_EXISTS_RENAME, 'en', array('source_field' => 'eps_psd_name'),
  56.       array('source_field' => 'eps_psd_filename'), array('source_field' => 'eps_psd_filename'), NULL, TRUE);
  57.    
  58.     $this->addFieldMapping('field_file', 'eps_psd_uri')
  59.          ->arguments($eps_arguments);
  60.    
  61.     // Add fields that are mapped via argument
  62.     #$this->addFieldMapping(NULL, 'eps_psd_uri');
  63.    $this->addFieldMapping(NULL, 'eps_psd_filename');
  64.     $this->addFieldMapping(NULL, 'eps_psd_name');
  65.    
  66.     // No unmapped source fields
  67.     $this->addUnmigratedSources( array('fcid', 'jpg_uri', 'jpg_filename', 'jpg_name', 'category_tid') );
  68.  
  69.     // Unmapped destination fields
  70.     $this->addUnmigratedDestinations( array('is_new', 'name', 'created', 'changed',
  71.       'status', 'promote', 'revision', 'language', 'sticky', 'uid', 'revision_uid',
  72.       'title', 'body', 'field_image', 'field_keywords', 'field_download_count',
  73.       'field_images_category', 'field_media_status', 'field_media_audience',
  74.       'field_roles_download', 'field_roles_share', 'field_roles_view', 'path', 'comment',
  75.       'bookmarks', 'cart', 'download', 'pathauto') );
  76.   }
  77.   /*
  78.   public function prepare(&$node, &$row) {
  79.    
  80.   }*/
  81.  
  82.   public function prepareRow($current_row) {
  83.     //If the file does not exist then skip it.
  84.     if (!file_exists(drupal_realpath($current_row->eps_psd_uri))) {
  85.       return FALSE;
  86.     }
  87.  
  88.     $result = db_query("SELECT ff.* FROM field_data_field_file ff INNER JOIN migrate_map_imageassetnode ian ON ff.entity_id = ian.destid1 WHERE sourceid1 = :sid", array(':sid' => $current_row->fcid));
  89.  
  90.     //If there is more then one file field entry attached to the node then skip.
  91.     if ($result->rowCount() > 1) {
  92.       return FALSE;
  93.     }
  94.   }
  95. }
  96.  
  97. class MigrateDestinationNodeExtended extends MigrateDestinationNode {
  98.   /**
  99.    * Basic initialization
  100.    *
  101.    * @param string $bundle
  102.    *  A.k.a. the content type (page, article, etc.) of the node.
  103.    * @param array $options
  104.    *  Options applied to nodes.
  105.    */
  106.   public function __construct($bundle, array $options = array()) {
  107.     parent::__construct($bundle, $options);
  108.   }
  109.  
  110.   /**
  111.    * Import a single node.
  112.    *
  113.    * @param $node
  114.    *  Node object to build. Prefilled with any fields mapped in the Migration.
  115.    * @param $row
  116.    *  Raw source data object - passed through to prepare/complete handlers.
  117.    * @return array
  118.    *  Array of key fields (nid only in this case) of the node that was saved if
  119.    *  successful. FALSE on failure.
  120.    */
  121.   public function import(stdClass $node, stdClass $row) {
  122.     // Updating previously-migrated content?
  123.     $migration = Migration::currentMigration();
  124.  
  125.     if (isset($row->migrate_map_destid1)) {
  126.       // Make sure is_new is off
  127.       $node->is_new = FALSE;
  128.  
  129.       if (isset($node->nid)) {
  130.         if ($node->nid != $row->migrate_map_destid1) {
  131.           throw new MigrateException(t("Incoming nid !nid and map destination nid !destid1 don't match",
  132.             array('!nid' => $node->nid, '!destid1' => $row->migrate_map_destid1)));
  133.         }
  134.       }
  135.       else {
  136.         $node->nid = $row->migrate_map_destid1;
  137.       }
  138.  
  139.       // Get the existing vid, tnid so updates don't generate notices
  140.       $values = db_select('node', 'n')
  141.                    ->fields('n', array('vid', 'tnid'))
  142.                    ->condition('nid', $node->nid)
  143.                    ->execute()
  144.                    ->fetchAssoc();
  145.      
  146.       $node->vid = $values['vid'];
  147.       $node->tnid = $values['tnid'];
  148.     }
  149.  
  150.     if ($migration->getSystemOfRecord() == Migration::DESTINATION) {
  151.       if (!isset($node->nid)) {
  152.         throw new MigrateException(t('System-of-record is DESTINATION, but no destination nid provided'));
  153.       }
  154.  
  155.       $old_node = node_load($node->nid);
  156.  
  157.       if (!isset($node->created) && isset($old_node->created)) {
  158.         $node->created = $old_node->created;
  159.       }
  160.  
  161.       if (!isset($node->vid) && isset($old_node->vid)) {
  162.         $node->vid = $old_node->vid;
  163.       }
  164.  
  165.       if (!isset($node->status) && isset($old_node->status)) {
  166.         $node->status = $old_node->status;
  167.       }
  168.  
  169.       if (!isset($node->uid) && isset($old_node->uid)) {
  170.         $node->uid = $old_node->uid;
  171.       }
  172.     }
  173.  
  174.     // Set some required properties.
  175.     // Set type before invoking prepare handlers - they may take type-dependent actions.
  176.     $node->type = $this->bundle;
  177.  
  178.     if ($migration->getSystemOfRecord() == Migration::SOURCE) {
  179.       if (!isset($node->language)) {
  180.         $node->language = $this->language;
  181.       }
  182.  
  183.       // Apply defaults, allow standard node prepare hooks to fire.
  184.       // node_object_prepare() will blow these away, so save them here and
  185.       // stuff them in later if need be.
  186.       if (isset($node->created)) {
  187.         $created = MigrationBase::timestamp($node->created);
  188.       }
  189.       else {
  190.         // To keep node_object_prepare() from choking
  191.         $node->created = REQUEST_TIME;
  192.       }
  193.  
  194.       if (isset($node->changed)) {
  195.         $changed = MigrationBase::timestamp($node->changed);
  196.       }
  197.  
  198.       if (isset($node->uid)) {
  199.         $uid = $node->uid;
  200.       }
  201.  
  202.       node_object_prepare($node);
  203.  
  204.       if (isset($created)) {
  205.         $node->created = $created;
  206.       }
  207.  
  208.       // No point to resetting $node->changed here, node_save() will overwrite it
  209.       if (isset($uid)) {
  210.         $node->uid = $uid;
  211.       }
  212.     }
  213.  
  214.     // Invoke migration prepare handlers
  215.     $this->prepare($node, $row);
  216.  
  217.     if (!isset($node->revision)) {
  218.       $node->revision = 0; // Saves disk space and writes. Can be overridden.
  219.     }
  220.  
  221.     // Trying to update an existing node
  222.     if ($migration->getSystemOfRecord() == Migration::DESTINATION) {
  223.       // Incoming data overrides existing data, so only copy non-existent fields
  224.       if ( !isset($old_node) || ( isset($old_node) && (empty($old_node) || !is_array($old_node)) )) {
  225.         $return = FALSE;
  226.       }
  227.       else {
  228.         foreach ($old_node as $field => $value) {
  229.           // An explicit NULL in the source data means to wipe to old     value (i.e.,
  230.           // don't copy it over from $old_node)
  231.           if (property_exists($node, $field) && $node->$field === NULL) {
  232.             // Ignore this field
  233.           }
  234.           elseif ($field == 'field_file') {
  235.             $file_field = $node->$field;
  236.             $lang_files = array();
  237.    
  238.             // We can import this, got to do it on a per language basis
  239.             foreach ($value AS $lang => $files) {
  240.               if (isset($file_field[$lang])) {
  241.                 $new_node_files = $file_field[$lang];
  242.               }
  243.               else {
  244.                 $new_node_files = array();
  245.               }
  246.    
  247.               $lang_files[$lang] = array_merge($new_node_files, $files);
  248.             }
  249.    
  250.             $node->$field = $lang_files;
  251.           }
  252.           elseif (!isset($node->$field)) {
  253.             $node->$field = $old_node->$field;
  254.           }
  255.         }
  256.       }
  257.      
  258.     }
  259.  
  260.     if (isset($node->nid) && !(isset($node->is_new) && $node->is_new)) {
  261.       $updating = TRUE;
  262.     }
  263.     else {
  264.       $updating = FALSE;
  265.     }
  266.  
  267.     migrate_instrument_start('node_save');
  268.     node_save($node);
  269.     migrate_instrument_stop('node_save');
  270.  
  271.     if (isset($node->nid)) {
  272.       if ($updating) {
  273.         $this->numUpdated++;
  274.       }
  275.       else {
  276.         $this->numCreated++;
  277.       }
  278.  
  279.       // Unfortunately, http://drupal.org/node/722688 was not accepted, so fix
  280.       // the changed timestamp
  281.       if (isset($changed)) {
  282.         db_update('node')
  283.           ->fields(array('changed' => $changed))
  284.           ->condition('nid', $node->nid)
  285.           ->execute();
  286.        
  287.         $node->changed = $changed;
  288.       }
  289.  
  290.       // Potentially fix uid and timestamp in node_revisions.
  291.       $query = db_update('node_revision')
  292.                  ->condition('vid', $node->vid);
  293.      
  294.       if (isset($changed)) {
  295.         $fields['timestamp'] = $changed;
  296.       }
  297.  
  298.       $revision_uid = isset($node->revision_uid) ? $node->revision_uid : $node->uid;
  299.  
  300.       if ($revision_uid != $GLOBALS['user']->uid) {
  301.         $fields['uid'] = $revision_uid;
  302.       }
  303.  
  304.       if (!empty($fields)) {
  305.         // We actually have something to update.
  306.         $query->fields($fields);
  307.         $query->execute();
  308.  
  309.         if (isset($changed)) {
  310.           $node->timestamp = $changed;
  311.         }
  312.       }
  313.  
  314.       $return = array($node->nid);
  315.     }
  316.     else {
  317.       $return = FALSE;
  318.     }
  319.  
  320.     $this->complete($node, $row);
  321.     return $return;
  322.   }
  323. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top