migration.inc 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595
  1. <?php
  2. /**
  3. * @file
  4. * Defines the base class for import/rollback processes.
  5. */
  6. /**
  7. * The base class for all import objects. This is where most of the smarts
  8. * of the migrate module resides. Migrations are created by deriving from this
  9. * class, and in the constructor (after calling parent::__construct()) initializing
  10. * at a minimum the name, description, source, and destination properties. The constructor
  11. * will also usually make several calls to addFieldMapping().
  12. */
  13. abstract class Migration extends MigrationBase {
  14. /**
  15. * Source object for the migration, derived from MigrateSource.
  16. *
  17. * @var MigrateSource
  18. */
  19. protected $source;
  20. public function getSource() {
  21. return $this->source;
  22. }
  23. public function setSource(MigrateSource $source) {
  24. $this->source = $source;
  25. }
  26. /**
  27. * Destination object for the migration, derived from MigrateDestination.
  28. *
  29. * @var MigrateDestination
  30. */
  31. protected $destination;
  32. public function getDestination() {
  33. return $this->destination;
  34. }
  35. public function setDestination(MigrateDestination $destination) {
  36. $this->destination = $destination;
  37. }
  38. /**
  39. * Map object tracking relationships between source and destination data
  40. *
  41. * @var MigrateMap
  42. */
  43. protected $map;
  44. public function getMap() {
  45. return $this->map;
  46. }
  47. public function setMap(MigrateMap $map) {
  48. $this->map = $map;
  49. }
  50. /**
  51. * Indicate whether the primary system of record for this migration is the
  52. * source, or the destination (Drupal). In the source case, migration of
  53. * an existing object will completely replace the Drupal object with data from
  54. * the source side. In the destination case, the existing Drupal object will
  55. * be loaded, then changes from the source applied; also, rollback will not be
  56. * supported.
  57. *
  58. * @var int
  59. */
  60. const SOURCE = 1;
  61. const DESTINATION = 2;
  62. protected $systemOfRecord = Migration::SOURCE;
  63. public function getSystemOfRecord() {
  64. return $this->systemOfRecord;
  65. }
  66. public function setSystemOfRecord($system_of_record) {
  67. $this->systemOfRecord = $system_of_record;
  68. }
  69. /**
  70. * Specify value of needs_update for current map row. Usually set by
  71. * MigrateFieldHandler implementations.
  72. *
  73. * @var int
  74. */
  75. public $needsUpdate = MigrateMap::STATUS_IMPORTED;
  76. /**
  77. * The default rollback action for this migration. Can be overridden on
  78. * a per-row basis by setting $row->rollbackAction in prepareRow().
  79. *
  80. * @var int
  81. */
  82. protected $defaultRollbackAction = MigrateMap::ROLLBACK_DELETE;
  83. public function getDefaultRollbackAction() {
  84. return $this->defaultRollbackAction;
  85. }
  86. public function setDefaultRollbackAction($rollback_action) {
  87. $this->defaultRollbackAction = $rollback_action;
  88. }
  89. /**
  90. * The rollback action to be saved for the current row.
  91. *
  92. * @var int
  93. */
  94. public $rollbackAction;
  95. /**
  96. * Field mappings defined in code.
  97. *
  98. * @var array
  99. */
  100. protected $storedFieldMappings = array();
  101. protected $storedFieldMappingsRetrieved = FALSE;
  102. public function getStoredFieldMappings() {
  103. if (!$this->storedFieldMappingsRetrieved) {
  104. $this->loadFieldMappings();
  105. $this->storedFieldMappingsRetrieved = TRUE;
  106. }
  107. return $this->storedFieldMappings;
  108. }
  109. /**
  110. * Field mappings retrieved from storage.
  111. *
  112. * @var array
  113. */
  114. protected $codedFieldMappings = array();
  115. public function getCodedFieldMappings() {
  116. return $this->codedFieldMappings;
  117. }
  118. /**
  119. * All field mappings, with those retrieved from the database overriding those
  120. * defined in code.
  121. *
  122. * @var array
  123. */
  124. protected $allFieldMappings = array();
  125. public function getFieldMappings() {
  126. if (empty($allFieldMappings)) {
  127. $this->allFieldMappings = array_merge($this->getCodedFieldMappings(),
  128. $this->getStoredFieldMappings());
  129. // If there are multiple mappings of a given source field to no
  130. // destination field, keep only the last (so the UI can override a source
  131. // field DNM that was defined in code).
  132. $no_destination = array();
  133. // But also remove a mapping of a source field to nothing, if there is
  134. // a mapping to something.
  135. $mapped_source_fields = array();
  136. /** @var MigrateFieldMapping $mapping */
  137. foreach ($this->allFieldMappings as $destination_field => $mapping) {
  138. $source_field = $mapping->getSourceField();
  139. // If the source field is not mapped to a destination field, the
  140. // array index is integer.
  141. if (is_int($destination_field)) {
  142. if (isset($no_destination[$source_field])) {
  143. unset($this->allFieldMappings[$no_destination[$source_field]]);
  144. unset($no_destination[$source_field]);
  145. }
  146. $no_destination[$source_field] = $destination_field;
  147. if (isset($mapped_source_fields[$source_field])) {
  148. unset($this->allFieldMappings[$destination_field]);
  149. }
  150. }
  151. else {
  152. $mapped_source_fields[$source_field] = $source_field;
  153. }
  154. }
  155. // Make sure primary fields come before their subfields
  156. ksort($this->allFieldMappings);
  157. }
  158. return $this->allFieldMappings;
  159. }
  160. /**
  161. * An array of counts. Initially used for cache hit/miss tracking.
  162. *
  163. * @var array
  164. */
  165. protected $counts = array();
  166. /**
  167. * When performing a bulkRollback(), the maximum number of items to pass in
  168. * a single call. Can be overridden in derived class constructor.
  169. *
  170. * @var int
  171. */
  172. protected $rollbackBatchSize = 50;
  173. /**
  174. * If present, an array with keys name and alias (optional). Name refers to
  175. * the source columns used for tracking highwater marks. alias is an
  176. * optional table alias.
  177. *
  178. * @var array
  179. */
  180. protected $highwaterField = array();
  181. public function getHighwaterField() {
  182. return $this->highwaterField;
  183. }
  184. public function setHighwaterField(array $highwater_field) {
  185. $this->highwaterField = $highwater_field;
  186. }
  187. /**
  188. * The object currently being constructed
  189. * @var stdClass
  190. */
  191. protected $destinationValues;
  192. /**
  193. * The current data row retrieved from the source.
  194. * @var stdClass
  195. */
  196. protected $sourceValues;
  197. /**
  198. * Queue up messages that can't be safely saved (in particular, if they're
  199. * generated in prepareRow().
  200. *
  201. * @var array
  202. */
  203. protected $queuedMessages = array();
  204. /**
  205. * General initialization of a Migration object.
  206. */
  207. public function __construct($arguments = array()) {
  208. parent::__construct($arguments);
  209. }
  210. /**
  211. * Register a new migration process in the migrate_status table. This will
  212. * generally be used in two contexts - by the class detection code for
  213. * static (one instance per class) migrations, and by the module implementing
  214. * dynamic (parameterized class) migrations.
  215. *
  216. * @param string $class_name
  217. * @param string $machine_name
  218. * @param array $arguments
  219. */
  220. static public function registerMigration($class_name, $machine_name = NULL,
  221. array $arguments = array()) {
  222. // Record any field mappings provided via arguments.
  223. if (isset($arguments['field_mappings'])) {
  224. self::saveFieldMappings($machine_name, $arguments['field_mappings']);
  225. unset($arguments['field_mappings']);
  226. }
  227. parent::registerMigration($class_name, $machine_name, $arguments);
  228. }
  229. /**
  230. * Deregister a migration - remove all traces of it from the database (without
  231. * touching any content which was created by this migration).
  232. *
  233. * We'd like to do this at uninstall time, but the implementing module is
  234. * already disabled, so we can't instantiate it to get at the map. This can
  235. * be done in hook_disable(), however.
  236. *
  237. * @param string $machine_name
  238. */
  239. static public function deregisterMigration($machine_name) {
  240. try {
  241. // Remove map and message tables
  242. $migration = self::getInstance($machine_name);
  243. if ($migration && method_exists($migration, 'getMap')) {
  244. $migration->getMap()->destroy();
  245. }
  246. // @todo: Clear log entries? Or keep for historical purposes?
  247. // Remove stored field mappings for this migration
  248. $rows_deleted = db_delete('migrate_field_mapping')
  249. ->condition('machine_name', $machine_name)
  250. ->execute();
  251. // Call the parent deregistration (which clears migrate_status) last, the
  252. // above will reference it.
  253. parent::deregisterMigration($machine_name);
  254. }
  255. catch (Exception $e) {
  256. // Fail silently if it's already gone
  257. }
  258. }
  259. /**
  260. * Record an array of field mappings to the database.
  261. *
  262. * @param $machine_name
  263. * @param array $field_mappings
  264. */
  265. static public function saveFieldMappings($machine_name, array $field_mappings) {
  266. // Clear existing field mappings
  267. db_delete('migrate_field_mapping')
  268. ->condition('machine_name', $machine_name)
  269. ->execute();
  270. foreach ($field_mappings as $field_mapping) {
  271. $destination_field = $field_mapping->getDestinationField();
  272. $source_field = $field_mapping->getSourceField();
  273. db_insert('migrate_field_mapping')
  274. ->fields(array(
  275. 'machine_name' => $machine_name,
  276. 'destination_field' => is_null($destination_field) ? '' : $destination_field,
  277. 'source_field' => is_null($source_field) ? '' : $source_field,
  278. 'options' => serialize($field_mapping)
  279. ))
  280. ->execute();
  281. }
  282. }
  283. /**
  284. * Load any stored field mappings from the database.
  285. */
  286. public function loadFieldMappings() {
  287. $result = db_select('migrate_field_mapping', 'mfm')
  288. ->fields('mfm', array('destination_field', 'source_field', 'options'))
  289. ->condition('machine_name', $this->machineName)
  290. ->execute();
  291. foreach ($result as $row) {
  292. $field_mapping = unserialize($row->options);
  293. $field_mapping->setMappingSource(MigrateFieldMapping::MAPPING_SOURCE_DB);
  294. if (empty($row->destination_field)) {
  295. $this->storedFieldMappings[] = $field_mapping;
  296. }
  297. else {
  298. $this->storedFieldMappings[$row->destination_field] = $field_mapping;
  299. }
  300. }
  301. }
  302. ////////////////////////////////////////////////////////////////////
  303. // Processing
  304. /**
  305. * Add a mapping for a destination field, specifying a source field and/or
  306. * a default value.
  307. *
  308. * @param string $destinationField
  309. * Name of the destination field.
  310. * @param string $sourceField
  311. * Name of the source field (optional).
  312. * @param boolean $warn_on_override
  313. * Set to FALSE to prevent warnings when there's an existing mapping
  314. * for this destination field.
  315. */
  316. public function addFieldMapping($destination_field, $source_field = NULL,
  317. $warn_on_override = TRUE) {
  318. // Warn of duplicate mappings
  319. if ($warn_on_override && !is_null($destination_field) &&
  320. isset($this->codedFieldMappings[$destination_field])) {
  321. self::displayMessage(
  322. t('!name addFieldMapping: !dest was previously mapped from !source, overridden',
  323. array('!name' => $this->machineName, '!dest' => $destination_field,
  324. '!source' => $this->codedFieldMappings[$destination_field]->getSourceField())),
  325. 'warning');
  326. }
  327. $mapping = new MigrateFieldMapping($destination_field, $source_field);
  328. if (is_null($destination_field)) {
  329. $this->codedFieldMappings[] = $mapping;
  330. }
  331. else {
  332. $this->codedFieldMappings[$destination_field] = $mapping;
  333. }
  334. return $mapping;
  335. }
  336. /**
  337. * Remove any existing coded mappings for a given destination or source field.
  338. *
  339. * @param string $destination_field
  340. * Name of the destination field.
  341. * @param string $source_field
  342. * Name of the source field.
  343. */
  344. public function removeFieldMapping($destination_field, $source_field = NULL) {
  345. if (isset($destination_field)) {
  346. unset($this->codedFieldMappings[$destination_field]);
  347. }
  348. if (isset($source_field)) {
  349. foreach ($this->codedFieldMappings as $key => $mapping) {
  350. if ($mapping->getSourceField() == $source_field) {
  351. unset($this->codedFieldMappings[$key]);
  352. }
  353. }
  354. }
  355. }
  356. /**
  357. * Shortcut for adding several fields which have the same name on both source
  358. * and destination sides.
  359. *
  360. * @param array $fields
  361. * List of field names to map.
  362. */
  363. public function addSimpleMappings(array $fields) {
  364. foreach ($fields as $field) {
  365. $this->addFieldMapping($field, $field);
  366. }
  367. }
  368. /**
  369. * Shortcut for adding several destination fields which are to be explicitly
  370. * not migrated.
  371. *
  372. * @param array $fields
  373. * List of fields to mark as not for migration.
  374. *
  375. * @param string $issue_group
  376. * Issue group name to apply to the generated mappings (defaults to 'DNM').
  377. */
  378. public function addUnmigratedDestinations(array $fields, $issue_group = NULL, $warn_on_override = TRUE) {
  379. if (!$issue_group) {
  380. $issue_group = t('DNM');
  381. }
  382. foreach ($fields as $field) {
  383. $this->addFieldMapping($field, NULL, $warn_on_override)
  384. ->issueGroup($issue_group);
  385. }
  386. }
  387. /**
  388. * Shortcut for adding several source fields which are to be explicitly
  389. * not migrated.
  390. *
  391. * @param array $fields
  392. * List of fields to mark as not for migration.
  393. *
  394. * @param string $issue_group
  395. * Issue group name to apply to the generated mappings (defaults to 'DNM').
  396. */
  397. public function addUnmigratedSources(array $fields, $issue_group = NULL, $warn_on_override = TRUE) {
  398. if (!$issue_group) {
  399. $issue_group = t('DNM');
  400. }
  401. foreach ($fields as $field) {
  402. $this->addFieldMapping(NULL, $field, $warn_on_override)
  403. ->issueGroup($issue_group);
  404. }
  405. }
  406. /**
  407. * Reports whether this migration process is complete (i.e., all available
  408. * source rows have been processed).
  409. */
  410. public function isComplete() {
  411. $total = $this->sourceCount(TRUE);
  412. // If the source is uncountable, we have no way of knowing if it's
  413. // complete, so stipulate that it is.
  414. if ($total < 0) {
  415. return TRUE;
  416. }
  417. $processed = $this->processedCount();
  418. return $total <= $processed;
  419. }
  420. /**
  421. * Override MigrationBase::beginProcess, to make sure the map/message tables
  422. * are present.
  423. *
  424. * @param int $newStatus
  425. * Migration::STATUS_IMPORTING or Migration::STATUS_ROLLING_BACK
  426. */
  427. protected function beginProcess($newStatus) {
  428. parent::beginProcess($newStatus);
  429. // Do some standard setup
  430. if (isset($this->options['feedback']) && isset($this->options['feedback']['value']) &&
  431. isset($this->options['feedback']['unit'])) {
  432. $this->feedback = $this->options['feedback']['value'];
  433. $this->feedback_unit = $this->options['feedback']['unit'];
  434. if ($this->feedback_unit == 'item') {
  435. $this->feedback_unit = 'items';
  436. }
  437. elseif ($this->feedback_unit == 'second') {
  438. $this->feedback_unit = 'seconds';
  439. }
  440. }
  441. $this->lastfeedback = $this->starttime;
  442. $this->total_processed = $this->total_successes =
  443. $this->processed_since_feedback = $this->successes_since_feedback = 0;
  444. // Call pre-process methods
  445. if ($this->status == Migration::STATUS_IMPORTING) {
  446. $this->preImport();
  447. }
  448. elseif ($this->status == Migration::STATUS_ROLLING_BACK) {
  449. $this->preRollback();
  450. }
  451. }
  452. /**
  453. * Override MigrationBase::endProcess, to call post hooks. Note that it must
  454. * be public to be callable as the shutdown function.
  455. */
  456. public function endProcess() {
  457. // Call post-process methods
  458. if ($this->status == Migration::STATUS_IMPORTING) {
  459. $this->postImport();
  460. }
  461. elseif ($this->status == Migration::STATUS_ROLLING_BACK) {
  462. $this->postRollback();
  463. }
  464. parent::endProcess();
  465. }
  466. /**
  467. * Default implementations of pre/post import/rollback methods. These call
  468. * the destination methods (if they exist) - when overriding, always
  469. * call parent::preImport() etc.
  470. */
  471. protected function preImport() {
  472. if (method_exists($this->destination, 'preImport')) {
  473. $this->destination->preImport();
  474. }
  475. }
  476. protected function preRollback() {
  477. if (method_exists($this->destination, 'preRollback')) {
  478. $this->destination->preRollback();
  479. }
  480. }
  481. protected function postImport() {
  482. if (method_exists($this->destination, 'postImport')) {
  483. $this->destination->postImport();
  484. }
  485. }
  486. protected function postRollback() {
  487. if (method_exists($this->destination, 'postRollback')) {
  488. $this->destination->postRollback();
  489. }
  490. }
  491. /**
  492. * Perform a rollback operation - remove migrated items from the destination.
  493. */
  494. protected function rollback() {
  495. $return = MigrationBase::RESULT_COMPLETED;
  496. $itemlimit = $this->getItemLimit();
  497. $idlist = $this->getOption('idlist');
  498. if ($idlist) {
  499. // Make the IDs keys, to more easily identify them
  500. $idlist = array_flip(explode(',', $idlist));
  501. }
  502. if (method_exists($this->destination, 'bulkRollback')) {
  503. // Too many at once can lead to memory issues, so batch 'em up
  504. $destids = array();
  505. $sourceids = array();
  506. $batch_count = 0;
  507. foreach ($this->map as $destination_key) {
  508. if ($this->timeOptionExceeded()) {
  509. break;
  510. }
  511. if (($return = $this->checkStatus()) != MigrationBase::RESULT_COMPLETED) {
  512. break;
  513. }
  514. if ($itemlimit && ($this->total_processed + $batch_count >= $itemlimit)) {
  515. break;
  516. }
  517. $current_source_key = $this->map->getCurrentKey();
  518. // If there's an idlist, skip anything not in the list
  519. if ($idlist && !isset($idlist[$current_source_key['sourceid1']])) {
  520. continue;
  521. }
  522. // Note that bulk rollback is only supported for single-column keys
  523. $sourceids[] = $current_source_key;
  524. if (!empty($destination_key->destid1)) {
  525. $map_row = $this->map->getRowByDestination((array)$destination_key);
  526. if ($map_row['rollback_action'] == MigrateMap::ROLLBACK_DELETE) {
  527. $destids[] = $destination_key->destid1;
  528. }
  529. }
  530. $batch_count++;
  531. if ($batch_count >= $this->rollbackBatchSize) {
  532. try {
  533. if ($this->systemOfRecord == Migration::SOURCE) {
  534. if (!empty($destids)) {
  535. migrate_instrument_start('destination bulkRollback');
  536. $this->destination->bulkRollback($destids);
  537. migrate_instrument_stop('destination bulkRollback');
  538. }
  539. }
  540. // Keep track in case of interruption
  541. migrate_instrument_start('rollback map/message update');
  542. $this->map->deleteBulk($sourceids);
  543. migrate_instrument_stop('rollback map/message update');
  544. $this->total_successes += $batch_count;
  545. $this->successes_since_feedback += $batch_count;
  546. }
  547. catch (Exception $e) {
  548. $this->handleException($e, FALSE);
  549. migrate_instrument_stop('bulkRollback');
  550. migrate_instrument_stop('rollback map/message update');
  551. }
  552. $destids = array();
  553. $sourceids = array();
  554. // Will increment even if there was an exception... But we don't
  555. // really have a way to know how many really were successfully rolled back
  556. $this->total_processed += $batch_count;
  557. $this->processed_since_feedback += $batch_count;
  558. $batch_count = 0;
  559. }
  560. }
  561. if ($batch_count > 0) {
  562. if ($this->systemOfRecord == Migration::SOURCE) {
  563. if (!empty($destids)) {
  564. migrate_instrument_start('destination bulkRollback');
  565. $this->destination->bulkRollback($destids);
  566. migrate_instrument_stop('destination bulkRollback');
  567. }
  568. $this->total_processed += $batch_count;
  569. $this->total_successes += $batch_count;
  570. $this->processed_since_feedback += $batch_count;
  571. $this->successes_since_feedback += $batch_count;
  572. }
  573. migrate_instrument_start('rollback map/message update');
  574. $this->map->deleteBulk($sourceids);
  575. migrate_instrument_stop('rollback map/message update');
  576. }
  577. }
  578. else {
  579. foreach ($this->map as $destination_key) {
  580. if ($this->timeOptionExceeded()) {
  581. break;
  582. }
  583. if (($return = $this->checkStatus()) != MigrationBase::RESULT_COMPLETED) {
  584. break;
  585. }
  586. if ($this->itemOptionExceeded()) {
  587. break;
  588. }
  589. $current_source_key = $this->map->getCurrentKey();
  590. // If there's an idlist, skip anything not in the list
  591. if ($idlist && !isset($idlist[$current_source_key['sourceid1']])) {
  592. continue;
  593. }
  594. // Rollback one record
  595. try {
  596. if ($this->systemOfRecord == Migration::SOURCE) {
  597. // Skip when the destination key is null
  598. $skip = FALSE;
  599. foreach ($destination_key as $key_value) {
  600. if (is_null($key_value)) {
  601. $skip = TRUE;
  602. break;
  603. }
  604. }
  605. if (!$skip) {
  606. $map_row = $this->map->getRowByDestination((array)$destination_key);
  607. if ($map_row['rollback_action'] == MigrateMap::ROLLBACK_DELETE) {
  608. migrate_instrument_start('destination rollback');
  609. $this->destination->rollback((array)$destination_key);
  610. migrate_instrument_stop('destination rollback');
  611. }
  612. }
  613. }
  614. migrate_instrument_start('rollback map/message update');
  615. $this->map->delete($current_source_key);
  616. migrate_instrument_stop('rollback map/message update');
  617. $this->total_successes++;
  618. $this->successes_since_feedback++;
  619. }
  620. catch (Exception $e) {
  621. // TODO: At least count failures
  622. continue;
  623. }
  624. $this->total_processed++;
  625. $this->processed_since_feedback++;
  626. }
  627. }
  628. $this->map->clearMessages();
  629. $this->progressMessage($return);
  630. // If we're using highwater marks, reset at completion of a full rollback
  631. // TODO: What about partial rollbacks? Probably little we can do to make
  632. // that work cleanly...
  633. if ($this->highwaterField) {
  634. $this->saveHighwater('', TRUE);
  635. }
  636. return $return;
  637. }
  638. /**
  639. * Perform an import operation - migrate items from source to destination.
  640. */
  641. protected function import() {
  642. $return = MigrationBase::RESULT_COMPLETED;
  643. try {
  644. $this->source->rewind();
  645. }
  646. catch (Exception $e) {
  647. self::displayMessage(
  648. t('Migration failed with source plugin exception: %e, in %file:%line',
  649. array('%e' => $e->getMessage(), '%file' => $e->getFile(), '%line' => $e->getLine())));
  650. return MigrationBase::RESULT_FAILED;
  651. }
  652. while ($this->source->valid()) {
  653. $data_row = $this->source->current();
  654. // Wipe old messages, and save any new messages.
  655. $this->map->delete($this->currentSourceKey(), TRUE);
  656. $this->saveQueuedMessages();
  657. $this->sourceValues = $data_row;
  658. $this->applyMappings();
  659. try {
  660. migrate_instrument_start('destination import', TRUE);
  661. $ids = $this->destination->import($this->destinationValues, $this->sourceValues);
  662. migrate_instrument_stop('destination import');
  663. if ($ids) {
  664. $this->map->saveIDMapping($this->sourceValues, $ids,
  665. $this->needsUpdate, $this->rollbackAction,
  666. $data_row->migrate_map_hash);
  667. $this->successes_since_feedback++;
  668. $this->total_successes++;
  669. }
  670. else {
  671. $this->map->saveIDMapping($this->sourceValues, array(),
  672. MigrateMap::STATUS_FAILED, $this->rollbackAction,
  673. $data_row->migrate_map_hash);
  674. if ($this->map->messageCount() == 0) {
  675. $message = t('New object was not saved, no error provided');
  676. $this->saveMessage($message);
  677. self::displayMessage($message);
  678. }
  679. }
  680. }
  681. catch (MigrateException $e) {
  682. $this->map->saveIDMapping($this->sourceValues, array(),
  683. $e->getStatus(), $this->rollbackAction, $data_row->migrate_map_hash);
  684. $this->saveMessage($e->getMessage(), $e->getLevel());
  685. self::displayMessage($e->getMessage());
  686. }
  687. catch (Exception $e) {
  688. $this->map->saveIDMapping($this->sourceValues, array(),
  689. MigrateMap::STATUS_FAILED, $this->rollbackAction,
  690. $data_row->migrate_map_hash);
  691. $this->handleException($e);
  692. }
  693. $this->total_processed++;
  694. $this->processed_since_feedback++;
  695. if ($this->highwaterField) {
  696. $this->saveHighwater($this->sourceValues->{$this->highwaterField['name']});
  697. }
  698. // Reset row properties.
  699. unset($this->sourceValues, $this->destinationValues);
  700. $this->needsUpdate = MigrateMap::STATUS_IMPORTED;
  701. // TODO: Temporary. Remove when http://drupal.org/node/375494 is committed.
  702. // TODO: Should be done in MigrateDestinationEntity
  703. if (!empty($this->destination->entityType)) {
  704. entity_get_controller($this->destination->entityType)->resetCache();
  705. }
  706. if ($this->timeOptionExceeded()) {
  707. break;
  708. }
  709. if (($return = $this->checkStatus()) != MigrationBase::RESULT_COMPLETED) {
  710. break;
  711. }
  712. if ($this->itemOptionExceeded()) {
  713. break;
  714. }
  715. try {
  716. $this->source->next();
  717. }
  718. catch (Exception $e) {
  719. self::displayMessage(
  720. t('Migration failed with source plugin exception: %e, in %file:%line',
  721. array('%e' => $e->getMessage(), '%file' => $e->getFile(), '%line' => $e->getLine())));
  722. return MigrationBase::RESULT_FAILED;
  723. }
  724. }
  725. $this->progressMessage($return);
  726. return $return;
  727. }
  728. /**
  729. * Perform an analysis operation - report on field values in the source.
  730. *
  731. * @return array
  732. * Array of analysis details - each element is keyed by field name and
  733. * contains an array describing the field values.
  734. */
  735. public function analyze() {
  736. // The source needs this to find the map table.
  737. self::$currentMigration = $this;
  738. try {
  739. $this->source->rewind();
  740. }
  741. catch (Exception $e) {
  742. self::displayMessage(
  743. t('Migration analysis failed with source plugin exception: !e',
  744. array('!e' => $e->getMessage())));
  745. self::$currentMigration = NULL;
  746. return array();
  747. }
  748. // Get the documented fields first
  749. $source_fields = $this->source->fields();
  750. $analysis = array();
  751. $field_init = array(
  752. 'is_numeric' => TRUE,
  753. 'min_numeric' => NULL,
  754. 'max_numeric' => NULL,
  755. 'min_strlen' => 0,
  756. 'max_strlen' => 0,
  757. 'distinct_values' => array(),
  758. );
  759. foreach ($source_fields as $field_name => $description) {
  760. // Ignore fields from the map table
  761. if (substr($field_name, 0, strlen('migrate_map_')) == 'migrate_map_') {
  762. continue;
  763. }
  764. $analysis[$field_name] = $field_init +
  765. array('description' => $description);
  766. }
  767. // For each data row...
  768. while ($this->source->valid()) {
  769. $row = $this->source->current();
  770. // Cheat for XML migrations, which don't pick up the source values
  771. // until applyMappings() applies the xpath()
  772. if (is_a($this, 'XMLMigration') && isset($row->xml)) {
  773. $this->sourceValues = $row;
  774. $this->applyMappings();
  775. $row = $this->sourceValues;
  776. unset($row->xml);
  777. }
  778. // For each field in this row...
  779. foreach ($row as $field_name => $raw_value) {
  780. // Ignore fields from the map table
  781. if (substr($field_name, 0, strlen('migrate_map_')) == 'migrate_map_') {
  782. continue;
  783. }
  784. // It might be an array of values, check each value
  785. if (!is_array($raw_value)) {
  786. $raw_value = array($raw_value);
  787. }
  788. foreach ($raw_value as $field_value) {
  789. // If this is an undocumented field, initialize it
  790. if (!isset($analysis[$field_name])) {
  791. $analysis[$field_name] = $field_init +
  792. array('description' => '');
  793. }
  794. // Ignore leading/trailing spaces in determing numerics
  795. $trimmed_value = trim($field_value);
  796. if (is_numeric($trimmed_value)) {
  797. $trimmed_value = floatval($trimmed_value);
  798. // First numeric value, initialize the min/max
  799. if (is_null($analysis[$field_name]['min_numeric'])) {
  800. $analysis[$field_name]['min_numeric'] = $trimmed_value;
  801. $analysis[$field_name]['max_numeric'] = $trimmed_value;
  802. }
  803. else {
  804. $analysis[$field_name]['min_numeric'] = min($trimmed_value,
  805. $analysis[$field_name]['min_numeric']);
  806. $analysis[$field_name]['max_numeric'] = max($trimmed_value,
  807. $analysis[$field_name]['max_numeric']);
  808. }
  809. }
  810. elseif ($trimmed_value !== '') {
  811. // Empty strings are !is_numeric(), but treat as empty rather than
  812. // assuming we don't have a numeric field
  813. $analysis[$field_name]['is_numeric'] = FALSE;
  814. }
  815. $strlen = strlen($field_value);
  816. // First string value, initialize both min and max
  817. if ($analysis[$field_name]['max_strlen'] == 0) {
  818. $analysis[$field_name]['min_strlen'] = $strlen;
  819. $analysis[$field_name]['max_strlen'] = $strlen;
  820. }
  821. else {
  822. $analysis[$field_name]['min_strlen'] = min($strlen,
  823. $analysis[$field_name]['min_strlen']);
  824. $analysis[$field_name]['max_strlen'] = max($strlen,
  825. $analysis[$field_name]['max_strlen']);
  826. }
  827. // Track up to 10 distinct values
  828. if (count($analysis[$field_name]['distinct_values']) <= 10) {
  829. $analysis[$field_name]['distinct_values'][$trimmed_value]++;
  830. }
  831. }
  832. }
  833. try {
  834. $this->source->next();
  835. }
  836. catch (Exception $e) {
  837. self::displayMessage(
  838. t('Migration analysis failed with source plugin exception: !e. Partial results follow:',
  839. array('!e' => $e->getMessage())));
  840. self::$currentMigration = NULL;
  841. return $analysis;
  842. }
  843. }
  844. self::$currentMigration = NULL;
  845. return $analysis;
  846. }
  847. /**
  848. * Fetch the key array for the current source record.
  849. *
  850. * @return array
  851. */
  852. protected function currentSourceKey() {
  853. return $this->source->getCurrentKey();
  854. }
  855. /**
  856. * Default implementation of prepareKey. This method is called from the source
  857. * plugin immediately after retrieving the raw data from the source - by
  858. * default, it simply assigns the key values based on the field names passed
  859. * to MigrateSQLMap(). Override this if you need to generate your own key
  860. * (e.g., the source doesn't have a natural unique key). Be sure to also
  861. * set any values you generate in $row.
  862. *
  863. * @param array $source_key
  864. * @param object $row
  865. *
  866. * @return array
  867. */
  868. public function prepareKey($source_key, $row) {
  869. $key = array();
  870. foreach ($source_key as $field_name => $field_schema) {
  871. $key[$field_name] = $row->$field_name;
  872. }
  873. return $key;
  874. }
  875. /**
  876. * Default implementation of prepareRow(). This method is called from the source
  877. * plugin upon first pulling the raw data from the source.
  878. *
  879. * @param $row
  880. * Object containing raw source data.
  881. * @return bool
  882. * TRUE to process this row, FALSE to have the source skip it.
  883. */
  884. public function prepareRow($row) {
  885. $this->rollbackAction = $this->defaultRollbackAction;
  886. return TRUE;
  887. }
  888. ////////////////////////////////////////////////////////////////////
  889. // Utility methods
  890. /**
  891. * Convenience function to return count of total source records
  892. *
  893. * @param boolean $refresh
  894. * Pass TRUE to refresh the cached count.
  895. */
  896. public function sourceCount($refresh = FALSE) {
  897. try {
  898. $count = $this->source->count($refresh);
  899. }
  900. catch (Exception $e) {
  901. $count = t('N/A');
  902. self::displayMessage($e->getMessage());
  903. }
  904. return $count;
  905. }
  906. /**
  907. * Get the number of source records processed.
  908. * @return int
  909. * Number of processed records.
  910. */
  911. public function processedCount() {
  912. try {
  913. $count = $this->map->processedCount();
  914. }
  915. catch (Exception $e) {
  916. $count = t('N/A');
  917. self::displayMessage($e->getMessage());
  918. }
  919. return $count;
  920. }
  921. /**
  922. * Get the number of records successfully imported.
  923. * @return int
  924. * Number of imported records.
  925. */
  926. public function importedCount() {
  927. try {
  928. $count = $this->map->importedCount();
  929. }
  930. catch (Exception $e) {
  931. $count = t('N/A');
  932. self::displayMessage($e->getMessage());
  933. }
  934. return $count;
  935. }
  936. /**
  937. * Get the number of records marked as needing update.
  938. * @return int
  939. */
  940. public function updateCount() {
  941. try {
  942. $count = $this->map->updateCount();
  943. }
  944. catch (Exception $e) {
  945. $count = t('N/A');
  946. self::displayMessage($e->getMessage());
  947. }
  948. return $count;
  949. }
  950. /**
  951. * Test whether we've exceeded the designated item limit.
  952. *
  953. * @return boolean
  954. * TRUE if the threshold is exceeded, FALSE if not.
  955. */
  956. protected function itemOptionExceeded() {
  957. $itemlimit = $this->getItemLimit();
  958. if ($itemlimit && $this->total_processed >= $itemlimit) {
  959. return TRUE;
  960. }
  961. return FALSE;
  962. }
  963. /**
  964. * Get the number of source records which failed to import.
  965. * TODO: Doesn't yet account for informationals, or multiple errors for
  966. * a source record.
  967. *
  968. * @return int
  969. * Number of records errored out.
  970. */
  971. public function errorCount() {
  972. return $this->map->errorCount();
  973. }
  974. /**
  975. * Get the number of messages associated with this migration
  976. *
  977. * @return int
  978. * Number of messages.
  979. */
  980. public function messageCount() {
  981. return $this->map->messageCount();
  982. }
  983. /**
  984. * Prepares this migration to run as an update - that is, in addition to
  985. * unmigrated content (source records not in the map table) being imported,
  986. * previously-migrated content will also be updated in place.
  987. */
  988. public function prepareUpdate() {
  989. $this->map->prepareUpdate();
  990. }
  991. /**
  992. * Outputs a progress message, reflecting the current status of a migration process.
  993. *
  994. * @param int $result
  995. * Status of the process, represented by one of the Migration::RESULT_* constants.
  996. */
  997. protected function progressMessage($result) {
  998. $time = microtime(TRUE) - $this->lastfeedback;
  999. if ($time > 0) {
  1000. $perminute = round(60*$this->processed_since_feedback/$time);
  1001. $time = round($time, 1);
  1002. }
  1003. else {
  1004. $perminute = '?';
  1005. }
  1006. if ($this->status == Migration::STATUS_IMPORTING) {
  1007. switch ($result) {
  1008. case Migration::RESULT_COMPLETED:
  1009. $basetext = "Processed !numitems (!created created, !updated updated, !failed failed, !ignored ignored) in !time sec (!perminute/min) - done with '!name'";
  1010. $type = 'completed';
  1011. break;
  1012. case Migration::RESULT_FAILED:
  1013. $basetext = "Processed !numitems (!created created, !updated updated, !failed failed, !ignored ignored) in !time sec (!perminute/min) - failure with '!name'";
  1014. $type = 'failed';
  1015. break;
  1016. case Migration::RESULT_INCOMPLETE:
  1017. $basetext = "Processed !numitems (!created created, !updated updated, !failed failed, !ignored ignored) in !time sec (!perminute/min) - continuing with '!name'";
  1018. $type = 'status';
  1019. break;
  1020. case Migration::RESULT_STOPPED:
  1021. $basetext = "Processed !numitems (!created created, !updated updated, !failed failed, !ignored ignored) in !time sec (!perminute/min) - stopped '!name'";
  1022. $type = 'warning';
  1023. break;
  1024. }
  1025. }
  1026. else {
  1027. switch ($result) {
  1028. case Migration::RESULT_COMPLETED:
  1029. $basetext = "Rolled back !numitems in !time sec (!perminute/min) - done with '!name'";
  1030. $type = 'completed';
  1031. break;
  1032. case Migration::RESULT_FAILED:
  1033. $basetext = "Rolled back !numitems in !time sec (!perminute/min) - failure with '!name'";
  1034. $type = 'failed';
  1035. break;
  1036. case Migration::RESULT_INCOMPLETE:
  1037. $basetext = "Rolled back !numitems in !time sec (!perminute/min) - continuing with '!name'";
  1038. $type = 'status';
  1039. break;
  1040. case Migration::RESULT_STOPPED:
  1041. $basetext = "Rolled back !numitems in !time sec (!perminute/min) - stopped '!name'";
  1042. $type = 'warning';
  1043. break;
  1044. }
  1045. }
  1046. $numitems = $this->processed_since_feedback + $this->source->getIgnored();
  1047. $message = t($basetext,
  1048. array('!numitems' => $numitems,
  1049. '!successes' => $this->successes_since_feedback,
  1050. '!failed' => $this->processed_since_feedback - $this->successes_since_feedback,
  1051. '!created' => $this->destination->getCreated(),
  1052. '!updated' => $this->destination->getUpdated(),
  1053. '!ignored' => $this->source->getIgnored(),
  1054. '!time' => $time,
  1055. '!perminute' => $perminute,
  1056. '!name' => $this->machineName));
  1057. self::displayMessage($message, $type);
  1058. // Report on lookup_cache hit rate. Only visible at 'debug' level.
  1059. if ($result != Migration::RESULT_INCOMPLETE && !empty($this->counts['lookup_cache'])) {
  1060. foreach ($this->counts['lookup_cache'] as $name => $tallies) {
  1061. $tallies += array('hit' => 0, 'miss_hit' => 0, 'miss_miss' => 0); // Set defaults to avoid NOTICE.
  1062. $sum = $tallies['hit']+$tallies['miss_hit']+$tallies['miss_miss'];
  1063. self::displayMessage(
  1064. t('Lookup cache: !mn SM=!name !hit hit, !miss_hit miss_hit, !miss_miss miss_miss (!total total).', array(
  1065. '!mn' => $this->machineName,
  1066. '!name' => $name,
  1067. '!hit' => round((100*$tallies['hit'])/$sum) . '%',
  1068. '!miss_hit' => round((100*$tallies['miss_hit'])/$sum) . '%',
  1069. '!miss_miss' => round((100*$tallies['miss_miss'])/$sum) . '%',
  1070. '!total' => $sum
  1071. )), 'debug');
  1072. }
  1073. $this->counts['lookup_cache'] = array();
  1074. }
  1075. if ($result == Migration::RESULT_INCOMPLETE) {
  1076. $this->lastfeedback = time();
  1077. $this->processed_since_feedback = $this->successes_since_feedback = 0;
  1078. $this->source->resetStats();
  1079. $this->destination->resetStats();
  1080. }
  1081. }
  1082. /**
  1083. * Standard top-of-loop stuff, common between rollback and import - check
  1084. * for exceptional conditions, and display feedback.
  1085. */
  1086. protected function checkStatus() {
  1087. if ($this->memoryExceeded()) {
  1088. return MigrationBase::RESULT_INCOMPLETE;
  1089. }
  1090. if ($this->timeExceeded()) {
  1091. return MigrationBase::RESULT_INCOMPLETE;
  1092. }
  1093. if ($this->getStatus() == Migration::STATUS_STOPPING) {
  1094. return MigrationBase::RESULT_STOPPED;
  1095. }
  1096. // If feedback is requested, produce a progress message at the proper time
  1097. if (isset($this->feedback)) {
  1098. if (($this->feedback_unit == 'seconds' && time() - $this->lastfeedback >= $this->feedback) ||
  1099. ($this->feedback_unit == 'items' && $this->processed_since_feedback >= $this->feedback)) {
  1100. $this->progressMessage(MigrationBase::RESULT_INCOMPLETE);
  1101. }
  1102. }
  1103. return MigrationBase::RESULT_COMPLETED;
  1104. }
  1105. /**
  1106. * Apply field mappings to a data row received from the source, returning
  1107. * a populated destination object.
  1108. */
  1109. protected function applyMappings() {
  1110. $this->destinationValues = new stdClass;
  1111. foreach ($this->getFieldMappings() as $mapping) {
  1112. $destination = $mapping->getDestinationField();
  1113. // Skip mappings with no destination (source fields marked DNM)
  1114. if ($destination) {
  1115. $source = $mapping->getSourceField();
  1116. $default = $mapping->getDefaultValue();
  1117. // When updating existing items, make sure we don't create a destination
  1118. // field that is not mapped to anything (a source field or a default value)
  1119. if (!$source && !isset($default)) {
  1120. continue;
  1121. }
  1122. $destination_values = NULL;
  1123. // If there's a source mapping, and a source value in the data row, copy
  1124. // to the destination
  1125. if ($source && isset($this->sourceValues->{$source})) {
  1126. $destination_values = $this->sourceValues->$source;
  1127. }
  1128. // Otherwise, apply the default value (if any)
  1129. elseif (!is_null($default)) {
  1130. $destination_values = $default;
  1131. }
  1132. // If there's a separator specified for this destination, then it
  1133. // will be populated as an array exploded from the source value
  1134. $separator = $mapping->getSeparator();
  1135. if ($separator && isset($destination_values)) {
  1136. $destination_values = explode($separator, $destination_values);
  1137. }
  1138. // If a source migration is supplied, use the current value for this field
  1139. // to look up a destination ID from the provided migration
  1140. $source_migration = $mapping->getSourceMigration();
  1141. if ($source_migration && isset($destination_values)) {
  1142. $destination_values = $this->handleSourceMigration($source_migration, $destination_values, $default, $this);
  1143. }
  1144. // Call any designated callbacks
  1145. $callbacks = $mapping->getCallbacks();
  1146. foreach ($callbacks as $callback) {
  1147. if (isset($destination_values)) {
  1148. $destination_values = call_user_func($callback, $destination_values);
  1149. }
  1150. }
  1151. // If specified, assure a unique value for this property.
  1152. $dedupe = $mapping->getDedupe();
  1153. if ($dedupe && isset($destination_values)) {
  1154. $destination_values = $this->handleDedupe($dedupe, $destination_values);
  1155. }
  1156. // Assign any arguments
  1157. if (isset($destination_values)) {
  1158. $arguments = $mapping->getArguments();
  1159. if ($arguments) {
  1160. if (!is_array($destination_values)) {
  1161. $destination_values = array($destination_values);
  1162. }
  1163. // TODO: Stuffing arguments into the destination field is gross - can
  1164. // we come up with a better way to communicate them to the field
  1165. // handlers?
  1166. $destination_values['arguments'] = array();
  1167. foreach ($arguments as $argname => $destarg) {
  1168. if (is_array($destarg) && isset($destarg['source_field']) && property_exists($this->sourceValues, $destarg['source_field'])) {
  1169. $destination_values['arguments'][$argname] = $this->sourceValues->$destarg['source_field'];
  1170. }
  1171. elseif (is_array($destarg) && isset($destarg['default_value'])) {
  1172. $destination_values['arguments'][$argname] = $destarg['default_value'];
  1173. }
  1174. else {
  1175. $destination_values['arguments'][$argname] = $destarg;
  1176. }
  1177. }
  1178. }
  1179. }
  1180. // Are we dealing with the primary value of the destination field, or a
  1181. // subfield?
  1182. $destination = explode(':', $destination);
  1183. // Count how many levels of fields are in the mapping. We'll use the
  1184. // last one.
  1185. $destination_count = count($destination);
  1186. $destination_field = $destination[0];
  1187. if ($destination_count == 2) {
  1188. $subfield = $destination[1];
  1189. // We're processing the subfield before the primary value, initialize it
  1190. if (!property_exists($this->destinationValues, $destination_field)) {
  1191. $this->destinationValues->$destination_field = array();
  1192. }
  1193. // We have a value, and need to convert to an array so we can add
  1194. // arguments.
  1195. elseif (!is_array($this->destinationValues->$destination_field)) {
  1196. $this->destinationValues->$destination_field = array($this->destinationValues->$destination_field);
  1197. }
  1198. // Add the subfield value to the arguments array.
  1199. $this->destinationValues->{$destination_field}['arguments'][$subfield] = $destination_values;
  1200. }
  1201. elseif ($destination_count == 3) {
  1202. $subfield2 = $destination[2];
  1203. // We're processing the subfield before the primary value, initialize it
  1204. if (!property_exists($this->destinationValues, $destination_field)) {
  1205. $this->destinationValues->$destination_field = array();
  1206. }
  1207. // We have a value, and need to convert to an array so we can add
  1208. // arguments.
  1209. elseif (!is_array($this->destinationValues->$destination_field)) {
  1210. $this->destinationValues->$destination_field = array($this->destinationValues->$destination_field);
  1211. }
  1212. if (!is_array($this->destinationValues->{$destination_field}['arguments'][$destination[1]])) {
  1213. // Convert first subfield level to an array so we can add to it.
  1214. $this->destinationValues->{$destination_field}['arguments'][$destination[1]] = array( $this->destinationValues->{$destination_field}['arguments'][$destination[1]] );
  1215. }
  1216. // Add the subfield value to the arguments array.
  1217. $this->destinationValues->{$destination_field}['arguments'][$destination[1]]['arguments'][$subfield2] = $destination_values;
  1218. }
  1219. // Just the primary value, the first time through for this field, simply
  1220. // set it.
  1221. elseif (!property_exists($this->destinationValues, $destination_field)) {
  1222. $this->destinationValues->$destination_field = $destination_values;
  1223. }
  1224. // We've seen a subfield, so add as an array value.
  1225. else {
  1226. $this->destinationValues->{$destination_field} = array_merge(
  1227. (array)$destination_values, $this->destinationValues->{$destination_field});
  1228. }
  1229. }
  1230. }
  1231. }
  1232. /**
  1233. * Look up a value migrated in another migration.
  1234. *
  1235. * @param mixed $source_migrations
  1236. * An array of source migrations, or string for a single migration.
  1237. * @param mixed $source_keys
  1238. * Key(s) to be looked up against the source migration(s). This may be a simple
  1239. * value (one single-field key), an array of values (multiple single-field keys
  1240. * to each be looked up), or an array of arrays (multiple multi-field keys to
  1241. * each be looked up).
  1242. * @param mixed $default
  1243. * The default value, if no ID was found.
  1244. * @param $migration
  1245. * The implementing migration.
  1246. * @return
  1247. * Destination value(s) from the source migration(s), as a single value if
  1248. * a single key was passed in, or an array of values if there were multiple
  1249. * keys to look up.
  1250. */
  1251. protected function handleSourceMigration($source_migrations, $source_keys, $default = NULL, $migration = NULL) {
  1252. // Handle the source migration(s) as an array.
  1253. $source_migrations = (array) $source_migrations;
  1254. // We want to treat source keys consistently as an array of arrays (each
  1255. // representing one key).
  1256. if (is_array($source_keys)) {
  1257. if (empty($source_keys)) {
  1258. // Empty value should return empty results.
  1259. return NULL;
  1260. }
  1261. elseif (is_array(reset($source_keys))) {
  1262. // Already an array of key arrays, fall through
  1263. }
  1264. else {
  1265. // An array of single-key values - make each one an array
  1266. $new_source_keys = array();
  1267. foreach ($source_keys as $source_key) {
  1268. $new_source_keys[] = array($source_key);
  1269. }
  1270. $source_keys = $new_source_keys;
  1271. }
  1272. }
  1273. else {
  1274. // A simple value - make it an array within an array
  1275. $source_keys = array(array($source_keys));
  1276. }
  1277. // Instantiate each migration, and store back in the array.
  1278. foreach ($source_migrations as $key => $source_migration) {
  1279. $source_migrations[$key] = Migration::getInstance($source_migration);
  1280. }
  1281. $results = array();
  1282. // Each $source_key will be an array of key values
  1283. foreach ($source_keys as $source_key) {
  1284. // If any source keys are NULL, skip this set
  1285. $continue = FALSE;
  1286. foreach ($source_key as $value) {
  1287. if (!isset($value)) {
  1288. $continue = TRUE;
  1289. break;
  1290. }
  1291. }
  1292. // Occasionally $source_key comes through with an empty string.
  1293. $sanity_check = array_filter($source_key);
  1294. if ($continue || empty($source_key) || empty($sanity_check)) {
  1295. continue;
  1296. }
  1297. // Loop through each source migration, checking for an existing dest ID.
  1298. foreach ($source_migrations as $source_migration) {
  1299. // Break out of the loop as soon as a destination ID is found.
  1300. if ($destids = $source_migration->getMap()->lookupDestinationID($source_key)) {
  1301. if (!empty($destids['destid1'])) {
  1302. break;
  1303. }
  1304. }
  1305. }
  1306. // If no destination ID was found, give each source migration a chance to
  1307. // create a stub.
  1308. if (!$destids) {
  1309. foreach ($source_migrations as $source_migration) {
  1310. // Is this a self reference?
  1311. if ($source_migration->machineName == $this->machineName) {
  1312. if (!array_diff($source_key, $this->currentSourceKey())) {
  1313. $destids = array();
  1314. $this->needsUpdate = MigrateMap::STATUS_NEEDS_UPDATE;
  1315. break;
  1316. }
  1317. }
  1318. // Break out of the loop if a stub was successfully created.
  1319. if ($destids = $source_migration->createStubWrapper($source_key, $migration)) {
  1320. break;
  1321. }
  1322. }
  1323. }
  1324. if ($destids) {
  1325. // Assume that if the destination key is a single value, it
  1326. // should be passed as such
  1327. if (count($destids) == 1) {
  1328. $results[] = reset($destids);
  1329. }
  1330. else {
  1331. $results[] = $destids;
  1332. }
  1333. }
  1334. // If no match found, apply the default value (if any)
  1335. elseif (!is_null($default)) {
  1336. $results[] = $default;
  1337. }
  1338. }
  1339. // Return a single result if we had a single key
  1340. if (count($source_keys) > 1) {
  1341. return $results;
  1342. }
  1343. else {
  1344. $value = reset($results);
  1345. return empty($value) && $value !== 0 && $value !== '0' ? NULL : $value;
  1346. }
  1347. }
  1348. /**
  1349. * For fields which require uniqueness, assign a new unique value if necessary.
  1350. *
  1351. * @param array $dedupe
  1352. * An array with two keys, 'table' the name of the Drupal table and 'column'
  1353. * the column within that table where uniqueness must be maintained.
  1354. * @param $original
  1355. * The value coming in, which must be checked for uniqueness.
  1356. * @return string
  1357. * The value to use - either the original, or a variation created by appending
  1358. * a sequence number.
  1359. */
  1360. protected function handleDedupe($dedupe, $original) {
  1361. // If we're remigrating a previously-existing value, simply running through
  1362. // our normal process will re-dedupe it - we must be sure to preserve the
  1363. // previously-written value. Note that this means that you cannot migrate
  1364. // changes to this field - the originally-migrated value will always
  1365. // remain, because we can't tell what the original was.
  1366. if (isset($this->sourceValues->migrate_map_destid1)) {
  1367. $key_field = key($this->destination->getKeySchema());
  1368. $existing_value = db_select($dedupe['table'], 't')
  1369. ->fields('t', array($dedupe['column']))
  1370. ->range(0, 1)
  1371. ->condition($key_field, $this->sourceValues->migrate_map_destid1)
  1372. ->execute()
  1373. ->fetchField();
  1374. // Note that if, for some reason, we don't find a value, fall through
  1375. // to the normal deduping process
  1376. if ($existing_value) {
  1377. return $existing_value;
  1378. }
  1379. }
  1380. $i = 1;
  1381. $candidate = $original;
  1382. while ($candidate_found = db_select($dedupe['table'], 't')
  1383. ->fields('t', array($dedupe['column']))
  1384. ->range(0, 1)
  1385. ->condition('t.' . $dedupe['column'], $candidate)
  1386. ->execute()
  1387. ->fetchField()) {
  1388. // We already have the candidate value. Find a non-existing value.
  1389. $i++;
  1390. // @TODO: support custom replacement pattern instead of just append.
  1391. $candidate = $original . '_' . $i;
  1392. }
  1393. if ($i > 1) {
  1394. $message = t('Replacing !column !original with !candidate',
  1395. array('!column' => $dedupe['column'],
  1396. '!original' => $original,
  1397. '!candidate' => $candidate));
  1398. $migration = Migration::currentMigration();
  1399. $migration->saveMessage($message, Migration::MESSAGE_INFORMATIONAL);
  1400. }
  1401. return $candidate;
  1402. }
  1403. /**
  1404. * If stub creation is enabled, try to create a stub and save the mapping.
  1405. */
  1406. protected function createStubWrapper(array $source_key, $migration = NULL) {
  1407. if (method_exists($this, 'createStub')) {
  1408. $destids = $this->createStub($migration, $source_key);
  1409. if ($destids) {
  1410. // Fake a data row with the source key in it
  1411. $map_source_key = $this->map->getSourceKey();
  1412. $data_row = new stdClass;
  1413. $i = 0;
  1414. foreach ($map_source_key as $key => $definition) {
  1415. $data_row->$key = $source_key[$i++];
  1416. }
  1417. $this->map->saveIDMapping($data_row, $destids,
  1418. MigrateMap::STATUS_NEEDS_UPDATE, $this->defaultRollbackAction);
  1419. }
  1420. }
  1421. else {
  1422. $destids = NULL;
  1423. }
  1424. return $destids;
  1425. }
  1426. /**
  1427. * Pass messages through to the map class.
  1428. *
  1429. * @param string $message
  1430. * The message to record.
  1431. * @param int $level
  1432. * Optional message severity (defaults to MESSAGE_ERROR).
  1433. */
  1434. public function saveMessage($message, $level = MigrationBase::MESSAGE_ERROR) {
  1435. $this->map->saveMessage($this->currentSourceKey(), $message, $level);
  1436. }
  1437. /**
  1438. * Queue messages to be later saved through the map class.
  1439. *
  1440. * @param string $message
  1441. * The message to record.
  1442. * @param int $level
  1443. * Optional message severity (defaults to MESSAGE_ERROR).
  1444. */
  1445. public function queueMessage($message, $level = MigrationBase::MESSAGE_ERROR) {
  1446. $this->queuedMessages[] = array('message' => $message, 'level' => $level);
  1447. }
  1448. /**
  1449. * Save any messages we've queued up to the message table.
  1450. */
  1451. public function saveQueuedMessages() {
  1452. foreach ($this->queuedMessages as $queued_message) {
  1453. $this->saveMessage($queued_message['message'], $queued_message['level']);
  1454. }
  1455. $this->queuedMessages = array();
  1456. }
  1457. /**
  1458. * Set the specified row to be updated, if it exists.
  1459. */
  1460. public function setUpdate(array $source_key = NULL) {
  1461. if (!$source_key) {
  1462. $source_key = $this->currentSourceKey();
  1463. }
  1464. $this->map->setUpdate($source_key);
  1465. }
  1466. }
  1467. /**
  1468. * @deprecated - This class is no longer necessary, inherit directly from
  1469. * Migration instead.
  1470. */
  1471. abstract class DynamicMigration extends Migration {
  1472. static $deprecationWarning = FALSE;
  1473. public function __construct($arguments) {
  1474. parent::__construct($arguments);
  1475. if (variable_get('migrate_deprecation_warnings', 1) &&
  1476. !self::$deprecationWarning) {
  1477. self::displayMessage(t('The DynamicMigration class is no longer necessary and is now deprecated - please derive your migration classes directly from Migration.'));
  1478. self::$deprecationWarning = TRUE;
  1479. }
  1480. }
  1481. /**
  1482. * Overrides default of FALSE
  1483. */
  1484. static public function isDynamic() {
  1485. return TRUE;
  1486. }
  1487. }