term_merge.module 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. <?php
  2. /**
  3. * Implementation of hook_permission().
  4. *
  5. * Adds a permission to merge terms.
  6. */
  7. function term_merge_permission() {
  8. return array(
  9. 'merge terms' => array(
  10. 'title' => t('Merge terms'),
  11. 'description' => t('Gives the user the ability to merge terms.'),
  12. )
  13. );
  14. }
  15. /**
  16. * Implements hook_menu():
  17. */
  18. function term_merge_menu() {
  19. $items = array(
  20. 'admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/merge' => array(
  21. 'title' => 'Merge terms',
  22. 'page callback' => 'drupal_get_form',
  23. 'page arguments' => array('term_merge_term_merge_form', 3),
  24. 'access arguments' => array('merge terms'),
  25. 'type' => MENU_LOCAL_TASK,
  26. )
  27. );
  28. return $items;
  29. }
  30. /**
  31. * Implements hook_help().
  32. */
  33. function term_merge_help($path, $arg) {
  34. switch ($path) {
  35. // Main module help for the block module
  36. case 'admin/help#term_merge':
  37. return '<p>Allows you to merge multiple terms into one and and at the same time update all fields referencing to the old ones.</p>';
  38. /*case 'admin/structure/taxonomy/%/merge':
  39. return '<p>This form simply lets you merge multiple terms into one and at the same time update all fields referencing to the old ones.</p>';*/
  40. }
  41. }
  42. /**
  43. * Implements hook_form_FORM_ID_alter().
  44. *
  45. * Inserts the Merge button into the actions of the form.
  46. */
  47. function term_merge_form_taxonomy_overview_terms_alter(&$form, &$form_state, $form_id) {
  48. if ($form['#total_entries'] > 0) {
  49. $form['actions'][] = array(
  50. 'merge' => array(
  51. '#type' => 'submit',
  52. '#value' => t('Merge'),
  53. '#submit' => array('term_merge_form_taxonomy_overview_terms_merge_submit'),
  54. '#weight' => 1,
  55. )
  56. );
  57. $form['actions']['submit']['#weight'] = 0;
  58. $form['actions']['reset_alphabetical']['#weight'] = 2;
  59. }
  60. }
  61. /**
  62. * Submit function for the merge button in the alteration of form form_taxonomy_overview_terms (see above).
  63. * Redirects the user to the term merge form/page.
  64. */
  65. function term_merge_form_taxonomy_overview_terms_merge_submit($form, &$form_state) {
  66. unset($form_state['storage']);
  67. $form_state['redirect'] = 'admin/structure/taxonomy/' . $form['#vocabulary']->machine_name . '/merge';
  68. }
  69. /**
  70. * Implements hook_form().
  71. *
  72. * Menu callback; displays components to let user select one or more terms for merging and
  73. * let them be merged into another, specified term.
  74. */
  75. function term_merge_term_merge_form($form, $form_state, $vocabulary) {
  76. if (!isset($form_state['storage']['term_list'])) { // Create th merge form.
  77. $form = array(
  78. 'term_list' => array(
  79. '#type' => 'select',
  80. '#title' => t('Merge terms'),
  81. '#options' => _term_delete_form_replacement_term_options($vocabulary->vid, 0, FALSE),
  82. '#multiple' => TRUE,
  83. '#required' => TRUE,
  84. '#attributes' => array('size' => 15),
  85. '#prefix' => '<div class="merge-container clearfix"><div class="terms-selector">',
  86. ),
  87. 'replacement_term' => array(
  88. '#type' => 'select',
  89. '#title' => t('Into'),
  90. '#description' => t('Cannot be any of the terms selected in the list to the left.'),
  91. '#options' => _term_delete_form_replacement_term_options($vocabulary->vid, 0, TRUE),
  92. '#prefix' => '</div><div class="merge-selectors">',
  93. ),
  94. 'replacement_term_new' => array(
  95. '#type' => 'textfield',
  96. '#title' => t('Name of new term'),
  97. '#description' => t('A new term will be created with the specified name.'),
  98. '#suffix' => '</div>',
  99. ),
  100. 'keep_merged' => array(
  101. '#type' => 'checkbox',
  102. '#title' => t('Only merge occurrences'),
  103. '#description' => t('Check this if you only want to merge occurrences of the merged terms leaving them as they are in the vocabulary.'),
  104. '#prefix' => '</div>',
  105. ),
  106. '#vocabulary' => $vocabulary,
  107. 'merge_redirect_path' => array(
  108. '#type' => 'value',
  109. '#value' => 'admin/structure/taxonomy/' . $vocabulary->machine_name,
  110. ),
  111. );
  112. // Adds the .js and .css used by form.
  113. $form['#after_build'] = array('_term_merge_form_attach');
  114. }
  115. else { // Let the user confirm the deletion.
  116. $form = array(
  117. 'confirm_markup' => array(
  118. '#markup' => _term_merge_get_confirm_merge_markup($form_state),
  119. '#prefix' => '<div>',
  120. '#suffix' => '</div>',
  121. )
  122. );
  123. }
  124. $form['actions'] = array (
  125. 'submit' => array(
  126. '#type' => 'submit',
  127. '#value' => t('Merge'),
  128. ),
  129. 'cancel' => array(
  130. '#type' => 'link',
  131. '#title' => t('Cancel'),
  132. '#href' => 'admin/structure/taxonomy/' . $vocabulary->machine_name,
  133. )
  134. );
  135. return $form;
  136. }
  137. /**
  138. * Validation handler for term_merge_term_merge_form().
  139. */
  140. function term_merge_term_merge_form_validate($form, &$form_state) {
  141. $form_values = $form_state['values'];
  142. if (!isset($form_state['storage']['term_list'])) {
  143. // Convert the array of terms to merge into a normally keyed array.
  144. $form_values['term_list'] = array_values($form_values['term_list']);
  145. if ($form_values['replacement_term'] == '0' &&
  146. empty($form_values['replacement_term_new'])) {
  147. form_set_error('replacement_term_new', t('You must enter a name for the new term.'));
  148. }
  149. elseif ($pos = array_search($form_values['replacement_term'], $form_values['term_list'])) {
  150. array_splice($form_values['term_list'], $pos, 1);
  151. }
  152. }
  153. }
  154. /**
  155. * Submit handler for term_merge_term_merge_form().
  156. *
  157. * Collects data about what terms to merge into what term and sends it to term_merge().
  158. */
  159. function term_merge_term_merge_form_submit($form, &$form_state) {
  160. if (!isset($form_state['storage']['term_list'])) { // Store values and rebuild form for merge confirmation.
  161. $form_values = $form_state['values'];
  162. $form_state['storage']['term_list'] = $form_values['term_list'];
  163. $form_state['storage']['replacement_term'] = $form_values['replacement_term'];
  164. $form_state['storage']['replacement_term_new'] = $form_values['replacement_term_new'];
  165. $form_state['storage']['merge_redirect_path'] = $form_values['merge_redirect_path'];
  166. $form_state['storage']['keep_merged'] = $form_values['keep_merged'];
  167. $form_state['storage']['working_vocabulary'] = $form['#vocabulary'];
  168. $form_state['rebuild'] = TRUE;
  169. }
  170. else { // Merge confirmed, do it!
  171. $replacement_term = $form_state['storage']['replacement_term'];
  172. $merged_terms = $form_state['storage']['term_list'];
  173. $replacement_term_new = $form_state['storage']['replacement_term_new'];
  174. // Create a new tid id the value of $replacement_term is equal to 0.
  175. if ($replacement_term == '0') {
  176. $new_term = _term_merge_term_create($replacement_term_new, $form_state['storage']['working_vocabulary'], $merged_terms);
  177. $dest_tid = $new_term->tid;
  178. }
  179. else { // Else, the value of $replacement_term contains the tid of the new term.
  180. $dest_tid = $replacement_term;
  181. }
  182. // Redirect user after merge.
  183. $form_state['redirect'] = $form_state['storage']['merge_redirect_path'];
  184. // Now merge.
  185. term_merge($merged_terms, $dest_tid, $form_state['storage']['keep_merged']);
  186. }
  187. }
  188. /**
  189. * Implements hook_form_FORM_ID_alter().
  190. *
  191. * Add fields to allow term merging on the confirm deletion state of the form_taxonomy_form_term form.
  192. */
  193. function term_merge_form_taxonomy_form_term_alter(&$form, &$form_state, $form_id) {
  194. // Only modify the form if it is in the "Confirm Delete" states.
  195. if (isset($form_state['confirm_delete']) && $form_state['confirm_delete'] === TRUE && user_access('term merge')) {
  196. $form['description']['#markup'] .= '<br /><br />' . t('You can replace any occurrences of the deleted term with another term by specifying the replacement below. This is useful when correcting typos, or to consolidate multiple, synonymous terms.') . '<br /><br />';
  197. $form['replacement_term_replace'] = array(
  198. '#type' => 'checkbox',
  199. '#title' => t('Replace deleted term with:'),
  200. '#prefix' => '<div>',
  201. );
  202. $form['replacement_term'] = array(
  203. '#type' => 'select',
  204. '#options' => _term_delete_form_replacement_term_options($form['#vocabulary']->vid, $form['#term']->tid, TRUE),
  205. '#suffix' => '</div>',
  206. );
  207. $form['replacement_term_new'] = array(
  208. '#type' => 'textfield',
  209. '#title' => t('Name of new term'),
  210. );
  211. $form['#after_build'] = array('_term_merge_form_attach');
  212. $form['#submit'] = array('term_merge_form_taxonomy_form_term_submit');
  213. $form['#validate'] = array('term_merge_form_taxonomy_form_term_validate');
  214. }
  215. }
  216. /**
  217. * Validation function for override of form_taxonomy_form_term (see above).
  218. *
  219. * If the user want's to create a new term, check to see if he has entered a name for it.
  220. */
  221. function term_merge_form_taxonomy_form_term_validate($form, &$form_state) {
  222. $form_values = $form_state['values'];
  223. if ($form_values['replacement_term'] == '0' &&
  224. empty($form_state['values']['replacement_term_new'])) {
  225. form_set_error('replacement_term_new', t('You must enter a name for the new term.'));
  226. }
  227. }
  228. /**
  229. * Submit function for alteration of form_taxonomy_form_term (see above).
  230. *
  231. * If the user choose to create a new term for merging, create and save a term with the entered name.
  232. * Call the merge function to merge the replacement term into the deleted term.
  233. */
  234. function term_merge_form_taxonomy_form_term_submit($form, &$form_state) {
  235. if ($form_state['values']['replacement_term_replace']) {
  236. $replacement_term = $form_state['values']['replacement_term'];
  237. /// Create a new tid id the value of $replacement_term is equal to 0.
  238. if ($replacement_term == '0') {
  239. $new_term = _term_merge_term_create(check_plain($form_state['values']['replacement_term_new']), $form['#vocabulary'], $form['#term']->tid);
  240. $dest_tid = $new_term->tid;
  241. }
  242. else { // Else, the value of $replacement_term contains the tid of the new term.
  243. $dest_tid = $replacement_term;
  244. }
  245. // Merge.
  246. term_merge($form['#term']->tid, $dest_tid, TRUE);
  247. }
  248. else {
  249. // Continue as the confirm deletion form would normally.
  250. taxonomy_term_confirm_delete_submit($form, $form_state);
  251. }
  252. }
  253. /**
  254. * Merge source terms into one destination term.
  255. * @param $source
  256. * A single term tid or an array of term tids to be merged.
  257. * @param $dest
  258. * The tid of the term to merge sources into.
  259. */
  260. function term_merge($source, $dest, $keep_merged) {
  261. // Create an array of source if it isn't already one.
  262. if (!is_array($source)) {
  263. $source = array($source);
  264. }
  265. $source = array_values($source);
  266. // Create a skeleton for the merging batch.
  267. $update_batch = array(
  268. 'title' => t('Merging terms'),
  269. 'operations' => array(
  270. array('_term_merge_batch_store_merged_terms', array(
  271. $keep_merged ? array() : $source,
  272. count($source),
  273. ))
  274. ),
  275. 'finished' => '_term_merge_finished',
  276. );
  277. // For every field existing on the site.
  278. foreach (field_info_fields() as $key => $field) {
  279. if ($field['type'] == 'taxonomy_term_reference') {
  280. $table_name = 'field_data_' . $key;
  281. $tid_field = $key . '_tid';
  282. $update_data = array();
  283. foreach ($source as $source_tid) {
  284. // Get data from fields previously containing a reference to the merged term.
  285. $fields_result = db_select($table_name, 'df')
  286. ->fields('df', array('entity_type', 'entity_id', 'delta'))
  287. ->condition($tid_field, $source_tid)
  288. ->execute();
  289. // Collect update data form the batch process and group them by their entity.
  290. foreach ($fields_result as $field_row) {
  291. $batch_key = $field_row->entity_type . '_' . $field_row->entity_id;
  292. $update_data[$batch_key][] = array(
  293. 'field_name' => $key,
  294. 'source_tid' => $source_tid,
  295. 'dest_tid' => $dest,
  296. );
  297. }
  298. }
  299. // Create a batch processing step for every entity that needs an update.
  300. foreach ($update_data as $key => $batch_data) {
  301. $delimiter_pos = strripos($key, '_');
  302. $type = drupal_substr($key, 0, $delimiter_pos);
  303. $id = drupal_substr($key, $delimiter_pos + 1);
  304. $batch_data = array(
  305. 'entity_type' => $type,
  306. 'entity_id' => $id,
  307. 'data' => $batch_data
  308. );
  309. $update_batch['operations'][] = array(
  310. '_term_merge_insert_field_values',
  311. array($batch_data)
  312. );
  313. }
  314. }
  315. }
  316. // Initialize the batch process.
  317. batch_set($update_batch);
  318. }
  319. /**
  320. * Creates a new term with the specified name. The new term will have the same
  321. * parent as the merged terms as long as long as they all a common parent.
  322. */
  323. function _term_merge_term_create($name, $vocabulary, $merged_terms) {
  324. $new_term = new stdClass();
  325. if (!is_array($merged_terms)) {
  326. $merged_terms = array(0 => $merged_terms);
  327. }
  328. // Get parent of merged terms.
  329. $merged_parent_query = db_select('taxonomy_term_hierarchy', 'tth')
  330. ->fields('tth', array('parent'));
  331. $conditions = db_or();
  332. foreach ($merged_terms as $merged_tid) {
  333. $conditions->condition('tid', $merged_tid);
  334. }
  335. $merged_parent_result = $merged_parent_query->condition($conditions)
  336. ->execute()->fetchCol();
  337. if (count($parent = array_unique($merged_parent_result)) == 1) {
  338. $parent_tid = $parent[0];
  339. }
  340. else {
  341. $parent_tid = 0;
  342. }
  343. $term = new stdClass();
  344. $term->name = $name;
  345. $term->vid = $vocabulary->vid;
  346. $term->parent = $parent_tid;
  347. $term->vocabulary_machine_name = $vocabulary->machine_name;
  348. $term->description = '';
  349. taxonomy_term_save((object) $term);
  350. return $term;
  351. }
  352. /**
  353. * Stores the merged terms in the context of the batch operation,
  354. * I need them in the finish function of the batch operation.
  355. */
  356. function _term_merge_batch_store_merged_terms($merged_terms_delete, $num_merged_terms, &$context) {
  357. $context['results']['merged_terms_delete'] = $merged_terms_delete;
  358. $context['results']['num_merged_terms'] = $num_merged_terms;
  359. }
  360. /**
  361. * Batch operation for adding field values into entities.
  362. *
  363. * Loads the entity specified in $update_data and add the term reference
  364. * to all fields specified in $update_data['data'].
  365. */
  366. function _term_merge_insert_field_values($update_data, &$context) {
  367. // Extract entity information.
  368. $entity_type = $update_data['entity_type'];
  369. $entity_id = $update_data['entity_id'];
  370. // Load the entity.
  371. $entity = entity_load($entity_type, array($entity_id));
  372. $entity = $entity[$entity_id];
  373. $context['message'] = 'Merging terms in fields of ' . $entity_type . ' ' . $entity->title . '.';
  374. $target_merged = FALSE;
  375. foreach ($update_data['data'] as $i => &$update_data_arr) {
  376. $update_data_arr = array_reverse($update_data_arr);
  377. $field_lang = field_language('node', $entity, $update_data_arr['field_name']);
  378. $field_values = &$entity->{$update_data_arr['field_name']}[$field_lang];
  379. foreach ($field_values as $i => $value) {
  380. if ($value['tid'] == $update_data_arr['source_tid']) {
  381. if (!$target_merged) {
  382. $field_values[$i]['tid'] = $update_data_arr['dest_tid']->tid;
  383. $target_merged = TRUE;
  384. }
  385. // Any more occurrences of the source tid will simply be removed.
  386. // We don't want duplicates.
  387. else {
  388. array_splice($field_values, $i, 1);
  389. }
  390. // If target tid is one of the source tids, remove it from the array
  391. // of terms that will be removed at the end of the process.
  392. if($update_data_arr['source_tid']== $update_data_arr['dest_tid']->tid) {
  393. foreach ($context['results']['merged_terms_delete'] as $i => $merged_term) {
  394. if ($merged_term == $update_data_arr['source_tid']) {
  395. array_splice($context['results']['merged_terms_delete'], $i, 1);
  396. }
  397. }
  398. }
  399. $context['results'][] = 'Merged ' . $update_data_arr['source_tid'] . ' with '
  400. . $update_data_arr['dest_tid']->tid . ' in ' . $update_data_arr['field_name']
  401. . ' of ' . $entity_type . ' ' . $entity_id;
  402. break;
  403. }
  404. }
  405. }
  406. if (empty($context['sandbox'])) {
  407. $context['sandbox']['progress'] = 0;
  408. }
  409. $context['sandbox']['progress']++;
  410. $context['finished'] = $context['sandbox']['progress']/$context['results']['num_merged_terms'];
  411. // Save the new field values if something has changed.
  412. if ($target_merged) {
  413. field_attach_update($entity_type, $entity);
  414. }
  415. }
  416. /**
  417. * The merge batch operation was finished.
  418. */
  419. function _term_merge_finished($success, $results, $operations) {
  420. if ($success) {
  421. $message = format_plural($results['num_merged_terms'], 'One term merged.', '@count terms merged.');
  422. $message .= '<br />';
  423. $message .= format_plural(count($results) - 2, 'One term occurrence merged.', '@count term occurrences merged.');
  424. if (count($results['merged_terms_delete']) > 0) {
  425. $message .= '<br />';
  426. $message .= format_plural(count($results['merged_terms_delete']), 'One term deleted', '@count terms deleted.');
  427. }
  428. }
  429. else {
  430. $message = t('Finished with an error.');
  431. }
  432. drupal_set_message($message);
  433. // Delete merged terms on success. We don't want to do this earlier if something went wrong during the batch process.
  434. if ($success) {
  435. foreach ($results['merged_terms_delete'] as $merged_term) {
  436. taxonomy_term_delete($merged_term);
  437. }
  438. }
  439. }
  440. /**
  441. * Returns the markup text for the confirmation message of term merging.
  442. */
  443. function _term_merge_get_confirm_merge_markup($form_state) {
  444. $form_values = $form_state['values'];
  445. $terms = taxonomy_term_load_multiple($form_values['term_list']);
  446. $dest_term_name = ($dest_term = taxonomy_term_load($form_values['replacement_term'])) ?
  447. $dest_term->name : $form_values['replacement_term_new'];
  448. $merged_names = '';
  449. foreach (array_values($terms) as $i => $term) {
  450. $merged_names .= $term->name;
  451. if ($i < count($terms) - 2) {
  452. $merged_names .= ', ';
  453. }
  454. else if ($i == count($terms) - 2) {
  455. $merged_names .= ' & ';
  456. }
  457. }
  458. $output = 'Are you sure you want to merge <b>%term_names</b> with <b>%destination_term</b>'
  459. . (($form_state['storage']['replacement_term_new']) ? ' (new)' : '')
  460. . ' ? ';
  461. if ($form_values['keep_merged']) {
  462. $output .= 'Due to your choice, the merged terms will not be deleted from their vocabulary.<br />&nbsp;';
  463. }
  464. else {
  465. $output .= '<br /><u>All merged terms will be deleted</u>!<br />&nbsp;';
  466. }
  467. $output = t($output, array('%term_names' => $merged_names, '%destination_term' => $dest_term_name));
  468. return $output;
  469. }
  470. /**
  471. * Returns values for the replacement_term select box in the form (see form builder at top).
  472. * Don't return the value for the term that will be merged.
  473. */
  474. function _term_delete_form_replacement_term_options($vid, $merged_term_tid, $add_new_option) {
  475. $tree = taxonomy_get_tree($vid);
  476. foreach ($tree as $i => $term) {
  477. if ($merged_term_tid != $term->tid) {
  478. $options[$term->tid] = $term->name;
  479. }
  480. }
  481. if ($add_new_option) {
  482. $options['0'] = t('New term, specified below');
  483. }
  484. return $options;
  485. }
  486. /**
  487. * Add necessary JavaScript and css to the form.
  488. */
  489. function _term_merge_form_attach($form_element) {
  490. if ($form_element['#id'] == 'term-merge-term-merge-form') {
  491. drupal_add_js(drupal_get_path('module', 'term_merge') . '/term_merge.js');
  492. }
  493. elseif ($form_element['#id'] == 'taxonomy-form-term') {
  494. drupal_add_js(drupal_get_path('module', 'term_merge') . '/term_merge_deletion.js');
  495. }
  496. drupal_add_css(drupal_get_path('module', 'term_merge') . '/term_merge.css');
  497. return $form_element;
  498. }