term_merge.module 28 KB

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