123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797 |
- <?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;
- }
|