term_merge.pages.inc 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. <?php
  2. /**
  3. * @file
  4. * Menu page callbacks for Term Merge module.
  5. */
  6. /**
  7. * Menu callback.
  8. *
  9. * Allow user to specify which terms to be merged into which term and any
  10. * other settings needed for the term merge action.
  11. *
  12. * @param object $vocabulary
  13. * Fully loaded taxonomy vocabulary object
  14. * @param object $term
  15. * Fully loaded taxonomy term object that should be selected as the default
  16. * merge term in the form. If the $vocabulary is omitted, the vocabulary of
  17. * $term is considered
  18. *
  19. * @return array
  20. * Array of the form in Form API format
  21. */
  22. function term_merge_form($form, $form_state, $vocabulary = NULL, $term = NULL) {
  23. if (is_null($vocabulary)) {
  24. $vocabulary = taxonomy_vocabulary_load($term->vid);
  25. }
  26. // It's always handy to have the vocabulary by hand.
  27. $form['#vocabulary'] = $vocabulary;
  28. if (!isset($form_state['storage']['confirm'])) {
  29. // We are at the set up step.
  30. $tree = taxonomy_get_tree($vocabulary->vid);
  31. $term_branch_value = is_null($term) ? NULL : array($term->tid);
  32. if (variable_get('taxonomy_override_selector', FALSE) && module_exists('hs_taxonomy')) {
  33. // We use Hierarchical Select module if it's available and configured to
  34. // be used for taxonomy selects.
  35. $form['term_branch'] = array(
  36. '#type' => 'hierarchical_select',
  37. // @todo: figure out why #required => TRUE doesn't work.
  38. // As a matter of fact, this issue seems to cover our case.
  39. // http://drupal.org/node/1275862.
  40. //'#required' => TRUE,
  41. '#config' => array(
  42. 'module' => 'hs_taxonomy',
  43. 'params' => array(
  44. 'vid' => $vocabulary->vid,
  45. 'exclude_tid' => NULL,
  46. 'root_term' => FALSE,
  47. ),
  48. 'enforce_deepest' => 0,
  49. 'entity_count' => 0,
  50. 'require_entity' => 0,
  51. 'save_lineage' => 0,
  52. 'level_labels' => array(
  53. 'status' => 0,
  54. ),
  55. 'dropbox' => array(
  56. 'status' => 1,
  57. 'limit' => 0,
  58. ),
  59. 'editability' => array(
  60. 'status' => 0,
  61. ),
  62. 'resizable' => TRUE,
  63. 'render_flat_select' => 0,
  64. ),
  65. );
  66. }
  67. else {
  68. // Falling back on a simple <select>.
  69. $options = array();
  70. foreach ($tree as $v) {
  71. $options[$v->tid] = str_repeat('-', $v->depth) . $v->name . ' [tid: ' . $v->tid . ']';
  72. }
  73. $form['term_branch'] = array(
  74. '#type' => 'select',
  75. '#required' => TRUE,
  76. '#multiple' => TRUE,
  77. '#options' => $options,
  78. '#size' => 8,
  79. );
  80. }
  81. $form['term_branch'] = array(
  82. '#title' => t('Terms to Merge'),
  83. '#description' => t('Please, choose the terms you want to merge into another term.'),
  84. '#ajax' => array(
  85. 'callback' => 'term_merge_form_term_trunk',
  86. 'wrapper' => 'term-merge-form-term-trunk',
  87. 'method' => 'replace',
  88. 'effect' => 'fade',
  89. ),
  90. '#default_value' => $term_branch_value,
  91. ) + $form['term_branch'];
  92. if (is_null($form['term_branch']['#default_value'])) {
  93. unset($form['term_branch']['#default_value']);
  94. }
  95. $form['term_trunk'] = array(
  96. '#type' => 'fieldset',
  97. '#title' => t('Merge Into'),
  98. '#prefix' => '<div id="term-merge-form-term-trunk">',
  99. '#suffix' => '</div>',
  100. '#tree' => TRUE,
  101. );
  102. // Array of currently available widgets for choosing term trunk.
  103. $term_trunk_widget_options = array(
  104. 'autocomplete' => 'Autocomplete',
  105. );
  106. if (variable_get('taxonomy_override_selector', FALSE) && module_exists('hs_taxonomy')) {
  107. $term_trunk_widget_options['hs_taxonomy'] = t('Hierarchical Select');
  108. $term_trunk_widget = 'hs_taxonomy';
  109. }
  110. else {
  111. $term_trunk_widget_options['select'] = t('Select');
  112. $term_trunk_widget = 'select';
  113. }
  114. // If the vocabulary is too big, by default we want the trunk term widget to
  115. // be autocomplete instead of select or hs_taxonomy.
  116. if (count($tree) > 200) {
  117. $term_trunk_widget = 'autocomplete';
  118. }
  119. // Override the term trunk widget if settings are found in $form_state.
  120. if (isset($form_state['values']['term_trunk']['widget']) && in_array($form_state['values']['term_trunk']['widget'], array_keys($term_trunk_widget_options))) {
  121. $term_trunk_widget = $form_state['values']['term_trunk']['widget'];
  122. }
  123. $form['term_trunk']['widget'] = array(
  124. '#type' => 'radios',
  125. '#title' => t('Widget'),
  126. '#required' => TRUE,
  127. '#options' => $term_trunk_widget_options,
  128. '#default_value' => $term_trunk_widget,
  129. '#description' => t('Choose what widget you prefer for entering the term trunk.'),
  130. '#ajax' => array(
  131. 'callback' => 'term_merge_form_term_trunk',
  132. 'wrapper' => 'term-merge-form-term-trunk',
  133. 'method' => 'replace',
  134. 'effect' => 'fade',
  135. ),
  136. );
  137. // @todo:
  138. // There is a known bug, if user has selected something in one widget, and
  139. // then changes the widget, $form_states['values'] will hold the value for
  140. // term trunk form element in the format that is used in one widget, while
  141. // this value will be passed to another widget. This triggers different
  142. // unpleasant effects like showing tid instead of term's name or vice-versa.
  143. // I think we should just empty $form_state['values'] for the term trunk
  144. // form element when widget changes. Better ideas are welcome!
  145. $function = 'term_merge_form_term_trunk_widget_' . $term_trunk_widget;
  146. $function($form, $form_state, $vocabulary);
  147. // Ensuring the Merge Into form element has the same title no matter what
  148. // widget has been used.
  149. $form['term_trunk']['tid']['#title'] = t('Merge into');
  150. // Adding necessary options of merging.
  151. $form += term_merge_merge_options_elements($vocabulary);
  152. $form['actions'] = array(
  153. '#type' => 'actions',
  154. );
  155. $form['actions']['submit'] = array(
  156. '#type' => 'submit',
  157. '#value' => t('Submit'),
  158. );
  159. }
  160. else {
  161. // We are at the confirmation step.
  162. $count = count($form_state['values']['term_branch']);
  163. $question = format_plural($count, 'Are you sure want to merge 1 term?', 'Are you sure want to merge @count terms?');
  164. $form = confirm_form($form, $question, 'admin/structure/taxonomy/' . $vocabulary->machine_name);
  165. }
  166. return $form;
  167. }
  168. /**
  169. * Supportive function.
  170. *
  171. * Validate the term_merge_form(). Make sure term trunk is not among the
  172. * selected term branches or their children.
  173. */
  174. function term_merge_form_validate($form, &$form_state) {
  175. if (!isset($form_state['storage']['confirm'])) {
  176. // We only validate the 1st step of the form.
  177. $prohibited_trunks = array();
  178. foreach ($form_state['values']['term_branch'] as $term_branch) {
  179. $children = taxonomy_get_tree($form['#vocabulary']->vid, $term_branch);
  180. $prohibited_trunks[] = $term_branch;
  181. foreach ($children as $child) {
  182. $prohibited_trunks[] = $child->tid;
  183. }
  184. }
  185. if (in_array($form_state['values']['term_trunk']['tid'], $prohibited_trunks)) {
  186. form_error($form['term_trunk']['tid'], t('Trunk term cannot be one of the selected branch terms or their children.'));
  187. }
  188. }
  189. }
  190. /**
  191. * Submit handler for term_merge_form(). Merge terms one into another.
  192. */
  193. function term_merge_form_submit($form, &$form_state) {
  194. if (!isset($form_state['storage']['confirm'])) {
  195. // Since merging terms is an important operation, we better confirm user
  196. // really wants to do this.
  197. $form_state['storage']['confirm'] = 0;
  198. $form_state['rebuild'] = TRUE;
  199. $form_state['storage']['info'] = $form_state['values'];
  200. $form_state['storage']['merge_settings'] = term_merge_merge_options_submit($form, $form_state, $form);
  201. }
  202. else {
  203. // The user has confirmed merging. We pull up the submitted values.
  204. $form_state['values'] = $form_state['storage']['info'];
  205. term_merge(array_values($form_state['values']['term_branch']), $form_state['values']['term_trunk']['tid'], $form_state['storage']['merge_settings']);
  206. $form_state['redirect'] = array('taxonomy/term/' . $form_state['values']['term_trunk']['tid']);
  207. }
  208. }
  209. /**
  210. * Supportive function.
  211. *
  212. * Generate form elements for select widget for term trunk element of the
  213. * term_merge_form().
  214. *
  215. * @param object $vocabulary
  216. * Fully loaded taxonomy vocabulary object
  217. */
  218. function term_merge_form_term_trunk_widget_select(&$form, &$form_state, $vocabulary) {
  219. $tree = taxonomy_get_tree($vocabulary->vid);
  220. $options = array();
  221. foreach ($tree as $v) {
  222. $options[$v->tid] = str_repeat('-', $v->depth) . $v->name . ' [tid: ' . $v->tid . ']';
  223. }
  224. $term_branch_value = array();
  225. // Firstly trying to look up selected term branches in the default value of
  226. // term branch form element.
  227. if (isset($form['term_branch']['#default_value']) && is_array($form['term_branch']['#default_value'])) {
  228. $term_branch_value = $form['term_branch']['#default_value'];
  229. }
  230. if (isset($form_state['values']['term_branch']) && is_array($form_state['values']['term_branch'])) {
  231. $term_branch_value = $form_state['values']['term_branch'];
  232. }
  233. if (!empty($term_branch_value)) {
  234. // We have to make sure among term_trunk there is no term_branch or any of
  235. // their children.
  236. foreach ($term_branch_value as $v) {
  237. unset($options[$v]);
  238. foreach (taxonomy_get_tree($vocabulary->vid, $v) as $child) {
  239. unset($options[$child->tid]);
  240. }
  241. }
  242. }
  243. else {
  244. // Term branch has not been selected yet.
  245. $options = array();
  246. }
  247. $form['term_trunk']['tid'] = array(
  248. '#type' => 'select',
  249. '#required' => TRUE,
  250. '#description' => t('Choose into what term you want to merge.'),
  251. '#options' => $options,
  252. );
  253. }
  254. /**
  255. * Supportive function.
  256. *
  257. * Generate form element for hierarchical select widget for term trunk element
  258. * of the term_merge_form().
  259. *
  260. * @param object $vocabulary
  261. * Fully loaded taxonomy vocabulary object
  262. */
  263. function term_merge_form_term_trunk_widget_hs_taxonomy(&$form, &$form_state, $vocabulary) {
  264. $form['term_trunk']['tid'] = array(
  265. '#type' => 'hierarchical_select',
  266. '#description' => t('Please select a term to merge into.'),
  267. '#required' => TRUE,
  268. '#element_validate' => array('term_merge_form_trunk_term_widget_hs_taxonomy_validate'),
  269. '#config' => array(
  270. 'module' => 'hs_taxonomy',
  271. 'params' => array(
  272. 'vid' => $vocabulary->vid,
  273. 'exclude_tid' => NULL,
  274. 'root_term' => FALSE,
  275. ),
  276. 'enforce_deepest' => 0,
  277. 'entity_count' => 0,
  278. 'require_entity' => 0,
  279. 'save_lineage' => 0,
  280. 'level_labels' => array(
  281. 'status' => 0,
  282. ),
  283. 'dropbox' => array(
  284. 'status' => 0,
  285. ),
  286. 'editability' => array(
  287. 'status' => 0,
  288. ),
  289. 'resizable' => TRUE,
  290. 'render_flat_select' => 0,
  291. ),
  292. );
  293. }
  294. /**
  295. * Supportive function.
  296. *
  297. * Generate form elements for autocomplete widget for term trunk element of the
  298. * term_merge_form().
  299. *
  300. * @param object $vocabulary
  301. * Fully loaded taxonomy vocabulary object
  302. */
  303. function term_merge_form_term_trunk_widget_autocomplete(&$form, &$form_state, $vocabulary) {
  304. $form['term_trunk']['tid'] = array(
  305. '#type' => 'textfield',
  306. '#description' => t("Start typing in a term's name in order to get some suggestions."),
  307. '#required' => TRUE,
  308. '#autocomplete_path' => 'term-merge/autocomplete/term-trunk/' . $vocabulary->machine_name,
  309. '#element_validate' => array('term_merge_form_trunk_term_widget_autocomplete_validate'),
  310. );
  311. }
  312. /**
  313. * Supportive function.
  314. *
  315. * Validate form element of the autocomplete widget of term trunk element of
  316. * the form term_merge_form(). Make sure the entered string is a name of one of
  317. * the existing terms in the vocabulary where the merge occurs. If term is found
  318. * the function substitutes the name with its {taxonomy_term_data}.tid as it is
  319. * what is expected from a term trunk widget to provide in its value.
  320. */
  321. function term_merge_form_trunk_term_widget_autocomplete_validate($element, &$form_state, $form) {
  322. $term = taxonomy_get_term_by_name($element['#value'], $form['#vocabulary']->machine_name);
  323. if (!is_array($term) || empty($term)) {
  324. // Seems like the user has entered a non existing name in the autocomplete
  325. // textfield.
  326. form_error($element, t('There are no terms with name %name in the %vocabulary vocabulary.', array(
  327. '%name' => $element['#value'],
  328. '%vocabulary' => $form['#vocabulary']->name,
  329. )));
  330. }
  331. else {
  332. // We have to substitute the term's name with its tid in order to make this
  333. // widget consistent with the interface.
  334. $term = array_pop($term);
  335. form_set_value($element, $term->tid, $form_state);
  336. }
  337. }
  338. /**
  339. * Supportive function.
  340. *
  341. * Validate form element of the Hierarchical Select widget of term trunk element
  342. * of the form term_merge_form(). Convert the value from array to a single tid
  343. * integer value.
  344. */
  345. function term_merge_form_trunk_term_widget_hs_taxonomy_validate($element, &$form_state, $form) {
  346. $tid = 0;
  347. if (is_array($element['#value']) && !empty($element['#value'])) {
  348. $tid = (int) array_pop($element['#value']);
  349. }
  350. form_set_value($element, $tid, $form_state);
  351. }
  352. /**
  353. * Menu page callback function.
  354. *
  355. * Autocomplete callback function for the trunk term form element in the widget
  356. * of autocomplete. The code of this function was mainly copy-pasted from
  357. * Taxonomy autocomplete widget menu callback function.
  358. *
  359. * @param object $vocabulary
  360. * Fully loaded vocabulary object inside of which the terms are about to be
  361. * merged
  362. */
  363. function term_merge_form_term_trunk_widget_autocomplete_autocomplete($vocabulary) {
  364. // If the request has a '/' in the search text, then the menu system will have
  365. // split it into multiple arguments, recover the intended $tags_typed.
  366. $args = func_get_args();
  367. // Shift off the $vocabulary argument.
  368. array_shift($args);
  369. $tags_typed = implode('/', $args);
  370. // Querying database for suggestions.
  371. $query = db_select('taxonomy_term_data', 't');
  372. $tags_return = $query->addTag('translatable')
  373. ->addTag('term_access')
  374. ->fields('t', array('tid', 'name'))
  375. ->condition('t.vid', $vocabulary->vid)
  376. ->condition('t.name', '%' . db_like($tags_typed) . '%', 'LIKE')
  377. ->range(0, 10)
  378. ->execute()
  379. ->fetchAllKeyed();
  380. $term_matches = array();
  381. foreach ($tags_return as $tid => $name) {
  382. $n = $name;
  383. // Term names containing commas or quotes must be wrapped in quotes.
  384. if (strpos($name, ',') !== FALSE || strpos($name, '"') !== FALSE) {
  385. $n = '"' . str_replace('"', '""', $name) . '"';
  386. }
  387. $term_matches[$n] = check_plain($name . ' [tid: ' . $tid . ']');
  388. }
  389. drupal_json_output($term_matches);
  390. }
  391. /**
  392. * Ajax callback function.
  393. *
  394. * Used in term_merge_term_merge_form() to replace the term_trunk element
  395. * depending on already selected term_branch values.
  396. */
  397. function term_merge_form_term_trunk($form, $form_state) {
  398. return $form['term_trunk'];
  399. }
  400. /**
  401. * Generate 'term_merge_duplicates_form'.
  402. *
  403. * Allow merging terms with the same or similar names.
  404. *
  405. * @param object $vocabulary
  406. * Fully loaded taxonomy vocabulary object inside of which term merging
  407. * occurs, if this argument is omitted, then $parent_term is required and will
  408. * be used to obtain information about Taxonomy vocabulary
  409. * @param object $parent_term
  410. * Fully loaded taxonomy term object using which the function will pull up
  411. * the vocabulary inside of which term merging occurs. Duplicate terms will be
  412. * sought only among children of this term
  413. */
  414. function term_merge_duplicates_form($form, &$form_state, $vocabulary = NULL, $parent_term = NULL) {
  415. $form['#attached']['js'][drupal_get_path('module', 'term_merge') . '/js/duplicate.form.js'] = array();
  416. // Checking if we were not given vocabulary object, we will use term object to
  417. // obtain the former.
  418. if (!is_null($parent_term) && is_null($vocabulary)) {
  419. $vocabulary = taxonomy_vocabulary_load($parent_term->vid);
  420. }
  421. $tree = taxonomy_get_tree($vocabulary->vid, is_null($parent_term) ? 0 : $parent_term->tid);
  422. // Helpful and self explaining text that should help people understand what's
  423. // up.
  424. $form['help'] = array(
  425. '#markup' => '<p>' . t('Here you can merge terms with the same names. It is a useful tool against term-duplicates. If this tool is invoked on a term (not on the entire vocabulary), duplicate terms will be sought only among children of that term. The terms are grouped by names. Term into which the merging will occur is selected manually by user, however you must know that it is impossible to merge a parent term into any of its children.') . '</p>',
  426. );
  427. $form['settings'] = array(
  428. '#type' => 'fieldset',
  429. '#title' => t('Advanced settings'),
  430. '#description' => t('Fine tune the duplicate search tool. You can adjust these settings if your vocabulary is very large. Also, you can control within these settings how the potential duplicates are presented below.'),
  431. '#tree' => TRUE,
  432. '#collapsible' => TRUE,
  433. );
  434. $form['settings']['help'] = array(
  435. '#markup' => '<p>' . format_plural(count($tree), 'Vocabulary %vocabulary has only 1 term. It is very unlikely you will merge anything here.', 'Vocabulary %vocabulary has @count terms. If this tool works slow, you may instruct the duplicate finder tool to terminate its work after it has found a specific number of possible duplicates.', array(
  436. '%vocabulary' => $vocabulary->name,
  437. )) . '</p>',
  438. );
  439. $form['settings']['max_duplicates'] = array(
  440. '#type' => 'textfield',
  441. '#title' => t('Show N duplicates'),
  442. '#description' => t('Input an integer here - this many duplicates will be shown on the form. Once this amount of possible duplicates is found, the search process terminates.'),
  443. '#required' => TRUE,
  444. '#default_value' => isset($form_state['values']['settings']['max_duplicates']) ? $form_state['values']['settings']['max_duplicates'] : 300,
  445. '#element_validate' => array('element_validate_integer_positive'),
  446. );
  447. $options = array();
  448. foreach (term_merge_duplicate_suggestion() as $plugin) {
  449. $options[$plugin['name']] = $plugin['title'];
  450. }
  451. $form['settings']['duplicate_suggestion'] = array(
  452. '#type' => 'checkboxes',
  453. '#title' => t('Mark terms as duplicate if all the checked conditions stand true'),
  454. '#options' => $options,
  455. '#default_value' => isset($form_state['values']['settings']['duplicate_suggestion']) ? $form_state['values']['settings']['duplicate_suggestion'] : array('name'),
  456. );
  457. $options = array();
  458. $bundle = field_extract_bundle('taxonomy_term', $vocabulary);
  459. foreach (field_info_instances('taxonomy_term', $bundle) as $instance) {
  460. $options[$instance['field_name']] = $instance['label'];
  461. }
  462. if (!empty($options)) {
  463. $form['settings']['fields'] = array(
  464. '#type' => 'checkboxes',
  465. '#title' => t('Display fields'),
  466. '#description' => t('Check which fields you wish to display in the results below for each possible duplicate term.'),
  467. '#options' => $options,
  468. '#default_value' => isset($form_state['values']['settings']['fields']) ? array_values(array_filter($form_state['values']['settings']['fields'])) : array(),
  469. );
  470. }
  471. $form['settings']['update'] = array(
  472. '#type' => 'button',
  473. '#value' => t('Re-run duplicate search'),
  474. '#ajax' => array(
  475. 'callback' => 'term_merge_duplicates_form_settings',
  476. 'wrapper' => 'term-merge-duplicate-wrapper',
  477. 'method' => 'replace',
  478. 'effect' => 'fade',
  479. ),
  480. );
  481. // Amount of found duplicates.
  482. $count = 0;
  483. // Array of groups of terms with the same name. Each group is an array of
  484. // duplicates. Trunk term of each group will be chosen by user.
  485. $groups = array();
  486. foreach ($tree as $term) {
  487. if ($count >= $form['settings']['max_duplicates']['#default_value']) {
  488. // We have reached the limit of possible duplicates to be found.
  489. break;
  490. }
  491. $hash = '';
  492. foreach ($form['settings']['duplicate_suggestion']['#default_value'] as $duplicate_suggestion) {
  493. $duplicate_suggestion = term_merge_duplicate_suggestion($duplicate_suggestion);
  494. $function = ctools_plugin_get_function($duplicate_suggestion, 'hash callback');
  495. if ($function) {
  496. $hash .= $function($term);
  497. }
  498. }
  499. if (!isset($groups[$hash])) {
  500. $groups[$hash] = array();
  501. }
  502. else {
  503. // We increment count by one for the just encountered duplicate. Plus, if
  504. // it is the second duplicate in this group, we also increment it by one
  505. // for the 1st duplicate in the group.
  506. $count++;
  507. if (count($groups[$hash]) == 1) {
  508. $count++;
  509. }
  510. }
  511. $groups[$hash][$term->tid] = $term;
  512. }
  513. $form['wrapper'] = array(
  514. '#prefix' => '<div id="term-merge-duplicate-wrapper">',
  515. '#suffix' => '</div>',
  516. );
  517. if ($count > 0) {
  518. $form['wrapper']['global_switch'] = array(
  519. '#type' => 'checkbox',
  520. '#title' => t('Select All Terms'),
  521. '#description' => t('Checking here will select for merging all the encountered duplicate terms.'),
  522. '#attributes' => array(
  523. 'class' => array('term-merge-duplicate-general-switch'),
  524. ),
  525. );
  526. }
  527. $form['wrapper']['group'] = array(
  528. '#tree' => TRUE,
  529. );
  530. $groups = array_filter($groups, 'term_merge_duplicates_form_filter');
  531. $tids = array();
  532. foreach ($groups as $group) {
  533. $tids = array_merge($tids, array_keys($group));
  534. }
  535. // This array will be keyed by term tid and values will be counts of how many
  536. // other entities reference to this term through values of fields attached to
  537. // them.
  538. $terms_count = array_fill_keys($tids, 0);
  539. if (!empty($tids)) {
  540. foreach (term_merge_fields_with_foreign_key('taxonomy_term_data', 'tid') as $referencing_field) {
  541. if ($referencing_field['storage']['type'] == 'field_sql_storage') {
  542. $table = array_keys($referencing_field['storage']['details']['sql'][FIELD_LOAD_CURRENT]);
  543. $table = reset($table);
  544. $column = $referencing_field['storage']['details']['sql'][FIELD_LOAD_CURRENT][$table][$referencing_field['term_merge_field_column']];
  545. $select = db_select($table, 'reference')
  546. ->condition($column, $tids);
  547. $select->addField('reference', $column, 'tid');
  548. $select->addExpression('COUNT(1)', 'count');
  549. $select->groupBy($column);
  550. $select = $select->execute();
  551. foreach ($select as $row) {
  552. $terms_count[$row->tid] += $row->count;
  553. }
  554. }
  555. }
  556. }
  557. if (!empty($form['settings']['fields']['#default_value'])) {
  558. // We need to load full term entities, because we are requested to show
  559. // fields.
  560. $terms = taxonomy_term_load_multiple($tids);
  561. foreach ($groups as $i => $group) {
  562. $groups[$i] = array_intersect_key($terms, $group);
  563. }
  564. }
  565. foreach ($groups as $i => $group) {
  566. // Sorting terms by tid for better usage experience.
  567. ksort($group);
  568. $first_term = reset($group);
  569. $options = array();
  570. foreach ($group as $term) {
  571. $parents = array();
  572. // Adding Root to the hierarchy.
  573. $parents[] = t('Vocabulary Root');
  574. foreach (taxonomy_get_parents_all($term->tid) as $parent) {
  575. // We do not include the current term in the hierarchy.
  576. if ($parent->tid != $term->tid) {
  577. $parents[] = $parent->name;
  578. }
  579. }
  580. $language = isset($term->language) ? $term->language : LANGUAGE_NONE;
  581. if ($language == LANGUAGE_NONE) {
  582. $language = t('Not Specified');
  583. }
  584. $options[$term->tid] = array(
  585. 'id' => $term->tid,
  586. 'title' => l($term->name, 'taxonomy/term/' . $term->tid),
  587. 'language' => $language,
  588. 'description' => check_markup($term->description, $term->format),
  589. 'parents' => implode(' &raquo; ', $parents),
  590. 'count' => format_plural($terms_count[$term->tid], '@count time', '@count times'),
  591. );
  592. if (isset($form['settings']['fields'])) {
  593. foreach ($form['settings']['fields']['#default_value'] as $instance) {
  594. $field = field_info_field($instance);
  595. $items = field_get_items('taxonomy_term', $term, $field['field_name']);
  596. $options[$term->tid][$field['field_name']] = '';
  597. if (is_array($items)) {
  598. $options[$term->tid][$field['field_name']] = array(
  599. '#theme' => 'item_list',
  600. '#items' => array(),
  601. );
  602. foreach ($items as $item) {
  603. switch ($field['type']) {
  604. case 'image':
  605. $display = array();
  606. $image_style = image_style_load('thumbnail');
  607. if ($image_style) {
  608. $cache = _field_info_field_cache();
  609. $display = $cache->prepareInstanceDisplay($display, $field['type']);
  610. $display['settings']['image_style'] = $image_style['name'];
  611. }
  612. $rendered_item = drupal_render(field_view_value('taxonomy_term', $term, $field['field_name'], $item, $display));
  613. break;
  614. default:
  615. $rendered_item = drupal_render(field_view_value('taxonomy_term', $term, $field['field_name'], $item));
  616. break;
  617. }
  618. $options[$term->tid][$field['field_name']]['#items'][] = $rendered_item;
  619. }
  620. if (count($options[$term->tid][$field['field_name']]['#items']) > 1) {
  621. $options[$term->tid][$field['field_name']] = drupal_render($options[$term->tid][$field['field_name']]);
  622. }
  623. else {
  624. $options[$term->tid][$field['field_name']] = $options[$term->tid][$field['field_name']]['#items'][0];
  625. }
  626. }
  627. }
  628. }
  629. }
  630. $form['wrapper']['group'][$i] = array(
  631. '#type' => 'fieldset',
  632. '#title' => check_plain($first_term->name),
  633. '#collapsible' => TRUE,
  634. '#pre_render' => array('term_merge_duplicates_fieldset_preprocess'),
  635. '#element_validate' => array('term_merge_duplicates_fieldset_validate'),
  636. );
  637. $header = array(
  638. 'id' => t('ID'),
  639. 'title' => t('Title'),
  640. 'description' => t('Description'),
  641. 'language' => t('Language'),
  642. 'parents' => t('Parents'),
  643. 'count' => t('Referenced'),
  644. );
  645. if (isset($form['settings']['fields'])) {
  646. $header += array_map('check_plain', array_intersect_key($form['settings']['fields']['#options'], drupal_map_assoc($form['settings']['fields']['#default_value'])));
  647. }
  648. $form['wrapper']['group'][$i]['duplicates'] = array(
  649. '#type' => 'tableselect',
  650. '#title' => 'Duplicates',
  651. '#header' => $header,
  652. '#options' => $options,
  653. );
  654. $options = array();
  655. foreach ($group as $term) {
  656. $options[$term->tid] = $term->name;
  657. }
  658. $form['wrapper']['group'][$i]['trunk_tid'] = array(
  659. '#type' => 'radios',
  660. '#title' => t('Merge Into'),
  661. '#options' => $options,
  662. '#attributes' => array(
  663. 'class' => array('term-merge-duplicate-trunk'),
  664. ),
  665. );
  666. }
  667. if ($count > 0) {
  668. // Adding necessary options of merging.
  669. $form += term_merge_merge_options_elements($vocabulary);
  670. $form['actions'] = array(
  671. '#type' => 'actions',
  672. );
  673. $form['actions']['submit'] = array(
  674. '#type' => 'submit',
  675. '#value' => t('Submit'),
  676. );
  677. }
  678. else {
  679. if (is_null($parent_term)) {
  680. $no_match_text = t('Sorry, seems like we were not able to find any possible duplicate terms in %vocabulary vocabulary.', array(
  681. '%vocabulary' => $vocabulary->name,
  682. ));
  683. }
  684. else {
  685. $no_match_text = t('Sorry, seems like we were not able to find any possible duplicate terms among children of %term term. You may want to search for duplicates through the entire <a href="!url">vocabulary</a>.', array(
  686. '%term' => $parent_term->name,
  687. '!url' => url('admin/structure/taxonomy/' . $vocabulary->machine_name . '/merge/duplicates'),
  688. ));
  689. }
  690. $form['nothing_found'] = array(
  691. '#markup' => '<p><b>' . $no_match_text . '</b></p>',
  692. );
  693. }
  694. return $form;
  695. }
  696. /**
  697. * Submit handler for 'term_merge_duplicates_form'.
  698. *
  699. * Actually merge duplicate terms.
  700. */
  701. function term_merge_duplicates_form_submit($form, &$form_state) {
  702. $batch = array(
  703. 'title' => t('Merging terms'),
  704. 'operations' => array(),
  705. 'finished' => 'term_merge_batch_finished',
  706. 'file' => drupal_get_path('module', 'term_merge') . '/term_merge.batch.inc',
  707. );
  708. // Processing general options for merging.
  709. $merge_settings = term_merge_merge_options_submit($form, $form_state, $form);
  710. if (isset($form_state['values']['group'])) {
  711. foreach ($form_state['values']['group'] as $values) {
  712. // Filtering out only the selected duplicate terms.
  713. $term_branches = array_filter($values['duplicates']);
  714. // We also do not want to have trunk term to be among the branch terms.
  715. unset($term_branches[$values['trunk_tid']]);
  716. if (!empty($term_branches)) {
  717. // If something has been selected in this group we schedule its merging.
  718. $batch['operations'][] = array('_term_merge_batch_process', array(
  719. $term_branches,
  720. $values['trunk_tid'],
  721. $merge_settings,
  722. ));
  723. }
  724. }
  725. }
  726. if (empty($batch['operations'])) {
  727. drupal_set_message(t('No merging has been made, because you have not selected any duplicate term to merge.'));
  728. }
  729. else {
  730. batch_set($batch);
  731. }
  732. }
  733. /**
  734. * Form element preprocess function.
  735. *
  736. * Insert extra column for choosing term trunk into tableselect of terms to be
  737. * merged.
  738. */
  739. function term_merge_duplicates_fieldset_preprocess($element) {
  740. $options = &$element['duplicates']['#options'];
  741. foreach ($options as $tid => $row) {
  742. $element['trunk_tid'][$tid]['#title_display'] = 'invisible';
  743. $options[$tid] = array(
  744. 'trunk' => drupal_render($element['trunk_tid'][$tid]),
  745. ) + $options[$tid];
  746. }
  747. $element['trunk_tid']['#title_display'] = 'invisible';
  748. $element['duplicates']['#header'] = array(
  749. 'trunk' => $element['trunk_tid']['#title'],
  750. ) + $element['duplicates']['#header'];
  751. return $element;
  752. }
  753. /**
  754. * FAPI element validation callback.
  755. *
  756. * Validate fieldset of a 'term_merge_duplicates_form' form, if any duplicate
  757. * has been selected for merging, it makes sure the trunk term has been
  758. * selected. We can't allow merging without knowing the explicit trunk term.
  759. */
  760. function term_merge_duplicates_fieldset_validate($element, &$form_state, $form) {
  761. if (!empty($element['duplicates']['#value']) && !is_numeric($element['trunk_tid']['#value'])) {
  762. form_error($element, t('Please, choose %trunk_tid_label for the group %group_label', array(
  763. '%trunk_tid_label' => $element['trunk_tid']['#title'],
  764. '%group_label' => $element['#title'],
  765. )));
  766. }
  767. }
  768. /**
  769. * Ajax callback function.
  770. *
  771. * Used in term_merge_duplicates_form() to replace the duplicates tables with
  772. * new data per current settings.
  773. */
  774. function term_merge_duplicates_form_settings($form, &$form_state) {
  775. return $form['wrapper'];
  776. }
  777. /**
  778. * Supportive array_filter() callback function.
  779. *
  780. * Eliminate all array elements, whose dimension is less than 1.
  781. */
  782. function term_merge_duplicates_form_filter($array_element) {
  783. return count($array_element) > 1;
  784. }