You are here

class WordPressAttachment in WordPress Migrate 7

Same name and namespace in other branches
  1. 7.2 wordpress_attachment.inc \WordPressAttachment

Implementation of WordPressMigration, for attachments

Hierarchy

Expanded class hierarchy of WordPressAttachment

1 string reference to 'WordPressAttachment'
WordPressBlog::migrationClasses in ./wordpress.inc
The implemented WordPress migrations, in the order they should be run.

File

./wordpress_attachment.inc, line 31

View source
class WordPressAttachment extends WordPressMigration {

  /**
   * Set it up
   */
  public function __construct(array $arguments = array()) {
    parent::__construct($arguments);
    $this->dependencies = array(
      $this
        ->generateMachineName('WordPressBlogEntry'),
      $this
        ->generateMachineName('WordPressPage'),
    );
    $dest_options = array(
      'copy_file' => TRUE,
    );

    // Make use of the media module if present
    if (module_exists('media') && module_exists('migrate_extras')) {
      $dest_options['source_migrations'] = $this->dependencies;
      $this->destination = new MigrateDestinationMedia('image', $dest_options);
      $keySchema = MigrateDestinationMedia::getKeySchema();
      $this
        ->addFieldMapping('media_title', 'title');
      $this
        ->addFieldMapping('media_description', 'content');
      $this
        ->addFieldMapping('file')
        ->issueGroup(t('DNM'));
    }
    else {
      $this->destination = new MigrateDestinationFile($dest_options);
      $keySchema = MigrateDestinationFile::getKeySchema();
      $this
        ->addFieldMapping(NULL, 'title')
        ->issueGroup(t('DNM'));
      $this
        ->addFieldMapping(NULL, 'content')
        ->issueGroup(t('DNM'));
    }

    // post_id is the unique ID of items in WordPress
    $this->map = new MigrateSQLMap($this->machineName, array(
      'post_id' => array(
        'type' => 'int',
        'not null' => TRUE,
        'unsigned' => TRUE,
        'description' => 'WordPress post ID',
      ),
    ), $keySchema);

    // Construct the source object.
    $this->source = new WordPressAttachmentSource($this->wxrFile);
    $this
      ->addFieldMapping('fid')
      ->issueGroup(t('DNM'));
    $this
      ->addFieldMapping('uid', 'creator')
      ->description('Use matching username if any, otherwise current user');
    $this
      ->addFieldMapping('filename')
      ->description(t('Defaults to basename(uri)'));
    $this
      ->addFieldMapping('uri', 'attachment_url');
    $this
      ->addFieldMapping('filemime')
      ->description(t('Determined by default'));
    $this
      ->addFieldMapping('status')
      ->defaultValue(FILE_STATUS_PERMANENT);
    $this
      ->addFieldMapping('timestamp', 'post_date');
    $this
      ->addFieldMapping(NULL, 'post_parent')
      ->description('For attachments, indicates item attached to')
      ->issueGroup(t('Open issues'))
      ->issuePriority(MigrateFieldMapping::ISSUE_PRIORITY_MEDIUM);

    // Unmapped destination fields
    $this
      ->addFieldMapping('path')
      ->issueGroup(t('DNM'));

    // Unmapped source fields
    $this
      ->addFieldMapping(NULL, 'link')
      ->issueGroup(t('DNM'));
    $this
      ->addFieldMapping(NULL, 'guid')
      ->issueGroup(t('DNM'));
    $this
      ->addFieldMapping(NULL, 'description')
      ->issueGroup(t('DNM'));
    $this
      ->addFieldMapping(NULL, 'excerpt')
      ->issueGroup(t('DNM'));
    $this
      ->addFieldMapping(NULL, 'post_id')
      ->description(t('Primary key of source'))
      ->issueGroup(t('DNM'));
    $this
      ->addFieldMapping(NULL, 'pubDate')
      ->description('Use post_date')
      ->issueGroup(t('DNM'));
    $this
      ->addFieldMapping(NULL, 'post_date_gmt')
      ->description('Use post_date')
      ->issueGroup(t('DNM'));
    $this
      ->addFieldMapping(NULL, 'comment_status')
      ->issueGroup(t('DNM'));
    $this
      ->addFieldMapping(NULL, 'ping_status')
      ->issueGroup(t('DNM'));
    $this
      ->addFieldMapping(NULL, 'post_name')
      ->issueGroup(t('DNM'));
    $this
      ->addFieldMapping(NULL, 'status')
      ->issueGroup(t('DNM'));
    $this
      ->addFieldMapping(NULL, 'menu_order')
      ->issueGroup(t('DNM'));
    $this
      ->addFieldMapping(NULL, 'post_type')
      ->issueGroup(t('DNM'));
    $this
      ->addFieldMapping(NULL, 'post_password')
      ->issueGroup(t('DNM'));
    $this
      ->addFieldMapping(NULL, 'is_sticky')
      ->issueGroup(t('DNM'));
    $this
      ->addFieldMapping(NULL, 'category')
      ->issueGroup(t('DNM'));
    $this
      ->addFieldMapping(NULL, '_wp_attached_file')
      ->issueGroup(t('DNM'));
    $this
      ->addFieldMapping(NULL, '_wp_attachment_metadata')
      ->issueGroup(t('DNM'));
  }

  /**
   * Data manipulations to be performed before migrate module applies mappings.
   *
   * @param stdClass $row
   * @return string
   */
  public function prepareRow($row) {

    // If incoming date is zero (indicates unpublished content), use the current time
    if ($row->post_date == '0000-00-00 00:00:00') {
      $row->post_date = time();
    }
    return TRUE;
  }

  /**
   * Prepare node - called just before node_save().
   *
   * @param stdClass $node
   * @param stdClass $row
   */
  public function prepare(stdClass $file, stdClass $row) {

    // Match creator username to Drupal username if possible; otherwise, use
    // the user that initiated the import
    static $drupal_static_fast;
    if (!isset($drupal_static_fast)) {
      $drupal_static_fast['user_map'] =& drupal_static(__FUNCTION__);
      $drupal_static_fast['default_user'] =& drupal_static(__FUNCTION__ . 'DefaultUser');
    }
    $user_map =& $drupal_static_fast['user_map'];
    if (!isset($user_map[$row->creator])) {
      $user_map[$row->creator] = db_select('users', 'u')
        ->fields('u', array(
        'uid',
      ))
        ->condition('name', $row->creator)
        ->execute()
        ->fetchField();
      if (!$user_map[$row->creator]) {
        $default_user =& $drupal_static_fast['default_user'];
        if (!isset($default_user)) {
          $default_user = db_select('wordpress_migrate', 'wpm')
            ->fields('wpm', array(
            'uid',
          ))
            ->condition('filename', $this->wxrFile)
            ->execute()
            ->fetchField();
        }
        $user_map[$row->creator] = $default_user;
      }
    }
    $file->uid = $user_map[$row->creator];
  }

  /**
   * Called after file object is saved - maintain a mapping from the URL on the
   * original WordPress blog to the URI in Drupal.
   *
   * @param stdClass $file
   * @param stdClass $row
   */
  public function complete(stdClass $file, stdClass $row) {
    db_merge('wordpress_migrate_attachment')
      ->key(array(
      'filename' => $this->wxrFile,
      'original_url' => $row->attachment_url,
    ))
      ->fields(array(
      'new_uri' => parse_url(file_create_url($file->uri), PHP_URL_PATH),
    ))
      ->execute();

    // If media_gallery is enabled, add this image to the user's gallery.
    // Lazy-create the gallery node if it doesn't already exist
    // TODO: Needs generalization, takes for granted blog module
    // TODO: Cache fids to add, do them all at once
    if (module_exists('media_gallery')) {
      global $user;
      $blog_title = t("@name's blog", array(
        '@name' => format_username($user),
      ));
      $gallery_nid = db_select('node', 'n')
        ->fields('n', array(
        'nid',
      ))
        ->condition('type', 'media_gallery')
        ->condition('title', $blog_title)
        ->execute()
        ->fetchField();
      if ($gallery_nid) {
        $gallery_node = node_load($gallery_nid);
      }
      else {
        $gallery_node = new stdClass();
        $gallery_node->type = 'media_gallery';
        $gallery_node->title = $blog_title;
        $gallery_node->uid = $user->uid;
        $gallery_node->language = LANGUAGE_NONE;
      }
      $gallery_node->media_gallery_media[LANGUAGE_NONE][] = array(
        'fid' => $file->fid,
      );
      node_save($gallery_node);
    }
  }

  /**
   * Called after all attachments are imported - fix up references to the imported
   * attachments in node bodies.
   */
  public function postImport() {
    parent::postImport();
    migrate_instrument_start('WordPressAttachment postImport');
    $source_migrations = array(
      $this
        ->generateMachineName('WordPressBlogEntry'),
      $this
        ->generateMachineName('WordPressPage'),
    );
    foreach ($source_migrations as $source_migration) {
      $migration = MigrationBase::getInstance($source_migration);
      $map = $migration
        ->getMap();
      foreach ($map as $map_row) {
        $nid = $map_row->destid1;
        $node = node_load($nid);
        $body = $node->body[LANGUAGE_NONE][0]['value'];
        $result = db_select('wordpress_migrate_attachment', 'a')
          ->fields('a', array(
          'original_url',
          'new_uri',
        ))
          ->condition('filename', $this->wxrFile)
          ->execute();
        foreach ($result as $row) {
          $body = str_replace($row->original_url, $row->new_uri, $body);
        }
        $node->body[LANGUAGE_NONE][0]['value'] = $body;
        node_save($node);
      }
    }
    migrate_instrument_stop('WordPressAttachment postImport');
  }

  /**
   * Remove all attachment records
   */
  public function postRollback() {
    db_delete('wordpress_migrate_attachment')
      ->condition('filename', $this->wxrFile)
      ->execute();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DynamicMigration::$deprecationWarning static property
DynamicMigration::isDynamic public static function Overrides default of FALSE Overrides MigrationBase::isDynamic
Migration::$allFieldMappings protected property All field mappings, with those retrieved from the database overriding those defined in code.
Migration::$codedFieldMappings protected property Field mappings retrieved from storage.
Migration::$counts protected property An array of counts. Initially used for cache hit/miss tracking.
Migration::$defaultRollbackAction protected property The default rollback action for this migration. Can be overridden on a per-row basis by setting $row->rollbackAction in prepareRow().
Migration::$destination protected property Destination object for the migration, derived from MigrateDestination.
Migration::$destinationValues protected property The object currently being constructed
Migration::$highwaterField protected property If present, an array with keys name and alias (optional). Name refers to the source columns used for tracking highwater marks. alias is an optional table alias.
Migration::$map protected property Map object tracking relationships between source and destination data
Migration::$needsUpdate public property Specify value of needs_update for current map row. Usually set by MigrateFieldHandler implementations.
Migration::$queuedMessages protected property Queue up messages that can't be safely saved (in particular, if they're generated in prepareRow().
Migration::$rollbackAction public property The rollback action to be saved for the current row.
Migration::$rollbackBatchSize protected property When performing a bulkRollback(), the maximum number of items to pass in a single call. Can be overridden in derived class constructor.
Migration::$source protected property Source object for the migration, derived from MigrateSource.
Migration::$sourceValues protected property The current data row retrieved from the source.
Migration::$storedFieldMappings protected property Field mappings defined in code.
Migration::$storedFieldMappingsRetrieved protected property
Migration::$subfieldDelimiter protected property
Migration::$systemOfRecord protected property
Migration::addFieldMapping public function Add a mapping for a destination field, specifying a source field and/or a default value. 1
Migration::addSimpleMappings public function Shortcut for adding several fields which have the same name on both source and destination sides.
Migration::addUnmigratedDestinations public function Shortcut for adding several destination fields which are to be explicitly not migrated.
Migration::addUnmigratedSources public function Shortcut for adding several source fields which are to be explicitly not migrated.
Migration::analyze public function Perform an analysis operation - report on field values in the source.
Migration::applyMappings protected function Apply field mappings to a data row received from the source, returning a populated destination object. 1
Migration::beginProcess protected function Override MigrationBase::beginProcess, to make sure the map/message tables are present. Overrides MigrationBase::beginProcess
Migration::checkStatus protected function Standard top-of-loop stuff, common between rollback and import - check for exceptional conditions, and display feedback.
Migration::createStubWrapper protected function If stub creation is enabled, try to create a stub and save the mapping.
Migration::currentSourceKey protected function Fetch the key array for the current source record.
Migration::deregisterMigration public static function Deregister a migration - remove all traces of it from the database (without touching any content which was created by this migration). Overrides MigrationBase::deregisterMigration
Migration::DESTINATION constant
Migration::endProcess public function Override MigrationBase::endProcess, to call post hooks. Note that it must be public to be callable as the shutdown function. Overrides MigrationBase::endProcess
Migration::errorCount public function Get the number of source records which failed to import. TODO: Doesn't yet account for informationals, or multiple errors for a source record.
Migration::getCodedFieldMappings public function
Migration::getDefaultRollbackAction public function
Migration::getDestination public function
Migration::getFieldMappings public function
Migration::getHighwaterField public function
Migration::getMap public function
Migration::getSource public function
Migration::getStoredFieldMappings public function
Migration::getSystemOfRecord public function
Migration::handleDedupe protected function For fields which require uniqueness, assign a new unique value if necessary.
Migration::handleSourceMigration protected function Look up a value migrated in another migration.
Migration::import protected function Perform an import operation - migrate items from source to destination.
Migration::importedCount public function Get the number of records successfully imported.
Migration::isComplete public function Reports whether this migration process is complete (i.e., all available source rows have been processed). Overrides MigrationBase::isComplete
Migration::itemOptionExceeded protected function Test whether we've exceeded the designated item limit.
Migration::loadFieldMappings public function Load any stored field mappings from the database.
Migration::messageCount public function Get the number of messages associated with this migration
Migration::onEmptyDestination protected function React when migration didn't failed but destination ids are empty.
Migration::onException protected function React when there is an exception
Migration::onMigrateException protected function React when there is a migrate exception
Migration::onSuccess protected function React when the migration has been successful.
Migration::preImport protected function Default implementations of pre/post import/rollback methods. These call the destination methods (if they exist) - when overriding, always call parent::preImport() etc.
Migration::prepareKey public function Default implementation of prepareKey. This method is called from the source plugin immediately after retrieving the raw data from the source - by default, it simply assigns the key values based on the field names passed to MigrateSQLMap(). Override…
Migration::prepareUpdate public function Prepares this migration to run as an update - that is, in addition to unmigrated content (source records not in the map table) being imported, previously-migrated content will also be updated in place.
Migration::preRollback protected function
Migration::processedCount public function Get the number of source records processed.
Migration::progressMessage protected function Outputs a progress message, reflecting the current status of a migration process.
Migration::queueMessage public function Queue messages to be later saved through the map class.
Migration::registerMigration public static function Register a new migration process in the migrate_status table. This will generally be used in two contexts - by the class detection code for static (one instance per class) migrations, and by the module implementing dynamic (parameterized class)… Overrides MigrationBase::registerMigration
Migration::removeFieldMapping public function Remove any existing coded mappings for a given destination or source field.
Migration::rollback protected function Perform a rollback operation - remove migrated items from the destination.
Migration::saveFieldMappings public static function Record an array of field mappings to the database.
Migration::saveMessage public function Pass messages through to the map class. Overrides MigrationBase::saveMessage
Migration::saveQueuedMessages public function Save any messages we've queued up to the message table.
Migration::setDefaultRollbackAction public function
Migration::setDestination public function
Migration::setHighwaterField public function
Migration::setMap public function
Migration::setSource public function
Migration::setSystemOfRecord public function
Migration::setUpdate public function Set the specified row to be updated, if it exists.
Migration::SOURCE constant Indicate whether the primary system of record for this migration is the source, or the destination (Drupal). In the source case, migration of an existing object will completely replace the Drupal object with data from the source side. In the…
Migration::sourceCount public function Convenience function to return count of total source records
Migration::updateCount public function Get the number of records marked as needing update.
MigrationBase::$arguments protected property Arguments configuring a migration.
MigrationBase::$batchTimeLimit protected property A time limit in seconds appropriate to be used in a batch import. Defaults to 240.
MigrationBase::$currentMigration protected static property Track the migration currently running, so handlers can easily determine it without having to pass a Migration object everywhere.
MigrationBase::$dependencies protected property List of other Migration classes which should be imported before this one. E.g., a comment migration class would typically have node and user migrations as dependencies.
MigrationBase::$description protected property Detailed information describing the migration.
MigrationBase::$disableHooks protected property Any module hooks which should be disabled during migration processes.
MigrationBase::$displayFunction protected static property Name of a function for displaying feedback. It must take the message to display as its first argument, and a (string) message type as its second argument (see drush_log()).
MigrationBase::$emptyArgumentsWarning protected static property
MigrationBase::$enabled protected property Disabling a migration prevents it from running with --all, or individually without --force
MigrationBase::$group protected property A migration group object, used to collect related migrations.
MigrationBase::$groupArgumentWarning protected static property Have we already warned about obsolete constructor argumentss on this request?
MigrationBase::$issuePattern protected property If provided, an URL for an issue tracking system containing :id where the issue number will go (e.g., 'http://example.com/project/ticket/:id').
MigrationBase::$logHistory protected property Whether to maintain a history of migration processes in migrate_log
MigrationBase::$logID protected property Primary key of the current history record (inserted at the beginning of a process, to be updated at the end)
MigrationBase::$machineName protected property The machine name of this Migration object, derived by removing the 'Migration' suffix from the class name. Used to construct default map/message table names, displayed in drush migrate-status, key to migrate_status table...
MigrationBase::$mailSystem protected property An array to track 'mail_system' variable if disabled.
MigrationBase::$memoryLimit protected property The PHP memory_limit expressed in bytes.
MigrationBase::$memoryThreshold protected property The fraction of the memory limit at which an operation will be interrupted. Can be overridden by a Migration subclass if one would like to push the envelope. Defaults to 85%.
MigrationBase::$options protected property Save options passed to current operation
MigrationBase::$previousErrorHandler protected property If we set an error handler (during import), remember the previous one so it can be restored.
MigrationBase::$processing protected property Indicates that we are processing a rollback or import - used to avoid excess writes in endProcess()
MigrationBase::$showEncryptionWarning protected static property Track whether or not we've already displayed an encryption warning
MigrationBase::$starttime protected property When the current operation started.
MigrationBase::$status protected property Are we importing, rolling back, or doing nothing?
MigrationBase::$team protected property MigrateTeamMember objects representing people involved with this migration.
MigrationBase::$timeLimit protected property The PHP max_execution_time.
MigrationBase::$timeThreshold protected property The fraction of the time limit at which an operation will be interrupted. Can be overridden by a Migration subclass if one would like to push the envelope. Defaults to 90%.
MigrationBase::$total_processed protected property Number of "items" processed in the current migration process (whatever that means for the type of process)
MigrationBase::addArguments public function
MigrationBase::addHardDependencies public function
MigrationBase::addSoftDependencies public function
MigrationBase::currentMigration public static function
MigrationBase::decrypt public static function Decrypt an incoming value.
MigrationBase::decryptArguments public static function Make sure any arguments we want to be decrypted get decrypted.
MigrationBase::dependenciesComplete protected function Reports whether all (hard) dependencies have completed migration
MigrationBase::disableMailSystem public function Disables mail system to prevent emails from being sent during migrations.
MigrationBase::displayMessage public static function Output the given message appropriately (drush_print/drupal_set_message/etc.)
MigrationBase::encrypt public static function Encrypt an incoming value. Detects for existence of the Drupal 'Encrypt' module.
MigrationBase::encryptArguments public static function Make sure any arguments we want to be encrypted get encrypted.
MigrationBase::errorHandler public function Custom PHP error handler. TODO: Redundant with hook_watchdog?
MigrationBase::getArguments public function
MigrationBase::getDependencies public function
MigrationBase::getDescription public function
MigrationBase::getDisableHooks public function
MigrationBase::getEnabled public function
MigrationBase::getGroup public function
MigrationBase::getHardDependencies public function
MigrationBase::getHighwater public function Fetch the current highwater mark for updated content.
MigrationBase::getInstance public static function Return the single instance of the given migration.
MigrationBase::getIssuePattern public function
MigrationBase::getItemLimit public function
MigrationBase::getLastImported public function Retrieve the last time an import operation completed successfully.
MigrationBase::getLastThroughput public function Retrieve the last throughput for current Migration (items / minute).
MigrationBase::getMachineName public function
MigrationBase::getMessageLevelName public function Get human readable name for a message constant.
MigrationBase::getOption public function
MigrationBase::getSoftDependencies public function
MigrationBase::getStatus public function Check the current status of a migration.
MigrationBase::getTeam public function
MigrationBase::getTimeLimit public function
MigrationBase::handleException public function Takes an Exception object and both saves and displays it, pulling additional information on the location triggering the exception.
MigrationBase::incompleteDependencies public function Returns an array of the migration's dependencies that are incomplete.
MigrationBase::machineFromClass protected static function Given only a class name, derive a machine name (the class name with the "Migration" suffix, if any, removed).
MigrationBase::memoryExceeded protected function Test whether we've exceeded the desired memory threshold. If so, output a message.
MigrationBase::MESSAGE_ERROR constant Message types to be passed to saveMessage() and saved in message tables. MESSAGE_INFORMATIONAL represents a condition that did not prevent the operation from succeeding - all others represent different severities of conditions resulting in a source…
MigrationBase::MESSAGE_INFORMATIONAL constant
MigrationBase::MESSAGE_NOTICE constant
MigrationBase::MESSAGE_WARNING constant
MigrationBase::processImport public function Perform an operation during the import phase
MigrationBase::processRollback public function Perform an operation during the rollback phase.
MigrationBase::resetStatus public function Reset the status of the migration to IDLE (to be used when the status gets stuck, e.g. if a process core-dumped)
MigrationBase::restoreMailSystem public function Restores the original saved mail system for migrations that require it.
MigrationBase::RESULT_COMPLETED constant Codes representing the result of a rollback or import process.
MigrationBase::RESULT_DISABLED constant
MigrationBase::RESULT_FAILED constant
MigrationBase::RESULT_INCOMPLETE constant
MigrationBase::RESULT_SKIPPED constant
MigrationBase::RESULT_STOPPED constant
MigrationBase::saveHighwater protected function Save the highwater mark for this migration (but not when using an idlist).
MigrationBase::saveMailSystem public function Saves the current mail system, or set a system default if there is none.
MigrationBase::setArguments public function
MigrationBase::setBatchTimeLimit public function Set the PHP time limit. This method may be called from batch callbacks before calling the processImport method.
MigrationBase::setDescription public function
MigrationBase::setDisplayFunction public static function
MigrationBase::setEnabled public function
MigrationBase::setHardDependencies public function
MigrationBase::setIssuePattern public function
MigrationBase::setSoftDependencies public function
MigrationBase::setTeam public function
MigrationBase::staticInitialize public static function Initialize static members, before any class instances are created.
MigrationBase::STATUS_DISABLED constant
MigrationBase::STATUS_IDLE constant Codes representing the current status of a migration, and stored in the migrate_status table.
MigrationBase::STATUS_IMPORTING constant
MigrationBase::STATUS_ROLLING_BACK constant
MigrationBase::STATUS_STOPPING constant
MigrationBase::stopProcess public function Signal that any current import or rollback process should end itself at the earliest opportunity
MigrationBase::timeExceeded protected function Test whether we're approaching the PHP time limit.
MigrationBase::timeOptionExceeded protected function Test whether we've exceeded the designated time limit.
MigrationBase::timestamp public static function Convert an incoming string (which may be a UNIX timestamp, or an arbitrarily-formatted date/time string) to a UNIX timestamp.
WordPressAttachment::complete public function Called after file object is saved - maintain a mapping from the URL on the original WordPress blog to the URI in Drupal.
WordPressAttachment::postImport public function Called after all attachments are imported - fix up references to the imported attachments in node bodies. Overrides Migration::postImport
WordPressAttachment::postRollback public function Remove all attachment records Overrides Migration::postRollback
WordPressAttachment::prepare public function Prepare node - called just before node_save().
WordPressAttachment::prepareRow public function Data manipulations to be performed before migrate module applies mappings. Overrides Migration::prepareRow
WordPressAttachment::__construct public function Set it up Overrides WordPressMigration::__construct
WordPressMigration::$blog protected property
WordPressMigration::$wxrFile protected property The filespec of the WXR file this migration is based on.
WordPressMigration::generateMachineName protected function Construct the machine name from the blog title Overrides MigrationBase::generateMachineName
WordPressMigration::showMessage public function Suppress normal migrate module output in the browser. In drush, use drush_print instead of drush_log to capture output (non-informational) for email.