FINAL suepr merge step : added all modules to this super repos

This commit is contained in:
Bachir Soussi Chiadmi
2015-04-19 16:46:59 +02:00
7585 changed files with 1723356 additions and 18 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,53 @@
-- SUMMARY --
The Synonyms module extends the Drupal core Taxonomy features. Currently
the module provides this additional functionality:
* support of synonyms through Field API. Any field, for which synonyms extractor
is created, attached to a term can be enabled as source of synonyms.
* synonym-friendly autocomplete widget for taxonomy_term_reference fields
* integration with Drupal search functionality enabling searching content by
synonyms of the terms that the content references
-- REQUIREMENTS --
The Synonyms module requires the following modules:
* Taxonomy module
* Text module
-- SYNONYMS EXTRACTORS, SUPPORTED FIELD TYPES --
Module ships with ability to extract synonyms from the following field types:
* Text
* Taxonomy Term Reference
* Entity Reference
* Number
* Float
* Decimal
If you want to implement your own synonyms extractor that would enable support
for any other field type, please, refer to synonyms.api.php file for
instructions on how to do it, or file an issue against Synonyms module. We will
try to implement support for your field type too. If you have written your
synonyms extractor, please share by opening an issue, and it will be included
into this module.
-- INSTALLATION --
* Install as usual
-- CONFIGURATION --
* The module itself does not provide any configuration as of the moment.
Although during creation/editing of a Taxonomy vocabulary you will be able
to enable/disable for that particular vocabulary the additional functionality
this module provides, you will find additional fieldset at the bottom of
vocabulary edit page.
-- FUTURE DEVELOPMENT --
* If you are interested into converting this module from synonyms for Taxonomy
terms into synonyms for any entity types, please go to this issue
http://drupal.org/node/1194802 and leave a comment. Once we see some demand for
this great feature and the Synonyms module gets a little more mature, we will
try to make it happen.

View File

@@ -0,0 +1,112 @@
<?php
/**
* @file
* Define interface required for extracting synonyms from field types.
*/
abstract class AbstractSynonymsExtractor {
/**
* Return array of supported field types for synonyms extraction.
*
* @return array
* Array of Field API field types from which this class is able to extract
* synonyms
*/
static public abstract function fieldTypesSupported();
/**
* Extract synonyms from a field attached to an entity.
*
* We try to pass as many info about context as possible, however, normally
* you will only need $items to extract the synonyms.
*
* @param array $items
* Array of items
* @param array $field
* Array of field definition according to Field API
* @param array $instance
* Array of instance definition according to Field API
* @param object $entity
* Fully loaded entity object to which the $field and $instance with $item
* values is attached to
* @param string $entity_type
* Type of the entity $entity according to Field API definition of entity
* types
*
* @return array
* Array of synonyms extracted from $items
*/
static public abstract function synonymsExtract($items, $field, $instance, $entity, $entity_type);
/**
* Allow you to hook in during autocomplete suggestions generation.
*
* Allow you to include entities for autocomplete suggestion that are possible
* candidates based on your field as a source of synonyms. This method is
* void, however, you have to alter and add your condition to $query
* parameter.
*
* @param string $tag
* What user has typed in into autocomplete widget. Normally you would
* run LIKE '%$tag%' on your column
* @param EntityFieldQuery $query
* EntityFieldQuery object where you should put your conditions to
* @param array $field
* Array of field definition according to Field API
* @param array $instance
* Array of instance definition according to Field API
*/
static public abstract function processEntityFieldQuery($tag, EntityFieldQuery $query, $field, $instance);
/**
* Add an entity as a synonym into a field of another entity.
*
* Basically this method should be called when you want to add some entity
* as a synonym to another entity (for example when you merge one entity
* into another and besides merging want to add synonym of the merging
* entity into the trunk entity). You should extract synonym value (according
* to what value is expected in this field) and return it. We try to provide
* you with as much of context as possible, but normally you would only need
* $synonym_entity and $synonym_entity_type parameters. Return an empty array
* if entity of type $synonym_entity_type cannot be converted into a format
* expected by $field.
*
* @param array $items
* Array items that already exist in the field into which new synonyms is to
* be added
* @param array $field
* Field array definition according to Field API of the field into which new
* synonym is to be added
* @param array $instance
* Instance array definition according to Field API of the instance into
* which new synonym is to be added
* @param object $synonym_entity
* Fully loaded entity object which has to be added as synonym
* @param string $synonym_entity_type
* Entity type of $synonym_entity
*
* @return array
* Array of extra items to be merged into the items that already exist in
* field values
*/
static public abstract function mergeEntityAsSynonym($items, $field, $instance, $synonym_entity, $synonym_entity_type);
/**
* Supportive method.
*
* Set such a condition on $query that it will always yield no results. Should
* be called from $this->processEntityFieldQuery() when for whatever reason
* the object can't alter $query to include matched synonyms. As a fallback
* it should call this method to make sure it filtered everything out.
*
* @param EntityFieldQuery $query
* Query object passed to $this->processEntityFieldQuery() method
* @param array $field
* Field array passed to $this->processEntityFieldQuery() method
*/
static protected function emptyResultsCondition(EntityFieldQuery $query) {
$query->entityCondition('entity_id', -1);
}
}

View File

@@ -0,0 +1,71 @@
<?php
/**
* @file
* Enables Entity Reference field type to be source of synonyms.
*/
class EntityReferenceSynonymsExtractor extends AbstractSynonymsExtractor {
static public function fieldTypesSupported() {
return array('entityreference');
}
static public function synonymsExtract($items, $field, $instance, $entity, $entity_type) {
$synonyms = array();
// For speading up loading all the entities at once.
$target_tids = array();
foreach ($items as $item) {
$target_tids[] = $item['target_id'];
}
$entities = entity_load($field['settings']['target_type'], $target_tids);
foreach ($entities as $entity) {
$synonyms[] = entity_label($field['settings']['target_type'], $entity);
}
return $synonyms;
}
static public function processEntityFieldQuery($tag, EntityFieldQuery $query, $field, $instance) {
// Unfortunately EntityFieldQuery does not currently support INNER JOINing
// referenced entities via any field type.
// Thus, we use an ugly solution -- going through all entities that exist
// in such entity type trying to see if there is a match by entity's label.
$efq = new EntityFieldQuery();
$efq->entityCondition('entity_type', $field['settings']['target_type']);
// Additionally we have to figure out which column in the entity table
// represents entity label.
$entity_info = entity_get_info($field['settings']['target_type']);
if (!isset($entity_info['entity keys']['label'])) {
// We can't get any matches if we do not know what column to query
// against. So we add a condition to $query which will 100% yield empty
// results.
self::emptyResultsCondition($query);
return;
}
$efq->propertyCondition($entity_info['entity keys']['label'], '%' . $tag . '%', 'LIKE');
$result = $efq->execute();
if (!isset($result[$field['settings']['target_type']]) || !is_array($result[$field['settings']['target_type']])) {
self::emptyResultsCondition($query);
return;
}
$result = $result[$field['settings']['target_type']];
$query->fieldCondition($field, 'target_id', array_keys($result));
}
static public function mergeEntityAsSynonym($items, $field, $instance, $synonym_entity, $synonym_entity_type) {
// Firstly validating that this entity refernce is able to reference to that
// type of entity.
$expected_synonym_entity_type = $field['settings']['target_type'];
if ($expected_synonym_entity_type != $synonym_entity_type) {
return array();
}
$synonym_entity_id = entity_id($synonym_entity_type, $synonym_entity);
return array(array(
'target_id' => $synonym_entity_id,
));
}
}

View File

@@ -0,0 +1,48 @@
<?php
/**
* @file
* Default Synonyms Extractor class that ships together with the Synonym module.
*/
class SynonymsSynonymsExtractor extends AbstractSynonymsExtractor {
static public function fieldTypesSupported() {
return array('text', 'number_integer', 'number_float', 'number_decimal');
}
static public function synonymsExtract($items, $field, $instance, $entity, $entity_type) {
$synonyms = array();
foreach ($items as $item) {
$synonyms[] = $item['value'];
}
return $synonyms;
}
static public function processEntityFieldQuery($tag, EntityFieldQuery $query, $field, $instance) {
$query->fieldCondition($field, 'value', '%' . $tag . '%', 'LIKE');
}
static public function mergeEntityAsSynonym($items, $field, $instance, $synonym_entity, $synonym_entity_type) {
$synonym = entity_label($synonym_entity_type, $synonym_entity);
switch ($field['type']) {
case 'text':
break;
// We add synonyms for numbers only if $synonym is a number.
case 'number_integer':
case 'number_float':
case 'number_decimal':
if (!is_numeric($synonym)) {
return array();
}
break;
}
return array(array(
'value' => $synonym,
));
}
}

View File

@@ -0,0 +1,94 @@
<?php
/**
* @file
* Enables Taxonomy Term Reference field types to be source of synonyms.
*/
class TaxonomySynonymsExtractor extends AbstractSynonymsExtractor {
static public function fieldTypesSupported() {
return array('taxonomy_term_reference');
}
static public function synonymsExtract($items, $field, $instance, $entity, $entity_type) {
$synonyms = array();
$terms = array();
foreach ($items as $item) {
$terms[] = $item['tid'];
}
$terms = taxonomy_term_load_multiple($terms);
foreach ($terms as $term) {
$synonyms[] = entity_label('taxonomy_term', $term);
}
return $synonyms;
}
static public function processEntityFieldQuery($tag, EntityFieldQuery $query, $field, $instance) {
// Unfortunately EntityFieldQuery does not currently support INNER JOINing
// term entity that is referenced via taxonomy_term_reference field type.
// Thus, we use an ugly solution -- going through all terms that exist in
// vocabulary and trying to see if there is a match by term's name.
$tids = array();
foreach ($field['settings']['allowed_values'] as $settings) {
$efd = new EntityFieldQuery();
$efd->entityCondition('bundle', $settings['vocabulary'])
->entityCondition('entity_type', 'taxonomy_term')
->propertyCondition('name', '%' . $tag . '%', 'LIKE');
$result = $efd->execute();
if (isset($result['taxonomy_term'])) {
foreach ($result['taxonomy_term'] as $tid) {
$tids[] = $tid->tid;
}
}
}
// Now we have tids of terms from the referenced vocabulary which names
// LIKE %$tag%, suggested are the terms that refer to any of these $tids.
if (empty($tids)) {
// No possible suggestions were found. We have to make sure $query yields
// no results.
self::emptyResultsCondition($query);
return;
}
$query->fieldCondition($field, 'tid', $tids);
}
static public function mergeEntityAsSynonym($items, $field, $instance, $synonym_entity, $synonym_entity_type) {
// Taxonomy term reference supports only referencing of entity types
// 'taxonomy_term'.. duh.
if ($synonym_entity_type != 'taxonomy_term') {
return array();
}
// Checking that $field is configured to reference the vocabulary of
// $synonym_entity term.
$is_allowed = FALSE;
foreach ($field['settings']['allowed_values'] as $setting) {
if ($synonym_entity->vocabulary_machine_name == $setting['vocabulary']) {
if ($setting['parent'] == 0) {
// No need to check parent property as there is no limitation on it.
$is_allowed = TRUE;
break;
}
else {
foreach (taxonomy_get_parents_all($synonym_entity->tid) as $parent) {
if ($parent->tid == $setting['parent']) {
$is_allowed = TRUE;
break(2);
}
}
}
}
}
if (!$is_allowed) {
// Synonym term is from a vocabulary that is not expected by this field,
// or under unexpected parent.
return array();
}
return array(array(
'tid' => $synonym_entity->tid,
));
}
}

View File

@@ -0,0 +1,154 @@
<?php
/**
* @file
* Documentation for Synonyms module.
*/
/**
* Provide Synonyms module with names of synonyms extractor classes.
*
* Provide Synonyms module with names of classes that are able to extract
* synonyms from fields. Each of the provided classes should extend
* AbstractSynonymsExtractor base class.
*
* @return array
* Array of strings, where each value is a name of synonyms extractor class
*/
function hook_synonyms_extractor_info() {
return array(
// Please see below the defintion of ApiSynonymsSynonymsExtractor class
// for your reference.
'ApiSynonymsSynonymsExtractor',
);
}
/**
* Dummy synonyms extractor class for documentation purposes.
*
* This is a copy of SynonymsSynonymsExtractor class providing an example of
* how to write your own synonyms extractor class. See the definition of
* AbstractSynonymsExtractor for reference and incode comments. For more
* complicated examples take a look at EntityReferenceSynonymsExtractor class.
*/
class ApiSynonymsSynonymsExtractor extends AbstractSynonymsExtractor {
/**
* Return array of supported field types for synonyms extraction.
*
* @return array
* Array of Field API field types from which this class is able to extract
* synonyms
*/
static public function fieldTypesSupported() {
return array('text', 'number_integer', 'number_float', 'number_decimal');
}
/**
* Extract synonyms from a field attached to an entity.
*
* We try to pass as many info about context as possible, however, normally
* you will only need $items to extract the synonyms.
*
* @param array $items
* Array of items
* @param array $field
* Array of field definition according to Field API
* @param array $instance
* Array of instance definition according to Field API
* @param object $entity
* Fully loaded entity object to which the $field and $instance with $item
* values is attached to
* @param string $entity_type
* Type of the entity $entity according to Field API definition of entity
* types
*
* @return array
* Array of synonyms extracted from $items
*/
static public function synonymsExtract($items, $field, $instance, $entity, $entity_type) {
$synonyms = array();
foreach ($items as $item) {
$synonyms[] = $item['value'];
}
return $synonyms;
}
/**
* Allow you to hook in during autocomplete suggestions generation.
*
* Allow you to include entities for autocomplete suggestion that are possible
* candidates based on your field as a source of synonyms. This method is
* void, however, you have to alter and add your condition to $query
* parameter.
*
* @param string $tag
* What user has typed in into autocomplete widget. Normally you would
* run LIKE '%$tag%' on your column
* @param EntityFieldQuery $query
* EntityFieldQuery object where you should add your conditions to
* @param array $field
* Array of field definition according to Field API, autocomplete on which
* is fired
* @param array $instance
* Array of instance definition according to Field API, autocomplete on
* which is fired
*/
static public function processEntityFieldQuery($tag, EntityFieldQuery $query, $field, $instance) {
$query->fieldCondition($field, 'value', '%' . $tag . '%', 'LIKE');
}
/**
* Add an entity as a synonym into a field of another entity.
*
* Basically this method should be called when you want to add some entity
* as a synonym to another entity (for example when you merge one entity
* into another and besides merging want to add synonym of the merging
* entity into the trunk entity). You should extract synonym value (according
* to what value is expected in this field) and return it. We try to provide
* you with as much context as possible, but normally you would only need
* $synonym_entity and $synonym_entity_type parameters. Return an empty array
* if entity of type $synonym_entity_type cannot be converted into a format
* expected by $field.
*
* @param array $items
* Array items that already exist in the field into which new synonyms is to
* be added
* @param array $field
* Field array definition according to Field API of the field into which new
* synonym is to be added
* @param array $instance
* Instance array definition according to Field API of the instance into
* which new synonym is to be added
* @param object $synonym_entity
* Fully loaded entity object which has to be added as synonym
* @param string $synonym_entity_type
* Entity type of $synonym_entity
*
* @return array
* Array of extra items to be merged into the items that already exist in
* field values
*/
static public function mergeEntityAsSynonym($items, $field, $instance, $synonym_entity, $synonym_entity_type) {
$synonym = entity_label($synonym_entity_type, $synonym_entity);
switch ($field['type']) {
case 'text':
break;
// We add synonyms for numbers only if $synonym is a number.
case 'number_integer':
case 'number_float':
case 'number_decimal':
if (!is_numeric($synonym)) {
return array();
}
break;
}
return array(array(
'value' => $synonym,
));
}
}

View File

@@ -0,0 +1,19 @@
name = Synonyms
description = "Provides synonyms feature for working with Drupal Taxonomy"
package = Taxonomy
core = 7.x
dependencies[] = taxonomy
dependencies[] = text
files[] = synonyms.test
files[] = includes/AbstractSynonymsExtractor.class.inc
files[] = includes/SynonymsSynonymsExtractor.class.inc
files[] = includes/TaxonomySynonymsExtractor.class.inc
files[] = includes/EntityReferenceSynonymsExtractor.class.inc
; Information added by drupal.org packaging script on 2013-01-15
version = "7.x-1.1"
core = "7.x"
project = "synonyms"
datestamp = "1358220389"

View File

@@ -0,0 +1,46 @@
<?php
/**
* @file
* Install, update, and uninstall functions for the Synonyms module.
*/
/**
* Implements hook_uninstall().
*/
function synonyms_uninstall() {
// We rely on a constant defined in the main module's file, so we include it.
drupal_load('module', 'synonyms');
field_delete_field(SYNONYMS_DEFAULT_FIELD_NAME);
// Cleaning all configure variables.
$results = db_select('variable', 'var')
->fields('var', array('name'))
->condition('var.name', db_like('synonyms_') . '%', 'LIKE')
->execute();
foreach ($results as $var) {
variable_del($var->name);
}
}
/**
* Implements hook_update_N().
*
* Update to version 7.x-1.1 of Synonyms module.
*/
function synonyms_update_7101() {
$result = db_select('variable', 'var')
->fields('var', array('name'))
->condition('var.name', db_like('synonyms_settings_') . '%', 'LIKE')
->execute();
foreach ($result as $var) {
$settings = variable_get($var->name);
// Term merging has been deprecated in favor of Term Merge module.
unset($settings['term_merge']);
// Enabled synonyms now stored as field names, since the field independency
// has been introduced. See issue http://drupal.org/node/1850748.
drupal_load('module', 'synonyms');
$settings['synonyms'] = $settings['synonyms'] ? array(SYNONYMS_DEFAULT_FIELD_NAME) : array();
variable_set($var->name, $settings);
}
return t('Updated settings of synonyms.');
}

View File

@@ -0,0 +1,797 @@
<?php
/**
* @file
* Provide synonyms feature for Drupal Taxonomy.
*/
/**
* The default field name to be used as a source of synonyms for a term.
*/
define('SYNONYMS_DEFAULT_FIELD_NAME', 'synonyms_synonyms');
/**
* Implements hook_menu().
*/
function synonyms_menu() {
$items = array();
$items['synonyms/autocomplete'] = array(
'title' => 'Autocomplete Synonyms',
'page callback' => 'synonyms_autocomplete',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Implements hook_synonyms_extractor_info().
*/
function synonyms_synonyms_extractor_info() {
// Here we provide synonyms extractors that come along with Synonyms module.
return array(
'SynonymsSynonymsExtractor',
'TaxonomySynonymsExtractor',
'EntityReferenceSynonymsExtractor',
);
}
/**
* Public function.
*
* Provide info about what class reports ability to extract synonyms from
* which field type. The output information of this function is collected via
* hook_synonyms_extractor_info().
*
* @param string $field_type
* Optionally you may specify to get a class responsible for a specific field
* type only. If nothing is supplied, array of field_type => class_extractor
* relation is returned
* @param bool $reset
* Whether collect all the info again from hooks, or cached info is fine
*
* @return array
* Key of this array denote the field type while value of the array denotes
* which class reports ability to extract synonyms from such field type.
*/
function synonyms_extractor_info($field_type = NULL, $reset = FALSE) {
$cache = &drupal_static(__FUNCTION__);
// Trying static cache.
if (!is_array($cache) || $reset) {
// Trying Drupal DB cache layer.
$cid = 'synonyms_extractor_info';
$cache = cache_get($cid);
if (!isset($cache->data) || $reset) {
// No cache has been found at all. So we call hooks and collect data.
$info = array();
$extractor_classes = module_invoke_all('synonyms_extractor_info');
if (is_array($extractor_classes)) {
foreach ($extractor_classes as $class) {
if (class_exists($class) && is_subclass_of($class, 'AbstractSynonymsExtractor')) {
foreach ($class::fieldTypesSupported() as $_field_type) {
$info[$_field_type] = $class;
}
}
}
}
// Letting whoever wants to implement any changes after preprocessing the
// data.
drupal_alter('synonyms_extractor_info', $info);
// Validating that any changes made to $info do not break class hierarchy.
foreach ($info as $k => $v) {
if (!class_exists($v) || !is_subclass_of($v, 'AbstractSynonymsExtractor')) {
unset($info[$k]);
}
}
$cache = $info;
cache_set($cid, $cache, 'cache', CACHE_TEMPORARY);
}
else {
$cache = $cache->data;
}
}
if (!is_null($field_type) && isset($cache[$field_type])) {
return $cache[$field_type];
}
return $cache;
}
/**
* Implements hook_node_update_index().
*/
function synonyms_node_update_index($node) {
$output = '';
foreach (field_info_instances('node', $node->type) as $instance) {
// We go a field by field looking for taxonomy term reference and
// if that vocabulary has enabled synonyms, we add term's synonyms
// to the search index.
$field_info = field_info_field($instance['field_name']);
if ($field_info['type'] == 'taxonomy_term_reference') {
// For each term referenced in this node we have to add synonyms.
$_terms = field_get_items('node', $node, $instance['field_name']);
if (is_array($_terms) && !empty($_terms)) {
$terms = array();
foreach ($_terms as $v) {
$terms[] = $v['tid'];
}
$terms = taxonomy_term_load_multiple($terms);
foreach ($terms as $term) {
$synonyms = synonyms_get_term_synonyms($term);
if (!empty($synonyms)) {
$safe_synonyms = array();
foreach ($synonyms as $synonym) {
$safe_synonyms[] = $synonym['safe_value'];
}
$output .= '<strong>' . implode(', ', $safe_synonyms) . '</strong>';
}
}
}
}
}
return $output;
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function synonyms_form_taxonomy_form_vocabulary_alter(&$form, &$form_state) {
if (isset($form_state['confirm_delete']) && $form_state['confirm_delete']) {
return;
}
$form['synonyms'] = array(
'#type' => 'fieldset',
'#title' => t('Synonyms'),
'#collapsible' => TRUE,
'#tree' => TRUE,
);
$options = array(
SYNONYMS_DEFAULT_FIELD_NAME => t('Default synonyms field'),
);
if (isset($form['#vocabulary']->vid)) {
$instances = synonyms_instances_extract_applicapable($form['#vocabulary']);
foreach ($instances as $instance) {
// Here we prefer some informative text for the default synonyms field
// rather its label.
if ($instance['field_name'] != SYNONYMS_DEFAULT_FIELD_NAME) {
$options[$instance['field_name']] = $instance['label'];
}
}
}
$form['synonyms']['synonyms'] = array(
'#type' => 'checkboxes',
'#title' => t('Synonyms Fields'),
'#options' => $options,
'#description' => t('<p>This option allows you to assign synonym fields for each term of the vocabulary, allowing to reduce the amount of duplicates.</p><p><b>Important note:</b> unticking %default_field on a production website will result in loss of your synonyms.</p>', array('%default_field' => $options[SYNONYMS_DEFAULT_FIELD_NAME])),
'#default_value' => synonyms_synonyms_fields($form['#vocabulary']),
);
// Adding out own submit handler.
$form['#submit'][] = 'synonyms_taxonomy_form_vocabulary_submit';
}
/**
* Implements hook_field_widget_info().
*/
function synonyms_field_widget_info() {
return array(
'synonyms_autocomplete' => array(
'label' => t('Synonyms friendly autocomplete term widget'),
'field types' => array('taxonomy_term_reference'),
'settings' => array(
'size' => 60,
'autocomplete_path' => 'synonyms/autocomplete',
),
'behaviors' => array(
'multiple values' => FIELD_BEHAVIOR_CUSTOM,
),
),
);
}
/**
* Implements hook_field_widget_settings_form().
*/
function synonyms_field_widget_settings_form($field, $instance) {
$widget = $instance['widget'];
$settings = $widget['settings'];
$form = array();
$form['auto_creation'] = array(
'#type' => 'checkbox',
'#title' => t('Allow auto-creation?'),
'#description' => t('Whether users may create a new term by typing in a non-existing name into this field.'),
'#default_value' => isset($settings['auto_creation']) ? $settings['auto_creation'] : 0,
);
return $form;
}
/**
* Implements hook_field_widget_form().
*/
function synonyms_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
$tags = array();
foreach ($items as $item) {
$tags[$item['tid']] = isset($item['taxonomy_term']) ? $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
}
$element += array(
'#type' => 'textfield',
'#default_value' => taxonomy_implode_tags($tags),
'#autocomplete_path' => $instance['widget']['settings']['autocomplete_path'] . '/' . $field['field_name'],
'#size' => $instance['widget']['settings']['size'],
'#maxlength' => 1024,
'#element_validate' => array('taxonomy_autocomplete_validate', 'synonyms_autocomplete_validate'),
'#auto_creation' => isset($instance['widget']['settings']['auto_creation']) ? $instance['widget']['settings']['auto_creation'] : 0,
);
return $element;
}
/**
* Implements hook_field_widget_error().
*/
function synonyms_field_widget_error($element, $error, $form, &$form_state) {
form_error($element, $error['message']);
}
/**
* Form element validate handler.
*
* Handle validation for taxonomy term synonym-friendly autocomplete element.
*/
function synonyms_autocomplete_validate($element, &$form_state) {
// After taxonomy_autocomplete_validate() has finished its job
// it might left terms in the format for autocreation. Since our field
// supports auto creation as a configurable option, we have to make sure
// auto creation terms are allowed.
$value = drupal_array_get_nested_value($form_state['values'], $element['#parents']);
if (!$element['#auto_creation']) {
// Deleting all the terms meant to be auto-created.
foreach ($value as $delta => $term) {
if ($term['tid'] == 'autocreate') {
unset($value[$delta]);
}
}
$value = array_values($value);
}
form_set_value($element, $value, $form_state);
}
/**
* Submit hanlder for Taxonomy vocabulary edit form.
*
* Store extra values attached to form in this module.
*/
function synonyms_taxonomy_form_vocabulary_submit($form, &$form_state) {
$values = $form_state['values'];
if ($values['op'] == $form['actions']['submit']['#value']) {
if (isset($form['#vocabulary']->vid)) {
$vocabulary = taxonomy_vocabulary_load($form['#vocabulary']->vid);
}
else {
// As a fallback, if this is a just created vocabulary, we try to pull it
// up by the just submitted machine name.
$vocabulary = taxonomy_vocabulary_machine_name_load($values['machine_name']);
}
// Preprocessing values keeping only field names of the checked fields.
foreach ($values['synonyms']['synonyms'] as $k => $v) {
if (!$v) {
unset($values['synonyms']['synonyms'][$k]);
}
}
$values['synonyms']['synonyms'] = array_values($values['synonyms']['synonyms']);
$settings = synonyms_vocabulary_settings($vocabulary);
$settings = $values['synonyms'] + $settings;
synonyms_vocabulary_settings_save($vocabulary, $settings);
}
}
/**
* Page callback: Outputs JSON for taxonomy autocomplete suggestions.
*
* This callback outputs term name suggestions in response to Ajax requests
* made by the synonyms autocomplete widget for taxonomy term reference
* fields. The output is a JSON object of plain-text term suggestions,
* keyed by the user-entered value with the completed term name appended.
* Term names containing commas are wrapped in quotes. The search is made
* with consideration of synonyms.
*
* @param string $field_name
* The name of the term reference field.
* @param string $tags_typed
* (optional) A comma-separated list of term names entered in the
* autocomplete form element. Only the last term is used for autocompletion.
* Defaults to '' (an empty string).
*/
function synonyms_autocomplete($field_name, $tags_typed = '') {
// How many suggestions maximum we are able to output.
$max_suggestions = 10;
// 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 $field_name argument.
array_shift($args);
$tags_typed = implode('/', $args);
// Make sure the field exists and is a taxonomy field.
if (!($field = field_info_field($field_name)) || $field['type'] != 'taxonomy_term_reference') {
// Error string. The JavaScript handler will realize this is not JSON and
// will display it as debugging information.
print t('Taxonomy field @field_name not found.', array('@field_name' => $field_name));
exit;
}
// The user enters a comma-separated list of tags. We only autocomplete the
// last tag.
$tags_typed = drupal_explode_tags($tags_typed);
$tag_last = drupal_strtolower(array_pop($tags_typed));
$term_matches = array();
if ($tag_last != '') {
// Part of the criteria for the query come from the field's own settings.
$vocabularies = array();
$tmp = taxonomy_vocabulary_get_names();
foreach ($field['settings']['allowed_values'] as $tree) {
$vocabularies[$tmp[$tree['vocabulary']]->vid] = $tree['vocabulary'];
}
$vocabularies = taxonomy_vocabulary_load_multiple(array_keys($vocabularies));
// Firstly getting a list of tids that match by $term->name.
$query = db_select('taxonomy_term_data', 't');
$query->addTag('translatable');
$query->addTag('term_access');
// Do not select already entered terms.
if (!empty($tags_typed)) {
$query->condition('t.name', $tags_typed, 'NOT IN');
}
// Select rows that match by term name.
$tags_return = $query
->fields('t', array('tid', 'name'))
->condition('t.vid', array_keys($vocabularies))
->condition('t.name', '%' . db_like($tag_last) . '%', 'LIKE')
->range(0, $max_suggestions)
->execute()
->fetchAllKeyed();
// Converting results into another format.
foreach ($tags_return as $tid => $name) {
$tags_return[$tid] = array('name' => $name);
}
$synonym_tids = array();
// Now we go vocabulary by vocabulary looking through synonym fields.
foreach ($vocabularies as $vocabulary) {
// Now we go a synonym field by synonym field gathering suggestions.
// Since officially EntityFieldQuery doesn't support OR conditions
// we are enforced to go a field by field querying multiple times the DB.
$bundle = field_extract_bundle('taxonomy_term', $vocabulary);
foreach (synonyms_synonyms_fields($vocabulary) as $field) {
$field = field_info_field($field);
$instance = field_info_instance('taxonomy_term', $field['field_name'], $bundle);
if (count($tags_return) + count($synonym_tids) > $max_suggestions) {
// We have collected enough suggestions and the ongoing queries
// will be just a waste of time.
break;
}
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'taxonomy_term')
->entityCondition('bundle', $vocabulary->machine_name);
// We let the class that defines this field type as a source of synonyms
// filter our and provide its suggestions based on this field.
$class = synonyms_extractor_info($field['type']);
$class::processEntityFieldQuery($tag_last, $query, $field, $instance);
if (!empty($tags_typed)) {
$query->propertyCondition('name', $tags_typed, 'NOT IN');
}
if (!empty($tags_return)) {
// We don't want to search among the terms already found by term name.
$query->entityCondition('entity_id', array_keys($tags_return), 'NOT IN');
}
if (!empty($synonym_tids)) {
// Nor we want to search among the terms already mached by previous
// synonym fields.
$query->entityCondition('entity_id', $synonym_tids, 'NOT IN');
}
$tmp = $query->execute();
if (!empty($tmp)) {
// Merging the results.
$tmp = array_keys($tmp['taxonomy_term']);
$synonym_tids = array_merge($synonym_tids, $tmp);
}
}
}
if (!empty($synonym_tids)) {
$synonym_tids = array_slice($synonym_tids, 0, $max_suggestions - count($tags_return));
foreach (taxonomy_term_load_multiple($synonym_tids) as $synonym_term) {
$tags_return[$synonym_term->tid] = array('name' => $synonym_term->name);
// Additionally we have to find out which synonym triggered inclusion
// of this term.
$synonyms = synonyms_get_term_synonyms($synonym_term);
foreach ($synonyms as $item) {
if (strpos(mb_strtoupper($item['value'], 'UTF-8'), mb_strtoupper($tag_last, 'UTF-8')) !== FALSE) {
$tags_return[$synonym_term->tid]['synonym'] = $item['value'];
break;
}
}
}
}
$prefix = count($tags_typed) ? drupal_implode_tags($tags_typed) . ', ' : '';
// Now formatting the results.
foreach ($tags_return as $tid => $info) {
$n = $info['name'];
// Term names containing commas or quotes must be wrapped in quotes.
if (strpos($info['name'], ',') !== FALSE || strpos($info['name'], '"') !== FALSE) {
$n = '"' . str_replace('"', '""', $info['name']) . '"';
}
if (isset($info['synonym'])) {
$display_name = t('@synonym, synonym of %term', array('@synonym' => $info['synonym'], '%term' => $info['name']));
}
else {
$display_name = check_plain($info['name']);
}
$term_matches[$prefix . $n] = $display_name;
}
}
drupal_json_output($term_matches);
}
/**
* Try to find a term by its name or synonym.
*
* To maximize the match trimming and case-insensetive comparison is used.
*
* @param string $name
* The string to be searched for its {taxonomy_term}.tid
* @param object $vocabulary
* Fully loaded vocabulary object in which you wish to search
* @param int $parent
* Optional. In case you want to narrow your search scope, this parameter
* takes in the {taxonomy_term}.tid of the parent term, letting you search
* only among its children
*
* @return int
* If the look up was successfull returns the {taxonomy_term}.tid of the
* found term, otherwise returns 0
*/
function synonyms_get_term_by_synonym($name, $vocabulary, $parent = 0) {
$name = mb_strtoupper(trim($name), 'UTF-8');
$tree = taxonomy_get_tree($vocabulary->vid, $parent, NULL, TRUE);
foreach ($tree as $term) {
if (mb_strtoupper($term->name, 'UTF-8') == $name) {
return $term->tid;
}
// We additionally scan through the synonyms.
$synonyms = synonyms_get_term_synonyms($term);
foreach ($synonyms as $item) {
if (mb_strtoupper($item['safe_value'], 'UTF-8') == $name) {
return $term->tid;
}
}
}
// If we have reached down here, this means we haven't got any match
// as fallback we return 0.
return 0;
}
/**
* Look up a term considering synonyms and if nothing found add one.
*
* This function is useful for automated creation of new terms
* as it won't generate the same terms over and over again.
*
* @param string $name
* The string to be searched for its {taxonomy_term}.tid
* @param object $vocabulary
* Fully loaded vocabulary object in which you wish to search
* @param int $parent
* Optional. In case you want to narrow your search scope, this parameter
* takes in the {taxonomy_term}.tid of the parent term, letting you search
* only among its children
*
* @return int
* If a term already exists, its {taxonomy_term}.tid is returned,
* otherwise it creates a new term and returns its {taxonomy_term}.tid
*/
function synonyms_add_term_by_synonym($name, $vocabulary, $parent = 0) {
$tid = synonyms_get_term_by_synonym($name, $vocabulary, $parent);
if ($tid) {
// We found some term, returning its tid.
return $tid;
}
// We haven't found any term, so we create one.
$term = (object) array(
'name' => $name,
'vid' => $vocabulary->vid,
'parent' => array($parent),
);
taxonomy_term_save($term);
if (isset($term->tid)) {
return $term->tid;
}
// Normally we shouldn't reach up to here, because a term would have got
// created and the just created tid would have been returned. Nevertheless,
// as a fallback in case of any error we return 0.
return 0;
}
/**
* Public function for retrieving synonyms of a taxonomy term.
*
* @param object $term
* Fully loaded taxonomy term for which the synonyms are desired
*
* @return array
* Array of synonyms, if synonyms are disabled for the taxonomy term's
* vocabulary, an empty array is returned. Each synonyms array consists of the
* following keys:
* value - the value of a synonym as it was input by user
* safe_value - a sanitized value of a synonym
*/
function synonyms_get_term_synonyms($term) {
$synonyms = array();
$vocabulary = taxonomy_vocabulary_load($term->vid);
foreach (synonyms_synonyms_fields($vocabulary) as $field) {
$bundle = field_extract_bundle('taxonomy_term', $vocabulary);
$instance = field_info_instance('taxonomy_term', $field, $bundle);
$field = field_info_field($field);
$items = field_get_items('taxonomy_term', $term, $field['field_name']);
if (is_array($items) && !empty($items)) {
$class = synonyms_extractor_info($field['type']);
$synonyms = array_merge($synonyms, $class::synonymsExtract($items, $field, $instance, $term, 'taxonomy_term'));
}
}
// Applying sanitization to the extracted synonyms.
foreach ($synonyms as $k => $v) {
$synonyms[$k] = array(
'value' => $v,
'safe_value' => check_plain($v),
);
}
return $synonyms;
}
/**
* Allow to merge $synonym_entity as a synonym into $trunk_entity.
*
* Helpful function during various merging operations. It allows you to add a
* synonym (where possible) into one entity, which will represent another entity
* in the format expected by the field in which the synonym is being added.
* Important note: if the cardinality limit of the field into which you are
* adding synonym has been reached, calling to this function will take no
* effect.
*
* @param object $trunk_entity
* Fully loaded entity object in which the synonym is being added
* @param string $trunk_entity_type
* Entity type of $trunk_entity
* @param string $field
* Field name that should exist in $trunk_entity and be enabled as a synonym
* source. Into this field synonym will be added
* @param object $synonym_entity
* Fully loaded entity object which will be added as a synonym
* @param string $synonym_entity_type
* Entity type of $synonym_entity
*
* @return bool
* Whether synonym has been successfully added
*/
function synonyms_add_entity_as_synonym($trunk_entity, $trunk_entity_type, $field, $synonym_entity, $synonym_entity_type) {
if ($trunk_entity_type != 'taxonomy_term') {
// Currently synonyms module only operates on taxonomy terms.
return FALSE;
}
if (!in_array($field, synonyms_synonyms_fields(taxonomy_vocabulary_load($trunk_entity->vid)))) {
// $field either doesn't exist in the $trunk_entity or it's not enabled as
// a source of synonyms.
return FALSE;
}
// Preparing arguments for calling a method of Extractor class.
$field = field_info_field($field);
$extractor = synonyms_extractor_info($field['type']);
$items = field_get_items($trunk_entity_type, $trunk_entity, $field['field_name']);
$items = is_array($items) ? $items : array();
$trunk_entity_ids = entity_extract_ids($trunk_entity_type, $trunk_entity);
$instance = field_info_instance($trunk_entity_type, $field['field_name'], $trunk_entity_ids[2]);
$extra_items = $extractor::mergeEntityAsSynonym($items, $field, $instance, $synonym_entity, $synonym_entity_type);
// Merging extracted synonym items into the values of the field that already
// exist.
// @todo: Currently we hardcode to LANGUAGE_NONE, but in future it would be
// nice to have multilanguage support.
$items = array_merge($items, $extra_items);
$trunk_entity->{$field['field_name']}[LANGUAGE_NONE] = $items;
// In future if this module eventually becomes a gateway for synonyms for any
// entity types, we'll substitute it with entity_save().
taxonomy_term_save($trunk_entity);
return TRUE;
}
/**
* Return array of field names that are sources of synonyms.
*
* Return array of field names that are currently enabled as source of
* synonyms in the supplied vocabulary.
*
* @param object $vocabulary
* Fully loaded taxonomy vocabulary object
*
* @return array
* Array of field names
*/
function synonyms_synonyms_fields($vocabulary) {
$settings = synonyms_vocabulary_settings($vocabulary);
if (!isset($settings['synonyms']) || !is_array($settings['synonyms'])) {
// Wierd as normally we expect to see here at least an empty array but
// no problem. We simply initialize it.
$settings['synonyms'] = array();
}
// It's not just as easy as pulling up already saved value. After this
// we have to make sure that all the fields are still present and have not
// been deleted from the vocabulary.
$bundle = field_extract_bundle('taxonomy_term', $vocabulary);
$instances = field_info_instances('taxonomy_term', $bundle);
$settings['synonyms'] = array_intersect($settings['synonyms'], array_keys($instances));
return $settings['synonyms'];
}
/**
* Enforce the setting "synonyms".
*
* @param object $vocabulary
* Fully loaded entity of a taxonomy vocabulary
* @param array $fields
* Array of fields that are enabled as a source of synonyms
*/
function synonyms_synonyms_enforce($vocabulary, $fields) {
$bundle = field_extract_bundle('taxonomy_term', $vocabulary);
// Normally all the fields already exist, we just need to assure that
// default synonyms field exists if it is enabled as a source of synonyms.
// Otherwise we make sure we delete instance of the default field in the
// vocabulary.
$instance = field_info_instance('taxonomy_term', SYNONYMS_DEFAULT_FIELD_NAME, $bundle);
if (in_array(SYNONYMS_DEFAULT_FIELD_NAME, $fields)) {
if (is_null($instance)) {
// Make sure the field exists.
synonyms_default_field_ensure();
field_create_instance(array(
'field_name' => SYNONYMS_DEFAULT_FIELD_NAME,
'entity_type' => 'taxonomy_term',
'bundle' => $bundle,
'label' => t('Synonyms'),
'description' => t('Please, enter the synonyms which should be related to this term.'),
));
}
}
elseif (!is_null($instance)) {
// Deleting the instance, we will delete the field separately when the
// module gets uninstalled.
field_delete_instance($instance, FALSE);
}
}
/**
* Return the current settings for the supplied $vocabulary.
*
* @param object $vocabulary
* Fully loaded entity of a taxonomy vocabulary
*
* @return array
* Array of current synonyms settings for the supplied vocabulary.
* Should include the following keys:
* synonyms - array of field names that are enabled as source of synonyms
*/
function synonyms_vocabulary_settings($vocabulary) {
$settings = array();
if (isset($vocabulary->vid)) {
$settings = variable_get('synonyms_settings_' . $vocabulary->vid, array());
}
return $settings;
}
/**
* Save the current settings for the supplied $vocabulary.
*
* @param object $vocabulary
* Fully loaded entity of a taxonomy vocabulary
* @param array $settings
* Settings the have to be stored. The structure of this array has to be
* identical to the output array of the function
* synonyms_vocabulary_settings()
*/
function synonyms_vocabulary_settings_save($vocabulary, $settings) {
variable_set('synonyms_settings_' . $vocabulary->vid, $settings);
// Now enforcing each setting.
foreach ($settings as $k => $v) {
switch ($k) {
case 'synonyms':
synonyms_synonyms_enforce($vocabulary, $v);
break;
}
}
}
/**
* Make sure the default synonyms field exists.
*
* If the field doesn't exist function creates one, if the field exists,
* the function does nothing.
*/
function synonyms_default_field_ensure() {
$field = field_info_field(SYNONYMS_DEFAULT_FIELD_NAME);
if (is_null($field)) {
$field = array(
'field_name' => SYNONYMS_DEFAULT_FIELD_NAME,
'cardinality' => FIELD_CARDINALITY_UNLIMITED,
'locked' => TRUE,
'type' => 'text',
);
field_create_field($field);
}
}
/**
* Extract instances that are applicapable for being source of synonyms.
*
* Walk through all instances of a vocabulary and extract only valid candidates
* for becoming a source of synonyms for the vocabulary terms.
*
* @param object $vocabulary
* Fully loaded vocabulary object
*
* @return array
* Array of instance arrays
*/
function synonyms_instances_extract_applicapable($vocabulary) {
$applicapable_field_types = array_keys(synonyms_extractor_info());
$applicapable = array();
$bundle = field_extract_bundle('taxonomy_term', $vocabulary);
foreach (field_info_instances('taxonomy_term', $bundle) as $instance) {
$field = field_info_field($instance['field_name']);
if (in_array($field['type'], $applicapable_field_types)) {
$applicapable[] = $instance;
}
}
return $applicapable;
}

File diff suppressed because it is too large Load Diff