migrate.drush.inc 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520
  1. <?php
  2. /**
  3. * @file
  4. * Drush support for the migrate module
  5. */
  6. /**
  7. * Implements hook_drush_command().
  8. */
  9. function migrate_drush_command() {
  10. $migration_options = array(
  11. 'limit' => 'Limit on the length of each migration process, expressed in seconds or number of items',
  12. 'feedback' => 'Frequency of progress messages, in seconds or items processed',
  13. 'idlist' => 'A comma delimited list of ids to import or rollback. If unspecified, migrate imports all pending items or rolls back all items for the content set.',
  14. 'all' => 'Process all migrations that come after the specified migration. If no value is supplied, all migrations are processed.',
  15. 'instrument' => 'Capture performance information (timer, memory, or all)',
  16. 'force' => 'Force an operation to run, even if all dependencies are not satisfied',
  17. 'group' => 'Name of the migration group to run',
  18. 'notify' => 'Send email notification upon completion of operation',
  19. );
  20. $items['migrate-status'] = array(
  21. 'description' => 'List all migrations with current status.',
  22. 'options' => array(
  23. 'refresh' => 'Recognize new migrations and update counts',
  24. 'group' => 'Name of the migration group to list',
  25. 'names-only' => 'Only return names, not all the details (faster)',
  26. ),
  27. 'arguments' => array(
  28. 'migration' => 'Restrict to a single migration. Optional',
  29. ),
  30. 'examples' => array(
  31. 'migrate-status' => 'Retrieve status for all migrations',
  32. 'migrate-status BeerNode' => 'Retrieve status for just one migration',
  33. ),
  34. 'drupal dependencies' => array('migrate'),
  35. 'aliases' => array('ms'),
  36. );
  37. $items['migrate-fields-destination'] = array(
  38. 'description' => 'List the fields available for mapping in a destination.',
  39. 'options' => array(
  40. 'all' => $migration_options['all'],
  41. 'group' => $migration_options['group'],
  42. ),
  43. 'arguments' => array(
  44. 'migration' => 'Name of the migration or destination class to query for fields',
  45. ),
  46. 'examples' => array(
  47. 'migrate-fields-destination MyNode' => 'List fields for the destination in the MyNode migration',
  48. ),
  49. 'drupal dependencies' => array('migrate'),
  50. 'aliases' => array('mfd'),
  51. );
  52. $items['migrate-fields-source'] = array(
  53. 'description' => 'List the fields available for mapping from a source.',
  54. 'arguments' => array(
  55. 'migration' => 'Name of the migration or destination class to query for fields',
  56. ),
  57. 'options' => array(
  58. 'all' => $migration_options['all'],
  59. 'group' => $migration_options['group'],
  60. ),
  61. 'examples' => array(
  62. 'migrate-fields-destination MyNode' => 'List fields in the source query for the MyNode migration',
  63. ),
  64. 'drupal dependencies' => array('migrate'),
  65. 'aliases' => array('mfs'),
  66. );
  67. $items['migrate-mappings'] = array(
  68. 'description' => 'View information on all field mappings in a migration.',
  69. 'options' => array(
  70. 'all' => $migration_options['all'],
  71. 'group' => $migration_options['group'],
  72. 'csv' => 'Export information as a CSV',
  73. 'full' => 'Include more information on each mapping',
  74. ),
  75. 'arguments' => array(
  76. 'migration' => 'Name of the migration',
  77. ),
  78. 'examples' => array(
  79. 'migrate-mappings MyNode' => 'Show mappings for the MyNode migration',
  80. 'migrate-mappings MyNode --csv --full' => 'Export full mapping information in CSV format',
  81. ),
  82. 'drupal dependencies' => array('migrate'),
  83. 'aliases' => array('mm'),
  84. );
  85. $items['migrate-messages'] = array(
  86. 'description' => 'View any messages associated with a migration.',
  87. 'options' => array(
  88. 'csv' => 'Export messages as a CSV',
  89. ),
  90. 'arguments' => array(
  91. 'migration' => 'Name of the migration',
  92. ),
  93. 'examples' => array(
  94. 'migrate-messages MyNode' => 'Show all messages for the MyNode migration',
  95. ),
  96. 'drupal dependencies' => array('migrate'),
  97. 'aliases' => array('mmsg'),
  98. );
  99. $items['migrate-analyze'] = array(
  100. 'description' => 'Analyze the source fields for a migration.',
  101. 'options' => array(
  102. 'all' => $migration_options['all'],
  103. 'group' => $migration_options['group'],
  104. ),
  105. 'arguments' => array(
  106. 'migration' => 'Name of the migration',
  107. ),
  108. 'examples' => array(
  109. 'migrate-analyze MyNode' => 'Report on field values for the MyNode migration',
  110. ),
  111. 'drupal dependencies' => array('migrate'),
  112. 'aliases' => array('maz'),
  113. );
  114. $items['migrate-audit'] = array(
  115. 'description' => 'View information on problems in a migration.',
  116. 'options' => array(
  117. 'all' => $migration_options['all'],
  118. 'group' => $migration_options['group'],
  119. ),
  120. 'arguments' => array(
  121. 'migration' => 'Name of the migration',
  122. ),
  123. 'examples' => array(
  124. 'migrate-audit MyNode' => 'Report on problems in the MyNode migration',
  125. ),
  126. 'drupal dependencies' => array('migrate'),
  127. 'aliases' => array('ma'),
  128. );
  129. $items['migrate-rollback'] = array(
  130. 'description' => 'Roll back the destination objects from a given migration',
  131. 'options' => $migration_options,
  132. 'arguments' => array(
  133. 'migration' => 'Name of migration(s) to roll back. Delimit multiple using commas.',
  134. ),
  135. 'examples' => array(
  136. 'migrate-rollback Article' => 'Roll back the article migration',
  137. 'migrate-rollback Article --idlist=4,9' => 'Roll back two articles. The ids refer to the value of the primary key in base table',
  138. 'migrate-rollback User --limit="50 items"' =>
  139. 'Roll back up to 50 items from the migration named User',
  140. 'migrate-rollback User --feedback="60 seconds"' => 'Display a progress message every 60 seconds or less',
  141. ),
  142. 'drupal dependencies' => array('migrate'),
  143. 'aliases' => array('mr'),
  144. );
  145. $migration_options['update'] = 'In addition to processing unprocessed items from the source, update previously-imported items with new data';
  146. $migration_options['needs-update'] =
  147. 'Reimport up to 10K records where needs_update=1. This option is only needed when your Drupal DB is on a different DB server from your source data. Otherwise, these records get migrated with just migrate-import.';
  148. $migration_options['stop'] = 'Stop specified migration(s) if applicable.';
  149. $migration_options['rollback'] = 'Rollback specified migration(s) if applicable.';
  150. $migration_options['file_function'] = 'Override file function to use when migrating images.';
  151. $migration_options['ignore-highwater'] = 'Ignore the highwater field during migration';
  152. $items['migrate-import'] = array(
  153. 'description' => 'Perform one or more migration processes',
  154. 'options' => $migration_options,
  155. 'arguments' => array(
  156. 'migration' => 'Name of migration(s) to import. Delimit multiple using commas.',
  157. ),
  158. 'examples' => array(
  159. 'migrate-import Article' => 'Import new articles',
  160. 'migrate-import Article --update' => 'Import new items, and also update previously-imported items',
  161. 'migrate-import Article --idlist=4,9' => 'Import two specific articles. The ids refer to the value of the primary key in base table',
  162. 'migrate-import Article --limit="60 seconds" --stop --rollback' =>
  163. 'Import for up to 60 seconds after stopping and rolling back the Article migration.',
  164. 'migrate-import Article --limit="100 items"' =>
  165. 'Import up to 100 items from the migration named Article.',
  166. 'migrate-import User --feedback="1000 items"' => 'Display a progress message every 1000 processed items or less',
  167. 'migrate-import --all=User' => 'Perform User migrations and all that follow it.',
  168. ),
  169. 'drupal dependencies' => array('migrate'),
  170. 'aliases' => array('mi'),
  171. );
  172. $items['migrate-stop'] = array(
  173. 'description' => 'Stop an active migration operation',
  174. 'options' => array('all' => 'Stop all active migration operations',
  175. 'group' => 'Name of a specific migration group to stop'),
  176. 'arguments' => array(
  177. 'migration' => 'Name of migration to stop',
  178. ),
  179. 'examples' => array(
  180. 'migrate-stop Article' => 'Stop any active operation on the Article migration',
  181. 'migrate-stop --all' => 'Stop all active migration operations',
  182. ),
  183. 'drupal dependencies' => array('migrate'),
  184. 'aliases' => array('mst'),
  185. );
  186. $items['migrate-reset-status'] = array(
  187. 'description' => 'Reset a active migration\'s status to idle',
  188. 'options' => array('all' => 'Reset all active migration operations'),
  189. 'arguments' => array(
  190. 'migration' => 'Name of migration to reset',
  191. ),
  192. 'examples' => array(
  193. 'migrate-reset-status Article' => 'Reset any active operation on the Article migration',
  194. 'migrate-reset-status --all' => 'Reset all active migration operations',
  195. ),
  196. 'drupal dependencies' => array('migrate'),
  197. 'aliases' => array('mrs'),
  198. );
  199. $items['migrate-deregister'] = array(
  200. 'description' => 'Remove all tracking of a migration',
  201. 'options' => array(
  202. 'orphans' => 'Remove tracking for any migrations whose implementing class no longer exists',
  203. 'group' => 'Remove tracking of a migration group, and any migrations assigned to it',
  204. ),
  205. 'arguments' => array(
  206. 'migration' => 'Name of migration to deregister',
  207. ),
  208. 'examples' => array(
  209. 'migrate-deregister Article' => 'Deregister the Article migration',
  210. 'migrate-deregister --orphans' => 'Deregister any no-longer-implemented migrations',
  211. 'migrate-deregister --group=myblog' => 'Deregister the myblog group and all migrations within it',
  212. ),
  213. 'drupal dependencies' => array('migrate'),
  214. );
  215. $items['migrate-auto-register'] = array(
  216. 'description' => 'Register any newly defined migration classes',
  217. 'drupal dependencies' => array('migrate'),
  218. 'aliases' => array('mar'),
  219. );
  220. $items['migrate-register'] = array(
  221. 'description' => 'Register or reregister any statically defined migrations',
  222. 'drupal dependencies' => array('migrate'),
  223. 'aliases' => array('mreg'),
  224. );
  225. $items['migrate-wipe'] = array(
  226. 'description' => 'Delete all nodes from specified content types.',
  227. 'examples' => array(
  228. "migrate-wipe story article" => 'Delete all story and article nodes.',
  229. ),
  230. 'arguments' => array(
  231. 'type' => 'A space delimited list of content type machine readable Ids.',
  232. ),
  233. 'drupal dependencies' => array('migrate'),
  234. 'aliases' => array('mw'),
  235. );
  236. return $items;
  237. }
  238. /**
  239. * Get the value of all migrate related options. Used when spawning a subshell.
  240. * Don't pass along all, stop, update, and rollback options.
  241. *
  242. * @return
  243. * An array of command specific options and their values.
  244. */
  245. function drush_migrate_get_options() {
  246. $options = array();
  247. $blacklist = array('stop', 'rollback', 'update', 'all', 'group');
  248. $command = drush_parse_command();
  249. $global_options = drush_get_global_options();
  250. $opts = array_merge($command['options'], $global_options);
  251. foreach ($opts as $key => $value) {
  252. // Strip leading --
  253. $key = ltrim($key, '-');
  254. if (!in_array($key, $blacklist)) {
  255. $value = drush_get_option($key);
  256. if (isset($value)) {
  257. $options[$key] = $value;
  258. }
  259. }
  260. }
  261. return $options;
  262. }
  263. /*
  264. * Spawn a subshell which runs the same command we are currently running.
  265. */
  266. function drush_migrate_invoke_process($migrations = '') {
  267. $args = drush_get_arguments();
  268. $options = drush_migrate_get_options();
  269. if (intval(DRUSH_MAJOR_VERSION) < 4) {
  270. // @todo: use drush_backend_invoke_args() as per http://drupal.org/node/658420.
  271. return drush_backend_invoke(implode(' ', $args), $options);
  272. }
  273. else {
  274. // $args[0] is the command name, $args[1] is the list of migrations.
  275. if (empty($migrations)) {
  276. $command_args = array($args[1]);
  277. }
  278. else {
  279. $command_args = array($migrations);
  280. }
  281. $return = drush_invoke_process('@self', $args[0], $command_args, $options);
  282. return $return;
  283. }
  284. }
  285. /**
  286. * A simplified version of the dashboard page.
  287. */
  288. function drush_migrate_status($name = NULL) {
  289. try {
  290. $refresh = drush_get_option('refresh');
  291. $group_option = drupal_strtolower(drush_get_option('group'));
  292. $names_only = drush_get_option('names-only');
  293. // Validate input and load Migration(s).
  294. if ($name) {
  295. if ($migration = MigrationBase::getInstance($name)) {
  296. $migrations = array($migration);
  297. }
  298. else {
  299. return drush_set_error(dt('Unrecognized migration: !cn', array('!cn' => $name)));
  300. }
  301. }
  302. else {
  303. $migrations = migrate_migrations();
  304. }
  305. $groups = MigrateGroup::groups();
  306. $table = array();
  307. foreach ($groups as $group) {
  308. if ($group_option && drupal_strtolower($group->getName()) != $group_option) {
  309. continue;
  310. }
  311. $group_members_count = 0;
  312. foreach ($migrations as $migration) {
  313. if ($migration->getGroup() != $group) {
  314. // This migration is not from this group.
  315. continue;
  316. }
  317. ++$group_members_count;
  318. if ($group_members_count == 1) {
  319. // An empty line and the headers.
  320. $table[] = array('');
  321. if ($names_only) {
  322. $table[] = array(dt('Group: !name',
  323. array('!name' => $group->getName())));
  324. }
  325. else {
  326. $table[] = array(dt('Group: !name',
  327. array('!name' => $group->getName())), dt('Total'), dt('Imported'),
  328. dt('Unprocessed'), dt('Status'), dt('Last imported'));
  329. }
  330. }
  331. if (!$names_only) {
  332. $has_counts = TRUE;
  333. if (method_exists($migration, 'sourceCount')) {
  334. $total = $migration->sourceCount($refresh);
  335. if ($total < 0) {
  336. $has_counts = FALSE;
  337. $total = dt('N/A');
  338. }
  339. }
  340. else {
  341. $has_counts = FALSE;
  342. $total = dt('N/A');
  343. }
  344. if (method_exists($migration, 'importedCount')) {
  345. $imported = $migration->importedCount();
  346. $processed = $migration->processedCount();
  347. }
  348. else {
  349. $has_counts = FALSE;
  350. $imported = dt('N/A');
  351. }
  352. if ($has_counts) {
  353. $unimported = $total - $processed;
  354. }
  355. else {
  356. $unimported = dt('N/A');
  357. }
  358. $status = $migration->getStatus();
  359. switch ($status) {
  360. case MigrationBase::STATUS_IDLE:
  361. $status = dt('Idle');
  362. break;
  363. case MigrationBase::STATUS_IMPORTING:
  364. $status = dt('Importing');
  365. break;
  366. case MigrationBase::STATUS_ROLLING_BACK:
  367. $status = dt('Rolling back');
  368. break;
  369. case MigrationBase::STATUS_STOPPING:
  370. $status = dt('Stopping');
  371. break;
  372. case MigrationBase::STATUS_DISABLED:
  373. $status = dt('Disabled');
  374. break;
  375. default:
  376. $status = dt('Unknown');
  377. break;
  378. }
  379. $table[] = array($migration->getMachineName(), $total, $imported, $unimported, $status, $migration->getLastImported());
  380. }
  381. else {
  382. $table[] = array($migration->getMachineName());
  383. }
  384. }
  385. }
  386. drush_print_table($table);
  387. }
  388. catch (MigrateException $e) {
  389. drush_print($e->getMessage());
  390. exit;
  391. }
  392. }
  393. // TODO: Use drush_choice for detailed field info
  394. function drush_migrate_fields_destination($args = NULL) {
  395. try {
  396. $migrations = drush_migrate_get_migrations($args);
  397. foreach ($migrations as $name => $migration) {
  398. drush_print("\n" . dt('@migration Destination Fields', array('@migration' => $name)) . "\n");
  399. $destination = $migration->getDestination();
  400. if (method_exists($destination, 'fields')) {
  401. $table = array();
  402. foreach ($destination->fields($migration) as $machine_name => $description) {
  403. $table[] = array(strip_tags($description), $machine_name);
  404. }
  405. drush_print_table($table);
  406. }
  407. else {
  408. drush_print(dt('No fields were found.'));
  409. }
  410. }
  411. }
  412. catch (MigrateException $e) {
  413. drush_print($e->getMessage());
  414. exit;
  415. }
  416. }
  417. function drush_migrate_fields_source($args = NULL) {
  418. try {
  419. $migrations = drush_migrate_get_migrations($args);
  420. foreach ($migrations as $name => $migration) {
  421. drush_print("\n" . dt('@migration Source Fields', array('@migration' => $name)) . "\n");
  422. $source = $migration->getSource();
  423. if (method_exists($source, 'fields')) {
  424. $table = array();
  425. foreach ($source->fields() as $machine_name => $description) {
  426. $table[] = array(strip_tags($description), $machine_name);
  427. }
  428. drush_print_table($table);
  429. }
  430. else {
  431. drush_print(dt('No fields were found.'));
  432. }
  433. }
  434. }
  435. catch (MigrateException $e) {
  436. drush_print($e->getMessage());
  437. exit;
  438. }
  439. }
  440. /**
  441. * Display field mappings for a migration.
  442. */
  443. function drush_migrate_mappings($args = NULL) {
  444. try {
  445. $full = drush_get_option('full');
  446. $migrations = drush_migrate_get_migrations($args);
  447. foreach ($migrations as $name => $migration) {
  448. drush_print("\n" . dt('@migration Mappings', array('@migration' => $name)) . "\n");
  449. // In verbose mode, we'll also get source and destination field descriptions
  450. if ($full) {
  451. $destination = $migration->getDestination();
  452. $dest_descriptions = array();
  453. if (method_exists($destination, 'fields')) {
  454. foreach ($destination->fields($migration) as $machine_name => $description) {
  455. if (is_array($description)) {
  456. $description = reset($description);
  457. }
  458. $dest_descriptions[$machine_name] = strip_tags($description);
  459. }
  460. }
  461. $source = $migration->getSource();
  462. $src_descriptions = array();
  463. if (method_exists($source, 'fields')) {
  464. foreach ($source->fields() as $machine_name => $description) {
  465. if (is_array($description)) {
  466. $description = reset($description);
  467. }
  468. $src_descriptions[$machine_name] = strip_tags($description);
  469. }
  470. }
  471. }
  472. if (method_exists($migration, 'getFieldMappings')) {
  473. // First group the mappings. We want "interesting" mappings first, so
  474. // put the boring Done and DNM mappings last.
  475. $descriptions = array();
  476. $done = array();
  477. $dnm = array();
  478. foreach ($migration->getFieldMappings() as $mapping) {
  479. $group = $mapping->getIssueGroup();
  480. $lowergroup = drupal_strtolower($group);
  481. if ($lowergroup == dt('done')) {
  482. $done[$group][] = $mapping;
  483. }
  484. elseif ($lowergroup == dt('dnm') || $lowergroup == dt('do not migrate')) {
  485. $dnm[$group][] = $mapping;
  486. }
  487. else {
  488. $descriptions[$group][] = $mapping;
  489. }
  490. }
  491. $descriptions = array_merge($descriptions, $done, $dnm);
  492. // Put out each group header
  493. $table = array();
  494. if ($full) {
  495. $table[] = array(dt('Destination'), dt(''), dt('Source'), dt(''), dt('Default'),
  496. dt('Description'));
  497. }
  498. else {
  499. $table[] = array(dt('Destination'), dt('Source'), dt('Default'),
  500. dt('Description'));
  501. }
  502. $first = TRUE;
  503. foreach ($descriptions as $group => $mappings) {
  504. if ($first) {
  505. $first = FALSE;
  506. }
  507. else {
  508. $table[] = array(' ');
  509. }
  510. // Attempt to highlight the group header a bit so it stands out
  511. $group_header = '--- ' . drupal_strtoupper($group) . ' ---';
  512. $table[] = array($group_header);
  513. foreach ($mappings as $mapping) {
  514. if (is_array($mapping->getDefaultValue())) {
  515. $default = implode(',', $mapping->getDefaultValue());
  516. }
  517. else {
  518. $default = $mapping->getDefaultValue();
  519. }
  520. $destination = $mapping->getDestinationField();
  521. $source = $mapping->getSourceField();
  522. if ($full) {
  523. if ($destination && $dest_descriptions[$destination]) {
  524. $dest_description = $dest_descriptions[$destination];
  525. }
  526. else {
  527. $dest_description = '';
  528. }
  529. if ($source && $src_descriptions[$source]) {
  530. $src_description = $src_descriptions[$source];
  531. }
  532. else {
  533. $src_description = '';
  534. }
  535. $table[] = array($destination, $dest_description, $source, $src_description,
  536. $default, $mapping->getDescription());
  537. }
  538. else {
  539. $table[] = array($destination, $source,
  540. $default, $mapping->getDescription());
  541. }
  542. }
  543. }
  544. if (drush_get_option('csv')) {
  545. foreach ($table as $row) {
  546. fputcsv(STDOUT, $row);
  547. }
  548. }
  549. else {
  550. drush_print_table($table, TRUE);
  551. }
  552. }
  553. }
  554. }
  555. catch (MigrateException $e) {
  556. drush_print($e->getMessage());
  557. exit;
  558. }
  559. }
  560. /**
  561. * Display messages for a migration.
  562. */
  563. function drush_migrate_messages($migration_name) {
  564. if (!trim($migration_name)) {
  565. drush_log(dt('You must specify a migration name'), 'status');
  566. return;
  567. }
  568. try {
  569. $migration = MigrationBase::getInstance($migration_name);
  570. if (is_a($migration, 'Migration')) {
  571. $map = $migration->getMap();
  572. $message_table = $map->getMessageTable();
  573. $result = db_select($message_table, 'msg', array('fetch' => PDO::FETCH_ASSOC))
  574. ->fields('msg')
  575. ->execute();
  576. $first = TRUE;
  577. $table = array();
  578. foreach ($result as $row) {
  579. unset($row['msgid']);
  580. unset($row['level']);
  581. if ($first) {
  582. $table[] = array_keys($row);
  583. $first = FALSE;
  584. }
  585. $table[] = $row;
  586. }
  587. }
  588. if (empty($table)) {
  589. drush_log(dt('No messages for this migration'), 'status');
  590. }
  591. else {
  592. if (drush_get_option('csv')) {
  593. foreach ($table as $row) {
  594. fputcsv(STDOUT, $row);
  595. }
  596. }
  597. else {
  598. $widths = array();
  599. foreach ($table[0] as $header) {
  600. $widths[] = strlen($header) + 1;
  601. }
  602. drush_print_table($table, TRUE, $widths);
  603. }
  604. }
  605. }
  606. catch (MigrateException $e) {
  607. drush_print($e->getMessage());
  608. exit;
  609. }
  610. }
  611. /**
  612. * Analyze the source fields for any passed migrations.
  613. */
  614. function drush_migrate_analyze($args = NULL) {
  615. $migrations = drush_migrate_get_migrations($args);
  616. foreach ($migrations as $name => $migration) {
  617. // "Migrations" derived from MigrationBase won't have an analyze method.
  618. if (method_exists($migration, 'analyze')) {
  619. drush_print("\n" . dt('Analyzing @migration', array('@migration' => $name)) . "\n");
  620. $analysis = $migration->analyze();
  621. if (!empty($analysis)) {
  622. foreach ($analysis as $field_name => $details) {
  623. if (!empty($details['description'])) {
  624. drush_print(dt('@name (@description):', array('@name' => $field_name,
  625. '@description' => $details['description'])));
  626. }
  627. else {
  628. drush_print(dt('@name:', array('@name' => $field_name)));
  629. }
  630. // Special handling in degenerate cases
  631. if (count($details['distinct_values']) == 1) {
  632. $value = trim(reset(array_keys($details['distinct_values'])));
  633. if ($value === '') {
  634. drush_print(' ' . dt('The field is always empty'));
  635. }
  636. else {
  637. drush_print(' ' . dt('Only one value present: @value',
  638. array('@value' => $value)));
  639. }
  640. }
  641. else {
  642. if ($details['is_numeric']) {
  643. drush_print(' ' . dt('Numeric field with a range of @min to @max',
  644. array('@min' => $details['min_numeric'], '@max' => $details['max_numeric'])));
  645. }
  646. else {
  647. drush_print(' ' . dt('String field with a length ranging from @min to @max',
  648. array('@min' => $details['min_strlen'], '@max' => $details['max_strlen'])));
  649. }
  650. $values = array();
  651. $header = NULL;
  652. // If the max of 10 tracked distinct values was reached, we assume
  653. // there are many values and treat them as samples. Under 10 this
  654. // may be an enumerated field, show all values with their counts.
  655. if (count($details['distinct_values']) < 10) {
  656. drush_print(' ' . dt('Distinct values:'));
  657. $header = array('', dt('Value'), dt('Count'));
  658. $values[] = $header;
  659. }
  660. else {
  661. drush_print(' ' . dt('Sample values:'));
  662. }
  663. ksort($details['distinct_values']);
  664. foreach ($details['distinct_values'] as $value => $count) {
  665. // Truncate long strings
  666. $value = substr($value, 0, 60);
  667. if (strlen($value) == 60) {
  668. $value .= dt('...');
  669. }
  670. $row = array(' ', $value);
  671. if (count($details['distinct_values']) < 10) {
  672. $row[] = $count;
  673. }
  674. $values[] = $row;
  675. }
  676. // No header for sample values.
  677. drush_print_table($values, !is_null($header));
  678. }
  679. }
  680. }
  681. }
  682. }
  683. }
  684. /**
  685. * Display field mappings for a migration.
  686. */
  687. function drush_migrate_audit($args = NULL) {
  688. try {
  689. $problem_descriptions = array(
  690. 'wtf' => dt("Probably an incomplete migration:"),
  691. 'noted_issues' => dt("Noted as an issue:"),
  692. // I wish drush had dformat_plural().
  693. 'sources_unmapped' => dt("Source(s) not used in a mapping:"),
  694. 'sources_missing' => dt("Used as source field in mapping but not in source field list:"),
  695. 'destinations_unmapped' => dt("Destination(s) not used in a mapping:"),
  696. 'destinations_missing' => dt("Used as destination field in mapping but not in destination field list:"),
  697. );
  698. drush_print("Auditing migrations");
  699. $migrations = drush_migrate_get_migrations($args);
  700. foreach ($migrations as $name => $migration) {
  701. $problems = array();
  702. foreach ($problem_descriptions as $key => $description) {
  703. $problems[$key] = array();
  704. }
  705. drush_print("\n" . dt('@migration', array('@migration' => $name)) . "\n");
  706. if (!method_exists($migration, 'getSource') || !($source = $migration->getSource())) {
  707. $problems['wtf'][] = dt('Missing a source');
  708. $source_fields = array();
  709. }
  710. else {
  711. $source_fields = $source->fields();
  712. }
  713. if (!method_exists($migration, 'getDestination') || !($destination = $migration->getDestination())) {
  714. $problems['wtf'][] = dt('Missing a destination');
  715. $destination_fields = array();
  716. }
  717. else {
  718. $destination_fields = $destination->fields($migration);
  719. }
  720. if (!method_exists($migration, 'getFieldMappings')) {
  721. $problems['wtf'][] = dt('Missing field mappings');
  722. $field_mappings = array();
  723. }
  724. else {
  725. $field_mappings = $migration->getFieldMappings();
  726. }
  727. $used_sources = array();
  728. $used_destinations = array();
  729. foreach ($field_mappings as $mapping) {
  730. $source_field = $mapping->getSourceField();
  731. $destination_field = $mapping->getDestinationField();
  732. $used_sources[$source_field] = TRUE;
  733. $used_destinations[$destination_field] = TRUE;
  734. $issue_priority = $mapping->getIssuePriority();
  735. if (!is_null($issue_priority) && $issue_priority != MigrateFieldMapping::ISSUE_PRIORITY_OK) {
  736. $problems['noted_issues'][] = array(
  737. dt('Source') => $source_field,
  738. dt('Destination') => $destination_field,
  739. dt('Priority') => MigrateFieldMapping::$priorities[$issue_priority],
  740. dt('Description') => $mapping->getDescription(),
  741. );
  742. }
  743. // Validate source and destination fields actually exist
  744. if (!is_null($source_field) && !isset($source_fields[$source_field])) {
  745. $problems['sources_missing'][] = $source_field;
  746. }
  747. if (!is_null($destination_field) && !isset($destination_fields[$destination_field])) {
  748. $problems['destinations_missing'][] = $destination_field;
  749. }
  750. }
  751. foreach (array_diff_key($source_fields, $used_sources) as $name => $description) {
  752. $problems['sources_unmapped'][] = array('Field' => $name, 'Description' => $description);
  753. }
  754. foreach (array_diff_key($destination_fields, $used_destinations) as $name => $description) {
  755. $problems['destinations_unmapped'][] = array('Field' => $name, 'Description' => $description);
  756. }
  757. $problems = array_filter($problems);
  758. if (empty($problems)) {
  759. drush_print(dt('No problems found.') . "\n", 1);
  760. }
  761. else {
  762. foreach ($problems as $type => $some_problems) {
  763. drush_print($problem_descriptions[$type]);
  764. // If the contents of each row are arrays print it as a table.
  765. if (is_array($some_problems[0])) {
  766. $table = array_merge(array(array_keys($some_problems[0])), $some_problems);
  767. drush_print_table($table, TRUE);
  768. }
  769. else {
  770. foreach ($some_problems as $problem) {
  771. drush_print($problem, 1);
  772. }
  773. // Add an extra new line to keep the spacing consistent with the
  774. // tables.
  775. drush_print();
  776. }
  777. }
  778. }
  779. }
  780. }
  781. catch (MigrateException $e) {
  782. drush_print($e->getMessage());
  783. exit;
  784. }
  785. }
  786. /**
  787. * Roll back one specified migration
  788. */
  789. function drush_migrate_rollback($args = NULL) {
  790. try {
  791. if (drush_get_option('notify', FALSE)) {
  792. // Capture non-informational output for mailing
  793. ob_start();
  794. ob_implicit_flush(FALSE);
  795. // Save original mail setup, which Migrate will disable, so we can
  796. // restore it later.
  797. global $conf;
  798. if (!empty($conf['mail_system'])) {
  799. $mail_system = $conf['mail_system'];
  800. }
  801. else {
  802. $mail_system = NULL;
  803. }
  804. }
  805. $migrations = drush_migrate_get_migrations($args);
  806. // Rollback in reverse order
  807. $migrations = array_reverse($migrations, TRUE);
  808. $options = array();
  809. if ($idlist = drush_get_option('idlist', FALSE)) {
  810. $options['idlist'] = $idlist;
  811. }
  812. if (drush_get_option('force', FALSE) == 1) {
  813. $options['force'] = TRUE;
  814. }
  815. $limit = drush_get_option('limit');
  816. if ($limit) {
  817. $parts = explode(' ', $limit);
  818. $options['limit']['value'] = $parts[0];
  819. $options['limit']['unit'] = $parts[1];
  820. if (!$options['limit']['unit']) {
  821. $options['limit']['unit'] = 'items';
  822. }
  823. elseif ($options['limit']['unit'] != 'seconds' &&
  824. $options['limit']['unit'] != 'second' &&
  825. $options['limit']['unit'] != 'items' &&
  826. $options['limit']['unit'] != 'item') {
  827. drush_set_error(NULL, dt("Invalid limit unit '!unit'",
  828. array('!unit' => $options['limit']['unit'])));
  829. return;
  830. }
  831. }
  832. $feedback = drush_get_option('feedback');
  833. if ($feedback) {
  834. $parts = explode(' ', $feedback);
  835. $options['feedback']['value'] = $parts[0];
  836. $options['feedback']['unit'] = $parts[1];
  837. if ($options['feedback']['unit'] != 'seconds' &&
  838. $options['feedback']['unit'] != 'second' &&
  839. $options['feedback']['unit'] != 'items' &&
  840. $options['feedback']['unit'] != 'item') {
  841. drush_set_error(NULL, dt("Invalid feedback frequency unit '!unit'",
  842. array('!unit' => $options['feedback']['unit'])));
  843. return;
  844. }
  845. }
  846. $instrument = drush_get_option('instrument');
  847. global $_migrate_track_memory, $_migrate_track_timer;
  848. switch ($instrument) {
  849. case 'timer':
  850. $_migrate_track_timer = TRUE;
  851. break;
  852. case 'memory':
  853. $_migrate_track_memory = TRUE;
  854. break;
  855. case 'all':
  856. $_migrate_track_timer = TRUE;
  857. $_migrate_track_memory = TRUE;
  858. break;
  859. }
  860. foreach ($migrations as $migration) {
  861. drush_log(dt("Rolling back '!description' migration",
  862. array('!description' => $migration->getMachineName())));
  863. $return = $migration->processRollback($options);
  864. // If it couldn't finish (presumably because it was appraoching memory_limit),
  865. // continue in a subprocess
  866. if ($return == MigrationBase::RESULT_INCOMPLETE) {
  867. drush_migrate_invoke_process();
  868. }
  869. // If stopped, don't process any further
  870. elseif ($return == MigrationBase::RESULT_STOPPED) {
  871. break;
  872. }
  873. elseif ($return == MigrationBase::RESULT_SKIPPED) {
  874. drush_log(dt("Skipping migration !name due to unfulfilled dependencies, use the --force option to run it anyway.",
  875. array('!name' => $migration->getMachineName())),
  876. 'warning');
  877. }
  878. }
  879. }
  880. catch (MigrateException $e) {
  881. drush_print($e->getMessage());
  882. exit;
  883. }
  884. if ($_migrate_track_memory) {
  885. drush_migrate_print_memory();
  886. }
  887. if ($_migrate_track_timer && !drush_get_context('DRUSH_DEBUG')) {
  888. drush_print_timers();
  889. }
  890. // Notify user
  891. if (drush_get_option('notify')) {
  892. if (is_null($mail_system)) {
  893. unset($conf['mail_system']);
  894. }
  895. else {
  896. $conf['mail_system'] = $mail_system;
  897. }
  898. _drush_migrate_notify();
  899. }
  900. }
  901. /**
  902. * Send email notification to the user running the operation.
  903. */
  904. function _drush_migrate_notify() {
  905. global $user;
  906. if ($user->uid) {
  907. $uid = $user->uid;
  908. }
  909. else {
  910. $uid = 1;
  911. }
  912. $account = user_load($uid);
  913. $params['account'] = $account;
  914. $params['output'] = ob_get_contents();
  915. drush_print_r(ob_get_status());
  916. ob_end_flush();
  917. drupal_mail('migrate_ui', 'import_complete', $account->mail,
  918. user_preferred_language($account), $params);
  919. }
  920. function drush_migrate_get_migrations($args) {
  921. $migration_objects = migrate_migrations();
  922. if ($start = drush_get_option('all')) {
  923. // Handle custom first migration when --all=foo is supplied.
  924. $seen = $start === TRUE ? TRUE : FALSE;
  925. foreach ($migration_objects as $name => $migration) {
  926. if (!$seen && (drupal_strtolower($start) == drupal_strtolower($name))) {
  927. // We found our starting migration. $seen is always TRUE now.
  928. $seen = TRUE;
  929. }
  930. if (!$migration->getEnabled() || !$seen) {
  931. // This migration is disabled or is before our starting migration.
  932. unset($migration_objects[$name]);
  933. }
  934. }
  935. }
  936. elseif ($group = drush_get_option('group')) {
  937. foreach ($migration_objects as $name => $migration) {
  938. if (drupal_strtolower($group) !=
  939. drupal_strtolower($migration->getGroup()->getName()) ||
  940. !$migration->getEnabled()) {
  941. unset($migration_objects[$name]);
  942. }
  943. }
  944. }
  945. else {
  946. $named_migrations = array();
  947. foreach (explode(',', $args) as $name) {
  948. $found = FALSE;
  949. foreach ($migration_objects as $machine_name => $migration) {
  950. if (drupal_strtolower($name) == drupal_strtolower($machine_name)) {
  951. if ($migration->getEnabled()) {
  952. $named_migrations[$name] = $migration;
  953. $found = TRUE;
  954. break;
  955. }
  956. else {
  957. drush_log(dt('Migration !name is disabled', array('!name' => $name)), 'warning');
  958. }
  959. }
  960. }
  961. if (!$found) {
  962. drush_log(dt('No migration with machine name !name found', array('!name' => $name)), 'error');
  963. }
  964. }
  965. $migration_objects = $named_migrations;
  966. }
  967. return $migration_objects;
  968. }
  969. // Implement drush_hook_COMMAND_validate().
  970. function drush_migrate_fields_destination_validate($args = NULL) {
  971. return drush_migrate_validate_common($args);
  972. }
  973. // Implement drush_hook_COMMAND_validate().
  974. function drush_migrate_fields_source_validate($args = NULL) {
  975. return drush_migrate_validate_common($args);
  976. }
  977. // Implement drush_hook_COMMAND_validate().
  978. function drush_migrate_mappings_validate($args = NULL) {
  979. return drush_migrate_validate_common($args);
  980. }
  981. // Implement drush_hook_COMMAND_validate().
  982. function drush_migrate_analyze_validate($args = NULL) {
  983. return drush_migrate_validate_common($args);
  984. }
  985. // Implement drush_hook_COMMAND_validate().
  986. function drush_migrate_audit_validate($args = NULL) {
  987. return drush_migrate_validate_common($args);
  988. }
  989. // Implement drush_hook_COMMAND_validate().
  990. function drush_migrate_import_validate($args = NULL) {
  991. return drush_migrate_validate_common($args);
  992. }
  993. // Implement drush_hook_COMMAND_validate().
  994. function drush_migrate_stop_validate($args = NULL) {
  995. return drush_migrate_validate_common($args);
  996. }
  997. // Implement drush_hook_COMMAND_validate().
  998. function drush_migrate_reset_status_validate($args = NULL) {
  999. return drush_migrate_validate_common($args);
  1000. }
  1001. // Implement drush_hook_COMMAND_validate().
  1002. function drush_migrate_rollback_validate($args = NULL) {
  1003. return drush_migrate_validate_common($args);
  1004. }
  1005. function drush_migrate_validate_common($args) {
  1006. if (drush_get_option('all')) {
  1007. if (!empty($args) || drush_get_option('group')) {
  1008. return drush_set_error(NULL, dt('You must specify exactly one of a migration name, --all, or --group'));
  1009. }
  1010. }
  1011. elseif (drush_get_option('group')) {
  1012. if (!empty($args) || drush_get_option('all')) {
  1013. return drush_set_error(NULL, dt('You must specify exactly one of a migration name, --all, or --group'));
  1014. }
  1015. }
  1016. else {
  1017. if (empty($args)) {
  1018. return drush_set_error(NULL, dt('You must specify exactly one of a migration name, --all, or --group'));
  1019. }
  1020. $machine_names = explode(',', $args);
  1021. foreach ($machine_names as $machine_name) {
  1022. $machine_name = trim($machine_name);
  1023. $class_name = db_select('migrate_status', 'ms')
  1024. ->fields('ms', array('class_name'))
  1025. ->condition('machine_name', $machine_name)
  1026. ->execute()
  1027. ->fetchField();
  1028. if (!$class_name || !class_exists($class_name)) {
  1029. drush_set_error(dt('Unrecognized migration: !name', array('!name' => $machine_name)));
  1030. }
  1031. }
  1032. }
  1033. $feedback = drush_get_option('feedback');
  1034. if ($feedback) {
  1035. $parts = explode(' ', $feedback);
  1036. $options['feedback']['value'] = $parts[0];
  1037. $options['feedback']['unit'] = $parts[1];
  1038. if ($options['feedback']['unit'] != 'seconds' &&
  1039. $options['feedback']['unit'] != 'second' &&
  1040. $options['feedback']['unit'] != 'items' &&
  1041. $options['feedback']['unit'] != 'item') {
  1042. drush_set_error(NULL, dt("Invalid feedback frequency unit '!unit'",
  1043. array('!unit' => $options['feedback']['unit'])));
  1044. return;
  1045. }
  1046. }
  1047. }
  1048. /*
  1049. * A 'pre' callback for migrate-import command.
  1050. * Call migrate-stop and migrate-rollback commands if requested.
  1051. */
  1052. function drush_migrate_pre_migrate_import($args = NULL) {
  1053. if (drush_get_option('stop')) {
  1054. drush_invoke('migrate-stop', $args);
  1055. }
  1056. if (drush_get_option('rollback')) {
  1057. drush_unset_option('rollback');
  1058. drush_invoke('migrate-rollback', $args);
  1059. }
  1060. }
  1061. /**
  1062. * Perform import on one or more migrations.
  1063. *
  1064. * @param $machine_names
  1065. * A comma delimited list of machine names, or the special name 'all'
  1066. */
  1067. function drush_migrate_import($args = NULL) {
  1068. try {
  1069. if (drush_get_option('notify', FALSE)) {
  1070. // Capture non-informational output for mailing
  1071. ob_start();
  1072. ob_implicit_flush(FALSE);
  1073. // Save original mail setup, which Migrate will disable, so we can
  1074. // restore it later.
  1075. global $conf;
  1076. if (!empty($conf['mail_system'])) {
  1077. $mail_system = $conf['mail_system'];
  1078. }
  1079. else {
  1080. $mail_system = NULL;
  1081. }
  1082. }
  1083. $migrations = drush_migrate_get_migrations($args);
  1084. $options = array();
  1085. if ($idlist = drush_get_option('idlist', FALSE)) {
  1086. $options['idlist'] = $idlist;
  1087. }
  1088. if ($file_function = drush_get_option('file_function', '')) {
  1089. $options['file_function'] = $file_function;
  1090. }
  1091. if (drush_get_option('force', FALSE) == 1) {
  1092. $options['force'] = TRUE;
  1093. }
  1094. $limit = drush_get_option('limit');
  1095. if ($limit) {
  1096. $parts = explode(' ', $limit);
  1097. $options['limit']['value'] = $parts[0];
  1098. $options['limit']['unit'] = $parts[1];
  1099. if (!$options['limit']['unit']) {
  1100. $options['limit']['unit'] = 'items';
  1101. }
  1102. elseif ($options['limit']['unit'] != 'seconds' &&
  1103. $options['limit']['unit'] != 'second' &&
  1104. $options['limit']['unit'] != 'items' &&
  1105. $options['limit']['unit'] != 'item') {
  1106. drush_set_error(NULL, dt("Invalid limit unit '!unit'",
  1107. array('!unit' => $options['limit']['unit'])));
  1108. return;
  1109. }
  1110. }
  1111. $feedback = drush_get_option('feedback');
  1112. if ($feedback) {
  1113. $parts = explode(' ', $feedback);
  1114. $options['feedback']['value'] = $parts[0];
  1115. $options['feedback']['unit'] = $parts[1];
  1116. if ($options['feedback']['unit'] != 'seconds' &&
  1117. $options['feedback']['unit'] != 'second' &&
  1118. $options['feedback']['unit'] != 'items' &&
  1119. $options['feedback']['unit'] != 'item') {
  1120. drush_set_error(NULL, dt("Invalid feedback frequency unit '!unit'",
  1121. array('!unit' => $options['feedback']['unit'])));
  1122. return;
  1123. }
  1124. }
  1125. $instrument = drush_get_option('instrument');
  1126. global $_migrate_track_memory, $_migrate_track_timer;
  1127. switch ($instrument) {
  1128. case 'timer':
  1129. $_migrate_track_timer = TRUE;
  1130. break;
  1131. case 'memory':
  1132. $_migrate_track_memory = TRUE;
  1133. break;
  1134. case 'all':
  1135. $_migrate_track_timer = TRUE;
  1136. $_migrate_track_memory = TRUE;
  1137. break;
  1138. }
  1139. $stop = FALSE;
  1140. foreach ($migrations as $machine_name => $migration) {
  1141. drush_log(dt("Importing '!description' migration",
  1142. array('!description' => $machine_name)));
  1143. if (drush_get_option('update') && !$idlist) {
  1144. $migration->prepareUpdate();
  1145. if (drush_get_option('ignore-highwater')) {
  1146. $migration->setHighwaterField(array());
  1147. }
  1148. }
  1149. if (drush_get_option('needs-update')) {
  1150. $map_rows = $migration->getMap()->getRowsNeedingUpdate(10000);
  1151. $idlist = array();
  1152. foreach ($map_rows as $row) {
  1153. $idlist[] = $row->sourceid1;
  1154. }
  1155. $options['idlist'] = implode(',', $idlist);
  1156. }
  1157. // The goal here is to do one migration in the parent process and then
  1158. // spawn subshells as needed when memory is depleted. We show feedback
  1159. // after each subshell depletes itself. Best we can do in PHP.
  1160. if (!drush_get_context('DRUSH_BACKEND')) {
  1161. // Our first pass and in the parent process. Run a migration right here.
  1162. $status = $migration->processImport($options);
  1163. if ($status == MigrationBase::RESULT_SKIPPED) {
  1164. drush_log(dt("Skipping migration !name due to unfulfilled dependencies:\n !depends\nUse the --force option to run it anyway.",
  1165. array(
  1166. '!name' => $machine_name,
  1167. '!depends' => implode("\n ", $migration->incompleteDependencies()),
  1168. )),
  1169. 'warning');
  1170. }
  1171. elseif ($status == MigrationBase::RESULT_STOPPED) {
  1172. break;
  1173. }
  1174. elseif ($status == MigrationBase::RESULT_INCOMPLETE) {
  1175. $stop = TRUE;
  1176. }
  1177. // Subsequent run in the parent process. Spawn subshells ad infinitum.
  1178. $migration_string = implode(',', array_keys($migrations));
  1179. while ($status == MigrationBase::RESULT_INCOMPLETE) {
  1180. $return = drush_migrate_invoke_process($migration_string);
  1181. // 'object' holds the return code we care about.
  1182. $status = $return['object']['status'];
  1183. $migration_string = $return['object']['migrations'];
  1184. if ($status == MigrationBase::RESULT_SKIPPED) {
  1185. drush_log(dt("Skipping migration !name due to unfulfilled dependencies:\n !depends\nUse the --force option to run it anyway.",
  1186. array(
  1187. '!name' => $machine_name,
  1188. '!depends' => implode("\n ", $migration->incompleteDependencies()),
  1189. )),
  1190. 'warning');
  1191. }
  1192. elseif ($status == MigrationBase::RESULT_STOPPED) {
  1193. $stop = TRUE;
  1194. break;
  1195. }
  1196. }
  1197. }
  1198. else {
  1199. // I'm in a subshell. Import then set return value so parent process can respawn or move on.
  1200. $status = $migration->processImport($options);
  1201. if ($status == MigrationBase::RESULT_SKIPPED) {
  1202. drush_log(dt("Skipping migration !name due to unfulfilled dependencies:\n !depends\n",
  1203. array(
  1204. '!name' => $machine_name,
  1205. '!depends' => implode("\n ", $migration->incompleteDependencies()),
  1206. )),
  1207. 'warning');
  1208. }
  1209. elseif ($status == MigrationBase::RESULT_INCOMPLETE) {
  1210. $stop = TRUE;
  1211. }
  1212. drush_backend_set_result(array('status' => $status,
  1213. 'migrations' => implode(',', array_keys($migrations))));
  1214. }
  1215. if ($stop) {
  1216. break;
  1217. }
  1218. unset($migrations[$machine_name]);
  1219. }
  1220. }
  1221. catch (MigrateException $e) {
  1222. drush_print($e->getMessage());
  1223. exit;
  1224. }
  1225. if ($_migrate_track_memory) {
  1226. drush_migrate_print_memory();
  1227. }
  1228. if ($_migrate_track_timer && !drush_get_context('DRUSH_DEBUG')) {
  1229. drush_print_timers();
  1230. }
  1231. // Notify user
  1232. if (drush_get_option('notify')) {
  1233. if (is_null($mail_system)) {
  1234. unset($conf['mail_system']);
  1235. }
  1236. else {
  1237. $conf['mail_system'] = $mail_system;
  1238. }
  1239. _drush_migrate_notify();
  1240. }
  1241. }
  1242. /**
  1243. * Stop clearing or importing a given content set.
  1244. *
  1245. * @param $content_set
  1246. * The name of the Migration
  1247. */
  1248. function drush_migrate_stop($args = NULL) {
  1249. try {
  1250. $migrations = drush_migrate_get_migrations($args);
  1251. foreach ($migrations as $migration) {
  1252. drush_log(dt("Stopping '!description' migration", array('!description' => $migration->getMachineName())));
  1253. $migration->stopProcess();
  1254. }
  1255. }
  1256. catch (MigrateException $e) {
  1257. drush_print($e->getMessage());
  1258. exit;
  1259. }
  1260. }
  1261. /**
  1262. * Reset the status of a given migration.
  1263. */
  1264. function drush_migrate_reset_status($args = NULL) {
  1265. try {
  1266. $migrations = drush_migrate_get_migrations($args);
  1267. foreach ($migrations as $migration) {
  1268. drush_log(dt("Resetting '!description' migration",
  1269. array('!description' => $migration->getMachineName())));
  1270. $migration->resetStatus();
  1271. }
  1272. }
  1273. catch (MigrateException $e) {
  1274. drush_print($e->getMessage());
  1275. exit;
  1276. }
  1277. }
  1278. /**
  1279. * Deregister a given migration, migration group, or all orphaned migrations.
  1280. * Note that the migration might no longer "exist" (the class implementation
  1281. * might be gone), so we can't count on being able to instantiate it, or use
  1282. * migrate_migrations().
  1283. */
  1284. function drush_migrate_deregister($args = NULL) {
  1285. try {
  1286. $orphans = drush_get_option('orphans');
  1287. $group = drush_get_option('group');
  1288. if ($group) {
  1289. MigrateGroup::deregister($group);
  1290. drush_log(dt("Deregistered group '!description' and all its migrations",
  1291. array('!description' => $group)), 'success');
  1292. }
  1293. else {
  1294. if ($orphans) {
  1295. $migrations = array();
  1296. $result = db_select('migrate_status', 'ms')
  1297. ->fields('ms', array('class_name', 'machine_name'))
  1298. ->execute();
  1299. foreach ($result as $row) {
  1300. if (!class_exists($row->class_name)) {
  1301. $migrations[] = $row->machine_name;
  1302. }
  1303. }
  1304. }
  1305. else {
  1306. $migrations = explode(',', $args);
  1307. }
  1308. foreach ($migrations as $machine_name) {
  1309. drush_migrate_deregister_migration(drupal_strtolower($machine_name));
  1310. drush_log(dt("Deregistered '!description' migration",
  1311. array('!description' => $machine_name)), 'success');
  1312. }
  1313. }
  1314. }
  1315. catch (MigrateException $e) {
  1316. drush_print($e->getMessage());
  1317. exit;
  1318. }
  1319. }
  1320. /**
  1321. * Given a migration machine name, remove its tracking from the database.
  1322. *
  1323. * @param $machine_name
  1324. */
  1325. function drush_migrate_deregister_migration($machine_name) {
  1326. // The class is gone, so we'll manually clear migrate_status, and make
  1327. // the default assumptions about the map/message tables.
  1328. db_drop_table('migrate_map_' . $machine_name);
  1329. db_drop_table('migrate_message_' . $machine_name);
  1330. db_delete('migrate_status')
  1331. ->condition('machine_name', $machine_name)
  1332. ->execute();
  1333. db_delete('migrate_field_mapping')
  1334. ->condition('machine_name', $machine_name)
  1335. ->execute();
  1336. }
  1337. /**
  1338. * Auto-registration is no longer supported. This command should be removed
  1339. * entirely in a future point release.
  1340. *
  1341. * @deprecated
  1342. */
  1343. function drush_migrate_auto_register($args = NULL) {
  1344. drush_log(dt('The auto-registration feature has been removed. Migrations '
  1345. . 'must now be explicitly registered.'), 'error');
  1346. }
  1347. /**
  1348. * Register any migrations defined in hook_migrate_api().
  1349. */
  1350. function drush_migrate_register($args = NULL) {
  1351. migrate_static_registration();
  1352. drush_log(dt('All statically defined migrations have been (re)registered.'), 'success');
  1353. }
  1354. /**
  1355. * A drush command callback.
  1356. */
  1357. function drush_migrate_wipe() {
  1358. $types = func_get_args();
  1359. $nids = db_select('node', 'n')
  1360. ->fields('n', array('nid'))
  1361. ->condition('type', $types, 'IN')
  1362. ->execute()
  1363. ->fetchCol();
  1364. $chunks = array_chunk($nids, 50);
  1365. foreach ($chunks as $chunk) {
  1366. node_delete_multiple($chunk);
  1367. }
  1368. migrate_instrument_stop('node_delete');
  1369. }
  1370. // Print all timers for the request.
  1371. function drush_migrate_print_memory() {
  1372. global $_migrate_memory;
  1373. $temparray = array();
  1374. foreach ((array)$_migrate_memory as $name => $memoryrec) {
  1375. // We have to use timer_read() for active timers, and check the record for others
  1376. if (isset($memoryrec['start'])) {
  1377. $temparray[$name] = migrate_memory_read($name);
  1378. }
  1379. else {
  1380. $temparray[$name] = $memoryrec['bytes'];
  1381. }
  1382. }
  1383. // Go no farther if there were no timers
  1384. if (count($temparray) > 0) {
  1385. // Put the highest cumulative times first
  1386. arsort($temparray);
  1387. $table = array();
  1388. $table[] = array('Name', 'Cum (bytes)', 'Count', 'Avg (bytes)');
  1389. foreach ($temparray as $name => $memory) {
  1390. $count = $_migrate_memory[$name]['count'];
  1391. if ($count > 0) {
  1392. $avg = round($memory/$count, 0);
  1393. }
  1394. else {
  1395. $avg = 'N/A';
  1396. }
  1397. $table[] = array($name, $memory, $count, $avg);
  1398. }
  1399. drush_print_table($table, TRUE);
  1400. }
  1401. }
  1402. /**
  1403. * Command argument complete callback.
  1404. *
  1405. * @return
  1406. * List of migrations.
  1407. */
  1408. function migrate_migrate_status_complete() {
  1409. return array('values' => drush_migrate_migrations());
  1410. }
  1411. function migrate_migrate_import_complete() {
  1412. return array('values' => drush_migrate_migrations());
  1413. }
  1414. function migrate_migrate_rollback_complete() {
  1415. return array('values' => drush_migrate_migrations());
  1416. }
  1417. function migrate_migrate_fields_destination_complete() {
  1418. return array('values' => drush_migrate_migrations());
  1419. }
  1420. function migrate_migrate_fields_source_complete() {
  1421. return array('values' => drush_migrate_migrations());
  1422. }
  1423. function migrate_migrate_mappings_complete() {
  1424. return array('values' => drush_migrate_migrations());
  1425. }
  1426. function migrate_migrate_reset_status_complete() {
  1427. return array('values' => drush_migrate_migrations());
  1428. }
  1429. function migrate_migrate_stop_complete() {
  1430. return array('values' => drush_migrate_migrations());
  1431. }
  1432. function drush_migrate_migrations() {
  1433. drush_bootstrap(DRUPAL_BOOTSTRAP_FULL);
  1434. $migrations = migrate_migrations();
  1435. foreach ($migrations as $migration) {
  1436. $values[] = $migration->getMachineName();
  1437. }
  1438. return $values;
  1439. }