You are here

sharemessage.module in Share Message 7

Same filename and directory in other branches
  1. 8 sharemessage.module

New Sharing Module.

File

sharemessage.module
View source
<?php

/**
 * @file
 * New Sharing Module.
 */

/**
 * Implements hook_permission().
 */
function sharemessage_permission() {
  return array(
    'view sharemessage entities' => array(
      'title' => t('View ShareMessage entities.'),
    ),
    'administer sharemessage entities' => array(
      'title' => t('Administer ShareMessage entities.'),
    ),
  );
}

/**
 * Implements hook_entity_info().
 */
function sharemessage_entity_info() {
  $entities = array(
    'sharemessage' => array(
      'module' => 'sharemessage',
      'label' => t('ShareMessage'),
      'access callback' => 'sharemessage_access',
      'entity class' => 'ShareMessage',
      'controller class' => 'ShareMessageController',
      'metadata controller class' => 'ShareMessageMetadataController',
      'fieldable' => TRUE,
      'exportable' => TRUE,
      'base table' => 'sharemessage',
      'entity keys' => array(
        'id' => 'smid',
        'label' => 'label',
        'name' => 'name',
      ),
      'view modes' => array(
        'full' => array(
          'label' => t('Share links with OG tags and AddThis attributes'),
          'custom settings' => FALSE,
        ),
        'only_og_tags' => array(
          'label' => t('Only OG tags'),
          'custom settings' => FALSE,
        ),
        'no_attributes' => array(
          'label' => t('Share links with OG tags only'),
          'custom settings' => FALSE,
        ),
        'attributes_only' => array(
          'label' => t('Share links with AddThis attributes only'),
          'custom settings' => FALSE,
        ),
      ),
      'bundles' => array(
        'sharemessage' => array(
          'label' => t('Sharemessage'),
          'admin' => array(
            'path' => 'admin/config/services/sharemessage',
            'access arguments' => array(
              'administer sharemessage entities',
            ),
          ),
        ),
      ),
      'admin ui' => array(
        'controller class' => 'ShareMessageUIController',
        'path' => 'admin/config/services/sharemessage',
        'menu wildcard' => '%sharemessage',
      ),
      'translation' => array(
        'entity_translation' => array(
          'base path' => 'admin/config/services/sharemessage/manage/%sharemessage',
          'edit path' => 'admin/config/services/sharemessage/manage/%sharemessage',
          'path wildcard' => '%sharemessage',
        ),
      ),
      'field replacement' => array(
        'label' => array(
          'field' => array(
            'type' => 'text',
            'cardinality' => 1,
            'translatable' => TRUE,
          ),
          'instance' => array(
            'label' => t('Label'),
            'description' => '',
            'required' => TRUE,
            'settings' => array(
              'text_processing' => 0,
            ),
            'widget' => array(
              'weight' => -5,
            ),
            'display' => array(
              'default' => array(
                'type' => 'hidden',
              ),
            ),
          ),
        ),
      ),
    ),
  );
  return $entities;
}

/**
 * Implements hook_field_extra_fields().
 */
function sharemessage_field_extra_fields() {
  $extra['sharemessage']['sharemessage'] = array(
    'form' => array(
      'label' => array(
        'label' => t('Label'),
        'weight' => -5,
      ),
    ),
  );
  return $extra;
}

/**
 * Implements hook_menu().
 */
function sharemessage_menu() {
  $items = array();
  $items['admin/config/services/sharemessage/settings'] = array(
    'title' => 'Share message settings',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'sharemessage_addthis_settings',
    ),
    'access arguments' => array(
      'administer sharemessage entities',
    ),
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}

/**
 * Access callback for sharemessage.
 */
function sharemessage_access($op, $sharemessage, $account = NULL, $entity_type = NULL) {
  switch ($op) {
    case 'view':

      // Check whether there is actually an entity that gets rendered. The view
      // permission is also used on the entity admin ui. There, the ShareMessage
      // object is null and the access check falls back to the admin permission.
      if (!empty($sharemessage)) {
        return user_access('view sharemessage entities', $account);
      }
    default:
      return user_access('administer sharemessage entities', $account);
  }
}

/**
 * Implements hook_block_info().
 */
function sharemessage_block_info() {
  $sharemessages = entity_load('sharemessage', FALSE, array(
    'block' => 1,
  ));
  $blocks = array();
  if (!empty($sharemessages)) {
    foreach ($sharemessages as $sharemessage) {
      $blocks[$sharemessage->name] = array(
        'info' => $sharemessage->label,
        'cache' => DRUPAL_NO_CACHE,
      );
    }
  }
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function sharemessage_block_view($delta = '') {
  $sharemessage = entity_load_single('sharemessage', $delta);
  $block = array();
  if (!$sharemessage) {
    return $block;
  }
  $block['subject'] = $sharemessage->label;
  $block['content'] = sharemessage_view($sharemessage);
  return $block;
}

/**
 * Load a ShareMessage.
 */
function sharemessage_load($smid, $reset = FALSE) {
  $sharemessage = sharemessage_load_multiple(array(
    $smid,
  ), array(), $reset);
  return $sharemessage ? reset($sharemessage) : FALSE;
}

/**
 * Load multiple share messages based on certain conditions.
 */
function sharemessage_load_multiple($smids = array(), $conditions = array(), $reset = FALSE) {
  return entity_load('sharemessage', $smids, $conditions, $reset);
}

/**
 * Save share message.
 */
function sharemessage_save($sharemessage) {
  entity_save('sharemessage', $sharemessage);
}

/**
 * Delete single share message.
 */
function sharemessage_delete($sharemessage) {
  entity_delete('sharemessage', entity_id('sharemessage', $sharemessage));
}

/**
 * Delete multiple share messages.
 */
function sharemessage_delete_multiple($sharemessage_ids) {
  entity_delete_multiple('sharemessage', $sharemessage_ids);
}

/**
 * Share message form.
 */
function sharemessage_form($form, &$form_state, $sharemessage) {
  global $language;
  $form_state['sharemessage'] = $sharemessage;
  $smid = entity_id('sharemessage', $sharemessage);
  $form['label'] = array(
    '#type' => 'textfield',
    '#title' => t('Label'),
    '#required' => TRUE,
    '#default_value' => isset($sharemessage->label) ? $sharemessage->label : '',
    '#weight' => -3,
  );
  if (empty($smid)) {
    $form['name'] = array(
      '#type' => 'machine_name',
      '#title' => t('Machine Name'),
      '#machine_name' => array(
        'exists' => 'sharemessage_check_machine_name_if_exist',
        'source' => array(
          'label',
        ),
      ),
      '#required' => TRUE,
      '#weight' => -2,
    );
  }
  field_attach_form('sharemessage', $sharemessage, $form, $form_state, $language->language);

  // Settings fieldset.
  $form['override_default_settings'] = array(
    '#type' => 'checkbox',
    '#title' => t('Override default settings'),
    '#default_value' => isset($sharemessage->override_default_settings) ? $sharemessage->override_default_settings : FALSE,
    '#weight' => 101,
  );
  $form['settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('Customized settings'),
    '#tree' => TRUE,
    '#weight' => 102,
    '#states' => array(
      'invisible' => array(
        ':input[name="override_default_settings"]' => array(
          'checked' => FALSE,
        ),
      ),
    ),
  );
  if (module_exists('shariff')) {
    $form['settings']['type'] = [
      '#type' => 'radios',
      '#title' => t('Type'),
      '#options' => array(
        'addthis' => 'Addthis',
        'shariff' => 'Shariff',
      ),
      '#default_value' => isset($sharemessage->settings['type']) ? $sharemessage->settings['type'] : variable_get('sharemessage_default_type', 'addthis'),
    ];
  }
  $form['settings']['icon_style'] = array(
    '#type' => 'radios',
    '#title' => t('Icon style'),
    '#options' => sharemessage_get_sharewidget_options(),
    '#default_value' => isset($sharemessage->settings['icon_style']) ? $sharemessage->settings['icon_style'] : variable_get('sharemessage_default_icon_style', 'addthis_16x16_style'),
    '#description' => t('For the vertical floated items with counters, the only available services are Facebook Like, Google+ Share and Tweet. The addthis counter will also get added automatically when enabling additional services button.'),
  );
  $form['settings']['services'] = array(
    '#type' => 'select',
    '#title' => t('Visible services'),
    '#multiple' => TRUE,
    '#options' => sharemessage_get_addthis_services(),
    '#default_value' => !empty($sharemessage->settings['services']) ? $sharemessage->settings['services'] : variable_get('sharemessage_default_services', array()),
    '#size' => 10,
    '#states' => array(
      'invisible' => array(
        ':input[name="settings[icon_style]"]' => array(
          'value' => 'addthis_counter_style',
        ),
      ),
    ),
  );
  $form['settings']['additional_services'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show additional services button'),
    '#default_value' => isset($sharemessage->settings['additional_services']) ? $sharemessage->settings['additional_services'] : variable_get('sharemessage_default_additional_services', TRUE),
  );
  $form['settings']['counter'] = array(
    '#type' => 'select',
    '#title' => t('Show Addthis counter'),
    '#empty_option' => t('No'),
    '#options' => array(
      'addthis_pill_style' => t('Pill style'),
      'addthis_bubble_style' => t('Bubble style'),
    ),
    '#default_value' => isset($sharemessage->settings['counter']) ? $sharemessage->settings['counter'] : variable_get('sharemessage_default_counter', FALSE),
    '#states' => array(
      'invisible' => array(
        ':input[name="settings[icon_style]"]' => array(
          'value' => 'addthis_counter_style',
        ),
      ),
    ),
  );
  $form['block'] = array(
    '#type' => 'checkbox',
    '#title' => t('Provide a block'),
    '#default_value' => isset($sharemessage->block) ? $sharemessage->block : 0,
    '#weight' => 103,
  );
  if (variable_get('sharemessage_message_enforcement', TRUE)) {
    $form['enforce_usage'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enforce the usage of this share message on the page it points to'),
      '#description' => t('If checked, this sharemessage will be used on the page that it is referring to and override the sharemessage there.'),
      '#default_value' => isset($sharemessage->settings['enforce_usage']) ? $sharemessage->settings['enforce_usage'] : 0,
      '#weight' => 105,
    );
  }
  if (module_exists('token')) {
    $form['sharemessage_token_help'] = array(
      '#title' => t('Replacement patterns'),
      '#type' => 'fieldset',
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#description' => t('These tokens can be used in all text fields.'),
      '#weight' => 104,
    );
    $form['sharemessage_token_help']['browser'] = array(
      '#theme' => 'token_tree',
      '#token_types' => array(
        'node',
        'sharemessage',
      ),
      '#dialog' => TRUE,
    );
  }
  $submit = array();
  if (!empty($form['#submit'])) {
    $submit += $form['#submit'];
  }
  $form['actions'] = array(
    '#weight' => 106,
  );
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save share message'),
    '#submit' => $submit + array(
      'sharemessage_form_submit',
    ),
  );
  return $form;
}

/**
 * Returns whether a machine name already exists.
 */
function sharemessage_check_machine_name_if_exist($value) {
  return db_query_range('SELECT 1 FROM {sharemessage} WHERE name = :name', 0, 1, array(
    ':name' => $value,
  ))
    ->fetchField();
}

/**
 * Share message form submit.
 */
function sharemessage_form_submit($form, &$form_state) {
  if (!$form_state['values']['override_default_settings']) {
    $form_state['values']['settings'] = array();
  }
  else {

    // Set default settings for the addthis counter style.
    if ($form_state['values']['settings']['icon_style'] == 'addthis_counter_style') {
      $form_state['values']['settings']['services'] = array(
        'facebook_like' => 'facebook_like',
        'tweet' => 'tweet',
        'google_plusone' => 'google_plusone',
      );

      // Counter will be added anyway for this style.
      $form_state['values']['settings']['counter'] = FALSE;
    }
  }
  if (variable_get('sharemessage_message_enforcement', TRUE)) {
    $form_state['values']['settings']['enforce_usage'] = $form_state['values']['enforce_usage'];
    unset($form_state['values']['enforce_usage']);
  }
  $sharemessage = $form_state['sharemessage'];
  entity_form_submit_build_entity('sharemessage', $sharemessage, $form, $form_state);
  sharemessage_save($sharemessage);
  $info = entity_get_info('sharemessage');
  $form_state['redirect'] = $info['admin ui']['path'];
  drupal_set_message(t('Message %title saved.', array(
    '%title' => entity_label('sharemessage', $sharemessage),
  )));
}

/**
 * Entity view callback.
 */
function sharemessage_view(ShareMessage $sharemessage) {
  $view_mode = variable_get('sharemessage_view_default_view_mode', 'full');
  return entity_view($sharemessage
    ->entityType(), array(
    $sharemessage,
  ), $view_mode, NULL, TRUE);
}

/**
 * Implements hook_sytem_settings().
 */
function sharemessage_addthis_settings($form, $form_state) {
  if (module_exists('shariff')) {
    $form['sharemessage_default_type'] = [
      '#type' => 'radios',
      '#title' => t('Type'),
      '#options' => array(
        'addthis' => 'Addthis',
        'shariff' => 'Shariff',
      ),
      '#default_value' => variable_get('sharemessage_default_type', 'addthis'),
      '#description' => t('The settings below are only for Addthis sharing, the shariff settings are on the <a href="@shariff_settings_url">shariff settings page</a>.', array(
        '@shariff_settings_url' => url('admin/config/services/shariff'),
      )),
    ];
  }
  $form['sharemessage_addthis_profile_id'] = array(
    '#title' => t('AddThis Profile ID'),
    '#type' => 'textfield',
    '#default_value' => variable_get('sharemessage_addthis_profile_id', ''),
  );
  $form['sharemessage_default_services'] = array(
    '#title' => t('Default visible services'),
    '#type' => 'select',
    '#multiple' => TRUE,
    '#options' => sharemessage_get_addthis_services(),
    '#default_value' => variable_get('sharemessage_default_services', array()),
    '#size' => 10,
  );
  $form['sharemessage_default_additional_services'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show additional services button'),
    '#default_value' => variable_get('sharemessage_default_additional_services', TRUE),
  );
  $form['sharemessage_default_counter'] = array(
    '#type' => 'select',
    '#title' => t('Show Addthis counter'),
    '#empty_option' => t('No'),
    '#options' => array(
      'addthis_pill_style' => t('Pill style'),
      'addthis_bubble_style' => t('Bubble style'),
    ),
    '#default_value' => variable_get('sharemessage_default_counter', FALSE),
  );
  $form['sharemessage_default_icon_style'] = array(
    '#title' => t('Default icon style'),
    '#type' => 'radios',
    '#options' => sharemessage_get_sharewidget_options(),
    '#default_value' => variable_get('sharemessage_default_icon_style', 'addthis_16x16_style'),
  );
  $form['sharemessage_message_enforcement'] = array(
    '#type' => 'checkbox',
    '#title' => t('Allow to enforce share messages'),
    '#description' => t('This will enforce loading of a sharemessage if the ?smid argument is present in an URL. If something else on your site is using this argument, disable this this option.'),
    '#default_value' => variable_get('sharemessage_message_enforcement', TRUE),
  );
  $form['sharemessage_local_services_definition'] = array(
    '#type' => 'checkbox',
    '#title' => t('Use local service definitions file'),
    '#description' => t('Check this if you are behind a firewall and the module cannot access the services definition at http://cache.addthiscdn.com/services/v1/sharing.en.json.'),
    '#default_value' => variable_get('sharemessage_local_services_definition', FALSE),
  );
  $form['sharemessage_shared_video_width'] = array(
    '#title' => t('Video width'),
    '#description' => t('The width of the player when sharing a video.'),
    '#type' => 'textfield',
    '#default_value' => variable_get('sharemessage_shared_video_width', 360),
  );
  $form['sharemessage_shared_video_height'] = array(
    '#title' => t('Video height'),
    '#description' => t('The height of the player when sharing a video.'),
    '#type' => 'textfield',
    '#default_value' => variable_get('sharemessage_shared_video_height', 270),
  );
  $form['sharemessage_add_twitter_card'] = array(
    '#type' => 'checkbox',
    '#title' => t("Add meta tags for twitter's summary card with large image"),
    '#description' => t('Enables sharing of images on twitter, check <a href="@url">this</a> for more information.', array(
      '@url' => 'https://dev.twitter.com/cards/types/summary-large-image',
    )),
    '#default_value' => variable_get('sharemessage_add_twitter_card', FALSE),
    '#element_validate' => array(
      'sharemessage_validate_twitter_card_requirements',
    ),
  );
  $form['sharemessage_twitter_user'] = array(
    '#title' => t('Twitter account username'),
    '#description' => t('This is required when enabling the meta tags for twitter cards above.'),
    '#type' => 'textfield',
    '#default_value' => variable_get('sharemessage_twitter_user', ''),
    '#states' => array(
      'visible' => array(
        ':input[name="sharemessage_add_twitter_card"]' => array(
          'checked' => TRUE,
        ),
      ),
    ),
  );
  return system_settings_form($form);
}

/**
 * Validate handler to ensure twitter user is available when cards are enabled.
 */
function sharemessage_validate_twitter_card_requirements($element, &$form_state) {
  if (!empty($form_state['values']['sharemessage_add_twitter_card']) && empty($form_state['values']['sharemessage_twitter_user'])) {
    form_error($element, t('Please enter your twitter account username in order to activate meta tags for twitter cards.'));
  }
}

/**
 * Load AddThis services.
 */
function sharemessage_get_addthis_services() {
  global $language;
  $options =& drupal_static(__FUNCTION__);
  if (!isset($options)) {
    if ($cache = cache_get('sharemessage_addthis_services:' . $language->language)) {
      $options = $cache->data;
    }
    else {
      $json = sharemessage_get_services_json();
      $output = json_decode($json);
      if (!empty($output)) {
        $options = array(
          t('Common') => array(),
          t('Mail') => array(),
          t('Other') => array(),
        );
        foreach ($output->data as $service) {
          if (in_array($service->code, array(
            'facebook',
            'facebook_like',
            'twitter',
            'xing',
            'linkedin',
            'wordpress',
            'google_plusone_share',
          ))) {
            $options[t('Common')][$service->code] = $service->name;
          }
          elseif (in_array($service->code, array(
            'mail',
            'gmail',
            'yahoomail',
            'aolmail',
            'email',
            'mailto',
          ))) {
            $options[t('Mail')][$service->code] = $service->name;
          }
          else {
            $options[t('Other')][$service->code] = $service->name;
          }
        }

        // Tweet is not defined?
        $options[t('Common')]['tweet'] = t('Tweet');

        // Neither is Pinterest Follow.
        $options[t('Common')]['pinterest_follow'] = t('Pinterest follow');
        cache_set('sharemessage_addthis_services:' . $language->language, $options);
      }
      else {
        cache_clear_all('sharemessage_addthis_services:' . $language->language, 'cache', TRUE);
      }
    }
  }
  return $options;
}

/**
 * Implements hook_init().
 */
function sharemessage_init() {
  if (!empty($_GET['smid']) && variable_get('sharemessage_message_enforcement', TRUE)) {
    $sharemessage = entity_load_single('sharemessage', $_GET['smid']);
    if (!empty($sharemessage)) {
      entity_view('sharemessage', array(
        $sharemessage
          ->identifier() => $sharemessage,
      ), 'only_og_tags');
    }
  }
}

/**
 * Getter for the services definitions.
 *
 * If option is set the local file within the module folder will be read instead
 * of the file that is hosted on the addthis cdn.
 *
 * @return string
 *   The path to the services definition file.
 */
function sharemessage_get_services_json() {
  if (variable_get('sharemessage_local_services_definition', FALSE)) {
    $file_uri = drupal_get_path('module', 'sharemessage') . '/addthis/sharing.en.json';
  }
  else {
    $file_uri = 'http://cache.addthiscdn.com/services/v1/sharing.en.json';
  }
  return file_get_contents($file_uri);
}

/**
 * Getter for the widget format options.
 *
 * @return array
 *   The available styles indexed by html class used by addthis.
 *
 * @todo add all available styles here.
 */
function sharemessage_get_sharewidget_options() {
  return array(
    'addthis_16x16_style' => '16x16 pix',
    'addthis_32x32_style' => '32x32 pix',
    'addthis_counter_style' => 'Vertical floated with counters',
  );
}

/**
 * Implements hook__variable_group_info().
 */
function sharemessage_variable_group_info() {
  $groups['sharemessage'] = array(
    'title' => t('Share message'),
    'description' => t('Variables related to Share message'),
    'access' => 'administer sharemessage entities',
  );
  return $groups;
}

/**
 * Implements hook_variable_info().
 */
function sharemessage_variable_info($options) {

  // Variables used in output within the kampa_theme.
  $variables['sharemessage_twitter_user'] = [
    'localize' => TRUE,
    'title' => t('Twitter user', [], $options),
    'group' => 'sharemessage',
  ];
  return $variables;
}

Functions

Namesort descending Description
sharemessage_access Access callback for sharemessage.
sharemessage_addthis_settings Implements hook_sytem_settings().
sharemessage_block_info Implements hook_block_info().
sharemessage_block_view Implements hook_block_view().
sharemessage_check_machine_name_if_exist Returns whether a machine name already exists.
sharemessage_delete Delete single share message.
sharemessage_delete_multiple Delete multiple share messages.
sharemessage_entity_info Implements hook_entity_info().
sharemessage_field_extra_fields Implements hook_field_extra_fields().
sharemessage_form Share message form.
sharemessage_form_submit Share message form submit.
sharemessage_get_addthis_services Load AddThis services.
sharemessage_get_services_json Getter for the services definitions.
sharemessage_get_sharewidget_options Getter for the widget format options.
sharemessage_init Implements hook_init().
sharemessage_load Load a ShareMessage.
sharemessage_load_multiple Load multiple share messages based on certain conditions.
sharemessage_menu Implements hook_menu().
sharemessage_permission Implements hook_permission().
sharemessage_save Save share message.
sharemessage_validate_twitter_card_requirements Validate handler to ensure twitter user is available when cards are enabled.
sharemessage_variable_group_info Implements hook__variable_group_info().
sharemessage_variable_info Implements hook_variable_info().
sharemessage_view Entity view callback.