Browse Source

added term_merge module

Bachir Soussi Chiadmi 8 years ago
parent
commit
d7e7410950

+ 339 - 0
sites/all/modules/contrib/taxonomy/term_merge/LICENSE.txt

@@ -0,0 +1,339 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+                            NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.

+ 55 - 0
sites/all/modules/contrib/taxonomy/term_merge/README.txt

@@ -0,0 +1,55 @@
+Term Merge
+------------------------
+by:
+ * Max Nylin <max@articstudios.se>
+ * Oleksandr Trotsenko
+
+Description
+-----------
+When using taxonomy for free tagging purposes, it's easy to end up with
+several terms having the same meaning. This may be due to spelling errors,
+or different users simply making up synonymous terms as they go.
+
+You, as an administrator, may then want to correct such errors or unify
+synonymous terms, thereby pruning the taxonomy to a more manageable set.
+This module allows you to merge multiple terms into one, while updating
+all fields referring to those terms to refer to the replacement term instead.
+
+Currently, the module only acts on:
+ * fields of 'taxonomy term reference' type
+ * Views Taxonomy Term filter handlers
+ * Redirects
+
+It would be desirable to update other possible
+places where deleted terms are used.
+
+Integration
+-------------
+Currently module integrates with the following core and contributed modules:
+ * Redirect module (http://drupal.org/project/redirect). During term merging
+ you may set up SEO friendly redirects from the branch terms to point to the
+ trunk term
+ * Synonyms module (http://drupal.org/project/synonyms). During term merging
+ you will be able to choose a trunk term's field into which all the branch terms
+ will be added as synonyms (until cardinality limit for that field is reached).
+ * Hierarchical Select (http://drupal.org/project/hierarchical_select). If
+ Hierarchical Select module is configured to be used for working with Taxonomy,
+ its widget will be shown on the form, where you choose what terms to merge into
+ what term.
+ * Views (http://drupal.org/project/views). If the branch terms are to be
+ deleted after the merging process, you could end up having some Views filters
+ to filter on no longer existing terms. Term Merge module, while merging terms,
+ will update those filters to filter not on the branch term, but on the trunk
+ term. This way you will not have senseless filters and will not have to update
+ them manually.
+
+Requirements
+-------------
+The modules requires enabled the following modules:
+ * Taxonomy module (ships with Drupal core)
+ * Entity API (http://drupal.org/project/entity)
+
+Installation
+------------
+ * Copy the module's directory to your modules directory and activate the
+ module.

+ 66 - 0
sites/all/modules/contrib/taxonomy/term_merge/js/duplicate.form.js

@@ -0,0 +1,66 @@
+/**
+ * @file
+ * JavaScript enhancements for "Merge Duplicate Terms" form.
+ */
+(function ($) {
+
+  /**
+   * Behavior that elaborates Tableselect of duplicate terms.
+   */
+  Drupal.behaviors.termMergeDuplicateTableselect = {
+    attach: function(context) {
+      // We want to disable checkbox of a duplicate term if it is currently
+      // selected as a trunk term in that group of duplicate terms, i.e. you
+      // cannot (and should not) merge a term into itself.
+      $('.term-merge-duplicate-trunk', context).closest(':has(.form-checkbox)').once('term-merge-duplicate-trunk', function() {
+        var container = $(this);
+        container.find('.term-merge-duplicate-trunk').change(function() {
+          // Removing disabled from all disabled checkboxes.
+          container.parents('table').find('.form-checkbox:disabled').removeAttr('disabled');
+          if ($(this).is(':checked')) {
+            container.find('.form-checkbox').attr('disabled', true);
+          }
+        });
+      });
+    }
+  };
+
+  /**
+   * Behavior that kicks off general switch button on Duplicate terms form.
+   */
+  Drupal.behaviors.termMergeDuplicateGeneralSwitch = {
+    attach: function (context) {
+      $('.term-merge-duplicate-general-switch', context).once('term-merge-duplicate-general-switch', function() {
+        var container = $(this).parents('form');
+        $(this).change(function() {
+          var term_branches = container.find('table:not(.sticky-header) .select-all .form-checkbox');
+          if ($(this).is(':checked')) {
+            term_branches.attr('checked', true).trigger({
+              type: 'click',
+              target: this
+            });
+            // For some reason the checkboxes get unchecked, we check them back.
+            term_branches.attr('checked', true);
+
+            // We also want to trigger "change" on those radio buttons, see
+            // Drupal.behaviors.termMergeDuplicateTableselect for more info.
+            container.find('table').find('.term-merge-duplicate-trunk:first').attr('checked', true).trigger('change');
+          }
+          else {
+            term_branches.removeAttr('checked').trigger({
+              type: 'click',
+              target: this
+            });
+            // For some reason the checkboxes get checked, we uncheck them back.
+            term_branches.removeAttr('checked');
+
+            // We also want to trigger "change" on those radio buttons, see
+            // Drupal.behaviors.termMergeDuplicateTableselect for more info.
+            container.find('table').find('.term-merge-duplicate-trunk').removeAttr('checked').trigger('change');
+          }
+        });
+      });
+    }
+  };
+
+})(jQuery);

+ 28 - 0
sites/all/modules/contrib/taxonomy/term_merge/term_merge.api.php

@@ -0,0 +1,28 @@
+<?php
+
+/**
+ * @file
+ * Documentation for Term Merge module.
+ */
+
+/**
+ * Notify other modules when merging of 2 taxonomy terms occurs.
+ *
+ * @param object $term_trunk
+ *   Fully loaded taxonomy term object of the term trunk, term into which
+ *   merging occurs, aka 'destination'
+ * @param object $term_branch
+ *   Fully loaded taxonomy term object of the term branch, term that is being
+ *   merged, aka 'source'
+ * @param array $context
+ *   Array $context as it is passed to term_merge_action() - you can get a
+ *   little more info about context about merging from this array
+ */
+function hook_term_merge($term_trunk, $term_branch, $context) {
+  // Here we might want to run a query like:
+  // UPDATE {my_table}
+  //   SET term_tid = $term_trunk->tid
+  //   WHERE term_tid = $term_branch->tid
+  // Or do anything else that you own logic requires when merging of 2 terms
+  // happens.
+}

+ 102 - 0
sites/all/modules/contrib/taxonomy/term_merge/term_merge.batch.inc

@@ -0,0 +1,102 @@
+<?php
+
+/**
+ * @file
+ * Batch process callbacks for Term Merge module.
+ */
+
+/**
+ * Process batch function.
+ *
+ * Trigger action 'term_merge_action' on each pair of term branch:term trunk.
+ *
+ * @param array $term_branch
+ *   An array of term tids to be merged, aka term branches
+ * @param int $term_trunk
+ *   The tid of the term to merge term branches into, aka term trunk
+ * @param array $merge_settings
+ *   Array of settings that control how merging should happen. Currently
+ *   supported settings are:
+ *     - term_branch_keep: (bool) Whether the term branches should not be
+ *       deleted, also known as "merge only occurrences" option
+ *     - merge_fields: (array) Array of field names whose values should be
+ *       merged into the values of corresponding fields of term trunk (until
+ *       each field's cardinality limit is reached)
+ *     - keep_only_unique: (bool) Whether after merging within one field only
+ *       unique taxonomy term references should be kept in other entities. If
+ *       before merging your entity had 2 values in its taxonomy term reference
+ *       field and one was pointing to term branch while another was pointing to
+ *       term trunk, after merging you will end up having your entity
+ *       referencing to the same term trunk twice. If you pass TRUE in this
+ *       parameter, only a single reference will be stored in your entity after
+ *       merging
+ *     - redirect: (int) HTTP code for redirect from $term_branch to
+ *       $term_trunk, 0 stands for the default redirect defined in Redirect
+ *       module. Use constant TERM_MERGE_NO_REDIRECT to denote not creating any
+ *       HTTP redirect. Note: this parameter requires Redirect module enabled,
+ *       otherwise it will be disregarded
+ *     - synonyms: (array) Array of field names of trunk term into which branch
+ *       terms should be added as synonyms (until each field's cardinality limit
+ *       is reached). Note: this parameter requires Synonyms module enabled,
+ *       otherwise it will be disregarded
+ *     - step: (int) How many term branches to merge per script run in batch. If
+ *       you are hitting time or memory limits, decrease this parameter
+ * @param array $context
+ *   Drupal Batch API context array
+ */
+function _term_merge_batch_process($term_branch, $term_trunk, $merge_settings, &$context) {
+  // Initializing sandbox.
+  if (!isset($context['sandbox']['current'])) {
+    $context['sandbox']['current'] = 0;
+  }
+
+  // Populating $merge_settings with defaults.
+  $merge_settings += array(
+    'term_branch_keep' => FALSE,
+    'merge_fields' => array(),
+    'keep_only_unique' => TRUE,
+    'redirect' => TERM_MERGE_NO_REDIRECT,
+    'synonyms' => array(),
+    'step' => 40,
+  );
+
+  $total = count($term_branch);
+  // To speed up the process we take advantage of taxonomy_term_load_multiple()
+  // instead of just repeating calls to taxonomy_term_load().
+  $till = min($total, $context['sandbox']['current'] + $merge_settings['step']);
+  $length = $till - $context['sandbox']['current'];
+  $term_branch = array_slice($term_branch, $context['sandbox']['current'], $length);
+  $term_branch = array_values(taxonomy_term_load_multiple($term_branch));
+  for ($i = 0; $i < $merge_settings['step'] && $context['sandbox']['current'] < $total; $i++) {
+    actions_do('term_merge_action', $term_branch[$i], array(
+      'term_trunk' => $term_trunk,
+      'term_branch_keep' => $merge_settings['term_branch_keep'],
+      'merge_fields' => $merge_settings['merge_fields'],
+      'keep_only_unique' => $merge_settings['keep_only_unique'],
+      'redirect' => $merge_settings['redirect'],
+      'synonyms' => $merge_settings['synonyms'],
+    ));
+    $context['sandbox']['current']++;
+  }
+
+  if ($context['sandbox']['current'] != $total) {
+    $context['finished'] = $context['sandbox']['current'] / $total;
+    $term = $term_branch[$i - 1];
+    $context['message'] = t('Merged up to @term', array('@term' => $term->name));
+  }
+}
+
+/**
+ * Batch 'finished' callback.
+ *
+ * Process results of Term Merge batch.
+ */
+function term_merge_batch_finished($success, $results, $operations) {
+  if ($success) {
+    drupal_set_message(t('The terms have been successfully merged.'));
+  }
+  else {
+    // An error happened. We have to notify the user.
+    drupal_set_message(t('An error occurred. We are sorry, please, report this error to the maintainers of Term Merge module.'), 'error');
+  }
+}

+ 16 - 0
sites/all/modules/contrib/taxonomy/term_merge/term_merge.info

@@ -0,0 +1,16 @@
+name = Term Merge
+description = This module allows you to merge multiple terms into one, while updating all fields referring to those terms to refer to the replacement term instead.
+package = Taxonomy
+core = 7.x
+
+files[] = term_merge.test
+
+dependencies[] = taxonomy
+dependencies[] = entity
+
+; Information added by Drupal.org packaging script on 2015-01-14
+version = "7.x-1.2"
+core = "7.x"
+project = "term_merge"
+datestamp = "1421194982"
+

+ 711 - 0
sites/all/modules/contrib/taxonomy/term_merge/term_merge.module

@@ -0,0 +1,711 @@
+<?php
+
+/**
+ * @file
+ * Provide functionality for merging taxonomy terms one into another.
+ */
+
+/**
+ * Constant to use in term merge action.
+ *
+ * Constant denotes "do not create HTTP redirect" logic for term merge action.
+ *
+ * @var int
+ */
+define('TERM_MERGE_NO_REDIRECT', -1);
+
+/**
+ * Constant to use in term merge action.
+ *
+ * Constant denotes "Create a new term and use it as the term trunk" logic
+ * for term merge action.
+ *
+ * @var int
+ */
+define('TERM_MERGE_NEW_TERM_TRUNK', -1);
+
+/**
+ * Implements hook_menu().
+ */
+function term_merge_menu() {
+  $items = array();
+
+  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/merge'] = array(
+    'title' => 'Merge terms',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('term_merge_form', 3),
+    'access callback' => 'term_merge_access',
+    'access arguments' => array(3),
+    'file' => 'term_merge.pages.inc',
+    'type' => MENU_LOCAL_TASK,
+  );
+
+  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/merge/default'] = array(
+    'title' => 'Default',
+    'type' => MENU_DEFAULT_LOCAL_TASK,
+  );
+
+  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/merge/duplicates'] = array(
+    'title' => 'Merge Duplicate Terms',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('term_merge_duplicates_form', 3),
+    'access callback' => 'term_merge_access',
+    'access arguments' => array(3),
+    'file' => 'term_merge.pages.inc',
+    'type' => MENU_LOCAL_TASK,
+  );
+
+  $items['taxonomy/term/%taxonomy_term/merge'] = array(
+    'title' => 'Merge Terms',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('term_merge_form', NULL, 2),
+    'access callback' => 'term_merge_access',
+    'access arguments' => array(NULL, 2),
+    'file' => 'term_merge.pages.inc',
+    'type' => MENU_LOCAL_TASK,
+    'weight' => 10,
+  );
+
+  $items['taxonomy/term/%taxonomy_term/merge/default'] = array(
+    'title' => 'Default',
+    'type' => MENU_DEFAULT_LOCAL_TASK,
+  );
+
+  $items['taxonomy/term/%taxonomy_term/merge/duplicates'] = array(
+    'title' => 'Merge Duplicate Terms',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('term_merge_duplicates_form', NULL, 2),
+    'access callback' => 'term_merge_access',
+    'access arguments' => array(NULL, 2),
+    'file' => 'term_merge.pages.inc',
+    'type' => MENU_LOCAL_TASK,
+  );
+
+  $items['term-merge/autocomplete/term-trunk/%taxonomy_vocabulary_machine_name'] = array(
+    'title' => 'Autocomplete Term Merge form term trunk',
+    'page callback' => 'term_merge_form_term_trunk_widget_autocomplete_autocomplete',
+    'page arguments' => array(3),
+    'access callback' => 'term_merge_access',
+    'access arguments' => array(3),
+    'file' => 'term_merge.pages.inc',
+    'type' => MENU_CALLBACK,
+  );
+
+  return $items;
+}
+
+/**
+ * Implements hook_admin_paths().
+ */
+function term_merge_admin_paths() {
+  return array(
+    'taxonomy/term/*/merge' => TRUE,
+    'taxonomy/term/*/merge/*' => TRUE,
+  );
+}
+
+/**
+ * Implements hook_permission().
+ */
+function term_merge_permission() {
+  $permissions = array();
+  $permissions['merge terms'] = array(
+    'title' => t('Merge any terms'),
+    'description' => t('Gives the ability to merge any taxonomy terms.'),
+  );
+  $vocabularies = taxonomy_get_vocabularies();
+  foreach ($vocabularies as $vocabulary) {
+    $permissions['merge ' . $vocabulary->machine_name . ' terms'] = array(
+      'title' => t('Merge %name vocabulary terms', array('%name' => $vocabulary->name)),
+      'description' => t('Gives the ability to merge taxonomy terms that belong to vocabulary %name.', array('%name' => $vocabulary->name)),
+    );
+  }
+  return $permissions;
+}
+
+/**
+ * Implements hook_action_info().
+ */
+function term_merge_action_info() {
+  return array(
+    'term_merge_action' => array(
+      'type' => 'taxonomy',
+      'label' => t('Merge term'),
+      'configurable' => TRUE,
+      'behavior' => array('changes_property'),
+    ),
+  );
+}
+
+/**
+ * Implements hook_help().
+ */
+function term_merge_help($path, $arg) {
+  switch ($path) {
+    // Main module help for the Term Merge module.
+    case 'admin/help#term_merge':
+      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>';
+      break;
+  }
+}
+
+/**
+ * Access callback for term merge action.
+ *
+ * Decide whether to grant access to an account for an operation of merging
+ * terms in a vocabulary.
+ *
+ * @param object $vocabulary
+ *   Fully loaded vocabulary object inside of which term merge operation is
+ *   requested for access granting
+ * @param object $term
+ *   Fully loaded term object which belongs to the vocabulary inside of which
+ *   term merge operation is requested for access granting. You are supposed
+ *   only to provide either $vocabulary or $term. Depending on your context it
+ *   might be more convenient for you to provide $term, and on other occasions
+ *   it might be $vocabulary of more convenience
+ * @param object $account
+ *   Fully loaded user object who is requesting access granting for the
+ *   operation of term merging. You may provide nothing here, and the currently
+ *   logged in user will be considered
+ *
+ * @return bool
+ *   Whether the access for term merging operation has been granted
+ */
+function term_merge_access($vocabulary = NULL, $term = NULL, $account = NULL) {
+  if (is_null($vocabulary) && is_null($term)) {
+    // This is no go, at least one of these 2 has to be provided.
+    return FALSE;
+  }
+
+  if (is_null($account)) {
+    // Falling back on currently logged in user.
+    $account = $GLOBALS['user'];
+  }
+
+  if (is_null($vocabulary)) {
+    $vocabulary = taxonomy_vocabulary_load($term->vid);
+  }
+
+  return user_access('merge terms', $account) || user_access('merge ' . $vocabulary->machine_name . ' terms', $account);
+}
+
+/**
+ * Generate the configuration form for action "Term merge".
+ */
+function term_merge_action_form($context) {
+  $form = array();
+
+  $form['displaimer'] = array(
+    '#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>',
+  );
+
+  return $form;
+}
+
+/**
+ * Form submission function.
+ *
+ * Store information about configurable action.
+ */
+function term_merge_action_submit($form, &$form_state) {
+  // We don't have enabled UI for this action. It's just a dummy function.
+  return array();
+}
+
+/**
+ * Action function. Perform action "Term Merge".
+ */
+function term_merge_action($object, $context) {
+  $term_branch = $object;
+  $term_trunk = taxonomy_term_load($context['term_trunk']);
+  $vocabulary = taxonomy_vocabulary_load($term_branch->vid);
+
+  $term_branch_children = array();
+  foreach (taxonomy_get_tree($term_branch->vid, $term_branch->tid) as $term) {
+    $term_branch_children[] = $term->tid;
+  }
+
+  if ($term_branch->vid != $term_trunk->vid) {
+    watchdog('term_merge', 'Trying to merge 2 terms (%term_branch, %term_trunk) from different vocabularies', array(
+      '%term_branch' => $term_branch->name,
+      '%term_trunk' => $term_trunk->name,
+    ), WATCHDOG_WARNING);
+    return;
+  }
+  if ($term_branch->tid == $term_trunk->tid) {
+    watchdog('term_merge', 'Trying to merge a term %term into itself.', array('%term' => $term_branch->name), WATCHDOG_WARNING);
+    return;
+  }
+  if (in_array($term_trunk->tid, $term_branch_children)) {
+    watchdog('term_merge', 'Trying to merge a term %term_branch into its child %term_trunk.', array(
+      '%term_branch' => $term_branch->name,
+      '%term_trunk' => $term_trunk->name,
+    ), WATCHDOG_WARNING);
+    return;
+  }
+
+  // Defining some default values.
+  if (!isset($context['term_branch_keep'])) {
+    // It's easier to manually delete the unwanted terms, rather than
+    // search for your DB back up. So by default we keep the term branch.
+    $context['term_branch_keep'] = TRUE;
+  }
+  if (!isset($context['merge_fields'])) {
+    // Initializing it with an empty array if client of this function forgot to
+    // provide info about what fields to merge.
+    $context['merge_fields'] = array();
+  }
+  if (!isset($context['keep_only_unique'])) {
+    // Seems logical that mostly people will prefer to keep only one value in
+    // term reference field per taxonomy term.
+    $context['keep_only_unique'] = TRUE;
+  }
+  if (!isset($context['redirect']) || !module_exists('redirect')) {
+    // This behavior requires Redirect module installed and enabled.
+    $context['redirect'] = TERM_MERGE_NO_REDIRECT;
+  }
+  if (!isset($context['synonyms']) || !module_exists('synonyms')) {
+    // This behavior requires Synonyms module installed and enabled.
+    $context['synonyms'] = array();
+  }
+
+  // Calling a hook, this way we let whoever else to react and do his own extra
+  // logic when merging of terms occurs. We prefer to call it before we handle
+  // our own logic, because our logic might delete $term_branch and maybe a
+  // module that implements this hook needs this term not deleted yet.
+  module_invoke_all('term_merge', $term_trunk, $term_branch, $context);
+
+  if (!empty($context['merge_fields'])) {
+    // "Merging" the fields from $term_branch into $term_trunk where it is
+    // possible.
+    foreach ($context['merge_fields'] as $field_name) {
+      // Getting the list of available languages for this field.
+      $languages = array();
+      if (isset($term_trunk->$field_name) && is_array($term_trunk->$field_name)) {
+        $languages = array_merge($languages, array_keys($term_trunk->$field_name));
+      }
+      if (isset($term_branch->$field_name) && is_array($term_branch->$field_name)) {
+        $languages = array_merge($languages, array_keys($term_branch->$field_name));
+      }
+      $languages = array_unique($languages);
+      // Merging the data of both terms into $term_trunk.
+      foreach ($languages as $language) {
+        if (!isset($term_trunk->{$field_name}[$language])) {
+          $term_trunk->{$field_name}[$language] = array();
+        }
+        if (!isset($term_branch->{$field_name}[$language])) {
+          $term_branch->{$field_name}[$language] = array();
+        }
+        $term_trunk->{$field_name}[$language] = array_merge($term_trunk->{$field_name}[$language], $term_branch->{$field_name}[$language]);
+      }
+    }
+
+    // And now we can save $term_trunk after shifting all the fields from
+    // $term_branch.
+    taxonomy_term_save($term_trunk);
+  }
+
+  // Updating all the links to $term_branch to point now to $term_trunk
+  // firstly we go through the list of all fields searching for
+  // taxonomy_term_reference field type because potentially some of these fields
+  // values will have to be updated after merging terms.
+  $fields = field_info_field_map();
+  $result = array();
+  foreach ($fields as $field_name => $v) {
+    // Additionally we group by field_name to know what field has to be updated
+    // in each found entity.
+    // @todo: Here would be nice to throw in a hook, allowing other modules to
+    // supply meta data about their field types if they also use taxonomy
+    // references, defining it in their own field types.
+    if ($v['type'] == 'taxonomy_term_reference') {
+      $result[$field_name] = array();
+      $query = new EntityFieldQuery();
+      // Making sure we search in the entire scope of entities.
+      $query->addMetaData('account', user_load(1));
+      $query->fieldCondition($field_name, 'tid', $term_branch->tid);
+      $_result = $query->execute();
+      $result[$field_name] = array_merge_recursive($result[$field_name], $_result);
+    }
+  }
+  // Now we load all entities that have taxonomy_term_reference pointing to
+  // $term_branch.
+  foreach ($result as $field_name => $entity_types) {
+    foreach ($entity_types as $entity_type => $v) {
+      $ids = array_keys($v);
+      $entities = entity_load($entity_type, $ids);
+      // After we have loaded it, we alter the taxonomy_term_reference
+      // to point to $term_trunk.
+      foreach ($entities as $entity) {
+        // What is more, we have to do it for every available language.
+        foreach ($entity->$field_name as $language => $items) {
+          // Keeping track of whether term trunk is already present in this
+          // field in this language. This is useful for the option
+          // 'keep_only_unique'.
+          $is_trunk_added = FALSE;
+          foreach ($entity->{$field_name}[$language] as $delta => $item) {
+            if ($context['keep_only_unique'] && $is_trunk_added && in_array($item['tid'], array($term_trunk->tid, $term_branch->tid))) {
+              // We are instructed to keep only unique references and we already
+              // have term trunk in this field, so we just unset value for this
+              // delta.
+              unset($entity->{$field_name}[$language][$delta]);
+            }
+            else {
+              // Merging term references if necessary, and keep an eye on
+              // whether we already have term trunk among this field values.
+              switch ($item['tid']) {
+                case $term_trunk->tid:
+                  $is_trunk_added = TRUE;
+                  break;
+
+                case $term_branch->tid:
+                  $is_trunk_added = TRUE;
+                  $entity->{$field_name}[$language][$delta]['tid'] = $term_trunk->tid;
+                  break;
+              }
+            }
+          }
+          // Above in the code, while looping through all deltas of this field,
+          // we might have unset some of the deltas to keep term references
+          // unique. We should better keep deltas as a series of consecutive
+          // numbers, because it is what it is supposed to be.
+          $entity->{$field_name}[$language] = array_values($entity->{$field_name}[$language]);
+        }
+        // After updating all the references, save the entity.
+        entity_save($entity_type, $entity);
+      }
+    }
+  }
+
+  // Adding term branch as synonym (Synonyms module integration).
+  foreach ($context['synonyms'] as $synonym_field) {
+    synonyms_add_entity_as_synonym($term_trunk, 'taxonomy_term', $synonym_field, $term_branch, 'taxonomy_term');
+  }
+
+  // It turned out we gotta go tricky with the Redirect module. If we create
+  // redirection before deleting the branch term (if we are instructed to delete
+  // in this action) redirect module will do its "auto-clean up" in
+  // hook_entity_delete() and will delete our just created redirects. But at the
+  // same time we have to get the path alias of the $term_branch before it gets
+  // deleted. Otherwise the path alias will be deleted along with the term
+  // itself. Similarly would be lost all redirects pointing to branch term
+  // paths. We will redirect normal term path and its RSS feed.
+  $redirect_paths = array();
+  if ($context['redirect'] != TERM_MERGE_NO_REDIRECT) {
+    $redirect_paths['taxonomy/term/' . $term_trunk->tid] = array(
+      'taxonomy/term/' . $term_branch->tid,
+    );
+    $redirect_paths['taxonomy/term/' . $term_trunk->tid . '/feed'] = array(
+      'taxonomy/term/' . $term_branch->tid . '/feed',
+    );
+    foreach ($redirect_paths as $redirect_destination => $redirect_sources) {
+      // We create redirect from Drupal normal path, then we try to fetch its
+      // alias. Lastly we collect a set of redirects that point to either of the
+      // 2 former paths. Everything we were able to fetch will be redirecting to
+      // the trunk term.
+      $alias = drupal_get_path_alias($redirect_sources[0]);
+      if ($alias != $redirect_sources[0]) {
+        $redirect_sources[] = $alias;
+      }
+      $existing_redirects = array();
+      foreach ($redirect_sources as $redirect_source) {
+        foreach (redirect_load_multiple(array(), array('redirect' => $redirect_source)) as $v) {
+          $existing_redirects[] = $v->source;
+        }
+      }
+      $redirect_paths[$redirect_destination] = array_unique(array_merge($redirect_sources, $existing_redirects));
+    }
+  }
+
+  if (!$context['term_branch_keep']) {
+    // If we are going to delete branch term, we need firstly to make sure
+    // all its children now have the parent of term_trunk.
+    foreach (taxonomy_get_children($term_branch->tid, $vocabulary->vid) as $child) {
+      $parents = taxonomy_get_parents($child->tid);
+      // Deleting the parental link to the term that is being merged.
+      unset($parents[$term_branch->tid]);
+      // And putting the parental link to the term that we merge into.
+      $parents[$term_trunk->tid] = $term_trunk;
+      $parents = array_unique(array_keys($parents));
+      $child->parent = $parents;
+      taxonomy_term_save($child);
+    }
+
+    // Views module integration. We update all Views taxonomy filter handlers
+    // configured to filter on term branch to filter on term trunk now, since
+    // the former becomes the latter.
+    if (module_exists('views')) {
+      $views = views_get_all_views();
+      foreach ($views as $view) {
+        // For better efficiency, we keep track of whether we have updated
+        // anything in a view, and thus whether we need to save it.
+        $needs_saving = FALSE;
+        // Even worse, we have to go through each display of each view.
+        foreach ($view->display as $display_id => $display) {
+          $view->set_display($display_id);
+          $filters = $view->display_handler->get_handlers('filter');
+          foreach ($filters as $filter_id => $filter_handler) {
+            // Currently we know how to update filters only of this particular
+            // class.
+            if (get_class($filter_handler) == 'views_handler_filter_term_node_tid') {
+              $filter = $view->get_item($display_id, 'filter', $filter_id);
+              if (isset($filter['value'][$term_branch->tid])) {
+                // Substituting term branch with term trunk.
+                unset($filter['value'][$term_branch->tid]);
+                $filter['value'][$term_trunk->tid] = $term_trunk->tid;
+                $view->set_item($display_id, 'filter', $filter_id, $filter);
+                $needs_saving = TRUE;
+              }
+            }
+          }
+        }
+        if ($needs_saving) {
+          $view->save();
+        }
+      }
+    }
+
+    // We are instructed to delete the term branch after the merge,
+    // and so we do.
+    taxonomy_term_delete($term_branch->tid);
+  }
+
+  // Here we do the 2nd part of integration with the Redirect module. Once the
+  // branch term has been deleted (if deleted), we can add the redirects
+  // without being afraid that the redirect module will delete them in its
+  // hook_entity_delete().
+  foreach ($redirect_paths as $redirect_destination => $redirect_sources) {
+    foreach ($redirect_sources as $redirect_source) {
+      $redirect = redirect_load_by_source($redirect_source);
+      if (!$redirect) {
+        // Seems like redirect from such URI does not exist yet, we will create
+        // it.
+        $redirect = new stdClass();
+        redirect_object_prepare($redirect, array(
+          'source' => $redirect_source,
+        ));
+      }
+      $redirect->redirect = $redirect_destination;
+      $redirect->status_code = $context['redirect'];
+
+      redirect_save($redirect);
+    }
+  }
+
+  watchdog('term_merge', 'Successfully merged term %term_branch into term %term_trunk in vocabulary %vocabulary. Context: @context', array(
+    '%term_branch' => $term_branch->name,
+    '%term_trunk' => $term_trunk->name,
+    '%vocabulary' => $vocabulary->name,
+    '@context' => var_export($context, 1),
+  ));
+}
+
+/**
+ * Merge terms one into another using batch API.
+ *
+ * @param array $term_branch
+ *   A single term tid or an array of term tids to be merged, aka term branches
+ * @param int $term_trunk
+ *   The tid of the term to merge term branches into, aka term trunk
+ * @param array $merge_settings
+ *   Array of settings that control how merging should happen. Currently
+ *   supported settings are:
+ *     - term_branch_keep: (bool) Whether the term branches should not be
+ *       deleted, also known as "merge only occurrences" option
+ *     - merge_fields: (array) Array of field names whose values should be
+ *       merged into the values of corresponding fields of term trunk (until
+ *       each field's cardinality limit is reached)
+ *     - keep_only_unique: (bool) Whether after merging within one field only
+ *       unique taxonomy term references should be kept in other entities. If
+ *       before merging your entity had 2 values in its taxonomy term reference
+ *       field and one was pointing to term branch while another was pointing to
+ *       term trunk, after merging you will end up having your entity
+ *       referencing to the same term trunk twice. If you pass TRUE in this
+ *       parameter, only a single reference will be stored in your entity after
+ *       merging
+ *     - redirect: (int) HTTP code for redirect from $term_branch to
+ *       $term_trunk, 0 stands for the default redirect defined in Redirect
+ *       module. Use constant TERM_MERGE_NO_REDIRECT to denote not creating any
+ *       HTTP redirect. Note: this parameter requires Redirect module enabled,
+ *       otherwise it will be disregarded
+ *     - synonyms: (array) Array of field names of trunk term into which branch
+ *       terms should be added as synonyms (until each field's cardinality limit
+ *       is reached). Note: this parameter requires Synonyms module enabled,
+ *       otherwise it will be disregarded
+ *     - step: (int) How many term branches to merge per script run in batch. If
+ *       you are hitting time or memory limits, decrease this parameter
+ */
+function term_merge($term_branch, $term_trunk, $merge_settings = array()) {
+  // Older versions of this module had another interface of this function,
+  // as backward capability we still support the older interface, instead of
+  // supplying a $merge_settings array, it was supplying all the settings as
+  // additional function arguments.
+  // @todo: delete this backward capability at some point.
+  if (!is_array($merge_settings)) {
+    $merge_settings = array(
+      'term_branch_keep' => $merge_settings,
+    );
+  }
+
+  // Create an array of sources if it isn't yet.
+  if (!is_array($term_branch)) {
+    $term_branch = array($term_branch);
+  }
+
+  // Creating a skeleton for the merging batch.
+  $batch = array(
+    'title' => t('Merging terms'),
+    'operations' => array(
+      array('_term_merge_batch_process', array(
+        $term_branch,
+        $term_trunk,
+        $merge_settings,
+      )),
+    ),
+    'finished' => 'term_merge_batch_finished',
+    'file' => drupal_get_path('module', 'term_merge') . '/term_merge.batch.inc',
+  );
+
+  // Initialize the batch process.
+  batch_set($batch);
+}
+
+/**
+ * Generate and return form elements that control behavior of merge action.
+ *
+ * Output of this function should be used in any form that merges terms,
+ * ensuring unified interface. It should be used in conjunction with
+ * term_merge_merge_options_submit(), which will process the submitted values
+ * for you and return an array of merge settings.
+ *
+ * @param object $vocabulary
+ *   Fully loaded taxonomy vocabulary object in which merging occurs
+ *
+ * @return array
+ *   Array of form elements that allow controlling term merge action
+ *
+ * @see term_merge_merge_options_submit()
+ */
+function term_merge_merge_options_elements($vocabulary) {
+  // @todo: it would be nice to provide some ability to supply default values
+  // for each setting.
+  $form = array();
+
+  // Getting bundle name and a list of fields attached to this bundle for
+  // further use down below in the code while generating form elements.
+  $bundle = field_extract_bundle('taxonomy_term', $vocabulary);
+  $instances = field_info_instances('taxonomy_term', $bundle);
+
+  $form['term_branch_keep'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Only merge occurrences'),
+    '#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.'),
+  );
+
+  if (!empty($instances)) {
+    $options = array();
+    foreach ($instances as $instance) {
+      $options[$instance['field_name']] = $instance['label'];
+    }
+    $form['merge_fields'] = array(
+      '#type' => 'checkboxes',
+      '#title' => t('Merge Term Fields'),
+      '#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.'),
+      '#options' => $options,
+    );
+  }
+
+  $form['keep_only_unique'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Keep only unique terms after merging'),
+    '#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.'),
+  );
+
+  if (module_exists('redirect')) {
+    $options = array(
+      TERM_MERGE_NO_REDIRECT => t('No redirect'),
+      0 => t('Default (@default)', array(
+        '@default' => variable_get('redirect_default_status_code', 301),
+      )),
+    ) + redirect_status_code_options();
+    $form['redirect'] = array(
+      // We respect access rights defined in redirect.module here.
+      '#access' => user_access('administer redirects'),
+      '#type' => 'select',
+      '#title' => t('Create Redirect'),
+      '#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.'),
+      '#required' => TRUE,
+      '#options' => $options,
+      '#default_value' => TERM_MERGE_NO_REDIRECT,
+    );
+  }
+  else {
+    $form['redirect'] = array(
+      '#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.'),
+    );
+  }
+
+  if (module_exists('synonyms')) {
+    $options = array();
+    foreach (synonyms_synonyms_fields($vocabulary) as $field_name) {
+      $options[$field_name] = $instances[$field_name]['label'];
+    }
+    $form['synonyms'] = array(
+      '#type' => 'checkboxes',
+      '#title' => t('Add as Synonyms'),
+      '#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.'),
+      '#options' => $options,
+    );
+  }
+  else {
+    $form['synonyms'] = array(
+      '#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.'),
+    );
+  }
+
+  $form['step'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Step'),
+    '#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.'),
+    '#default_value' => 40,
+    '#required' => TRUE,
+    '#element_validate' => array('element_validate_integer_positive'),
+  );
+
+  return $form;
+}
+
+/**
+ * Return merge settings array.
+ *
+ * Output of this function should be used for supplying into term_merge()
+ * function or for triggering actions_do('term_merge_action', ...) action. This
+ * function should be invoked in a form submit handler for a form that used
+ * term_merge_merge_options_elements() for generating merge settings elements.
+ * It will process data and return an array of merge settings, according to the
+ * data user has submitted in your form.
+ *
+ * @param array $merge_settings_element
+ *   That part of form that was generated by term_merge_merge_options_elements()
+ * @param array $form_state
+ *   Form state array of the submitted form
+ * @param array $form
+ *   Form array of the submitted form
+ *
+ * @return array
+ *   Array of merge settings that can be used for calling term_merge() or
+ *   invoking 'term_merge_action' action
+ *
+ * @see term_merge_merge_options_elements()
+ */
+function term_merge_merge_options_submit($merge_settings_element, &$form_state, $form) {
+  $merge_settings = array(
+    'term_branch_keep' => (bool) $merge_settings_element['term_branch_keep']['#value'],
+    'merge_fields' => isset($merge_settings_element['merge_fields']['#value']) ? array_values(array_filter($merge_settings_element['merge_fields']['#value'])) : array(),
+    'keep_only_unique' => (bool) $merge_settings_element['keep_only_unique']['#value'],
+    'redirect' => isset($merge_settings_element['redirect']['#value']) ? $merge_settings_element['redirect']['#value'] : TERM_MERGE_NO_REDIRECT,
+    'synonyms' => isset($merge_settings_element['synonyms']['#value']) ? array_values(array_filter($merge_settings_element['synonyms']['#value'])) : array(),
+    'step' => (int) $merge_settings_element['step']['#value'],
+  );
+  return $merge_settings;
+}

+ 844 - 0
sites/all/modules/contrib/taxonomy/term_merge/term_merge.pages.inc

@@ -0,0 +1,844 @@
+<?php
+
+/**
+ * @file
+ * Menu page callbacks for Term Merge module.
+ */
+
+/**
+ * Menu callback.
+ *
+ * Allow user to specify which terms to be merged into which term and any
+ * other settings needed for the term merge action.
+ *
+ * @param object $vocabulary
+ *   Fully loaded taxonomy vocabulary object
+ * @param object $term
+ *   Fully loaded taxonomy term object that should be selected as the default
+ *   merge term in the form. If the $vocabulary is omitted, the vocabulary of
+ *   $term is considered
+ *
+ * @return array
+ *   Array of the form in Form API format
+ */
+function term_merge_form($form, $form_state, $vocabulary = NULL, $term = NULL) {
+  if (is_null($vocabulary)) {
+    $vocabulary = taxonomy_vocabulary_load($term->vid);
+  }
+
+  // It's always handy to have the vocabulary by hand.
+  $form['#vocabulary'] = $vocabulary;
+
+  if (!isset($form_state['storage']['confirm'])) {
+    // We are at the set up step.
+
+    $tree = taxonomy_get_tree($vocabulary->vid);
+
+    $term_branch_value = is_null($term) ? NULL : array($term->tid);
+    if (variable_get('taxonomy_override_selector', FALSE) && module_exists('hs_taxonomy')) {
+      // We use Hierarchical Select module if it's available and configured to
+      // be used for taxonomy selects.
+      $form['term_branch'] = array(
+        '#type' => 'hierarchical_select',
+        // @todo: figure out why #required => TRUE doesn't work.
+        // As a matter of fact, this issue seems to cover our case.
+        // http://drupal.org/node/1275862.
+        //'#required' => TRUE,
+        '#config' => array(
+          'module' => 'hs_taxonomy',
+          'params' => array(
+            'vid' => $vocabulary->vid,
+            'exclude_tid' => NULL,
+            'root_term'   => FALSE,
+          ),
+          'enforce_deepest' => 0,
+          'entity_count' => 0,
+          'require_entity' => 0,
+          'save_lineage' => 0,
+          'level_labels' => array(
+            'status' => 0,
+          ),
+          'dropbox' => array(
+            'status' => 1,
+            'limit' => 0,
+          ),
+          'editability' => array(
+            'status' => 0,
+          ),
+          'resizable' => TRUE,
+          'render_flat_select' => 0,
+        ),
+      );
+    }
+    else {
+      // Falling back on a simple <select>.
+      $options = array();
+      foreach ($tree as $v) {
+        $options[$v->tid] = str_repeat('-', $v->depth) . $v->name . ' [tid: ' . $v->tid . ']';
+      }
+      $form['term_branch'] = array(
+        '#type' => 'select',
+        '#required' => TRUE,
+        '#multiple' => TRUE,
+        '#options' => $options,
+        '#size' => 8,
+      );
+    }
+
+    $form['term_branch'] = array(
+      '#title' => t('Terms to Merge'),
+      '#description' => t('Please, choose the terms you want to merge into another term.'),
+      '#ajax' => array(
+        'callback' => 'term_merge_form_term_trunk',
+        'wrapper' => 'term-merge-form-term-trunk',
+        'method' => 'replace',
+        'effect' => 'fade',
+      ),
+      '#default_value' => $term_branch_value,
+    ) + $form['term_branch'];
+    if (is_null($form['term_branch']['#default_value'])) {
+      unset($form['term_branch']['#default_value']);
+    }
+
+    $form['term_trunk'] = array(
+      '#type' => 'fieldset',
+      '#title' => t('Merge Into'),
+      '#prefix' => '<div id="term-merge-form-term-trunk">',
+      '#suffix' => '</div>',
+      '#tree' => TRUE,
+    );
+
+    // Array of currently available widgets for choosing term trunk.
+    $term_trunk_widget_options = array(
+      'autocomplete' => 'Autocomplete',
+    );
+    if (variable_get('taxonomy_override_selector', FALSE) && module_exists('hs_taxonomy')) {
+      $term_trunk_widget_options['hs_taxonomy'] = t('Hierarchical Select');
+      $term_trunk_widget = 'hs_taxonomy';
+    }
+    else {
+      $term_trunk_widget_options['select'] = t('Select');
+      $term_trunk_widget = 'select';
+    }
+
+    // If the vocabulary is too big, by default we want the trunk term widget to
+    // be autocomplete instead of select or hs_taxonomy.
+    if (count($tree) > 200) {
+      $term_trunk_widget = 'autocomplete';
+    }
+
+    // Override the term trunk widget if settings are found in $form_state.
+    if (isset($form_state['values']['term_trunk']['widget']) && in_array($form_state['values']['term_trunk']['widget'], array_keys($term_trunk_widget_options))) {
+      $term_trunk_widget = $form_state['values']['term_trunk']['widget'];
+    }
+
+    $form['term_trunk']['widget'] = array(
+      '#type' => 'radios',
+      '#title' => t('Widget'),
+      '#required' => TRUE,
+      '#options' => $term_trunk_widget_options,
+      '#default_value' => $term_trunk_widget,
+      '#description' => t('Choose what widget you prefer for entering the term trunk.'),
+      '#ajax' => array(
+        'callback' => 'term_merge_form_term_trunk',
+        'wrapper' => 'term-merge-form-term-trunk',
+        'method' => 'replace',
+        'effect' => 'fade',
+      ),
+    );
+
+    // @todo:
+    // There is a known bug, if user has selected something in one widget, and
+    // then changes the widget, $form_states['values'] will hold the value for
+    // term trunk form element in the format that is used in one widget, while
+    // this value will be passed to another widget. This triggers different
+    // unpleasant effects like showing tid instead of term's name or vice-versa.
+    // I think we should just empty $form_state['values'] for the term trunk
+    // form element when widget changes. Better ideas are welcome!
+    $function = 'term_merge_form_term_trunk_widget_' . $term_trunk_widget;
+    $function($form, $form_state, $vocabulary);
+
+    // Ensuring the Merge Into form element has the same title no matter what
+    // widget has been used.
+    $form['term_trunk']['tid']['#title'] = t('Merge into');
+
+    // Adding necessary options of merging.
+    $form += term_merge_merge_options_elements($vocabulary);
+
+    $form['actions'] = array(
+      '#type' => 'actions',
+    );
+
+    $form['actions']['submit'] = array(
+      '#type' => 'submit',
+      '#value' => t('Submit'),
+    );
+  }
+  else {
+    // We are at the confirmation step.
+    $count = count($form_state['values']['term_branch']);
+    $question = format_plural($count, 'Are you sure want to merge 1 term?', 'Are you sure want to merge @count terms?');
+    $form = confirm_form($form, $question, 'admin/structure/taxonomy/' . $vocabulary->machine_name);
+  }
+
+  return $form;
+}
+
+/**
+ * Supportive function.
+ *
+ * Validate the term_merge_form(). Make sure term trunk is not among the
+ * selected term branches or their children.
+ */
+function term_merge_form_validate($form, &$form_state) {
+  if (!isset($form_state['storage']['confirm'])) {
+    // We only validate the 1st step of the form.
+    $prohibited_trunks = array();
+    foreach ($form_state['values']['term_branch'] as $term_branch) {
+      $children = taxonomy_get_tree($form['#vocabulary']->vid, $term_branch);
+      $prohibited_trunks[] = $term_branch;
+      foreach ($children as $child) {
+        $prohibited_trunks[] = $child->tid;
+      }
+    }
+    if (in_array($form_state['values']['term_trunk']['tid'], $prohibited_trunks)) {
+      form_error($form['term_trunk']['tid'], t('Trunk term cannot be one of the selected branch terms or their children.'));
+    }
+  }
+}
+
+/**
+ * Submit handler for term_merge_form(). Merge terms one into another.
+ */
+function term_merge_form_submit($form, &$form_state) {
+  if (!isset($form_state['storage']['confirm'])) {
+    // Since merging terms is an important operation, we better confirm user
+    // really wants to do this.
+    $form_state['storage']['confirm'] = 0;
+    $form_state['rebuild'] = TRUE;
+
+    // Before storing the submitted values we slightly preprocess them to make
+    // sure they correspond to what is expected by submit handler of taxonomy
+    // creation form.
+    if (isset($form_state['values']['relations'])) {
+      $form_state['values'] += $form_state['values']['relations'];
+    }
+    $form_state['storage']['info'] = $form_state['values'];
+    $form_state['storage']['merge_settings'] = term_merge_merge_options_submit($form, $form_state, $form);
+    $form_state['storage']['old_form'] = $form;
+  }
+  else {
+    // The user has confirmed merging. We pull up the submitted values.
+    $form_state['values'] = $form_state['storage']['info'];
+
+    // If necessary, create the term trunk.
+    if ($form_state['values']['term_trunk']['tid'] == TERM_MERGE_NEW_TERM_TRUNK) {
+      // We try to mimic normal form submission for taxonomy module.
+      module_load_include('inc', 'taxonomy', 'taxonomy.admin');
+      taxonomy_form_term_submit($form_state['storage']['old_form']['term_trunk']['term_create'], $form_state);
+      $term_trunk = $form_state['term'];
+    }
+    else {
+      $term_trunk = taxonomy_term_load($form_state['values']['term_trunk']['tid']);
+    }
+
+    term_merge(array_values($form_state['values']['term_branch']), $term_trunk->tid, $form_state['storage']['merge_settings']);
+
+    $form_state['redirect'] = array('taxonomy/term/' . $term_trunk->tid);
+  }
+}
+
+/**
+ * Supportive function.
+ *
+ * Generate form elements for select widget for term trunk element of the
+ * term_merge_form().
+ *
+ * @param object $vocabulary
+ *   Fully loaded taxonomy vocabulary object
+ */
+function term_merge_form_term_trunk_widget_select(&$form, &$form_state, $vocabulary) {
+  $tree = taxonomy_get_tree($vocabulary->vid);
+  $options = array();
+  foreach ($tree as $v) {
+    $options[$v->tid] = str_repeat('-', $v->depth) . $v->name . ' [tid: ' . $v->tid . ']';
+  }
+
+  $term_branch_value = array();
+  // Firstly trying to look up selected term branches in the default value of
+  // term branch form element.
+  if (isset($form['term_branch']['#default_value']) && is_array($form['term_branch']['#default_value'])) {
+    $term_branch_value = $form['term_branch']['#default_value'];
+  }
+  if (isset($form_state['values']['term_branch']) && is_array($form_state['values']['term_branch'])) {
+    $term_branch_value = $form_state['values']['term_branch'];
+  }
+
+  if (!empty($term_branch_value)) {
+    // We have to make sure among term_trunk there is no term_branch or any of
+    // their children.
+    foreach ($term_branch_value as $v) {
+      unset($options[$v]);
+      foreach (taxonomy_get_tree($vocabulary->vid, $v) as $child) {
+        unset($options[$child->tid]);
+      }
+    }
+    $options = array(TERM_MERGE_NEW_TERM_TRUNK => 'New Term') + $options;
+  }
+  else {
+    // Term branch has not been selected yet.
+    $options = array();
+  }
+
+  $form['term_trunk']['tid'] = array(
+    '#type' => 'select',
+    '#required' => TRUE,
+    '#description' => t('Choose into what term you want to merge.'),
+    '#options' => $options,
+    '#ajax' => array(
+      'callback' => 'term_merge_form_term_trunk_term_create',
+      'wrapper' => 'term-merge-form-term-trunk-term-create',
+      'method' => 'replace',
+      'effect' => 'fade',
+    ),
+  );
+
+  $form['term_trunk']['term_create'] = array(
+    '#prefix' => '<div id="term-merge-form-term-trunk-term-create">',
+    '#suffix' => '</div>',
+  );
+  // We throw in the Taxonomy native term create form only if the option for
+  // creation of a new term was selected by user.
+  if (isset($form_state['values']['term_trunk']['tid']) && $form_state['values']['term_trunk']['tid'] == TERM_MERGE_NEW_TERM_TRUNK) {
+    module_load_include('inc', 'taxonomy', 'taxonomy.admin');
+
+    $form['term_trunk']['term_create'] += array(
+      '#type' => 'fieldset',
+      '#title' => t('Create New Term'),
+    );
+
+    $form['term_trunk']['term_create'] += taxonomy_form_term($form['term_trunk']['term_create'], $form_state, array(), $vocabulary);
+    // We have our own submit button, so we unset the normal one from the term
+    // create form.
+    unset($form['term_trunk']['term_create']['actions']);
+    // Additionally we have to filter out from "Parent Terms" select the already
+    // selected branch terms and their children, because we can't merge into
+    // the term itself or its children.
+    // We do a trick here, since we know the 1st element is the <root> option
+    // and all others are normal taxonomy terms, we keep the 1st element as it
+    // is while all the other elements we substitute with our $options array
+    // which is basically identical but already has been filtered out unwanted
+    // terms. Plus we have to unset the 'New Term' option from $options.
+    unset($options[TERM_MERGE_NEW_TERM_TRUNK]);
+    if (is_array($form['term_trunk']['term_create']['relations']['parent']['#options'])) {
+      $form['term_trunk']['term_create']['relations']['parent']['#options'] = array_slice($form['term_trunk']['term_create']['relations']['parent']['#options'], 0, 1, TRUE) + $options;
+    }
+
+    // For each field attached to taxonomy term of this vocabulary that has
+    // unlimited cardinality we have to extra process the results, otherwise
+    // "Add another item" button doesn't work.
+    $instances = field_info_instances($form['term_trunk']['term_create']['#entity_type'], $form['term_trunk']['term_create']['#bundle']);
+    foreach ($instances as $instance) {
+      $field = field_info_field($instance['field_name']);
+      if ($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED) {
+        if (isset($form['term_trunk']['term_create'][$field['field_name']][LANGUAGE_NONE]['add_more']['#limit_validation_errors'])) {
+          $form['term_trunk']['term_create'][$field['field_name']][LANGUAGE_NONE]['add_more']['#limit_validation_errors'] = array(array('term_branch'), array('term_trunk'));
+        }
+      }
+    }
+  }
+}
+
+/**
+ * Supportive function.
+ *
+ * Generate form element for hierarchical select widget for term trunk element
+ * of the term_merge_form().
+ *
+ * @param object $vocabulary
+ *   Fully loaded taxonomy vocabulary object
+ */
+function term_merge_form_term_trunk_widget_hs_taxonomy(&$form, &$form_state, $vocabulary) {
+  $form['term_trunk']['tid'] = array(
+    '#type' => 'hierarchical_select',
+    '#description' => t('Please select a term to merge into.'),
+    '#required' => TRUE,
+    '#element_validate' => array('term_merge_form_trunk_term_widget_hs_taxonomy_validate'),
+    '#config' => array(
+      'module' => 'hs_taxonomy',
+      'params' => array(
+        'vid' => $vocabulary->vid,
+        'exclude_tid' => NULL,
+        'root_term'   => FALSE,
+      ),
+      'enforce_deepest' => 0,
+      'entity_count' => 0,
+      'require_entity' => 0,
+      'save_lineage' => 0,
+      'level_labels' => array(
+        'status' => 0,
+      ),
+      'dropbox' => array(
+        'status' => 0,
+      ),
+      'editability' => array(
+        'status' => 0,
+      ),
+      'resizable' => TRUE,
+      'render_flat_select' => 0,
+    ),
+  );
+}
+
+/**
+ * Supportive function.
+ *
+ * Generate form elements for autocomplete widget for term trunk element of the
+ * term_merge_form().
+ *
+ * @param object $vocabulary
+ *   Fully loaded taxonomy vocabulary object
+ */
+function term_merge_form_term_trunk_widget_autocomplete(&$form, &$form_state, $vocabulary) {
+  $form['term_trunk']['tid'] = array(
+    '#type' => 'textfield',
+    '#description' => t("Start typing in a term's name in order to get some suggestions."),
+    '#required' => TRUE,
+    '#autocomplete_path' => 'term-merge/autocomplete/term-trunk/' . $vocabulary->machine_name,
+    '#element_validate' => array('term_merge_form_trunk_term_widget_autocomplete_validate'),
+  );
+}
+
+/**
+ * Supportive function.
+ *
+ * Validate form element of the autocomplete widget of term trunk element of
+ * the form term_merge_form(). Make sure the entered string is a name of one of
+ * the existing terms in the vocabulary where the merge occurs. If term is found
+ * the function substitutes the name with its {taxonomy_term_data}.tid as it is
+ * what is expected from a term trunk widget to provide in its value.
+ */
+function term_merge_form_trunk_term_widget_autocomplete_validate($element, &$form_state, $form) {
+  $term = taxonomy_get_term_by_name($element['#value'], $form['#vocabulary']->machine_name);
+  if (!is_array($term) || empty($term)) {
+    // Seems like the user has entered a non existing name in the autocomplete
+    // textfield.
+    form_error($element, t('There are no terms with name %name in the %vocabulary vocabulary.', array(
+      '%name' => $element['#value'],
+      '%vocabulary' => $form['#vocabulary']->name,
+    )));
+  }
+  else {
+    // We have to substitute the term's name with its tid in order to make this
+    // widget consistent with the interface.
+    $term = array_pop($term);
+    form_set_value($element, $term->tid, $form_state);
+  }
+}
+
+/**
+ * Supportive function.
+ *
+ * Validate form element of the Hierarchical Select widget of term trunk element
+ * of the form term_merge_form(). Convert the value from array to a single tid
+ * integer value.
+ */
+function term_merge_form_trunk_term_widget_hs_taxonomy_validate($element, &$form_state, $form) {
+  $tid = 0;
+  if (is_array($element['#value']) && !empty($element['#value'])) {
+    $tid = (int) array_pop($element['#value']);
+  }
+  form_set_value($element, $tid, $form_state);
+}
+
+/**
+ * Menu page callback function.
+ *
+ * Autocomplete callback function for the trunk term form element in the widget
+ * of autocomplete. The code of this function was mainly copy-pasted from
+ * Taxonomy autocomplete widget menu callback function.
+ *
+ * @param object $vocabulary
+ *   Fully loaded vocabulary object inside of which the terms are about to be
+ *   merged
+ */
+function term_merge_form_term_trunk_widget_autocomplete_autocomplete($vocabulary) {
+  // If the request has a '/' in the search text, then the menu system will have
+  // split it into multiple arguments, recover the intended $tags_typed.
+  $args = func_get_args();
+  // Shift off the $vocabulary argument.
+  array_shift($args);
+  $tags_typed = implode('/', $args);
+
+  // Querying database for suggestions.
+  $query = db_select('taxonomy_term_data', 't');
+  $tags_return = $query->addTag('translatable')
+    ->addTag('term_access')
+    ->fields('t', array('tid', 'name'))
+    ->condition('t.vid', $vocabulary->vid)
+    ->condition('t.name', '%' . db_like($tags_typed) . '%', 'LIKE')
+    ->range(0, 10)
+    ->execute()
+    ->fetchAllKeyed();
+
+  $term_matches = array();
+  foreach ($tags_return as $tid => $name) {
+    $n = $name;
+    // Term names containing commas or quotes must be wrapped in quotes.
+    if (strpos($name, ',') !== FALSE || strpos($name, '"') !== FALSE) {
+      $n = '"' . str_replace('"', '""', $name) . '"';
+    }
+    $term_matches[$n] = check_plain($name . ' [tid: ' . $tid . ']');
+  }
+
+  drupal_json_output($term_matches);
+}
+
+/**
+ * Ajax callback function.
+ *
+ * Used in term_merge_term_merge_form() to replace the term_trunk element
+ * depending on already selected term_branch values.
+ */
+function term_merge_form_term_trunk($form, $form_state) {
+  return $form['term_trunk'];
+}
+
+/**
+ * Ajax callback function.
+ *
+ * Used in term_merge_term_merge_form() to replace the term create fieldset
+ * depending on already selected term_branch values and the term_trunk value.
+ */
+function term_merge_form_term_trunk_term_create($form, $form_state) {
+  return $form['term_trunk']['term_create'];
+}
+
+/**
+ * Generate 'term_merge_duplicates_form'.
+ *
+ * Allow merging terms with the same or similar names.
+ *
+ * @param object $vocabulary
+ *   Fully loaded taxonomy vocabulary object inside of which term merging
+ *   occurs, if this argument is omitted, then $term is required and will be
+ *   used to obtain information about Taxonomy vocabulary
+ * @param object $parent_term
+ *   Fully loaded taxonomy term object using which the function will pull up
+ *   the vocabulary inside of which term merging occurs. Duplicate terms will be
+ *   sought only among children of this term
+ */
+function term_merge_duplicates_form($form, &$form_state, $vocabulary = NULL, $parent_term = NULL) {
+  // TODO: make this JavaScript #attached.
+  drupal_add_js(drupal_get_path('module', 'term_merge') . '/js/duplicate.form.js');
+
+  // Checking if we were not given vocabulary object, we will use term object to
+  // obtain the former.
+  if (!is_null($parent_term) && is_null($vocabulary)) {
+    $vocabulary = taxonomy_vocabulary_load($parent_term->vid);
+  }
+
+  $tree = taxonomy_get_tree($vocabulary->vid, is_null($parent_term) ? 0 : $parent_term->tid);
+
+  // Helpful and self explaining text that should help people understand what's
+  // up.
+  $form['help'] = array(
+    '#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>',
+  );
+
+  $form['scaling'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Scaling for large vocabularies'),
+    '#description' => t('Adjust these settings if your vocabulary is very large.'),
+    '#tree' => TRUE,
+    '#collapsible' => TRUE,
+  );
+
+  $form['scaling']['help'] = array(
+    '#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(
+      '%vocabulary' => $vocabulary->name,
+    )) . '</p>',
+  );
+
+  $form['scaling']['max_duplicates'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Show N duplicates'),
+    '#description' => t('Input an integer here - this many duplicates will be show on the form. Once this amount of possible duplicates is found, the search process terminates.'),
+    '#required' => TRUE,
+    '#default_value' => isset($form_state['values']['scaling']['max_duplicates']) ? $form_state['values']['scaling']['max_duplicates'] : 300,
+    '#element_validate' => array('element_validate_integer_positive'),
+  );
+
+  $form['scaling']['update'] = array(
+    '#type' => 'button',
+    '#value' => t('Re-run duplicate search'),
+    '#ajax' => array(
+      'callback' => 'term_merge_duplicates_form_scaling',
+      'wrapper' => 'term-merge-duplicate-wrapper',
+      'method' => 'replace',
+      'effect' => 'fade',
+    ),
+  );
+
+  // Amount of found duplicates.
+  $count = 0;
+
+  // Array of groups of terms with the same name. Each group is an array of
+  // duplicates. Trunk term of each group will be chosen by user.
+  $groups = array();
+
+  foreach ($tree as $term) {
+    if ($count >= $form['scaling']['max_duplicates']['#default_value']) {
+      // We have reached the limit of possible duplicates to be found.
+      break;
+    }
+    $name = term_merge_duplicates_process_name($term->name);
+    if (!isset($groups[$name])) {
+      $groups[$name] = array();
+    }
+    else {
+      // We increment count by one for the just encountered duplicate. Plus, if
+      // it is the second duplicate in this group, we also increment it by one
+      // for the 1st duplicate in the group.
+      $count++;
+      if (count($groups[$name]) == 1) {
+        $count++;
+      }
+    }
+    $groups[$name][$term->tid] = $term;
+  }
+
+  $form['wrapper'] = array(
+    '#prefix' => '<div id="term-merge-duplicate-wrapper">',
+    '#suffix' => '</div>',
+  );
+
+  if ($count > 0) {
+    $form['wrapper']['global_switch'] = array(
+      '#type' => 'checkbox',
+      '#title' => t('Select All Terms'),
+      '#description' => t('Checking here will select for merging all the encountered duplicate terms.'),
+      '#attributes' => array(
+        'class' => array('term-merge-duplicate-general-switch'),
+      ),
+    );
+  }
+
+  $form['wrapper']['group'] = array(
+    '#tree' => TRUE,
+  );
+
+  foreach ($groups as $i => $group) {
+    if (count($group) > 1) {
+      // Sorting terms by tid for better usage experience.
+      ksort($group);
+
+      $first_term = reset($group);
+
+      $options = array();
+      foreach ($group as $term) {
+        $parents = array();
+        // Adding Root to the hierarchy.
+        $parents[] = t('Vocabulary Root');
+        foreach (taxonomy_get_parents_all($term->tid) as $parent) {
+          // We do not include the current term in the hierarchy.
+          if ($parent->tid != $term->tid) {
+            $parents[] = $parent->name;
+          }
+        }
+        $language = isset($term->language) ? $term->language : LANGUAGE_NONE;
+        if ($language == LANGUAGE_NONE) {
+          $language = t('Not Specified');
+        }
+
+        $options[$term->tid] = array(
+          'id' => $term->tid,
+          'title' => l($term->name, 'taxonomy/term/' . $term->tid),
+          'language' => $language,
+          'description' => check_markup($term->description, $term->format),
+          'parents' => implode(' &raquo; ', $parents),
+        );
+      }
+
+      $form['wrapper']['group'][$i] = array(
+        '#type' => 'fieldset',
+        '#title' => check_plain($first_term->name),
+        '#collapsible' => TRUE,
+        '#pre_render' => array('term_merge_duplicates_fieldset_preprocess'),
+        '#element_validate' => array('term_merge_duplicates_fieldset_validate'),
+      );
+
+      $form['wrapper']['group'][$i]['duplicates'] = array(
+        '#type' => 'tableselect',
+        '#title' => 'Duplicates',
+        '#header' => array(
+          'id' => t('ID'),
+          'title' => t('Title'),
+          'description' => t('Description'),
+          'language' => t('Language'),
+          'parents' => t('Parents'),
+        ),
+        '#options' => $options,
+      );
+
+      $options = array();
+      foreach ($group as $term) {
+        $options[$term->tid] = $term->name;
+      }
+      $form['wrapper']['group'][$i]['trunk_tid'] = array(
+        '#type' => 'radios',
+        '#title' => t('Merge Into'),
+        '#options' => $options,
+        '#attributes' => array(
+          'class' => array('term-merge-duplicate-trunk'),
+        ),
+      );
+    }
+  }
+
+  if ($count > 0) {
+    // Adding necessary options of merging.
+    $form += term_merge_merge_options_elements($vocabulary);
+
+    $form['actions'] = array(
+      '#type' => 'actions',
+    );
+
+    $form['actions']['submit'] = array(
+      '#type' => 'submit',
+      '#value' => t('Submit'),
+    );
+  }
+  else {
+    if (is_null($parent_term)) {
+      $no_match_text = t('Sorry, seems like we were not able to find any possible duplicate terms in %vocabulary vocabulary.', array(
+        '%vocabulary' => $vocabulary->name,
+      ));
+    }
+    else {
+      $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(
+        '%term' => $parent_term->name,
+        '!url' => url('admin/structure/taxonomy/' . $vocabulary->machine_name . '/merge/duplicates'),
+      ));
+    }
+    $form['nothing_found'] = array(
+      '#markup' => '<p><b>' . $no_match_text . '</b></p>',
+    );
+  }
+
+  return $form;
+}
+
+/**
+ * Submit handler for 'term_merge_duplicates_form'.
+ *
+ * Actually merge duplicate terms.
+ */
+function term_merge_duplicates_form_submit($form, &$form_state) {
+  $batch = array(
+    'title' => t('Merging terms'),
+    'operations' => array(),
+    'finished' => 'term_merge_batch_finished',
+    'file' => drupal_get_path('module', 'term_merge') . '/term_merge.batch.inc',
+  );
+
+  // Processing general options for merging.
+  $merge_settings = term_merge_merge_options_submit($form, $form_state, $form);
+
+  if (isset($form_state['values']['group'])) {
+    foreach ($form_state['values']['group'] as $values) {
+      // Filtering out only the selected duplicate terms.
+      $term_branches = array_filter($values['duplicates']);
+      // We also do not want to have trunk term to be among the branch terms.
+      unset($term_branches[$values['trunk_tid']]);
+      if (!empty($term_branches)) {
+        // If something has been selected in this group we schedule its merging.
+        $batch['operations'][] = array('_term_merge_batch_process', array(
+          $term_branches,
+          $values['trunk_tid'],
+          $merge_settings,
+        ));
+      }
+    }
+  }
+
+  if (empty($batch['operations'])) {
+    drupal_set_message(t('No merging has been made, because you have not selected any duplicate term to merge.'));
+  }
+  else {
+    batch_set($batch);
+  }
+}
+
+/**
+ * String process function.
+ *
+ * Manipulate supplied var $name and by the output of this function terms in a
+ * vocabulary are grouped as duplicates.
+ *
+ * @param string $name
+ *   String that needs to be manipulated
+ *
+ * @return string
+ *   Processed string (normally it implies making it upper case, stripping down
+ *   any special chars, etc.)
+ */
+function term_merge_duplicates_process_name($name) {
+  // Making upper case.
+  $name = drupal_strtoupper($name);
+  // Trying transliteration, if available.
+  if (module_exists('transliteration')) {
+    $name = transliteration_get($name);
+    // Keeping only ASCII chars.
+    $name = preg_replace('#\W#', '', $name);
+  }
+  return $name;
+}
+
+/**
+ * Form element preprocess function.
+ *
+ * Insert extra column for choosing term trunk into tableselect of terms to be
+ * merged.
+ */
+function term_merge_duplicates_fieldset_preprocess($element) {
+  $options = &$element['duplicates']['#options'];
+  foreach ($options as $tid => $row) {
+    $element['trunk_tid'][$tid]['#title_display'] = 'invisible';
+    $options[$tid] = array(
+      'trunk' => drupal_render($element['trunk_tid'][$tid]),
+    ) + $options[$tid];
+  }
+  $element['trunk_tid']['#title_display'] = 'invisible';
+  $element['duplicates']['#header'] = array(
+    'trunk' => $element['trunk_tid']['#title'],
+  ) + $element['duplicates']['#header'];
+
+  return $element;
+}
+
+/**
+ * FAPI element validation callback.
+ *
+ * Validate fieldset of a 'term_merge_duplicates_form' form, if any duplicate
+ * has been selected for merging, it makes sure the trunk term has been
+ * selected. We can't allow merging without knowing the explicit trunk term.
+ */
+function term_merge_duplicates_fieldset_validate($element, &$form_state, $form) {
+  if (!empty($element['duplicates']['#value']) && !is_numeric($element['trunk_tid']['#value'])) {
+    form_error($element, t('Please, choose %trunk_tid_label for the group %group_label', array(
+      '%trunk_tid_label' => $element['trunk_tid']['#title'],
+      '%group_label' => $element['#title'],
+    )));
+  }
+}
+
+/**
+ * Ajax callback function.
+ *
+ * Used in term_merge_duplicates_form() to replace the duplicates tables with
+ * new data per current scaling settings.
+ */
+function term_merge_duplicates_form_scaling($form, &$form_state) {
+  return $form['wrapper'];
+}

+ 1548 - 0
sites/all/modules/contrib/taxonomy/term_merge/term_merge.test

@@ -0,0 +1,1548 @@
+<?php
+
+/**
+ * @file
+ * Test the Term Merge module.
+ */
+
+/**
+ * Base class for all tests of Term Merge module.
+ */
+class TermMergeWebTestCase extends DrupalWebTestCase {
+
+  /**
+   * Fully loaded Drupal user who has access to all required parts of the
+   * website for testing.
+   *
+   * @var object
+   */
+  protected $admin;
+
+  /**
+   * Fully loaded Drupal taxonomy vocabulary object on which all tests are run.
+   *
+   * @var object
+   */
+  protected $vocabulary;
+
+  /**
+   * SetUp method.
+   *
+   * @param array $modules
+   *   Array of modules that need to be enabled for test case
+   */
+  public function setUp(array $modules = array()) {
+    $modules[] = 'term_merge';
+    parent::setUp($modules);
+
+    $this->admin = $this->drupalCreateUser(array(
+      'administer taxonomy',
+      'merge terms',
+      'administer content types',
+      'bypass node access',
+    ));
+
+    // Creating vocabularies.
+    $this->drupalLogin($this->admin);
+    $name = $this->randomName();
+    $this->drupalPost('admin/structure/taxonomy/add', array(
+      'name' => $name,
+      'machine_name' => 'vocabulary',
+      'description' => $this->randomName(),
+    ), 'Save');
+    $this->vocabulary = taxonomy_vocabulary_machine_name_load('vocabulary');
+    // Flushing static cache.
+    _field_info_collate_fields(TRUE);
+  }
+
+  /**
+   * Return last inserted term into the specified vocabulary.
+   *
+   * @param object $vocabulary
+   *   Fully loaded taxonomy vocabulary object
+   *
+   * @return object
+   *   Fully loaded taxonomy term object of the last inserted term into
+   *   the specified vocabulary
+   */
+  protected function getLastTerm($vocabulary) {
+    drupal_static_reset();
+    $tree = taxonomy_get_tree($vocabulary->vid);
+    $max = 0;
+    $term = NULL;
+    foreach ($tree as $v) {
+      if ($v->tid > $max) {
+        $max = $v->tid;
+        $term = $v;
+      }
+    }
+    $term = entity_load_unchanged('taxonomy_term', $term->tid);
+    return $term;
+  }
+}
+
+/**
+ * Test the functionality of Term Merge module.
+ */
+class TermMergeTermMergeWebTestCase extends TermMergeWebTestCase {
+
+  /**
+   * GetInfo method.
+   */
+  public function getInfo() {
+    return array(
+      'name' => 'Term Merge',
+      'description' => 'Ensure that the module Term Merge works correctly.',
+      'group' => 'Term Merge',
+    );
+  }
+
+  /**
+   * Test merging two terms.
+   */
+  public function testTermMerge() {
+    // Checking whether parent's relationship is handled as it should.
+    // At the same time we make sure 'term_branch_keep' property functions.
+    $terms = array(
+      'trunk' => FALSE,
+      'branch' => FALSE,
+      'another_parent' => FALSE,
+      'branch_child' => FALSE,
+    );
+    foreach ($terms as $term_type => $tmp) {
+      $url = 'admin/structure/taxonomy/vocabulary/add';
+      $name = $this->randomName();
+      $edit = array(
+        'name' => $name,
+      );
+
+      // Putting "branch" to be parent of "branch_child".
+      if ($term_type == 'branch_child') {
+        $edit['parent[]'] = array($terms['branch']->tid, $terms['another_parent']->tid);
+      }
+
+      $this->drupalPost($url, $edit, 'Save');
+      $terms[$term_type] = $this->getLastTerm($this->vocabulary);
+    }
+
+    // Firstly we try to merge without deleting the branch term and make sure
+    // branch's children are not reassigned to the trunk term nor the branch
+    // term itself is deleted.
+    actions_do('term_merge_action', $terms['branch'], array(
+      'term_trunk' => $terms['trunk']->tid,
+      'merge_fields' => array(),
+      'term_branch_keep' => TRUE,
+    ));
+    $this->drupalGet('taxonomy/term/' . $terms['branch']->tid);
+    $this->assertText($terms['branch']->name);
+    drupal_static_reset();
+    $parents = array();
+    foreach (taxonomy_get_parents_all($terms['branch_child']->tid) as $parent) {
+      $parents[] = $parent->tid;
+    }
+    $valid_parents = array(
+      $terms['branch_child']->tid,
+      $terms['branch']->tid,
+      $terms['another_parent']->tid,
+    );
+    $intersection = array_intersect($parents, $valid_parents);
+    $this->assertTrue(count($intersection) == count($valid_parents), 'The parents of children of term branch are not updated if property "term_branch_keep" is set to FALSE.');
+
+    // Now we merge with deletion of branch term, thus the parents of its
+    // children have to be updated.
+    actions_do('term_merge_action', $terms['branch'], array(
+      'term_trunk' => $terms['trunk']->tid,
+      'merge_fields' => array(),
+      'term_branch_keep' => FALSE,
+    ));
+    $this->drupalGet('taxonomy/term/' . $terms['branch']->tid);
+    $this->assertResponse(404, 'The branch term has been deleted.');
+    drupal_static_reset();
+    $parents = array();
+    foreach (taxonomy_get_parents_all($terms['branch_child']->tid) as $parent) {
+      $parents[] = $parent->tid;
+    }
+    $valid_parents = array(
+      $terms['branch_child']->tid,
+      $terms['trunk']->tid,
+      $terms['another_parent']->tid,
+    );
+    $intersection = array_intersect($parents, $valid_parents);
+    $this->assertTrue(count($intersection) == count($valid_parents), 'The parents of children of term branch are updated if property "term_branch_keep" is set to TRUE.');
+
+    // Now testing 'merge_fields' property. Attaching fields to taxonomy terms.
+    $bundle = field_extract_bundle('taxonomy_term', $this->vocabulary);
+    $fields_map = array(
+      'term_merge_test_single' => 1,
+      'term_merge_test_unlimited' => FIELD_CARDINALITY_UNLIMITED,
+      'term_merge_do_not_merge' => 10,
+    );
+
+    foreach ($fields_map as $field_name => $cardinality) {
+      $field = array(
+        'field_name' => $field_name,
+        'cardinality' => $cardinality,
+        'locked' => TRUE,
+        'type' => 'text',
+      );
+      field_create_field($field);
+
+      field_create_instance(array(
+        'field_name' => $field_name,
+        'entity_type' => 'taxonomy_term',
+        'bundle' => $bundle,
+        'label' => $this->randomName(),
+        'description' => $this->randomName(),
+      ));
+    }
+
+    $terms = array(
+      'trunk' => FALSE,
+      'branch' => FALSE,
+    );
+
+    foreach ($terms as $term_type => $tmp) {
+      $url = 'admin/structure/taxonomy/vocabulary/add';
+      $name = $this->randomName();
+      $edit = array(
+        'name' => $name,
+      );
+
+      foreach ($fields_map as $field_name => $cardinality) {
+        switch ($field_name) {
+          case 'term_merge_test_single':
+            $edit[$field_name . '[' . LANGUAGE_NONE . '][0][value]'] = $this->randomName();
+            break;
+
+          case 'term_merge_test_unlimited':
+          case 'term_merge_do_not_merge':
+            $count = rand(1, 3);
+            for ($i = 0; $i < $count; $i++) {
+              $edit[$field_name . '[' . LANGUAGE_NONE . '][' . $i . '][value]'] = $this->randomName();
+              $this->drupalPost($url, $edit, 'Add another item');
+              $url = NULL;
+            }
+            break;
+        }
+      }
+
+      $this->drupalPost($url, $edit, 'Save');
+      $terms[$term_type] = $this->getLastTerm($this->vocabulary);
+    }
+
+    // Firstly we make sure if 'merge_fields' is disabled, the fields are not
+    // merged.
+    actions_do('term_merge_action', $terms['branch'], array(
+      'term_trunk' => $terms['trunk']->tid,
+      'merge_fields' => array(),
+      'term_branch_keep' => TRUE,
+    ));
+
+    $this->drupalGet('taxonomy/term/' . $terms['trunk']->tid);
+    foreach ($fields_map as $field_name => $cardinality) {
+      foreach (field_get_items('taxonomy_term', $terms['branch'], $field_name) as $item) {
+        $this->assertNoText($item['value'], 'Values of field ' . $field_name . ' have not been added to the trunk term with disabled "merge_fields" option.');
+      }
+    }
+
+    // Now we try merging with merging 2 of 3 fields. The values of the branch
+    // term should be added to the trunk term's values only in those 2 fields.
+    actions_do('term_merge_action', $terms['branch'], array(
+      'term_trunk' => $terms['trunk']->tid,
+      'merge_fields' => array('term_merge_test_single', 'term_merge_test_unlimited'),
+      'term_branch_keep' => TRUE,
+    ));
+
+    $this->drupalGet('taxonomy/term/' . $terms['trunk']->tid);
+    foreach ($fields_map as $field_name => $cardinality) {
+      switch ($field_name) {
+        case 'term_merge_test_single':
+        case 'term_merge_do_not_merge':
+          // Make sure if cardinality limit is hit, firstly original trunk term
+          // values are stored. And make sure values of fields that are not
+          // instructed to be added to trunk term's values are actually not
+          // added.
+          foreach (field_get_items('taxonomy_term', $terms['branch'], $field_name) as $item) {
+            $this->assertNoText($item['value'], 'Values of field ' . $field_name . ' (cardinality ' . $cardinality . ') have not been added to the trunk term with enabled "merge_fields" option.');
+          }
+          break;
+
+        case 'term_merge_test_unlimited':
+          // Make sure values of fields that are instructed to be added to trunk
+          // term's values are actually added.
+          foreach (field_get_items('taxonomy_term', $terms['branch'], $field_name) as $item) {
+            $this->assertText($item['value'], 'Values of field ' . $field_name . ' (cardinality ' . $cardinality . ') have been added to the trunk term with enabled "merge_fields" option.');
+          }
+          break;
+      }
+    }
+
+    // Make sure that all taxonomy term reference fields are updated to point
+    // from a branch term to a trunk term in other entities that have taxonomy
+    // term reference fields.
+    $terms = array(
+      'trunk' => FALSE,
+      'branch' => FALSE,
+    );
+
+    foreach ($terms as $term_type => $tmp) {
+      $url = 'admin/structure/taxonomy/vocabulary/add';
+      $name = $this->randomName();
+      $edit = array(
+        'name' => $name,
+      );
+
+      $this->drupalPost($url, $edit, 'Save');
+      $terms[$term_type] = $this->getLastTerm($this->vocabulary);
+    }
+
+    // Firstly we need to create a new content type and assign term reference
+    // field to this new content type.
+    $this->drupalPost('admin/structure/types/add', array(
+      'name' => $this->randomName(),
+      'type' => 'term_merge_node',
+    ), 'Save content type');
+    $this->drupalPost('admin/structure/types/manage/term-merge-node/fields', array(
+      'fields[_add_new_field][label]' => 'Term Reference',
+      'fields[_add_new_field][field_name]' => 'term_reference',
+      'fields[_add_new_field][type]' => 'taxonomy_term_reference',
+      'fields[_add_new_field][widget_type]' => 'taxonomy_autocomplete',
+    ), 'Save');
+    $this->drupalPost(NULL, array(
+      'field[settings][allowed_values][0][vocabulary]' => $this->vocabulary->machine_name,
+    ), 'Save field settings');
+    $this->drupalPost(NULL, array(
+      'field[cardinality]' => FIELD_CARDINALITY_UNLIMITED,
+    ), 'Save settings');
+    // Flushing fields API cache.
+    _field_info_collate_fields(TRUE);
+    // Creating a new node and settings its term reference field to point to
+    // the term branch.
+    $title = $this->randomName();
+    $this->drupalPost('node/add/term-merge-node', array(
+      'title' => $title,
+      'field_term_reference[' . LANGUAGE_NONE . ']' => $terms['branch']->name,
+    ), 'Save');
+    $node = $this->drupalGetNodeByTitle($title, TRUE);
+    actions_do('term_merge_action', $terms['branch'], array(
+      'term_trunk' => $terms['trunk']->tid,
+      'merge_fields' => array(),
+      'term_branch_keep' => TRUE,
+    ));
+    $this->drupalGet('node/' . $node->nid);
+    $this->assertText($terms['trunk']->name, 'Taxonomy term reference field gets updated to point from term branch to term trunk after merging terms.');
+
+    // Testing 'Keep only unique' setting for merging. We create a node assigned
+    // to both branch and trunk terms, and merge with, and then without 'Keep
+    // only unique' setting, asserting each result.
+    $terms = array(
+      'trunk' => FALSE,
+      'branch' => FALSE,
+    );
+
+    foreach ($terms as $term_type => $tmp) {
+      $url = 'admin/structure/taxonomy/vocabulary/add';
+      $name = $this->randomName();
+      $edit = array(
+        'name' => $name,
+      );
+
+      $this->drupalPost($url, $edit, 'Save');
+      $terms[$term_type] = $this->getLastTerm($this->vocabulary);
+    }
+
+    $title = $this->randomName();
+    $this->drupalPost('node/add/term-merge-node', array(
+      'title' => $title,
+      'field_term_reference[' . LANGUAGE_NONE . ']' => $terms['branch']->name . ', ' . $terms['trunk']->name,
+    ), 'Save');
+    actions_do('term_merge_action', $terms['branch'], array(
+      'term_trunk' => $terms['trunk']->tid,
+      'merge_fields' => array(),
+      'term_branch_keep' => TRUE,
+      'keep_only_unique' => FALSE,
+    ));
+    $node = $this->drupalGetNodeByTitle($title);
+    $is_first_trunk = $node->field_term_reference[LANGUAGE_NONE][0]['tid'] == $terms['trunk']->tid;
+    $is_second_trunk = $node->field_term_reference[LANGUAGE_NONE][1]['tid'] == $terms['trunk']->tid;
+    $this->assertTrue($is_first_trunk && $is_second_trunk, 'The same terms are kept in term reference field values if "Keep only unique" is off.');
+
+    // We switch roles of 'trunk' and 'branch' now. We have a node with 2 terms,
+    // if we merge them into another with "Keep only unique" on we are supposed
+    // to have only 1 term after merging.
+    actions_do('term_merge_action', $terms['trunk'], array(
+      'term_trunk' => $terms['branch']->tid,
+      'merge_fields' => array(),
+      'term_branch_keep' => TRUE,
+      'keep_only_unique' => TRUE,
+    ));
+    $node = $this->drupalGetNodeByTitle($title, TRUE);
+    $is_single = count($node->field_term_reference[LANGUAGE_NONE]) == 1;
+    $is_expected_term = $node->field_term_reference[LANGUAGE_NONE][0]['tid'] == $terms['branch']->tid;
+    $this->assertTrue($is_single && $is_expected_term, 'Only one term is kept in term reference field values if "Keep only unique" is on.');
+  }
+
+  /**
+   * Test all cases for potentially "buggy" input.
+   *
+   * Test the functionality of the action "Term Merge" with various suspicious
+   * input arguments, and testing the web UI of the module with suspicious
+   * input.
+   */
+  public function testTermMergeResistance() {
+    drupal_static_reset();
+
+    // Trying to merge 2 terms from 2 different vocabularies.
+    $this->drupalPost('admin/structure/taxonomy/add', array(
+      'name' => $this->randomName(),
+      'machine_name' => 'vocabulary2',
+    ), 'Save');
+
+    $terms = array(
+      'vocabulary' => FALSE,
+      'vocabulary2' => FALSE,
+    );
+
+    foreach ($terms as $term_type => $tmp) {
+      $url = 'admin/structure/taxonomy/' . $term_type . '/add';
+      $edit = array(
+        'name' => $this->randomName(),
+      );
+
+      $this->drupalPost($url, $edit, 'Save');
+      $terms[$term_type] = $this->getLastTerm(taxonomy_vocabulary_machine_name_load($term_type));
+    }
+
+    actions_do('term_merge_action', $terms['vocabulary'], array(
+      'term_trunk' => $terms['vocabulary2']->tid,
+      'term_branch_keep' => FALSE,
+    ));
+    $this->termMergeResistanceAssert($terms, 'Testing merging 2 terms from 2 different vocabularies.');
+
+    // Trying to merge a parent into its child.
+    $terms = array(
+      'parent' => FALSE,
+      'child' => FALSE,
+    );
+    drupal_static_reset();
+
+    foreach ($terms as $term_type => $tmp) {
+      $url = 'admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/add';
+      $edit = array(
+        'name' => $this->randomName(),
+      );
+
+      if ($term_type == 'child') {
+        $edit['parent[]'] = array($terms['parent']->tid);
+      }
+
+      $this->drupalPost($url, $edit, 'Save');
+      $terms[$term_type] = $this->getLastTerm($this->vocabulary);
+    }
+
+    actions_do('term_merge_action', $terms['parent'], array(
+      'term_trunk' => $terms['child']->tid,
+      'term_branch_keep' => FALSE,
+    ));
+    $this->termMergeResistanceAssert($terms, 'Testing merging a parent into its child.');
+
+    // Trying to merge a term into itself.
+    $terms = array(
+      'single' => FALSE,
+    );
+
+    foreach ($terms as $term_type => $tmp) {
+      $url = 'admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/add';
+      $name = $this->randomName();
+      $edit = array(
+        'name' => $name,
+      );
+
+      $this->drupalPost($url, $edit, 'Save');
+      $terms[$term_type] = $this->getLastTerm($this->vocabulary);
+    }
+
+    actions_do('term_merge_action', $terms['single'], array(
+      'term_trunk' => $terms['single']->tid,
+      'term_branch_keep' => FALSE,
+    ));
+    $this->termMergeResistanceAssert($terms, 'Testing merging a term into itself.');
+
+    // Making sure the access rights are respected.
+    $account = $this->drupalCreateUser(array('merge vocabulary2 terms'));
+    $this->drupalLogin($account);
+    $this->drupalGet('admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/merge');
+    $this->assertResponse(403, 'Per vocabulary term merge permissions are respected in the module - an account cannot merge terms in the vocabulary in which he is not supposed to be able to merge.');
+    $this->drupalGet('admin/structure/taxonomy/vocabulary2/merge');
+    $this->assertResponse(200, 'Per vocabulary term merge permissions are respected in the module - an account can merge terms in the vocabulary in which he is supposed to be able to merge.');
+  }
+
+  /**
+   * Test all cases of usage of Term Merge Batch.
+   */
+  public function testTermMergeBatch() {
+    // Adding fields with unlimited cardinality to our vocabulary.
+    $this->drupalPost('admin/structure/taxonomy/vocabulary/fields', array(
+      'fields[_add_new_field][label]' => 'Test Unlimited Text',
+      'fields[_add_new_field][field_name]' => 'test_text',
+      'fields[_add_new_field][type]' => 'text',
+      'fields[_add_new_field][widget_type]' => 'text_textfield',
+    ), 'Save');
+    $this->drupalPost(NULL, array(), 'Save field settings');
+    $this->drupalPost(NULL, array(
+      'field[cardinality]' => FIELD_CARDINALITY_UNLIMITED,
+    ), 'Save settings');
+
+    // Additionally we need to create a new content type and assign term
+    // reference field to this new content type.
+    $this->drupalPost('admin/structure/types/add', array(
+      'name' => $this->randomName(),
+      'type' => 'term_merge_node',
+    ), 'Save content type');
+    $this->drupalPost('admin/structure/types/manage/term-merge-node/fields', array(
+      'fields[_add_new_field][label]' => 'Term Reference',
+      'fields[_add_new_field][field_name]' => 'term_reference',
+      'fields[_add_new_field][type]' => 'taxonomy_term_reference',
+      'fields[_add_new_field][widget_type]' => 'taxonomy_autocomplete',
+    ), 'Save');
+    $this->drupalPost(NULL, array(
+      'field[settings][allowed_values][0][vocabulary]' => $this->vocabulary->machine_name,
+    ), 'Save field settings');
+    $this->drupalPost(NULL, array(), 'Save settings');
+    // Flushing fields API cache.
+    _field_info_collate_fields(TRUE);
+
+    // Array of cases for which we test the Term Merge batch.
+    $cases = array(
+      'taxonomy_vocabulary_tab',
+      'taxonomy_term_tab',
+      'via_term_trunk_widget_select',
+      'via_term_trunk_widget_select_creating_new_term_trunk',
+      'via_term_trunk_widget_autocomplete',
+      'merge_fields',
+      'do_not_merge_fields',
+    );
+    foreach ($cases as $case) {
+      // Creating a necessary set of terms in the vocabulary.
+      drupal_static_reset();
+      $terms = array(
+        'parent' => FALSE,
+        'another_parent' => FALSE,
+        'child' => FALSE,
+        'term1' => FALSE,
+        'term2' => FALSE,
+        'term3' => FALSE,
+        'term_trunk_parent' => FALSE,
+        'term_trunk' => FALSE,
+      );
+
+      foreach ($terms as $term_type => $tmp) {
+        $url = 'admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/add';
+        $edit = array(
+          'name' => $term_type . '_' . $this->randomName(),
+          'field_test_text[' . LANGUAGE_NONE . '][0][value]' => $term_type,
+        );
+
+        switch ($term_type) {
+          case 'child':
+            $edit['parent[]'] = array($terms['parent']->tid, $terms['another_parent']->tid);
+            break;
+
+          case 'term_trunk':
+            $edit['parent[]'] = array($terms['term_trunk_parent']->tid);
+            break;
+        }
+
+        $this->drupalPost($url, $edit, 'Save');
+        $terms[$term_type] = $this->getLastTerm($this->vocabulary);
+      }
+
+      // The initial URL from where the form that kicks off batch is submitted.
+      $init_url = '';
+      // What widget to use for choosing term trunk.
+      $term_trunk_widget = '';
+      // Value for term trunk in the format, expected by the widget
+      // $term_trunk_widget. Additionally, if any test case requires any extra
+      // fields to be submitted, input those fields into this array and they
+      // won't be taken out from this array, then it will get merged into $edit,
+      // and this way eventually your values will be successfully submitted.
+      $term_trunk_edit = array();
+
+      // Setting up controlling vars based on case and doing any specific
+      // assertions for each case.
+      switch ($case) {
+        case 'taxonomy_vocabulary_tab':
+          $init_url = 'admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/merge';
+          // It doesn't really matter which widget we use, we test widgets
+          // throughout in other cases.
+          $term_trunk_widget = array_rand(drupal_map_assoc(array('select', 'autocomplete')));
+          break;
+
+        case 'taxonomy_term_tab':
+          $init_url = 'taxonomy/term/' . $terms['parent']->tid . '/merge';
+          // It doesn't really matter which widget we use, we test widgets
+          // throughout in other cases.
+          $term_trunk_widget = array_rand(drupal_map_assoc(array('select', 'autocomplete')));
+          // Assert that the term, for which the tab was clicked, is selected as
+          // term branch by default.
+          $this->drupalGet($init_url);
+          $this->assertOptionSelected('edit-term-branch', $terms['parent']->tid, 'Clicking the "Merge Terms" tab from a term view page sets the viewed term as a term branch by default.');
+          break;
+
+        case 'via_term_trunk_widget_select':
+          $init_url = 'taxonomy/term/' . $terms['parent']->tid . '/merge';
+          $term_trunk_widget = 'select';
+          // Making sure for the term trunk select the selected term branch are
+          // not available, nor their children.
+          $this->drupalGet($init_url);
+          $matches = array();
+          preg_match('#\<select[^>]+name="term_trunk\[tid\]"[^>]*\>.+?\</select\>#si', $this->content, $matches);
+          $term_trunk_options = $matches[0];
+          $str_pos = strpos($term_trunk_options, $terms['child']->name);
+          $this->assertIdentical(FALSE, $str_pos, 'Child is not available as option for term trunk if its parent is chosen among term branches.');
+          $str_pos = strpos($term_trunk_options, $terms['parent']->name);
+          $this->assertIdentical(FALSE, $str_pos, 'Selected branch term is not available as an option for term trunk.');
+          // At the same time asserting if we choose "New Term" option, among
+          // the available parents for the new term there are no children of the
+          // selected branch terms, nor the branch terms themselves.
+          $this->drupalPostAJAX(NULL, array(
+            'term_branch[]' => array($terms['parent']->tid),
+            'term_trunk[widget]' => $term_trunk_widget,
+            'term_trunk[tid]' => TERM_MERGE_NEW_TERM_TRUNK,
+          ), 'term_trunk[tid]');
+          $matches = array();
+          preg_match('#\<select[^>]+name="relations\[parent\]\[\]"[^>]*\>.+?\</select\>#si', $this->content, $matches);
+          $new_term_parent_options = $matches[0];
+          $str_pos = strpos($new_term_parent_options, $terms['child']->name);
+          $this->assertIdentical(FALSE, $str_pos, 'Child is not available as option for parent term for a new term trunk if its parent is chosen among term branches.');
+          $str_pos = strpos($new_term_parent_options, $terms['parent']->name);
+          $this->assertIdentical(FALSE, $str_pos, 'Selected branch term is not available as an option for parent term for a new term trunk.');
+          break;
+
+        case 'via_term_trunk_widget_select_creating_new_term_trunk':
+          $init_url = 'taxonomy/term/' . $terms['parent']->tid . '/merge';
+          $term_trunk_widget = 'select';
+          break;
+
+        case 'via_term_trunk_widget_autocomplete':
+          $init_url = 'admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/merge';
+          $term_trunk_widget = 'autocomplete';
+
+          // Test autocomplete widget menu path to make sure it does reply
+          // with valid suggestions.
+          $response = $this->drupalGet('term-merge/autocomplete/term-trunk/' . $this->vocabulary->machine_name . '/' . drupal_strtoupper($terms['term_trunk']->name));
+          $response = drupal_json_decode($response);
+          $this->assertTrue(isset($response[$terms['term_trunk']->name]), 'Autocomplete menu path replies with valid suggestions for term trunk autocomplete widget.');
+
+          // Making sure for the term trunk autocomplete widget doesn't allow to
+          // submit any of the selected term branches nor their children.
+          $prohibited_terms = array(
+            'parent' => 'Merging into the same term is not allowed in autocomplete widget for term trunk.',
+            'child' => 'Merging into any of child of selected branch terms is not allowed in autocomplete widget for term trunk.',
+          );
+          foreach ($prohibited_terms as $term => $assert_message) {
+            $term = $terms[$term];
+            $this->drupalGet($init_url);
+            $this->drupalPostAJAX(NULL, array(
+              'term_branch[]' => array($terms['parent']->tid),
+              'term_trunk[widget]' => $term_trunk_widget,
+            ), 'term_trunk[widget]');
+            $this->drupalPost(NULL, array(
+              'term_branch[]' => array($terms['parent']->tid),
+              'term_trunk[widget]' => $term_trunk_widget,
+              'term_trunk[tid]' => $term->name,
+            ), 'Submit');
+            $this->assertText('Trunk term cannot be one of the selected branch terms or their children', $assert_message);
+          }
+          break;
+
+        case 'merge_fields':
+          $init_url = 'admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/merge';
+          // It doesn't really matter which widget we use, we test widgets
+          // throughout in other cases.
+          $term_trunk_widget = array_rand(drupal_map_assoc(array('select', 'autocomplete')));
+          // We embed extra info related to field values merging into
+          // $term_trunk_edit.
+          $term_trunk_edit['merge_fields[field_test_text]'] = TRUE;
+          break;
+
+        case 'do_not_merge_fields':
+          $init_url = 'admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/merge';
+          // It doesn't really matter which widget we use, we test widgets
+          // throughout in other cases.
+          $term_trunk_widget = array_rand(drupal_map_assoc(array('select', 'autocomplete')));
+          break;
+      }
+
+      // Creating a new node and setting its term reference field to point to
+      // the term branch.
+      $title = $this->randomName();
+      $this->drupalPost('node/add/term-merge-node', array(
+        'title' => $title,
+        'field_term_reference[' . LANGUAGE_NONE . ']' => $terms['term1']->name,
+      ), 'Save');
+      $node = $this->drupalGetNodeByTitle($title, TRUE);
+
+      // Calling the Term Merge form.
+      $this->drupalGet($init_url);
+
+      // Choosing term branches.
+      $term_branches = array('term1', 'term2', 'term3');
+      $term_branches_edit = array();
+      foreach ($term_branches as $term_type) {
+        $term_branches_edit[] = $terms[$term_type]->tid;
+      }
+      $this->drupalPostAJAX(NULL, array(
+        'term_branch[]' => $term_branches_edit,
+      ), 'term_branch[]');
+
+      // Choosing the widget for trunk term.
+      $this->drupalPostAJAX(NULL, array(
+        'term_branch[]' => $term_branches_edit,
+        'term_trunk[widget]' => $term_trunk_widget,
+      ), 'term_trunk[widget]');
+
+      // Choosing term trunk.
+      switch ($term_trunk_widget) {
+        case 'select':
+          $term_trunk_edit += array('term_trunk[tid]' => $terms['term_trunk']->tid);
+          if ($case == 'via_term_trunk_widget_select_creating_new_term_trunk') {
+            // This is special case, we are gonna create a new term trunk using
+            // taxonomy create term embedded form.
+            $term_trunk_edit = array('term_trunk[tid]' => TERM_MERGE_NEW_TERM_TRUNK) + $term_trunk_edit;
+            $this->drupalPostAJAX(NULL, array(
+              'term_branch[]' => $term_branches_edit,
+              'term_trunk[widget]' => $term_trunk_widget,
+            ) + $term_trunk_edit, 'term_trunk[tid]');
+
+            // Adding another delta for text field. This way we make sure Field
+            // API gets embedded into our form without errors.
+            $this->drupalPostAJAX(NULL, array(
+              'term_branch[]' => $term_branches_edit,
+              'term_trunk[widget]' => $term_trunk_widget,
+            ) + $term_trunk_edit, array('field_test_text_add_more' => 'Add another item'));
+            // We store into $term_trunk_edit array the info about the just
+            // created new trunk term for further assertions down below in the
+            // code.
+            $term_trunk_edit += array(
+              'name' => $this->randomName(),
+              'description[value]' => $this->randomName(),
+              'field_test_text[' . LANGUAGE_NONE . '][0][value]' => $this->randomName(),
+              'field_test_text[' . LANGUAGE_NONE . '][1][value]' => $this->randomName(),
+              'relations[parent][]' => array($terms['term_trunk_parent']->tid),
+            );
+          }
+          break;
+
+        case 'autocomplete':
+          $term_trunk_edit += array('term_trunk[tid]' => $terms['term_trunk']->name);
+          break;
+      }
+
+      // Submitting the form.
+      $edit = $term_trunk_edit + array(
+        'term_branch[]' => $term_branches_edit,
+        'term_trunk[widget]' => $term_trunk_widget,
+        'term_branch_keep' => FALSE,
+        'step' => 2,
+      );
+      $this->drupalPost(NULL, $edit, 'Submit');
+      $this->drupalPost(NULL, array(), 'Confirm');
+
+      // Making sure all the branches are deleted.
+      foreach ($term_branches as $term_type) {
+        $term = $terms[$term_type];
+        $this->drupalGet('taxonomy/term/' . $term->tid);
+        $this->assertResponse(404, 'Branch term ' . $term_type . ' has been deleted after merging.');
+      }
+
+      $text_assertions = array();
+      $term_trunk = $terms['term_trunk'];
+
+      // Adding any extra text assertions on per test-case basis.
+      switch ($case) {
+        case 'via_term_trunk_widget_select_creating_new_term_trunk':
+          $term_trunk = $this->getLastTerm($this->vocabulary);
+
+          // Making sure the parent property of the just created trunk term is
+          // correct.
+          $parents = taxonomy_get_parents_all($term_trunk->tid);
+          $this->assertTrue(count($parents) == 2 && $parents[0]->tid == $term_trunk->tid && $parents[1]->tid == $terms['term_trunk_parent']->tid, 'Parent property of the just created new term trunk is correct.');
+
+          // Adding the submitted field values for further assertions too. This
+          // way we test whether the embedded form adds a new term along with
+          // any fields we have submitted into it.
+          $text_assertions['New Term name'] = $term_trunk_edit['name'];
+          $text_assertions['New Term description'] = $term_trunk_edit['description[value]'];
+          $text_assertions['New Term text field delta #0'] = $term_trunk_edit['field_test_text[' . LANGUAGE_NONE . '][0][value]'];
+          $text_assertions['New Term text field delta #1'] = $term_trunk_edit['field_test_text[' . LANGUAGE_NONE . '][1][value]'];
+          break;
+
+        case 'merge_fields':
+          // Making sure the term trunk has been merged all the fields from term
+          // branches into itself.
+          foreach ($term_branches as $term_type) {
+            $items = field_get_items('taxonomy_term', $terms[$term_type], 'field_test_text');
+            foreach ($items as $delta => $item) {
+              $text_assertions[$term_type . ' text field delta#' . $delta . ' has been merged when instructed to merge field values.'] = $item['value'];
+            }
+          }
+          break;
+
+        case 'do_not_merge_fields':
+          // We need to assert that no values for field have been merged from
+          // branch terms into the values of trunk term.
+          $this->drupalGet('taxonomy/term/' . $term_trunk->tid);
+          foreach ($term_branches as $term_type) {
+            $items = field_get_items('taxonomy_term', $terms[$term_type], 'field_test_text');
+            foreach ($items as $delta => $item) {
+              $this->assertNoText($item['value'], $term_type . ' text field delta#' . $delta . ' has not been merged when instrcuted not to merge field values.');
+            }
+          }
+          break;
+      }
+
+      $this->drupalGet('taxonomy/term/' . $term_trunk->tid);
+
+      foreach ($text_assertions as $k => $v) {
+        $this->assertText($v, 'Term trunk has the property ' . $k);
+      }
+
+      // Making sure the taxonomy term reference in other entities are updated
+      // to point from term branches to the just created term trunk.
+      $this->drupalGet('node/' . $node->nid);
+      $this->assertText($term_trunk->name, 'Taxonomy term reference fields in other entities are updated to point from term branches to the term trunk.');
+    }
+  }
+
+  /**
+   * Supportive function for the main test "testTermMergeResistance".
+   *
+   * Assert that each term of the array $terms is available.
+   *
+   * @param array $terms
+   *   Array of taxonomy terms objects
+   * @param string $message
+   *   Assertion message to be shown on the test results page
+   */
+  protected function termMergeResistanceAssert($terms, $message) {
+    foreach ($terms as $term) {
+      $this->drupalGet('taxonomy/term/' . $term->tid);
+      $this->assertResponse(200, $message);
+    }
+  }
+}
+
+/**
+ * Test the Merge Duplicate Terms feature of the Term Merge module.
+ */
+class DuplicatesTermMergeWebTestCase extends TermMergeWebTestCase {
+
+  /**
+   * GetInfo method.
+   */
+  public function getInfo() {
+    return array(
+      'name' => 'Duplicate terms merge',
+      'description' => 'Ensure that the feature <i>merge duplicate terms</i> of module Term Merge works correctly.',
+      'group' => 'Term Merge',
+    );
+  }
+
+  /**
+   * Test access rights.
+   */
+  public function testDisabledAndPermissions() {
+    // Trying a user who doesn't have enough permissions.
+    $account = $this->drupalCreateUser();
+    $this->drupalLogin($account);
+    $this->drupalGet('admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/merge/duplicates');
+    $this->assertResponse(403, 'Access to Merge Duplicate Terms is denied for a user who does not have enough permissions.');
+
+    // Trying a user who have enough permissions.
+    $this->drupalLogin($this->admin);
+    $this->drupalGet('admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/merge/duplicates');
+    $this->assertResponse(200, 'Access to Merge Duplicate Terms is granted for a user who has enough permissions.');
+  }
+
+  /**
+   * Test merging duplicates feature of Term Merge module.
+   *
+   * Test the following features:
+   * - Correctness of merging a group of duplicate terms, namely:
+   *   - Correctness of merge operation when duplicates feature is invoked on
+   *     the entire vocabulary
+   *   - Correctness of merge operation when duplicates feature is invoked on a
+   *     term (merge its children one into another)
+   * - Correctness of the mechanism that groups terms into sets of duplicate
+   *   entries, namely:
+   *   - Correctness of grouping by term name, i.e. unique terms should not be
+   *     listed in any set of duplicate terms
+   *   - Correctness of the initial set of terms, on which the duplicate tool is
+   *     invoked, i.e. when invoked on a vocabulary, we search for duplicates
+   *     in the whole vocabulary, but when invoked on a term, the tool should
+   *     only search for duplicate among the children of that term
+   */
+  public function testDuplicates() {
+    // Creating duplicate terms firstly.
+    $groups = array(
+      'single' => 1,
+      'triple_different_parent' => 3,
+      'random' => rand(2, 5),
+      // We need some term, that will be a parent of some other terms.
+      'parent' => 1,
+    );
+    $groups = $this->createTerms($groups);
+
+    // Let us make two of 'triple_different_parent' terms children of 'parent'
+    // term.
+    $groups['triple_different_parent'][1]->parent = $groups['parent'][0]->tid;
+    taxonomy_term_save($groups['triple_different_parent'][1]);
+    $groups['triple_different_parent'][2]->parent = $groups['parent'][0]->tid;
+    taxonomy_term_save($groups['triple_different_parent'][2]);
+
+    // Assuring the single term is not listed as duplicate.
+    $this->drupaLGet('admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/merge/duplicates');
+    $this->assertNoText($groups['single'][0]->name, 'Single term is not listed as a duplicate.');
+
+    // Making sure the term in 'triple_different_parent' that does not have a
+    // parent, is not listed when we invoke duplicate tool on a parent term.
+    $this->drupalGet('taxonomy/term/' . $groups['parent'][0]->tid . '/merge/duplicates');
+    $this->assertNoFieldByName('group[' . $this->duplicateProcessName('triple_different_parent') . '][duplicates][' . $groups['triple_different_parent'][0]->tid . ']', 'Duplicate term is not listed when it is not among children of a term, on which Term Merge module was invoked.');
+
+    $edit = array();
+    // Trying to merge a term into another, invoking Duplicate tool on a parent
+    // term of both. Important note: we do not test merging options, because
+    // supposedly those are tested in the main test of this module.
+    $edit['group[' . $this->duplicateProcessName('triple_different_parent') . '][trunk_tid]'] = $groups['triple_different_parent'][1]->tid;
+    $edit['group[' . $this->duplicateProcessName('triple_different_parent') . '][duplicates][' . $groups['triple_different_parent'][2]->tid . ']'] = TRUE;
+    $groups['triple_different_parent'][2]->merged = TRUE;
+    $this->drupalPost('taxonomy/term/' . $groups['parent'][0]->tid . '/merge/duplicates', $edit, 'Submit');
+
+    //  Trying to merge multiple terms. We merge all but the 1st term.
+    $edit = array();
+    $edit['group[' . $this->duplicateProcessName('random') . '][trunk_tid]'] = $groups['random'][0]->tid;
+    foreach ($groups['random'] as $k => $term) {
+      if ($k != 0) {
+        $edit['group[' . $this->duplicateProcessName('random') . '][duplicates][' . $term->tid . ']'] = TRUE;
+        $groups['random'][$k]->merged = TRUE;
+      }
+    }
+    $this->drupalPost('admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/merge/duplicates', $edit, 'Submit');
+
+    // Asserting results of merging.
+    foreach  ($groups as $group) {
+      foreach ($group as $term) {
+        $this->drupalGet('taxonomy/term/' . $term->tid);
+        $code = isset($term->merged) && $term->merged ? 404 : 200;
+        $message = isset($term->merged) && $term->merged ? 'Term #' . $term->tid . ' has been successfully merged.' : 'Term #' . $term->tid . ' has been successfully untouched during merging.';
+        $this->assertResponse($code, $message);
+      }
+    }
+  }
+
+  /**
+   * Supportive method.
+   *
+   * Create taxonomy terms with similar names.
+   *
+   * @param array $groups
+   *   Key should be a name of the group (terms' names in this group may only
+   *   differ in case, but will always use this string as their names), while
+   *   corresponding value to that key should denote how many terms in each
+   *   group should be created
+   *
+   * @return array
+   *   Array of fully loaded taxonomy terms objects of the just created terms,
+   *   grouped by their group name
+   */
+  private function createTerms($groups) {
+    foreach ($groups as $name => $quantity) {
+      $groups[$name] = array();
+      for ($i = 0; $i < $quantity; $i++) {
+        $term_name = '';
+        // Randomizing case of the group name.
+        foreach (str_split($name) as $symbol) {
+          $symbol = rand(0, 1) ? drupal_strtoupper($symbol) : drupal_strtolower($symbol);
+          $term_name .= $symbol;
+        }
+        $this->drupalPost('admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/add', array(
+          'name' => $term_name,
+        ), 'Save');
+        $groups[$name][] = $this->getLastTerm($this->vocabulary);
+      }
+    }
+    return $groups;
+  }
+
+  /**
+   * Supportive method.
+   *
+   * Manipulate supplied var $name and by the output of this function terms in a
+   * vocabulary are grouped as duplicates. This method should be identical to
+   * the function term_merge_duplicates_process_name(), test case replies on the
+   * fact that both manipulate the string in the identical way.
+   *
+   * @param string $name
+   *   String that needs to be manipulated
+   *
+   * @return string
+   *   Processed string (normally it implies making it upper case, stripping
+   *   down any special chars, etc.)
+   */
+  private function duplicateProcessName($name) {
+    // Making upper case.
+    $name = drupal_strtoupper($name);
+    // Trying transliteration, if available.
+    if (module_exists('transliteration')) {
+      $name = transliteration_get($name);
+      // Keeping only ASCII chars.
+      $name = preg_replace('#\W#', '', $name);
+    }
+    return $name;
+  }
+}
+
+
+/**
+ * Test the integration between Term Merge module and Path/Redirect modules.
+ */
+class RedirectTermMergeWebTestCase extends TermMergeWebTestCase {
+
+  /**
+   * Fully loaded Drupal user object of the user who has access to configure
+   * redirects.
+   *
+   * @var object
+   */
+  protected $superAdmin;
+
+  /**
+   * SetUp method.
+   */
+  public function setUp() {
+    parent::setUp(array('redirect', 'path'));
+
+    $this->superAdmin = $this->drupalCreateUser(array(
+      'administer taxonomy',
+      'merge terms',
+      'administer content types',
+      'bypass node access',
+      'administer redirects',
+      'administer url aliases',
+    ));
+  }
+
+  /**
+   * GetInfo method.
+   */
+  public function getInfo() {
+    return array(
+      'name' => 'Redirect module integration',
+      'description' => 'Ensure that the module Term Merge integrates with ' . l('Redirect', 'http://drupal.org/project/redirect') . '/Path modules correctly.',
+      'group' => 'Term Merge',
+    );
+  }
+
+  /**
+   * Test disabled Redirect module and access rights.
+   */
+  public function testDisabledAndPermissions() {
+    // Checking access rights required to set up redirection during term
+    // merging.
+    $this->drupalLogin($this->admin);
+    $this->drupalGet('admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/merge');
+    $this->assertNoPattern('#\<select[^>]+name="redirect"[^>]*\>#i', 'No redirection settings are available for a user that does not possess corresponding permissions.');
+
+    $this->drupalLogin($this->superAdmin);
+    $this->drupalGet('admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/merge');
+    $this->assertPattern('#\<select[^>]+name="redirect"[^>]*\>#i', 'Redirection settings are available for a user that possesses corresponding permissions.');
+
+    // Making sure redirect settings are not available during merging when
+    // merging with disabled Redirect module.
+    module_disable(array('redirect'));
+    $this->drupalGet('admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/merge');
+    $this->assertNoPattern('#\<select[^>]+name="redirect"[^>]*\>#i', 'No redirection settings are available when the redirect module is disabled.');
+  }
+
+  /**
+   * Test the action 'term_merge_action' in terms of integration with Redirect.
+   */
+  public function testTermMergeAction() {
+    $this->drupalLogin($this->superAdmin);
+    $terms = $this->createTerms(array('branch', 'trunk'));
+
+    // Testing default value.
+    actions_do('term_merge_action', $terms['branch'], array(
+      'term_trunk' => $terms['trunk']->tid,
+      'term_branch_keep' => TRUE,
+    ));
+    $this->assertRedirectIntegration($terms, 'By default no redirects should be made.');
+
+    // Testing no redirection.
+    actions_do('term_merge_action', $terms['branch'], array(
+      'term_trunk' => $terms['trunk']->tid,
+      'term_branch_keep' => TRUE,
+      'redirect' => TERM_MERGE_NO_REDIRECT,
+    ));
+    $this->assertRedirectIntegration($terms, 'No redirects are made, if action is not instructed to make ones.');
+
+    // Testing 301 redirection. Besides redirecting 'taxonomy/term/[branch-tid]'
+    // to 'taxonomy/term/[trunk-tid]' and their path aliases we want to
+    // additionally assert that all existing redirects to branch term will be
+    // replaced with redirects to trunk term in Redirect module. Lastly, we also
+    // assert that 'taxonomy/term/[branch-tid]/feed' path and all pointing there
+    // redirects now point to 'taxonomy/term/[trunk-tid]/feed.
+    $redirect_source = $this->randomName();
+    $redirect = new stdClass();
+    redirect_object_prepare($redirect, array(
+      'source' => $redirect_source,
+      'redirect' => 'taxonomy/term/' . $terms['branch']->tid,
+    ));
+    redirect_hash($redirect);
+    redirect_save($redirect);
+
+    $redirect = new stdClass();
+    redirect_object_prepare($redirect, array(
+      'source' => $redirect_source . '/feed',
+      'redirect' => 'taxonomy/term/' . $terms['branch']->tid . '/feed',
+    ));
+    redirect_hash($redirect);
+    redirect_save($redirect);
+
+    actions_do('term_merge_action', $terms['branch'], array(
+      'term_trunk' => $terms['trunk']->tid,
+      'redirect' => 301,
+    ));
+
+    $terms['branch']->redirect = $terms['trunk'];
+    $this->assertRedirectIntegration($terms, 'Redirects are made, if action is instructed to make ones.');
+
+    $this->drupalGet($redirect_source);
+    $this->assertUrl('taxonomy/term/' . $terms['trunk']->tid, array(), 'Redirect pointing to <em>taxonomy/term/[branch-tid]</em> now points to <em>taxonomy/term/[trunk-tid]</em>.');
+    $this->drupalGet($redirect_source . '/feed');
+    $this->assertUrl('taxonomy/term/' . $terms['trunk']->tid . '/feed', array(), 'Redirect pointing to <em>taxonomy/term/[branch-tid]/feed</em> now points to <em>taxonomy/term/[trunk-tid]/feed</em>.');
+  }
+
+  /**
+   * Test Term Merge batch in terms of integration with Redirect/Path modules.
+   */
+  public function testTermMergeBatch() {
+    $this->drupalLogin($this->superAdmin);
+
+    // Trying to merge without redirection.
+    $terms = $this->createTerms(array('branch', 'trunk'));
+    $this->drupalPost('taxonomy/term/' . $terms['branch']->tid . '/merge', array(
+      'term_branch[]' => array($terms['branch']->tid),
+      'term_trunk[widget]' => 'select',
+      'term_trunk[tid]' => $terms['trunk']->tid,
+      'term_branch_keep' => TRUE,
+      'redirect' => TERM_MERGE_NO_REDIRECT,
+    ), 'Submit');
+    $this->drupalPost(NULL, array(), 'Confirm');
+    $this->assertRedirectIntegration($terms, 'No redirections made after running merge batch when not instructed to make redirections.');
+
+    // Trying to merge into an existing term with redirection.
+    $this->drupalPost('taxonomy/term/' . $terms['branch']->tid . '/merge', array(
+      'term_branch[]' => array($terms['branch']->tid),
+      'term_trunk[widget]' => 'select',
+      'term_trunk[tid]' => $terms['trunk']->tid,
+      'redirect' => 0,
+    ), 'Submit');
+    $terms['branch']->redirect = $terms['trunk'];
+    $this->drupalPost(NULL, array(), 'Confirm');
+    $this->assertRedirectIntegration($terms, 'Redirection is made after running merge batch merging into an existing term, when instructed to make redirections.');
+
+    // Trying to merge into a new term with redirection.
+    $terms = $this->createTerms(array('branch'));
+    $this->drupalPostAJAX('taxonomy/term/' . $terms['branch']->tid . '/merge', array(
+      'term_branch[]' => array($terms['branch']->tid),
+      'term_trunk[widget]' => 'select',
+      'term_trunk[tid]' => TERM_MERGE_NEW_TERM_TRUNK,
+    ), 'term_trunk[tid]');
+
+    $this->drupalPost(NULL, array(
+      'term_branch[]' => array($terms['branch']->tid),
+      'term_trunk[widget]' => 'select',
+      'term_trunk[tid]' => TERM_MERGE_NEW_TERM_TRUNK,
+      'name' => $this->randomName(),
+      'redirect' => 0,
+    ), 'Submit');
+    $this->drupalPost(NULL, array(), 'Confirm');
+    $terms['trunk'] = $this->getLastTerm($this->vocabulary);
+    $terms['branch']->redirect = $terms['trunk'];
+    $this->assertRedirectIntegration($terms, 'Redirection is made after running merge batch merging into a new term, when instructed to make redirections.');
+  }
+
+  /**
+   * Supportive method.
+   *
+   * Assert expected results after doing any test actions.
+   *
+   * @param array $terms
+   *   Array of terms as returned by $this->createTerms(). Those terms that have
+   *   been merged and redirected to another terms, besides all normal keys
+   *   should have property 'redirect' which should be equal to the fully loaded
+   *   taxonomy term which they were redirected to
+   * @param string $message
+   *   Assert message to be shown on test results page
+   */
+  protected function assertRedirectIntegration($terms, $message) {
+    foreach ($terms as $term) {
+      if (isset($term->redirect)) {
+        $sources = array('taxonomy/term/' . $term->tid);
+        // Additionally checking path alias.
+        if (!in_array(drupal_get_path_alias($sources[0]), $sources)) {
+          $sources[] = drupal_get_path_alias($sources[0]);
+        }
+        foreach ($sources as $source) {
+          $this->drupalGet($source);
+          $this->assertUrl('taxonomy/term/' . $term->redirect->tid, array(), $message);
+        }
+
+        // Additionally assert the 'taxonomy/term/*/feed' path.
+        $sources = array('taxonomy/term/' . $term->tid . '/feed');
+        if (!in_array(drupal_get_path_alias($sources[0]), $sources)) {
+          $sources[] = drupal_get_path_alias($sources[0]);
+        }
+        foreach ($sources as $source) {
+          $this->drupalGet($source);
+          $this->assertUrl('taxonomy/term/' . $term->redirect->tid . '/feed', array(), $message);
+        }
+      }
+    }
+  }
+
+  /**
+   * Supportive method.
+   *
+   * Create a list of terms, assigning path aliases according to the values
+   * of the supplied array.
+   *
+   * @param array $terms
+   *   Array of machine readable term keys based on which is generated output
+   *
+   * @return array
+   *   Array of taxonomy term objects path alias of which is equal to the value
+   *   that corresponds to its position in the supplied array
+   */
+  protected function createTerms($terms) {
+    $return = array();
+    foreach ($terms as $v) {
+      $this->drupalPost('admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/add', array(
+        'name' => $this->randomName(),
+        'path[alias]' => $v . $this->randomName(),
+      ), 'Save');
+      $return[$v] = $this->getLastTerm($this->vocabulary);
+    }
+
+    return $return;
+  }
+}
+
+/**
+ * Test the integration between Term Merge module and Synonyms module.
+ */
+class SynonymsTermMergeWebTestCase extends TermMergeWebTestCase {
+
+  /**
+   * SetUp method.
+   */
+  public function setUp() {
+    parent::setUp(array('synonyms'));
+    // Additionally we enable default synonyms field in the vocabulary.
+    $this->drupalPost('admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/edit', array(
+      'synonyms[synonyms][' . SYNONYMS_DEFAULT_FIELD_NAME . ']' => TRUE,
+    ), 'Save');
+  }
+
+  /**
+   * GetInfo method.
+   */
+  public function getInfo() {
+    return array(
+      'name' => 'Synonyms module integration',
+      'description' => 'Ensure that the module Term Merge integrates with ' . l('Synonyms', 'http://drupal.org/project/synonyms') . ' module correctly.',
+      'group' => 'Term Merge',
+    );
+  }
+
+  /**
+   * Test disabled Synonyms module.
+   */
+  public function testDisabled() {
+    // Making sure synonyms settings are not available during merging when
+    // Synonyms module is disabled.
+    module_disable(array('synonyms'));
+    $this->drupalGet('admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/merge');
+    $this->assertNoText(t('Add as Synonyms'), 'No synonyms settings are available when the Synonyms module is disabled.');
+  }
+
+  /**
+   * Test the action 'term_merge_action' in terms of integration with Synonyms.
+   */
+  public function testTermMergeAction() {
+    $this->drupalLogin($this->admin);
+    $terms = $this->createTerms(array('branch', 'trunk'));
+
+    // Testing default value.
+    actions_do('term_merge_action', $terms['branch'], array(
+      'term_trunk' => $terms['trunk']->tid,
+      'term_branch_keep' => TRUE,
+    ));
+    $this->assertSynonymsIntegration($terms, 'By default no synonyms should be added.');
+
+    // Testing no synonyms adding.
+    actions_do('term_merge_action', $terms['branch'], array(
+      'term_trunk' => $terms['trunk']->tid,
+      'term_branch_keep' => TRUE,
+      'synonyms' => array(),
+    ));
+    $this->assertSynonymsIntegration($terms, 'No synonyms are added, if action is not instructed to make ones.');
+
+    // Testing adding as a synonym.
+    actions_do('term_merge_action', $terms['branch'], array(
+      'term_trunk' => $terms['trunk']->tid,
+      'synonyms' => array(SYNONYMS_DEFAULT_FIELD_NAME),
+    ));
+
+    $terms['trunk']->synonyms = array($terms['branch']->name);
+    $this->assertSynonymsIntegration($terms, 'Synonyms are added, if action is instructed to add ones.');
+  }
+
+  /**
+   * Test Term Merge batch in terms of integration with Synonyms module.
+   */
+  public function testTermMergeBatch() {
+    // Trying to merge without synonyms adding.
+    $terms = $this->createTerms(array('branch', 'trunk'));
+    $this->drupalPost('taxonomy/term/' . $terms['branch']->tid . '/merge', array(
+      'term_branch[]' => array($terms['branch']->tid),
+      'term_trunk[widget]' => 'select',
+      'term_trunk[tid]' => $terms['trunk']->tid,
+      'term_branch_keep' => TRUE,
+      'synonyms[' . SYNONYMS_DEFAULT_FIELD_NAME . ']' => FALSE,
+    ), 'Submit');
+    $this->drupalPost(NULL, array(), 'Confirm');
+    $this->assertSynonymsIntegration($terms, 'No synonyms are added after running merge batch when not instructed to add synonyms.');
+
+    // Trying to merge into an existing term with synonyms adding.
+    $this->drupalPost('taxonomy/term/' . $terms['branch']->tid . '/merge', array(
+      'term_branch[]' => array($terms['branch']->tid),
+      'term_trunk[widget]' => 'select',
+      'term_trunk[tid]' => $terms['trunk']->tid,
+      'term_branch_keep' => TRUE,
+      'synonyms[' . SYNONYMS_DEFAULT_FIELD_NAME . ']' => TRUE,
+    ), 'Submit');
+    $terms['trunk']->synonyms = array($terms['branch']->name);
+    $this->drupalPost(NULL, array(), 'Confirm');
+    $this->assertSynonymsIntegration($terms, 'Synonyms are added after running merge batch merging into an existing term, when instructed to add synonyms.');
+
+    // Trying to merge into a new term with synonyms adding.
+    $terms = $this->createTerms(array('branch'));
+    $this->drupalPostAJAX('taxonomy/term/' . $terms['branch']->tid . '/merge', array(
+      'term_branch[]' => array($terms['branch']->tid),
+      'term_trunk[widget]' => 'select',
+      'term_branch_keep' => TRUE,
+      'term_trunk[tid]' => TERM_MERGE_NEW_TERM_TRUNK,
+    ), 'term_trunk[tid]');
+
+    $this->drupalPost(NULL, array(
+      'term_branch[]' => array($terms['branch']->tid),
+      'term_trunk[widget]' => 'select',
+      'term_trunk[tid]' => TERM_MERGE_NEW_TERM_TRUNK,
+      'term_branch_keep' => TRUE,
+      'name' => $this->randomName(),
+      'synonyms[' . SYNONYMS_DEFAULT_FIELD_NAME . ']' => TRUE,
+    ), 'Submit');
+    $this->drupalPost(NULL, array(), 'Confirm');
+    $terms['trunk'] = $this->getLastTerm($this->vocabulary);
+    $terms['trunk']->synonyms = array($terms['branch']->name);
+    $this->assertSynonymsIntegration($terms, 'Synonyms are added after running merge batch merging into a new term, when instructed to add synonyms.');
+  }
+
+  /**
+   * Supportive method.
+   *
+   * Assert expected results after doing any test actions.
+   *
+   * @param array $terms
+   *   Array of terms as returned by $this->createTerms(). Those term trunks
+   *   that have merged any branch terms with "Synonyms" option on, besides all
+   *   normal keys should have property 'synonyms' which should be an array of
+   *   expected synonyms of this term
+   * @param string $message
+   *   Assert message to be shown on test results page
+   */
+  protected function assertSynonymsIntegration($terms, $message) {
+    drupal_static_reset();
+    foreach ($terms as $term) {
+      // Getting an array of synonyms according to Synonyms module.
+      $synonyms = array();
+      foreach (synonyms_get_term_synonyms(taxonomy_term_load($term->tid)) as $tmp) {
+        $synonyms[] = $tmp['value'];
+      }
+
+      $expected_synonyms = isset($term->synonyms) ? $term->synonyms : array();
+      // Comparing $synonyms to $expected_synonyms.
+      if (count($expected_synonyms) != count(array_intersect($expected_synonyms, $synonyms))) {
+        $this->fail($message);
+        return;
+      }
+    }
+    // If we got here, then all expected synonyms were found.
+    $this->pass($message);
+  }
+
+  /**
+   * Supportive method.
+   *
+   * Create a list of terms, assigning names according to the values of the
+   * supplied array.
+   *
+   * @param array $terms
+   *   Array of machine readable term keys based on which is generated output
+   *
+   * @return array
+   *   Array of taxonomy term objects name of which is equal to the value that
+   *   corresponds to its position in the supplied array
+   */
+  protected function createTerms($terms) {
+    $return = array();
+    foreach ($terms as $v) {
+      $this->drupalPost('admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/add', array(
+        'name' => $v,
+      ), 'Save');
+      $return[$v] = $this->getLastTerm($this->vocabulary);
+    }
+
+    return $return;
+  }
+}
+
+/**
+ * Test the integration between Term Merge module and Views module.
+ */
+class ViewsTermMergeWebTestCase extends TermMergeWebTestCase {
+
+  /**
+   * View object on which all tests happen.
+   *
+   * @var view
+   */
+  protected $view;
+
+  /**
+   * SetUp method.
+   */
+  public function setUp() {
+    parent::setUp(array('views'));
+    // Additionally we create a view.
+    $view = views_new_view();
+    $view->name = 'term_merge_view_test';
+    $view->description = 'Test view to test Term Merge module.';
+    $view->tag = '';
+    $view->base_table = 'node';
+    $view->api_version = '3.0';
+    $view->core = 7;
+
+    $display_id = 'default';
+    $view->set_display($display_id);
+
+    views_save_view($view);
+    $this->view = &$view;
+  }
+
+  /**
+   * GetInfo method.
+   */
+  public function getInfo() {
+    return array(
+      'name' => 'Views module integration',
+      'description' => 'Ensure that the module Term Merge integrates with ' . l('Views', 'http://drupal.org/project/views') . ' module correctly.',
+      'group' => 'Term Merge',
+    );
+  }
+
+  /**
+   * Test integration with Views Taxonomy Term reference filter.
+   */
+  public function testTermReferenceFieldFilter() {
+    // We need to create a content type and attach a term reference field to
+    // that bundle in order to have some term reference filter available in
+    // Views.
+    $this->drupalPost('admin/structure/types/add', array(
+      'name' => $this->randomName(),
+      'type' => 'term_merge_node',
+    ), 'Save content type');
+    $field_name = 'term_reference';
+    $this->drupalPost('admin/structure/types/manage/term-merge-node/fields', array(
+      'fields[_add_new_field][label]' => 'Term Reference',
+      'fields[_add_new_field][field_name]' => $field_name,
+      'fields[_add_new_field][type]' => 'taxonomy_term_reference',
+      'fields[_add_new_field][widget_type]' => 'taxonomy_autocomplete',
+    ), 'Save');
+    $field_name = 'field_' . $field_name;
+    $this->drupalPost(NULL, array(
+      'field[settings][allowed_values][0][vocabulary]' => $this->vocabulary->machine_name,
+    ), 'Save field settings');
+    $this->drupalPost(NULL, array(
+      'field[cardinality]' => FIELD_CARDINALITY_UNLIMITED,
+    ), 'Save settings');
+    // Flushing fields API cache.
+    _field_info_collate_fields(TRUE);
+    // Loading field definition array of the term reference field we just
+    // created.
+    $field = field_info_field($field_name);
+
+    // Creating terms to have stuff to work with.
+    $terms = array(
+      'branch' => FALSE,
+      'trunk' => FALSE,
+    );
+
+    foreach ($terms as $term_type => $tmp) {
+      $url = 'admin/structure/taxonomy/vocabulary/add';
+      $name = $this->randomName();
+      $edit = array(
+        'name' => $name,
+      );
+
+      $this->drupalPost($url, $edit, 'Save');
+      $terms[$term_type] = $this->getLastTerm($this->vocabulary);
+    }
+
+    // Adding a taxonomy term reference filter to the view.
+    $this->view->set_display('default');
+
+    // We use Field API info to look up necessary tables and columns.
+    $table = reset(array_keys($field['storage']['details']['sql']['FIELD_LOAD_CURRENT']));
+    $columns = $field['storage']['details']['sql']['FIELD_LOAD_CURRENT'][$table];
+
+    $this->view->display_handler->display->display_options['filters'][$columns['tid']]['id'] = $columns['tid'];
+    $this->view->display_handler->display->display_options['filters'][$columns['tid']]['table'] = $table;
+    $this->view->display_handler->display->display_options['filters'][$columns['tid']]['field'] = $columns['tid'];
+    $this->view->display_handler->display->display_options['filters'][$columns['tid']]['value'] = array(
+      $terms['branch']->tid => $terms['branch']->tid,
+    );
+    $this->view->display_handler->display->display_options['filters'][$columns['tid']]['type'] = 'select';
+    $this->view->display_handler->display->display_options['filters'][$columns['tid']]['vocabulary'] = $this->vocabulary->machine_name;
+    $this->view->display_handler->display->display_options['filters'][$columns['tid']]['hierarchy'] = 1;
+
+    views_save_view($this->view);
+
+    // After such merge we expect the view's filter to be changed from branch
+    // term to trunk term.
+    actions_do('term_merge_action', $terms['branch'], array(
+      'term_trunk' => $terms['trunk']->tid,
+      'term_branch_keep' => FALSE,
+    ));
+
+    // Loading again the view after merging action.
+    $this->view = views_get_view($this->view->name);
+
+    $this->view->set_display('default');
+    $filter = $this->view->display_handler->display->display_options['filters'][$columns['tid']]['value'];
+    $this->assertTrue(count($filter) == 1 && in_array($terms['trunk']->tid, array_keys($filter)), 'Views term reference filter gets updated to filter on trunk term instead of filtering on branch term if the branch term is instructed to be deleted during merging of terms.');
+  }
+}