term_merge.module 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. <?php
  2. /**
  3. * @file
  4. * Provide functionality for merging taxonomy terms one into another.
  5. */
  6. /**
  7. * Constant to use in term merge action.
  8. *
  9. * Constant denotes "do not create HTTP redirect" logic for term merge action.
  10. *
  11. * @var int
  12. */
  13. define('TERM_MERGE_NO_REDIRECT', -1);
  14. /**
  15. * Implements hook_menu().
  16. */
  17. function term_merge_menu() {
  18. $items = array();
  19. $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/merge'] = array(
  20. 'title' => 'Merge terms',
  21. 'page callback' => 'drupal_get_form',
  22. 'page arguments' => array('term_merge_form', 3),
  23. 'access callback' => 'term_merge_access',
  24. 'access arguments' => array(3),
  25. 'file' => 'term_merge.pages.inc',
  26. 'type' => MENU_LOCAL_TASK,
  27. );
  28. $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/merge/default'] = array(
  29. 'title' => 'Default',
  30. 'type' => MENU_DEFAULT_LOCAL_TASK,
  31. );
  32. $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/merge/duplicates'] = array(
  33. 'title' => 'Merge Duplicate Terms',
  34. 'page callback' => 'drupal_get_form',
  35. 'page arguments' => array('term_merge_duplicates_form', 3),
  36. 'access callback' => 'term_merge_access',
  37. 'access arguments' => array(3),
  38. 'file' => 'term_merge.pages.inc',
  39. 'type' => MENU_LOCAL_TASK,
  40. );
  41. $items['taxonomy/term/%taxonomy_term/merge'] = array(
  42. 'title' => 'Merge Terms',
  43. 'page callback' => 'drupal_get_form',
  44. 'page arguments' => array('term_merge_form', NULL, 2),
  45. 'access callback' => 'term_merge_access',
  46. 'access arguments' => array(NULL, 2),
  47. 'file' => 'term_merge.pages.inc',
  48. 'type' => MENU_LOCAL_TASK,
  49. 'weight' => 10,
  50. );
  51. $items['taxonomy/term/%taxonomy_term/merge/default'] = array(
  52. 'title' => 'Default',
  53. 'type' => MENU_DEFAULT_LOCAL_TASK,
  54. );
  55. $items['taxonomy/term/%taxonomy_term/merge/duplicates'] = array(
  56. 'title' => 'Merge Duplicate Terms',
  57. 'page callback' => 'drupal_get_form',
  58. 'page arguments' => array('term_merge_duplicates_form', NULL, 2),
  59. 'access callback' => 'term_merge_access',
  60. 'access arguments' => array(NULL, 2),
  61. 'file' => 'term_merge.pages.inc',
  62. 'type' => MENU_LOCAL_TASK,
  63. );
  64. $items['term-merge/autocomplete/term-trunk/%taxonomy_vocabulary_machine_name'] = array(
  65. 'title' => 'Autocomplete Term Merge form term trunk',
  66. 'page callback' => 'term_merge_form_term_trunk_widget_autocomplete_autocomplete',
  67. 'page arguments' => array(3),
  68. 'access callback' => 'term_merge_access',
  69. 'access arguments' => array(3),
  70. 'file' => 'term_merge.pages.inc',
  71. 'type' => MENU_CALLBACK,
  72. );
  73. return $items;
  74. }
  75. /**
  76. * Implements hook_admin_paths().
  77. */
  78. function term_merge_admin_paths() {
  79. return array(
  80. 'taxonomy/term/*/merge' => TRUE,
  81. 'taxonomy/term/*/merge/*' => TRUE,
  82. );
  83. }
  84. /**
  85. * Implements hook_permission().
  86. */
  87. function term_merge_permission() {
  88. $permissions = array();
  89. $permissions['merge terms'] = array(
  90. 'title' => t('Merge any terms'),
  91. 'description' => t('Gives the ability to merge any taxonomy terms.'),
  92. );
  93. $vocabularies = taxonomy_get_vocabularies();
  94. foreach ($vocabularies as $vocabulary) {
  95. $permissions['merge ' . $vocabulary->machine_name . ' terms'] = array(
  96. 'title' => t('Merge %name vocabulary terms', array('%name' => $vocabulary->name)),
  97. 'description' => t('Gives the ability to merge taxonomy terms that belong to vocabulary %name.', array('%name' => $vocabulary->name)),
  98. );
  99. }
  100. return $permissions;
  101. }
  102. /**
  103. * Implements hook_action_info().
  104. */
  105. function term_merge_action_info() {
  106. return array(
  107. 'term_merge_action' => array(
  108. 'type' => 'taxonomy',
  109. 'label' => t('Merge term'),
  110. 'configurable' => TRUE,
  111. 'behavior' => array('changes_property'),
  112. ),
  113. );
  114. }
  115. /**
  116. * Implements hook_help().
  117. */
  118. function term_merge_help($path, $arg) {
  119. switch ($path) {
  120. // Main module help for the Term Merge module.
  121. case 'admin/help#term_merge':
  122. return '<p>' . t('Allows you to merge multiple terms into one and and at the same time update all fields referencing to the old ones.') . '</p>';
  123. break;
  124. }
  125. }
  126. /**
  127. * Implements hook_ctools_plugin_type().
  128. */
  129. function term_merge_ctools_plugin_type() {
  130. $plugins = array();
  131. $plugins['duplicate_suggestion'] = array(
  132. 'defaults' => array(
  133. 'title' => NULL,
  134. 'description' => NULL,
  135. 'hash callback' => NULL,
  136. 'weight' => 0,
  137. ),
  138. );
  139. return $plugins;
  140. }
  141. /**
  142. * Implements hook_ctools_plugin_directory().
  143. */
  144. function term_merge_ctools_plugin_directory($owner, $plugin_type) {
  145. switch ($owner) {
  146. case 'term_merge':
  147. switch ($plugin_type) {
  148. case 'duplicate_suggestion':
  149. return 'plugins/' . $plugin_type;
  150. }
  151. break;
  152. }
  153. }
  154. /**
  155. * Access callback for term merge action.
  156. *
  157. * Decide whether to grant access to an account for an operation of merging
  158. * terms in a vocabulary.
  159. *
  160. * @param object $vocabulary
  161. * Fully loaded vocabulary object inside of which term merge operation is
  162. * requested for access granting
  163. * @param object $term
  164. * Fully loaded term object which belongs to the vocabulary inside of which
  165. * term merge operation is requested for access granting. You are supposed
  166. * only to provide either $vocabulary or $term. Depending on your context it
  167. * might be more convenient for you to provide $term, and on other occasions
  168. * it might be $vocabulary of more convenience
  169. * @param object $account
  170. * Fully loaded user object who is requesting access granting for the
  171. * operation of term merging. You may provide nothing here, and the currently
  172. * logged in user will be considered
  173. *
  174. * @return bool
  175. * Whether the access for term merging operation has been granted
  176. */
  177. function term_merge_access($vocabulary = NULL, $term = NULL, $account = NULL) {
  178. if (is_null($vocabulary) && is_null($term)) {
  179. // This is no go, at least one of these 2 has to be provided.
  180. return FALSE;
  181. }
  182. if (is_null($account)) {
  183. // Falling back on currently logged in user.
  184. $account = $GLOBALS['user'];
  185. }
  186. if (is_null($vocabulary)) {
  187. $vocabulary = taxonomy_vocabulary_load($term->vid);
  188. }
  189. return user_access('merge terms', $account) || user_access('merge ' . $vocabulary->machine_name . ' terms', $account);
  190. }
  191. /**
  192. * Generate the configuration form for action "Term merge".
  193. */
  194. function term_merge_action_form($context) {
  195. $form = array();
  196. $form['displaimer'] = array(
  197. '#markup' => '<b>' . t('Sorry, currently Term Merge action is not supported via user interface. Please, contact the maintainers at the official website if you need it enabled via user interface.') . '</b>',
  198. );
  199. return $form;
  200. }
  201. /**
  202. * Form submission function.
  203. *
  204. * Store information about configurable action.
  205. */
  206. function term_merge_action_submit($form, &$form_state) {
  207. // We don't have enabled UI for this action. It's just a dummy function.
  208. return array();
  209. }
  210. /**
  211. * Action function. Perform action "Term Merge".
  212. */
  213. function term_merge_action($object, $context) {
  214. $term_branch = $object;
  215. $term_trunk = taxonomy_term_load($context['term_trunk']);
  216. $vocabulary = taxonomy_vocabulary_load($term_branch->vid);
  217. $term_branch_children = array();
  218. foreach (taxonomy_get_tree($term_branch->vid, $term_branch->tid) as $term) {
  219. $term_branch_children[] = $term->tid;
  220. }
  221. if ($term_branch->vid != $term_trunk->vid) {
  222. watchdog('term_merge', 'Trying to merge 2 terms (%term_branch, %term_trunk) from different vocabularies', array(
  223. '%term_branch' => $term_branch->name,
  224. '%term_trunk' => $term_trunk->name,
  225. ), WATCHDOG_WARNING);
  226. return;
  227. }
  228. if ($term_branch->tid == $term_trunk->tid) {
  229. watchdog('term_merge', 'Trying to merge a term %term into itself.', array('%term' => $term_branch->name), WATCHDOG_WARNING);
  230. return;
  231. }
  232. if (in_array($term_trunk->tid, $term_branch_children)) {
  233. watchdog('term_merge', 'Trying to merge a term %term_branch into its child %term_trunk.', array(
  234. '%term_branch' => $term_branch->name,
  235. '%term_trunk' => $term_trunk->name,
  236. ), WATCHDOG_WARNING);
  237. return;
  238. }
  239. // Defining some default values.
  240. if (!isset($context['term_branch_keep'])) {
  241. // It's easier to manually delete the unwanted terms, rather than
  242. // search for your DB back up. So by default we keep the term branch.
  243. $context['term_branch_keep'] = TRUE;
  244. }
  245. if (!isset($context['merge_fields'])) {
  246. // Initializing it with an empty array if client of this function forgot to
  247. // provide info about what fields to merge.
  248. $context['merge_fields'] = array();
  249. }
  250. if (!isset($context['keep_only_unique'])) {
  251. // Seems logical that mostly people will prefer to keep only one value in
  252. // term reference field per taxonomy term.
  253. $context['keep_only_unique'] = TRUE;
  254. }
  255. if (!isset($context['redirect']) || !module_exists('redirect')) {
  256. // This behavior requires Redirect module installed and enabled.
  257. $context['redirect'] = TERM_MERGE_NO_REDIRECT;
  258. }
  259. if (!isset($context['synonyms']) || !module_exists('synonyms')) {
  260. // This behavior requires Synonyms module installed and enabled.
  261. $context['synonyms'] = array();
  262. }
  263. // Calling a hook, this way we let whoever else to react and do his own extra
  264. // logic when merging of terms occurs. We prefer to call it before we handle
  265. // our own logic, because our logic might delete $term_branch and maybe a
  266. // module that implements this hook needs this term not deleted yet.
  267. module_invoke_all('term_merge', $term_trunk, $term_branch, $context);
  268. if (!empty($context['merge_fields'])) {
  269. // "Merging" the fields from $term_branch into $term_trunk where it is
  270. // possible.
  271. foreach ($context['merge_fields'] as $field_name) {
  272. // Getting the list of available languages for this field.
  273. $languages = array();
  274. if (isset($term_trunk->$field_name) && is_array($term_trunk->$field_name)) {
  275. $languages = array_merge($languages, array_keys($term_trunk->$field_name));
  276. }
  277. if (isset($term_branch->$field_name) && is_array($term_branch->$field_name)) {
  278. $languages = array_merge($languages, array_keys($term_branch->$field_name));
  279. }
  280. $languages = array_unique($languages);
  281. // Merging the data of both terms into $term_trunk.
  282. foreach ($languages as $language) {
  283. if (!isset($term_trunk->{$field_name}[$language])) {
  284. $term_trunk->{$field_name}[$language] = array();
  285. }
  286. if (!isset($term_branch->{$field_name}[$language])) {
  287. $term_branch->{$field_name}[$language] = array();
  288. }
  289. $items = array_merge($term_trunk->{$field_name}[$language], $term_branch->{$field_name}[$language]);
  290. $unique_items = array();
  291. foreach ($items as $item) {
  292. $unique_items[serialize($item)] = $item;
  293. }
  294. $items = array_values($unique_items);
  295. $term_trunk->{$field_name}[$language] = $items;
  296. }
  297. }
  298. // And now we can save $term_trunk after shifting all the fields from
  299. // $term_branch.
  300. taxonomy_term_save($term_trunk);
  301. }
  302. $result = array();
  303. foreach (term_merge_fields_with_foreign_key('taxonomy_term_data', 'tid') as $field) {
  304. $result[$field['field_name']] = array();
  305. $query = new EntityFieldQuery();
  306. // Making sure we search in the entire scope of entities.
  307. $query->addMetaData('account', user_load(1));
  308. $query->fieldCondition($field['field_name'], $field['term_merge_field_column'], $term_branch->tid);
  309. $_result = $query->execute();
  310. $result[$field['field_name']]['entities'] = $_result;
  311. $result[$field['field_name']]['column'] = $field['term_merge_field_column'];
  312. }
  313. // Now we load all entities that have fields pointing to $term_branch.
  314. foreach ($result as $field_name => $field_data) {
  315. $column = $field_data['column'];
  316. foreach ($field_data['entities'] as $entity_type => $v) {
  317. $ids = array_keys($v);
  318. $entities = entity_load($entity_type, $ids);
  319. // After we have loaded it, we alter the field to point to $term_trunk.
  320. foreach ($entities as $entity) {
  321. // What is more, we have to do it for every available language.
  322. foreach ($entity->$field_name as $language => $items) {
  323. // Keeping track of whether term trunk is already present in this
  324. // field in this language. This is useful for the option
  325. // 'keep_only_unique'.
  326. $is_trunk_added = FALSE;
  327. foreach ($entity->{$field_name}[$language] as $delta => $item) {
  328. if ($context['keep_only_unique'] && $is_trunk_added && in_array($item[$column], array($term_trunk->tid, $term_branch->tid))) {
  329. // We are instructed to keep only unique references and we already
  330. // have term trunk in this field, so we just unset value for this
  331. // delta.
  332. unset($entity->{$field_name}[$language][$delta]);
  333. }
  334. else {
  335. // Merging term references if necessary, and keep an eye on
  336. // whether we already have term trunk among this field values.
  337. switch ($item[$column]) {
  338. case $term_trunk->tid:
  339. $is_trunk_added = TRUE;
  340. break;
  341. case $term_branch->tid:
  342. $is_trunk_added = TRUE;
  343. $entity->{$field_name}[$language][$delta][$column] = $term_trunk->tid;
  344. break;
  345. }
  346. }
  347. }
  348. // Above in the code, while looping through all deltas of this field,
  349. // we might have unset some of the deltas to keep term references
  350. // unique. We should better keep deltas as a series of consecutive
  351. // numbers, because it is what it is supposed to be.
  352. $entity->{$field_name}[$language] = array_values($entity->{$field_name}[$language]);
  353. }
  354. // Integration with workbench_moderation module. Without this code, if
  355. // we save the node for which workbench moderation is enabled, then
  356. // it will go from "published" state into "draft". Though in fact we do
  357. // not change anything in the node and therefore it should persist in
  358. // published state.
  359. if (module_exists('workbench_moderation') && $entity_type == 'node') {
  360. $entity->workbench_moderation['updating_live_revision'] = TRUE;
  361. }
  362. // After updating all the references, save the entity.
  363. entity_save($entity_type, $entity);
  364. }
  365. }
  366. }
  367. // Adding term branch as synonym (Synonyms module integration).
  368. foreach ($context['synonyms'] as $synonym_field) {
  369. synonyms_add_entity_as_synonym($term_trunk, 'taxonomy_term', $synonym_field, $term_branch, 'taxonomy_term');
  370. }
  371. // It turned out we gotta go tricky with the Redirect module. If we create
  372. // redirection before deleting the branch term (if we are instructed to delete
  373. // in this action) redirect module will do its "auto-clean up" in
  374. // hook_entity_delete() and will delete our just created redirects. But at the
  375. // same time we have to get the path alias of the $term_branch before it gets
  376. // deleted. Otherwise the path alias will be deleted along with the term
  377. // itself. Similarly would be lost all redirects pointing to branch term
  378. // paths. We will redirect normal term path and its RSS feed.
  379. $redirect_paths = array();
  380. if ($context['redirect'] != TERM_MERGE_NO_REDIRECT) {
  381. $redirect_paths['taxonomy/term/' . $term_trunk->tid] = array(
  382. 'taxonomy/term/' . $term_branch->tid,
  383. );
  384. $redirect_paths['taxonomy/term/' . $term_trunk->tid . '/feed'] = array(
  385. 'taxonomy/term/' . $term_branch->tid . '/feed',
  386. );
  387. foreach ($redirect_paths as $redirect_destination => $redirect_sources) {
  388. // We create redirect from Drupal normal path, then we try to fetch its
  389. // alias. Lastly we collect a set of redirects that point to either of the
  390. // 2 former paths. Everything we were able to fetch will be redirecting to
  391. // the trunk term.
  392. $alias = drupal_get_path_alias($redirect_sources[0]);
  393. if ($alias != $redirect_sources[0]) {
  394. $redirect_sources[] = $alias;
  395. }
  396. $existing_redirects = array();
  397. foreach ($redirect_sources as $redirect_source) {
  398. foreach (redirect_load_multiple(array(), array('redirect' => $redirect_source)) as $v) {
  399. $existing_redirects[] = $v->source;
  400. }
  401. }
  402. $redirect_paths[$redirect_destination] = array_unique(array_merge($redirect_sources, $existing_redirects));
  403. }
  404. }
  405. if (!$context['term_branch_keep']) {
  406. // If we are going to delete branch term, we need firstly to make sure
  407. // all its children now have the parent of term_trunk.
  408. foreach (taxonomy_get_children($term_branch->tid, $vocabulary->vid) as $child) {
  409. $parents = taxonomy_get_parents($child->tid);
  410. // Deleting the parental link to the term that is being merged.
  411. unset($parents[$term_branch->tid]);
  412. // And putting the parental link to the term that we merge into.
  413. $parents[$term_trunk->tid] = $term_trunk;
  414. $parents = array_unique(array_keys($parents));
  415. $child->parent = $parents;
  416. taxonomy_term_save($child);
  417. }
  418. // Views module integration. We update all Views taxonomy filter handlers
  419. // configured to filter on term branch to filter on term trunk now, since
  420. // the former becomes the latter.
  421. if (module_exists('views')) {
  422. $views = views_get_all_views();
  423. foreach ($views as $view) {
  424. // For better efficiency, we keep track of whether we have updated
  425. // anything in a view, and thus whether we need to save it.
  426. $needs_saving = FALSE;
  427. // Even worse, we have to go through each display of each view.
  428. foreach ($view->display as $display_id => $display) {
  429. $view->set_display($display_id);
  430. $filters = $view->display_handler->get_handlers('filter');
  431. foreach ($filters as $filter_id => $filter_handler) {
  432. // Currently we know how to update filters only of this particular
  433. // class.
  434. if (get_class($filter_handler) == 'views_handler_filter_term_node_tid') {
  435. $filter = $view->get_item($display_id, 'filter', $filter_id);
  436. if (isset($filter['value'][$term_branch->tid])) {
  437. // Substituting term branch with term trunk.
  438. unset($filter['value'][$term_branch->tid]);
  439. $filter['value'][$term_trunk->tid] = $term_trunk->tid;
  440. $view->set_item($display_id, 'filter', $filter_id, $filter);
  441. $needs_saving = TRUE;
  442. }
  443. }
  444. }
  445. }
  446. if ($needs_saving) {
  447. $view->save();
  448. }
  449. }
  450. }
  451. // We are instructed to delete the term branch after the merge,
  452. // and so we do.
  453. taxonomy_term_delete($term_branch->tid);
  454. }
  455. // Here we do the 2nd part of integration with the Redirect module. Once the
  456. // branch term has been deleted (if deleted), we can add the redirects
  457. // without being afraid that the redirect module will delete them in its
  458. // hook_entity_delete().
  459. foreach ($redirect_paths as $redirect_destination => $redirect_sources) {
  460. foreach ($redirect_sources as $redirect_source) {
  461. $redirect = redirect_load_by_source($redirect_source);
  462. if (!$redirect) {
  463. // Seems like redirect from such URI does not exist yet, we will create
  464. // it.
  465. $redirect = new stdClass();
  466. redirect_object_prepare($redirect, array(
  467. 'source' => $redirect_source,
  468. ));
  469. }
  470. $redirect->redirect = $redirect_destination;
  471. $redirect->status_code = $context['redirect'];
  472. redirect_save($redirect);
  473. }
  474. }
  475. watchdog('term_merge', 'Successfully merged term %term_branch into term %term_trunk in vocabulary %vocabulary. Context: @context', array(
  476. '%term_branch' => $term_branch->name,
  477. '%term_trunk' => $term_trunk->name,
  478. '%vocabulary' => $vocabulary->name,
  479. '@context' => var_export($context, 1),
  480. ));
  481. }
  482. /**
  483. * Merge terms one into another using batch API.
  484. *
  485. * @param array $term_branch
  486. * A single term tid or an array of term tids to be merged, aka term branches
  487. * @param int $term_trunk
  488. * The tid of the term to merge term branches into, aka term trunk
  489. * @param array $merge_settings
  490. * Array of settings that control how merging should happen. Currently
  491. * supported settings are:
  492. * - term_branch_keep: (bool) Whether the term branches should not be
  493. * deleted, also known as "merge only occurrences" option
  494. * - merge_fields: (array) Array of field names whose values should be
  495. * merged into the values of corresponding fields of term trunk (until
  496. * each field's cardinality limit is reached)
  497. * - keep_only_unique: (bool) Whether after merging within one field only
  498. * unique taxonomy term references should be kept in other entities. If
  499. * before merging your entity had 2 values in its taxonomy term reference
  500. * field and one was pointing to term branch while another was pointing to
  501. * term trunk, after merging you will end up having your entity
  502. * referencing to the same term trunk twice. If you pass TRUE in this
  503. * parameter, only a single reference will be stored in your entity after
  504. * merging
  505. * - redirect: (int) HTTP code for redirect from $term_branch to
  506. * $term_trunk, 0 stands for the default redirect defined in Redirect
  507. * module. Use constant TERM_MERGE_NO_REDIRECT to denote not creating any
  508. * HTTP redirect. Note: this parameter requires Redirect module enabled,
  509. * otherwise it will be disregarded
  510. * - synonyms: (array) Array of field names of trunk term into which branch
  511. * terms should be added as synonyms (until each field's cardinality limit
  512. * is reached). Note: this parameter requires Synonyms module enabled,
  513. * otherwise it will be disregarded
  514. * - step: (int) How many term branches to merge per script run in batch. If
  515. * you are hitting time or memory limits, decrease this parameter
  516. */
  517. function term_merge($term_branch, $term_trunk, $merge_settings = array()) {
  518. // Older versions of this module had another interface of this function,
  519. // as backward capability we still support the older interface, instead of
  520. // supplying a $merge_settings array, it was supplying all the settings as
  521. // additional function arguments.
  522. // @todo: delete this backward capability at some point.
  523. if (!is_array($merge_settings)) {
  524. $merge_settings = array(
  525. 'term_branch_keep' => $merge_settings,
  526. );
  527. }
  528. // Create an array of sources if it isn't yet.
  529. if (!is_array($term_branch)) {
  530. $term_branch = array($term_branch);
  531. }
  532. // Creating a skeleton for the merging batch.
  533. $batch = array(
  534. 'title' => t('Merging terms'),
  535. 'operations' => array(
  536. array('_term_merge_batch_process', array(
  537. $term_branch,
  538. $term_trunk,
  539. $merge_settings,
  540. )),
  541. ),
  542. 'finished' => 'term_merge_batch_finished',
  543. 'file' => drupal_get_path('module', 'term_merge') . '/term_merge.batch.inc',
  544. );
  545. // Initialize the batch process.
  546. batch_set($batch);
  547. }
  548. /**
  549. * Retrieve information about ctools plugin of type 'duplicate suggestion'.
  550. *
  551. * @param string $id
  552. * Supply here ID of the cTool plugin information about which you want to
  553. * retrieve. You may omit this argument and then information on all duplicate
  554. * suggestion plugins will be returned
  555. *
  556. * @return array
  557. * Array of information on all available duplicate suggestion plugins or if
  558. * $id was provided, then information on that plugin
  559. */
  560. function term_merge_duplicate_suggestion($id = NULL) {
  561. ctools_include('plugins');
  562. $plugins = ctools_get_plugins('term_merge', 'duplicate_suggestion', $id);
  563. if (!$id) {
  564. // Sort the list of plugins by their weight.
  565. uasort($plugins, 'drupal_sort_weight');
  566. }
  567. return $plugins;
  568. }
  569. /**
  570. * Generate and return form elements that control behavior of merge action.
  571. *
  572. * Output of this function should be used in any form that merges terms,
  573. * ensuring unified interface. It should be used in conjunction with
  574. * term_merge_merge_options_submit(), which will process the submitted values
  575. * for you and return an array of merge settings.
  576. *
  577. * @param object $vocabulary
  578. * Fully loaded taxonomy vocabulary object in which merging occurs
  579. *
  580. * @return array
  581. * Array of form elements that allow controlling term merge action
  582. *
  583. * @see term_merge_merge_options_submit()
  584. */
  585. function term_merge_merge_options_elements($vocabulary) {
  586. // @todo: it would be nice to provide some ability to supply default values
  587. // for each setting.
  588. $form = array();
  589. // Getting bundle name and a list of fields attached to this bundle for
  590. // further use down below in the code while generating form elements.
  591. $bundle = field_extract_bundle('taxonomy_term', $vocabulary);
  592. $instances = field_info_instances('taxonomy_term', $bundle);
  593. $form['term_branch_keep'] = array(
  594. '#type' => 'checkbox',
  595. '#title' => t('Only merge occurrences'),
  596. '#description' => t('Check this if you want to only merge the occurrences of the specified terms, i.e. the terms will not be deleted from your vocabulary.'),
  597. );
  598. if (!empty($instances)) {
  599. $options = array();
  600. foreach ($instances as $instance) {
  601. $options[$instance['field_name']] = $instance['label'];
  602. }
  603. $form['merge_fields'] = array(
  604. '#type' => 'checkboxes',
  605. '#title' => t('Merge Term Fields'),
  606. '#description' => t('Check the fields whose values from branch terms you want to add to the values of corresponding fields of the trunk term. <b>Important note:</b> the values will be added until the cardinality limit for the selected fields is reached and only unique values for each field will be saved.'),
  607. '#options' => $options,
  608. );
  609. }
  610. $form['keep_only_unique'] = array(
  611. '#type' => 'checkbox',
  612. '#title' => t('Keep only unique terms after merging'),
  613. '#description' => t('Sometimes after merging you may end up having a node (or any other entity) pointing twice to the same taxonomy term, tick this checkbox if want to keep only unique terms in other entities after merging.'),
  614. '#default_value' => TRUE,
  615. );
  616. if (module_exists('redirect')) {
  617. $options = array(
  618. TERM_MERGE_NO_REDIRECT => t('No redirect'),
  619. 0 => t('Default (@default)', array(
  620. '@default' => variable_get('redirect_default_status_code', 301),
  621. )),
  622. ) + redirect_status_code_options();
  623. $form['redirect'] = array(
  624. // We respect access rights defined in redirect.module here.
  625. '#access' => user_access('administer redirects'),
  626. '#type' => 'select',
  627. '#title' => t('Create Redirect'),
  628. '#description' => t('If you want to create an HTTP redirect from your branch terms to the trunk term, please, choose the HTTP redirect code here.'),
  629. '#required' => TRUE,
  630. '#options' => $options,
  631. '#default_value' => TERM_MERGE_NO_REDIRECT,
  632. );
  633. }
  634. else {
  635. $form['redirect'] = array(
  636. '#markup' => t('Enable the module ' . l('Redirect', 'http://drupal.org/project/redirect') . ' if you want to do an HTTP redirect from your term branch to the term trunk.'),
  637. );
  638. }
  639. if (module_exists('synonyms')) {
  640. $options = array();
  641. foreach (synonyms_synonyms_fields($vocabulary) as $field_name) {
  642. $options[$field_name] = $instances[$field_name]['label'];
  643. }
  644. $form['synonyms'] = array(
  645. '#type' => 'checkboxes',
  646. '#title' => t('Add as Synonyms'),
  647. '#description' => t('Synonyms module allows you to add branch terms as synonyms into any of fields, enabled as sources of synonyms in vocabulary. Check the fields into which you would like to add branch terms as synonyms. <b>Important note:</b> the values will be added until the cardinality limit for the selected fields is reached.'),
  648. '#options' => $options,
  649. );
  650. }
  651. else {
  652. $form['synonyms'] = array(
  653. '#markup' => t('Enable the module ' . l('Synonyms', 'http://drupal.org/project/synonyms') . ' if you want to be able to add branch terms as synonyms into a field of your trunk term.'),
  654. );
  655. }
  656. $form['step'] = array(
  657. '#type' => 'textfield',
  658. '#title' => t('Step'),
  659. '#description' => t('Please, specify how many terms to process per script run in batch. If you are hitting time or memory limits in your PHP, decrease this number.'),
  660. '#default_value' => 40,
  661. '#required' => TRUE,
  662. '#element_validate' => array('element_validate_integer_positive'),
  663. );
  664. return $form;
  665. }
  666. /**
  667. * Return merge settings array.
  668. *
  669. * Output of this function should be used for supplying into term_merge()
  670. * function or for triggering actions_do('term_merge_action', ...) action. This
  671. * function should be invoked in a form submit handler for a form that used
  672. * term_merge_merge_options_elements() for generating merge settings elements.
  673. * It will process data and return an array of merge settings, according to the
  674. * data user has submitted in your form.
  675. *
  676. * @param array $merge_settings_element
  677. * That part of form that was generated by term_merge_merge_options_elements()
  678. * @param array $form_state
  679. * Form state array of the submitted form
  680. * @param array $form
  681. * Form array of the submitted form
  682. *
  683. * @return array
  684. * Array of merge settings that can be used for calling term_merge() or
  685. * invoking 'term_merge_action' action
  686. *
  687. * @see term_merge_merge_options_elements()
  688. */
  689. function term_merge_merge_options_submit($merge_settings_element, &$form_state, $form) {
  690. $merge_settings = array(
  691. 'term_branch_keep' => (bool) $merge_settings_element['term_branch_keep']['#value'],
  692. 'merge_fields' => isset($merge_settings_element['merge_fields']['#value']) ? array_values(array_filter($merge_settings_element['merge_fields']['#value'])) : array(),
  693. 'keep_only_unique' => (bool) $merge_settings_element['keep_only_unique']['#value'],
  694. 'redirect' => isset($merge_settings_element['redirect']['#value']) ? $merge_settings_element['redirect']['#value'] : TERM_MERGE_NO_REDIRECT,
  695. 'synonyms' => isset($merge_settings_element['synonyms']['#value']) ? array_values(array_filter($merge_settings_element['synonyms']['#value'])) : array(),
  696. 'step' => (int) $merge_settings_element['step']['#value'],
  697. );
  698. return $merge_settings;
  699. }
  700. /**
  701. * Fetch all fields that have a foreign key to provided column.
  702. *
  703. * @param string $foreign_table
  704. * Name of the table for which to look among foreign keys of all the fields
  705. * @param string $foreign_column
  706. * Name of the column for which to look among foreign keys of all the fields
  707. *
  708. * @return array
  709. * Array of all fields that have the specified table and column within their
  710. * foreign keys. Each of the fields array will be extended to include the
  711. * following additional keys:
  712. * - term_merge_field_column: (string) Name of the field column that holds
  713. * foreign key to the provided table and column
  714. */
  715. function term_merge_fields_with_foreign_key($foreign_table, $foreign_column) {
  716. $fields = field_info_fields();
  717. $result = array();
  718. foreach ($fields as $field_name => $field_info) {
  719. foreach ($field_info['foreign keys'] as $foreign_key) {
  720. if ($foreign_key['table'] == $foreign_table) {
  721. $column = array_search($foreign_column, $foreign_key['columns']);
  722. if ($column) {
  723. $field_info['term_merge_field_column'] = $column;
  724. $result[] = $field_info;
  725. }
  726. }
  727. }
  728. }
  729. return $result;
  730. }