You are here

alinks.module in Alinks 7

Same filename and directory in other branches
  1. 8 alinks.module
  2. 6 alinks.module

this module allows users to associates defined text to links

File

alinks.module
View source
<?php

/**
 * @file
 * this module allows users to associates defined text to links
 */

/**
 * Implementation of hook_permission().
 */
function alinks_permission() {
  return array(
    'administer site configuration' => array(
      'title' => t('administer site configuration'),
    ),
    'edit alinks' => array(
      'title' => t('edit alinks'),
    ),
  );
}

/**
 * Theme function for the list of alinks
 */
function alinks_theme() {
  return array(
    'alinks_list' => array(
      'render element' => 'form',
    ),
  );
}

/**
 * Implementation of hook_menu().
 */
function alinks_menu() {
  $items = array();
  $admin = array(
    'administer site configuration',
  );
  $editor = array(
    'edit alinks',
  );
  $items['admin/config/content/alinks'] = array(
    'title' => t('Alinks'),
    'description' => t('Set the preferences for Alinks module.'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'alinks_admin_settings',
    ),
    'access arguments' => $admin,
  );
  $items['admin/structure/alinks'] = array(
    'title' => t('Alinks'),
    'description' => t('Define & edit alinks'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'alinks_add_form',
    ),
    'access arguments' => $editor,
    'type' => MENU_NORMAL_ITEM,
  );
  $items['admin/structure/alinks/add'] = array(
    'title' => t('Add Alink'),
    'description' => t('Add alink'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'alinks_add_form',
    ),
    'access arguments' => $editor,
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
  $items['admin/structure/alinks/edit'] = array(
    'title' => t('Edit Alinks'),
    'description' => t('Edit alinks'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'alinks_edit_form',
    ),
    'access arguments' => $editor,
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}

/*
 * Generate the form for the settings page
 */
function alinks_admin_settings() {

  // Get node types and create array for options field
  $types = node_type_get_types();
  $types_options = array();
  foreach ($types as $k => $v) {
    $types_options[$k] = $v->name;
  }
  $form['alinks_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('Alinks Settings'),
    '#collapsible' => FALSE,
  );
  $form['alinks_settings']['alinks_node_types'] = array(
    '#type' => 'fieldset',
    '#title' => t('Alinks node types'),
    '#description' => t('Choose the node types into which alinks will automatically insert links.'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['alinks_settings']['alinks_node_types']['alinks_node_types'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Alinks node types'),
    '#description' => t('Select node types'),
    '#options' => $types_options,
    '#default_value' => variable_get('alinks_node_types', array()),
  );
  $form['alinks_settings']['alinks_limit'] = array(
    '#type' => 'textfield',
    '#size' => 5,
    '#maxlenghth' => 3,
    '#title' => t('Alinks limit'),
    '#description' => t('Set the maxium instances an alink can replace. Use -1 if you want all instances in the node to be replaced.'),
    '#default_value' => variable_get('alinks_limit', 1),
  );
  return system_settings_form($form);
}

/**
 * Generate the page that will render the forms for adding and editing Alinks
 */
function alinks_page() {
  $output = drupal_get_form('alinks_add_form');
  $output .= drupal_get_form('alinks_edit_form');
  return $output;
}

/**
 * Implementation of hook_node_view().
 */
function alinks_node_view($node, $view_mode, $langcode) {
  $node_types = in_array($node->type, variable_get('alinks_node_types', array()), TRUE);
  if ($node_types) {
    $words = alinks_get_strings();
    if ($words) {
      if (is_array($words) && !empty($words) && isset($node->content['body'][0]['#markup'])) {
        $node->content['body'][0]['#markup'] = alinks_make_links($node->content['body'][0]['#markup'], $words);
      }
    }
  }
}

/**
 * Get the strings we have to replace from the database
 */
function alinks_get_strings() {
  $alink = array();
  $result = db_query("SELECT * FROM {alinks} ORDER BY alink_weight");
  if ($result
    ->rowCount() > 0) {
    foreach ($result as $alinks) {
      $alink[$alinks->id] = $alinks;
    }
  }
  return $alink;
}

/**
 * Transform the first instance of any word defined to links
 */
function alinks_make_links($body, $words) {
  if (is_array($words) && isset($body)) {

    // create the replacement array
    $url = drupal_lookup_path('alias', $_GET['q']) ? drupal_lookup_path('alias', $_GET['q']) : $_GET['q'];
    $i = 0;
    $alink_options = array();
    $links_chars = array(
      '/',
      '-',
    );
    $links_chars_replace = array(
      'alink_slash',
      'alink_minus',
    );
    $replacement = array();
    foreach ($words as $word) {
      if ($word->alink_url != $url) {
        $alink_start_boundary = $word->alink_start_boundary == 1 ? 'B' : 'b';
        $alink_end_boundary = $word->alink_end_boundary == 1 ? 'B' : 'b';
        $alink_case_insensivity = $word->alink_case_insensitive == 1 ? 'i' : '';
        $word->alink_text = trim(htmlspecialchars($word->alink_text));
        $alink_text[] = '$\\' . $alink_start_boundary . '(' . preg_quote($word->alink_text, '$') . ')\\' . $alink_end_boundary . '(?!((?!alink_replaced).)*alink_replaced</a>)$u' . $alink_case_insensivity;
        if ($word->alink_external != 1) {
          $alink_path = 'alink_check' . str_replace('/', 'alink_slash', $word->alink_url) . 'alink_check';
        }
        else {
          $alink_path = str_replace($links_chars, $links_chars_replace, $word->alink_url) . 'alink_check';
          $alink_options['absolute'] = TRUE;
        }
        if (!empty($word->alink_class)) {
          $alink_class = 'alink_check' . str_replace(' ', 'alink_space', $word->alink_class) . 'alink_check';
          $alink_options['attributes']['class'] = $alink_class;
        }
        if (!empty($word->url_title)) {
          $alink_title = 'alink_check' . str_replace(' ', 'alink_space', check_plain($word->url_title)) . 'alink_check';
          $alink_options['attributes']['title'] = $alink_title;
        }
        $alink_url[] = l('alink_replaced\\1alink_replaced', $alink_path, $alink_options);
        $i++;
      }
    }
    if ($i > 0) {
      $alink_url = str_replace(array(
        '&amp;amp;',
        '&amp;lt;',
        '&amp;gt;',
      ), array(
        '&amp;',
        '&lt;',
        '&gt;',
      ), $alink_url);

      // we replace new lines with a temporary delimiter
      $carriage = array(
        "\r\n",
        "\n",
        "\r",
      );
      $carriage_replacement = array(
        " cariage_replacement_rn ",
        " cariage_replacement_n ",
        " cariage_replacement_r ",
      );
      $body = str_replace($carriage, $carriage_replacement, $body);

      // we get out the already existing links
      preg_match_all('/\\<a\\s.*?\\>(.*?)\\<\\/a\\>/i', $body, $linka);

      // create the replacement array
      foreach ($linka[0] as $key => $values) {
        $replacement[] = ' alink_delimiter_' . $key . ' ';
      }

      // replace the links with the replacement text
      $body = str_replace($linka[0], $replacement, $body);

      // we get all the text that is not inside a html tag from the modified text
      preg_match_all('/\\>(.*?)\\</', $body, $output);
      $output[0] = array_unique($output[0]);
      $output[1] = array_unique($output[1]);

      // transform the result array to a string so we can use the limit argument
      $text = implode(' alink_delimiter_one_string ', $output[1]);
      $limit = variable_get('alinks_limit', 1);

      // make the actual replacement
      if ($limit == -1) {
        $output[1] = preg_replace($alink_text, $alink_url, $text);
      }
      else {
        $output[1] = preg_replace($alink_text, $alink_url, $text, $limit);
      }

      // rebuild the array
      $output[1] = explode(' alink_delimiter_one_string ', $output[1]);
      $our_output = array();
      $i = 0;

      // we make sure the text will pe replaced outside any tag
      foreach ($output[1] as $key => $values) {
        if (!$values) {
          $our_output[$i] = '><';
        }
        else {
          $our_output[$i] = str_replace($values, '>' . $values . '<', $values);
        }
        $i++;
      }

      // insert the new text in the full text
      $body = str_replace($output[0], $our_output, $body);

      // and put back the links in the text
      $body = str_replace($replacement, $linka[0], $body);
      $body = str_replace('alink_check', '', $body);
      $body = str_replace('alink_replaced', '', $body);
      $body = str_replace('alink_space', ' ', $body);
      $body = str_replace($links_chars_replace, $links_chars, $body);

      // and finaly put back the new lines
      $body = str_replace($carriage_replacement, $carriage, $body);
    }
  }
  return $body;
}

/**
 * Generate the form used to add alinks to drupal
 */
function alinks_add_form() {
  $form['alinks_add_form'] = array(
    '#type' => 'fieldset',
    '#title' => t('Add alink'),
    '#description' => t('Use this form to add alinks'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['alinks_add_form']['start_boundary'] = array(
    '#type' => 'checkbox',
    '#title' => t('Start Boundary'),
    '#description' => t('Enable if the string doesn\'t begin with an alphanumeric or underscore character.'),
  );
  $form['alinks_add_form']['word'] = array(
    '#type' => 'textfield',
    '#title' => t('Word/Phrase'),
    '#size' => 30,
    '#maxlength' => 255,
    '#description' => t('The word or phrase you wish to convert to a link. This field is case sensitive.'),
    '#required' => TRUE,
  );
  $form['alinks_add_form']['end_boundary'] = array(
    '#type' => 'checkbox',
    '#title' => t('End Boundary'),
    '#description' => t('Enable if the string doesn\'t end with an alphanumeric or underscore character.'),
  );
  $form['alinks_add_form']['case_insensitive'] = array(
    '#type' => 'checkbox',
    '#title' => t('Case Insensitivity'),
    '#description' => t('By default alinks are CaSe SeNsItIvE. Chech this checkbox if you want this particular ' . 'alink to be case insensitive.'),
  );
  $form['alinks_add_form']['url'] = array(
    '#type' => 'textfield',
    '#title' => t('URL'),
    '#size' => 30,
    '#maxlength' => 255,
    '#description' => t('The URL of the page to link to. Internal (Drupal) links take the form "my/page", from the ' . 'full URL of "example.com/my/page".'),
    '#required' => TRUE,
  );
  $form['alinks_add_form']['url_title'] = array(
    '#type' => 'textfield',
    '#title' => t('URL Title'),
    '#size' => 30,
    '#maxlength' => 255,
    '#description' => t('Title for the above URL. It will be embedded in the created link and appear as a tooltip ' . 'when hovering the mouse over the link.'),
  );
  $form['alinks_add_form']['external'] = array(
    '#type' => 'checkbox',
    '#title' => t('External Link'),
    '#description' => t('Check this if the link is to an external domain and be sure to include http:// in the link.'),
  );
  $form['alinks_add_form']['class'] = array(
    '#type' => 'textfield',
    '#title' => t('Class'),
    '#size' => 30,
    '#maxlength' => 255,
    '#default_value' => 'alinks-link',
    '#description' => t('Use this to add a class for the link. Default value is "alinks-link".'),
  );
  $form['alinks_add_form']['weight'] = array(
    '#type' => 'weight',
    '#title' => t('Weight'),
  );
  $form['alinks_add_form']['save'] = array(
    '#type' => 'submit',
    '#value' => t('Add alink'),
  );
  return $form;
}

/**
 * Submit the form used to add alinks and insert the data in the db
 */
function alinks_add_form_submit($form, &$form_state) {
  db_insert('alinks')
    ->fields(array(
    'alink_start_boundary' => $form_state['values']['start_boundary'],
    'alink_text' => $form_state['values']['word'],
    'alink_end_boundary' => $form_state['values']['end_boundary'],
    'alink_case_insensitive' => $form_state['values']['case_insensitive'],
    'alink_url' => $form_state['values']['url'],
    'url_title' => $form_state['values']['url_title'],
    'alink_external' => $form_state['values']['external'],
    'alink_class' => $form_state['values']['class'],
    'alink_weight' => $form_state['values']['weight'],
  ))
    ->execute();
  drupal_set_message('Alink succesfuly added');
  $form_state['redirect'] = 'admin/structure/alinks/edit';
}

/**
 * Generate the form used to edit alinks
 */
function alinks_edit_form() {
  $form['alinks_edit_form'] = array(
    '#type' => 'fieldset',
    '#title' => t('Edit alinks'),
    '#description' => t('Use this form to edit alinks. If you want to delete an entry, just select the corresponding ' . 'checkbox. To edit the entry, edit the desired text. Click update to confirm any changes.'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $result = db_select('alinks', 'a')
    ->extend('PagerDefault')
    ->orderBy('alink_weight')
    ->orderBy('alink_text')
    ->limit('30')
    ->fields('a')
    ->execute();
  if ($result
    ->rowCount() > 0) {
    $form['alinks_edit_form']['edit_alink'] = array(
      '#tree' => TRUE,
    );
    foreach ($result as $alink) {
      $alinks[$alink->id] = $alink;
      $form['alinks_edit_form']['edit_alink'][$alink->id]['start_boundary_edit'] = array(
        '#type' => 'checkbox',
        '#default_value' => $alink->alink_start_boundary,
      );
      $form['alinks_edit_form']['edit_alink'][$alink->id]['word_edit'] = array(
        '#type' => 'textfield',
        '#size' => 10,
        '#maxlength' => 255,
        '#default_value' => $alink->alink_text,
        '#required' => TRUE,
      );
      $form['alinks_edit_form']['edit_alink'][$alink->id]['end_boundary_edit'] = array(
        '#type' => 'checkbox',
        '#default_value' => $alink->alink_end_boundary,
      );
      $form['alinks_edit_form']['edit_alink'][$alink->id]['case_insensitive_edit'] = array(
        '#type' => 'checkbox',
        '#default_value' => $alink->alink_case_insensitive,
      );
      $form['alinks_edit_form']['edit_alink'][$alink->id]['url_edit'] = array(
        '#type' => 'textfield',
        '#size' => 30,
        '#maxlength' => 255,
        '#default_value' => $alink->alink_url,
        '#required' => TRUE,
      );
      $form['alinks_edit_form']['edit_alink'][$alink->id]['url_title_edit'] = array(
        '#type' => 'textfield',
        '#size' => 30,
        '#maxlength' => 255,
        '#default_value' => $alink->url_title,
      );
      $form['alinks_edit_form']['edit_alink'][$alink->id]['external_edit'] = array(
        '#type' => 'checkbox',
        '#default_value' => $alink->alink_external,
      );
      $form['alinks_edit_form']['edit_alink'][$alink->id]['class_edit'] = array(
        '#type' => 'textfield',
        '#size' => 30,
        '#maxlength' => 255,
        '#default_value' => $alink->alink_class,
      );
      $form['alinks_edit_form']['edit_alink'][$alink->id]['weight_edit'] = array(
        '#type' => 'weight',
        '#default_value' => $alink->alink_weight,
      );
      $form['alinks_edit_form']['edit_alink'][$alink->id]['weight_edit']['#attributes']['class'] = array(
        'alinks-weight',
      );
      $form['alinks_edit_form']['edit_alink'][$alink->id]['delete'] = array(
        '#type' => 'checkbox',
      );
    }
    $form['pager'] = array(
      '#markup' => theme('pager'),
    );
    $form['alinks_edit_form']['save_edit'] = array(
      '#type' => 'submit',
      '#value' => t('Update alinks'),
    );
    $form['alinks_edit_form']['alinks'] = array(
      '#type' => 'value',
      '#value' => $alinks,
    );
    $form['alinks_edit_form']['#theme'] = 'alinks_list';
  }
  return $form;
}

/**
 * Theme function for the list of alinks
 */
function theme_alinks_list($form) {
  $header = array(
    t('Start'),
    t('String'),
    t('End'),
    t('Case'),
    t('URL'),
    t('URL title'),
    t('External'),
    t('Class'),
    t('Weight'),
    t('Delete'),
  );
  $table_drag_weight_cls = 'alinks-weight';
  $rows = array();

  // We need only first argument of array
  $form = array_shift($form);
  foreach ($form['alinks']['#value'] as $id => $alink) {
    $rows[] = array(
      'data' => array(
        drupal_render($form['edit_alink'][$alink->id]['start_boundary_edit']),
        drupal_render($form['edit_alink'][$alink->id]['word_edit']),
        drupal_render($form['edit_alink'][$alink->id]['end_boundary_edit']),
        drupal_render($form['edit_alink'][$alink->id]['case_insensitive_edit']),
        drupal_render($form['edit_alink'][$alink->id]['url_edit']),
        drupal_render($form['edit_alink'][$alink->id]['url_title_edit']),
        drupal_render($form['edit_alink'][$alink->id]['external_edit']),
        drupal_render($form['edit_alink'][$alink->id]['class_edit']),
        drupal_render($form['edit_alink'][$alink->id]['weight_edit']),
        drupal_render($form['edit_alink'][$alink->id]['delete']),
      ),
      'class' => array(
        'draggable',
      ),
    );
  }
  $output = theme('table', array(
    'header' => $header,
    'rows' => $rows,
    'attributes' => array(
      'id' => 'alinks-table',
    ),
  ));
  $output .= drupal_render_children($form);
  drupal_add_tabledrag('alinks-table', 'order', 'siblings', $table_drag_weight_cls);
  return $output;
}

/**
 * Process the edit alinks form
 */
function alinks_edit_form_submit($form, &$form_state) {
  foreach ($form_state['values']['edit_alink'] as $id => $alink) {
    if ($alink['delete']) {
      db_delete('alinks')
        ->condition('id', $id)
        ->execute();
    }
    else {
      db_update('alinks')
        ->fields(array(
        'alink_start_boundary' => $alink['start_boundary_edit'],
        'alink_text' => $alink['word_edit'],
        'alink_end_boundary' => $alink['end_boundary_edit'],
        'alink_case_insensitive' => $alink['case_insensitive_edit'],
        'alink_url' => $alink['url_edit'],
        'url_title' => $alink['url_title_edit'],
        'alink_external' => $alink['external_edit'],
        'alink_class' => $alink['class_edit'],
        'alink_weight' => $alink['weight_edit'],
      ))
        ->condition('id', $id, '=')
        ->execute();
    }
  }
  drupal_set_message('Alinks succesfuly updated');
}

Functions

Namesort descending Description
alinks_add_form Generate the form used to add alinks to drupal
alinks_add_form_submit Submit the form used to add alinks and insert the data in the db
alinks_admin_settings
alinks_edit_form Generate the form used to edit alinks
alinks_edit_form_submit Process the edit alinks form
alinks_get_strings Get the strings we have to replace from the database
alinks_make_links Transform the first instance of any word defined to links
alinks_menu Implementation of hook_menu().
alinks_node_view Implementation of hook_node_view().
alinks_page Generate the page that will render the forms for adding and editing Alinks
alinks_permission Implementation of hook_permission().
alinks_theme Theme function for the list of alinks
theme_alinks_list Theme function for the list of alinks