You are here

shariff.module in Shariff Social Media Buttons 7

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

Integrating Shariff library, providing settings form and block.

File

shariff.module
View source
<?php

/**
 * @file
 * Integrating Shariff library, providing settings form and block.
 */

/**
 * Implements hook_help().
 */
function shariff_help($path, $arg) {

  // Generate help text for the settings form.
  if ($path == 'admin/config/services/shariff') {
    $output = '';
    $output .= '<h3>' . t('About') . '</h3>';
    $output .= '<p>' . t('The Shariff social media buttons library by heise online enables website users to share their favorite content without compromising their privacy. For more information see <a href="@url">@url</a>.', array(
      '@url' => 'https://github.com/heiseonline/shariff',
    )) . '</p>';
    return $output;
  }
}

/**
 * Implements hook_libraries().
 */
function shariff_libraries_info() {
  $library_path = libraries_get_path('shariff', FALSE);
  if (empty($library_path)) {
    drupal_set_message(t('Please download at least v1.4.6 of the !link library and place it in libraries under /shariff.
      So that the js file is available under .../libraries/shariff/build/shariff.min.js.', array(
      '!link' => l(t('Shariff'), 'https://github.com/heiseonline/shariff/releases/latest'),
    )), 'warning');
  }
  $libraries['shariff'] = array(
    'name' => 'Shariff Sharing',
    'vendor url' => 'https://github.com/heiseonline/shariff',
    'download url' => 'https://github.com/heiseonline/shariff/releases/latest',
    'version arguments' => array(
      'file' => 'build/shariff.min.js',
      'pattern' => '@shariff - v([0-9\\.a-z]+)@',
      'lines' => 4,
    ),
    'variants' => array(
      'naked' => array(
        'files' => array(
          'js' => array(
            'build/shariff.min.js' => array(
              'scope' => 'footer',
              'weight' => '1',
            ),
          ),
        ),
      ),
      'min' => array(
        'files' => array(
          'js' => array(
            'build/shariff.min.js' => array(
              'scope' => 'footer',
              'weight' => '1',
            ),
          ),
          'css' => array(
            'build/shariff.min.css',
          ),
        ),
      ),
      'complete' => array(
        'files' => array(
          'js' => array(
            'build/shariff.min.js' => array(
              'scope' => 'footer',
              'weight' => '1',
            ),
          ),
          'css' => array(
            'build/shariff.complete.css',
          ),
        ),
      ),
    ),
  );
  return $libraries;
}

/**
 * Implements hook_ctools_plugin_directory().
 */
function shariff_ctools_plugin_directory($module, $plugin) {
  if ($module == 'page_manager' || $module == 'ctools' || $module == 'panels' && $plugin == 'layouts') {
    return 'plugins/' . $plugin;
  }
}

/**
 * Implements hook_menu().
 */
function shariff_menu() {
  $items['admin/config/services/shariff'] = array(
    'title' => 'Shariff sharing buttons',
    'description' => 'Configure Shariff sharing button default settings.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'shariff_settings_form',
    ),
    'access arguments' => array(
      'administer site configuration',
    ),
  );
  return $items;
}

/**
 * Admin settings menu callback.
 *
 * @see shariff_menu()
 * @see shariff_settings_validate()
 * @see shariff_settings_submit()
 *
 * @ingroup forms
 */
function shariff_settings_form() {
  $settings = _shariff_get_settings();
  $form['shariff_services'] = array(
    '#title' => t('Activated services'),
    '#description' => t('Please define for which services a sharing button should be included.'),
    '#type' => 'checkboxes',
    '#options' => array(
      'twitter' => t('Twitter'),
      'facebook' => t('Facebook'),
      'googleplus' => t('Google+'),
      'linkedin' => t('LinkedIn'),
      'pinterest' => t('Pinterest'),
      'xing' => t('Xing'),
      'whatsapp' => t('WhatsApp'),
      'addthis' => t('AddThis'),
      'tumblr' => t('Tumblr'),
      'flattr' => t('Flattr'),
      'diaspora' => t('Diaspora'),
      'reddit' => t('reddit'),
      'stumbleupon' => t('StumbleUpon'),
      'threema' => t('Threema'),
      'mail' => t('E-Mail'),
      'weibo' => t('Weibo'),
      'tencent-weibo' => t('Tencent-Weibo'),
      'qzone' => t('Qzone'),
      'info' => t('Info Button'),
    ),
    '#default_value' => $settings['services'],
  );
  $form['shariff_theme'] = array(
    '#title' => t('Theme'),
    '#description' => t('Please choose a layout option.'),
    '#type' => 'radios',
    '#options' => array(
      'colored' => t('Colored'),
      'grey' => t('Grey'),
      'white' => t('White'),
    ),
    '#default_value' => $settings['shariff_theme'],
  );
  $form['shariff_css'] = array(
    '#title' => t('CSS'),
    '#description' => t('Please choose a CSS variant. !FontAwesome is used to display the services icons.', array(
      '!FontAwesome' => l(t('Font Awesome'), 'http://fortawesome.github.io/Font-Awesome/', array(
        'attributes' => array(
          'target' => '_blank',
        ),
      )),
    )),
    '#type' => 'radios',
    '#options' => array(
      'complete' => t('Complete (Contains also Font Awesome)'),
      'min' => t('Minimal (If Font Awesome is already included in your site)'),
      'naked' => t('None (Without any CSS)'),
    ),
    '#default_value' => variable_get('shariff_css', 'complete'),
  );
  $form['shariff_orientation'] = array(
    '#title' => t('Orientation'),
    '#description' => t('Vertical will stack the buttons vertically. Default is horizontally.'),
    '#type' => 'radios',
    '#options' => array(
      'vertical' => t('Vertical'),
      'horizontal' => t('Horizontal'),
    ),
    '#default_value' => $settings['orientation'],
  );
  $form['shariff_twitter_via'] = array(
    '#title' => t('Twitter Via User'),
    '#description' => t('Screen name of the Twitter user to attribute the Tweets to.'),
    '#type' => 'textfield',
    '#default_value' => $settings['twitter_via'],
  );
  $form['shariff_mail_url'] = array(
    '#title' => t('Mail link'),
    '#description' => t('The url target used for the mail service button. Leave it as "mailto:" to let the user
 choose an email address.'),
    '#type' => 'textfield',
    '#default_value' => $settings['mail_url'] ? $settings['mail_url'] : 'mailto:',
  );
  $form['shariff_mail_subject'] = array(
    '#title' => t('Mail subject'),
    '#description' => t("If a mailto: link is provided in Mail link above, then this value is used as the mail subject.\n Left empty the page's current (canonical) URL or og:url is used."),
    '#type' => 'textfield',
    '#default_value' => $settings['mail_subject'],
  );
  $form['shariff_mail_body'] = array(
    '#title' => t('Mail body'),
    '#description' => t("If a mailto: link is provided in Mail link above, then this value is used as the mail body.\n Left empty the page title is used."),
    '#type' => 'textarea',
    '#default_value' => $settings['mail_body'],
  );
  $form['shariff_referrer_track'] = array(
    '#title' => t('Referrer track code'),
    '#description' => t('A string that will be appended to the share url. Disabled when empty.'),
    '#type' => 'textfield',
    '#default_value' => $settings['referrer_track'],
  );
  $form['shariff_backend_url'] = array(
    '#title' => t('Backend URL'),
    '#description' => t('The path to your Shariff backend. Leaving the value blank disables the backend feature and no counts will occur.'),
    '#type' => 'textfield',
    '#default_value' => $settings['backend_url'],
  );
  $form['shariff_flattr_category'] = array(
    '#title' => t('Flattr category'),
    '#description' => t('Category to be used for Flattr.'),
    '#type' => 'textfield',
    '#default_value' => $settings['flattr_category'],
  );
  $form['shariff_flattr_user'] = array(
    '#title' => t('Flattr user'),
    '#description' => t('User that receives Flattr donation.'),
    '#type' => 'textfield',
    '#default_value' => $settings['flattr_user'],
  );
  $form['shariff_media_url'] = array(
    '#title' => t('Media url'),
    '#description' => t('Media url to be shared (Pinterest).'),
    '#type' => 'textfield',
    '#default_value' => $settings['media_url'],
  );
  $form['#validate'] = array(
    'shariff_settings_validate',
  );
  $form['#submit'] = array(
    'shariff_settings_submit',
  );
  return system_settings_form($form);
}

/**
 * Form validation handler for shariff_settings_form().
 *
 * @see shariff_settings_form()
 */
function shariff_settings_validate($form_id, &$form_state) {
  $backend_url = $form_state['values']['shariff_backend_url'];
  if ($backend_url && !valid_url($backend_url, TRUE)) {
    form_set_error('shariff_backend_url', t('Please enter a valid URL.'));
  }
}

/**
 * Form submit handler for shariff_settings_form().
 *
 * @see shariff_settings_form()
 */
function shariff_settings_submit($form, &$form_state) {

  // Clear the cache so an anonymous user sees all buttons updated.
  cache_clear_all();
  drupal_set_message(t('The cache has been cleared.'));
}

/**
 * Implements hook_block_info().
 */
function shariff_block_info() {
  $blocks['shariff_block'] = array(
    'info' => t('Shariff sharing buttons'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function shariff_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'shariff_block':
      $settings = _shariff_get_settings();
      if (!empty($settings['services'])) {
        $block['content'] = theme('shariff', $settings);
      }
      break;
  }
  return $block;
}

/**
 * Implements hook_theme().
 */
function shariff_theme() {
  return array(
    'shariff' => array(
      'variables' => array(
        'services' => NULL,
        'shariff_theme' => NULL,
        'orientation' => NULL,
        'twitter_via' => NULL,
        'referrer_track' => NULL,
        'mail_url' => NULL,
        'mail_subject' => NULL,
        'mail_body' => NULL,
        'backend_url' => NULL,
        'flattr_category' => NULL,
        'flattr_user' => NULL,
        'media_url' => NULL,
        'lang' => NULL,
        'url' => NULL,
      ),
    ),
  );
}

/**
 * Implements hook_preprocess().
 */
function shariff_preprocess_shariff(&$variables, $hook) {

  // Set class.
  $variables['classes'] = 'shariff';
  $data_settings = array(
    'services',
    'shariff_theme',
    'orientation',
    'twitter_via',
    'referrer_track',
    'mail_url',
    'mail_subject',
    'mail_body',
    'backend_url',
    'flattr_category',
    'flattr_user',
    'media_url',
    'lang',
    'url',
    'title',
  );

  // Build data html.
  $data = array();
  foreach ($data_settings as $setting) {
    if (!empty($variables[$setting])) {
      switch ($setting) {
        case 'services':
          $value = '["' . implode('","', $variables[$setting]) . '"]';
          break;
        case 'referrer_track':
          $value = urlencode(check_plain($variables[$setting]));
          break;
        case 'backend_url':
        case 'url':
        case 'mail_url':
        case 'media_url':
          $value = check_url($variables[$setting]);
          break;
        case 'twitter_via':
        case 'mail_subject':
        case 'mail_body':
        case 'flattr_user':
        case 'flattr_category':
        case 'title':
        default:
          $value = check_plain($variables[$setting]);
          break;
        case 'shariff_theme':
          $value = $variables[$setting];
          $setting = 'theme';
          break;
        case 'lang':
          $value = $variables[$setting];
          break;
      }

      // Shariff requires data-attributes with dashes instead of underscores.
      $data['data-' . str_replace('_', '-', $setting)] = $value;
    }
  }
  $variables['data_html'] = drupal_attributes($data);

  // Load shariff library.
  $variant = variable_get('shariff_css', 'complete');
  libraries_load('shariff', $variant);
}

/**
 * Returns html for default the sharing buttons.
 *
 * @param array $variables
 *   Array of variables to be used in the markup.
 *
 * @return string
 *   HTML to be displayed.
 */
function theme_shariff(array $variables) {
  $output = '<div class="' . $variables['classes'] . '" ' . $variables['data_html'] . '>';
  $output .= '</div>';
  return $output;
}

/**
 * Implements hook_field_info().
 */
function shariff_field_info() {
  return array(
    'shariff' => array(
      'label' => t('Shariff sharing buttons'),
      'description' => t('This field displays the Shariff sharing buttons for the activated services.'),
      'default_widget' => 'shariff_widget',
      'default_formatter' => 'shariff_formatter',
    ),
  );
}

/**
 * Implements hook_field_is_empty().
 */
function shariff_field_is_empty($item, $field) {
  return FALSE;
}

/**
 * Implements hook_field_formatter_info().
 */
function shariff_field_formatter_info() {
  return array(
    'shariff_formatter' => array(
      'label' => t('Shariff formatter'),
      'field types' => array(
        'shariff',
      ),
      'settings' => array(
        'hide_by_default' => NULL,
      ),
    ),
  );
}

/**
 * Implements hook_field_formatter_settings_form().
 */
function shariff_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $element = array();
  $element['hide_by_default'] = array(
    '#type' => 'checkbox',
    '#title' => t('Hide buttons by default for existing entities'),
    '#description' => t('Check this if you want to hide the share buttons on entities created previous to installing/enabling Shariff.
 If unchecked the share buttons will appear on all previously existing entities.'),
    '#default_value' => $settings['hide_by_default'],
  );
  return $element;
}

/**
 * Implements hook_field_formatter_settings_summary().
 */
function shariff_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $settings['hide_by_default'] ? $display = t('Yes') : ($display = t('No'));
  $summary = t('Hide buttons by default for existing entities: @hide_by_default', array(
    '@hide_by_default' => $display,
  ));
  return $summary;
}

/**
 * Implements hook_field_prepare_view().
 *
 * Adds a dummy value to the field to make rendering possible if the field is empty.
 */
function shariff_field_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items) {
  if ($field['type'] == 'shariff') {
    foreach ($items as $key => $item) {
      if (!isset($item[0]['value'])) {
        $items[$key][0]['value'] = NUll;
      }
    }
  }
}

/**
 * Implements hook_field_formatter_view().
 */
function shariff_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  switch ($display['type']) {
    case 'shariff_formatter':
      $settings = _shariff_get_settings();
      if (!empty($settings['services'])) {
        foreach ($items as $delta => $item) {

          // Only display buttons if the field has the right value or it should be displayed by default.
          if ($item['value'] === NULL && !$display['settings']['hide_by_default'] || $item['value'] == '1') {
            $uri = entity_uri($entity_type, $entity);
            $uri['options'] += array(
              'absolute' => TRUE,
            );
            $settings['url'] = url($uri['path'], $uri['options']);

            // Prepare settings variables to be used in the render array.
            $render_vars = array();
            foreach ($settings as $key => $setting) {
              $render_vars['#' . $key] = $setting;
            }
            $element[$delta]['#theme'] = 'shariff';
            $element[$delta] += $render_vars;
          }
        }
      }
      break;
    default:
      break;
  }
  return $element;
}

/**
 * Implements hook_field_widget_info().
 */
function shariff_field_widget_info() {
  return array(
    'shariff_widget' => array(
      'label' => t('Shariff Widget'),
      'field types' => array(
        'shariff',
      ),
    ),
  );
}

/**
 * Implements hook_field_widget_form().
 */
function shariff_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $value = isset($items[$delta]['value']) ? $items[$delta]['value'] : 1;
  $widget = $element;
  $widget['#delta'] = $delta;
  unset($widget['#title']);
  $widget += array(
    '#type' => 'checkbox',
    '#title' => t('Display Shariff sharing buttons'),
    '#default_value' => $value,
  );
  $element['value'] = $widget;
  return $element;
}

/**
 * Helper function to get the module settings.
 */
function _shariff_get_settings() {
  global $language;
  $lang = $language->language;
  $supported_languages = _shariff_supported_languages();
  $services = variable_get('shariff_services', array(
    'twitter' => 'twitter',
    'facebook' => 'facebook',
  ));
  foreach ($services as $key => $service) {
    if (!$service) {
      unset($services[$key]);
    }
  }
  $settings = array(
    'services' => $services,
    'shariff_theme' => variable_get('shariff_theme', 'colored'),
    'orientation' => variable_get('shariff_orientation', 'horizontal'),
    'twitter_via' => variable_get('shariff_twitter_via', NULL),
    'mail_url' => variable_get('shariff_mail_url', NULL),
    'mail_subject' => variable_get('shariff_mail_subject', NULL),
    'mail_body' => variable_get('shariff_mail_body', NULL),
    'referrer_track' => variable_get('shariff_referrer_track', NULL),
    'backend_url' => variable_get('shariff_backend_url', NULL),
    'flattr_category' => variable_get('shariff_flattr_category', NULL),
    'flattr_user' => variable_get('shariff_flattr_user', NULL),
    'media_url' => variable_get('shariff_media_url', NULL),
    'lang' => in_array($lang, $supported_languages) ? $lang : 'en',
  );
  return $settings;
}

/**
 * Helper function to list the supported languages.
 */
function _shariff_supported_languages() {
  return array(
    'bg',
    'de',
    'en',
    'es',
    'fi',
    'hr',
    'hu',
    'ja',
    'ko',
    'no',
    'pl',
    'pt',
    'ro',
    'ru',
    'sk',
    'sl',
    'sr',
    'sv',
    'tr',
    'zh',
  );
}