added term_merge module

This commit is contained in:
Bachir Soussi Chiadmi 2015-11-24 10:56:30 +01:00
parent 7298235d4f
commit d7e7410950
9 changed files with 3709 additions and 0 deletions

View File

@ -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.

View File

@ -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.

View File

@ -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);

View File

@ -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.
}

View File

@ -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');
}
}

View File

@ -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"

View File

@ -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;
}

View File

@ -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'];
}

File diff suppressed because it is too large Load Diff