<?php

/**
 * @file
 * A social share (facebook, twitter, google+) privacy (two clicks) plugin for jQuery 1.3
 */

/**
 * The default path to the socialSharePrivacy directory.
 */
define('SOCIALSHAREPRIVACY_PATH', 'sites/all/libraries/socialshareprivacy');
define('SOCIALSHAREPRIVACY_FIELD_TYPE', variable_get('socialshareprivacy_field_type'));
define('SOCIALSHAREPRIVACY_FORMATTER', variable_get('socialshareprivacy_formatter'));
define('SOCIALSHAREPRIVACY_WIDGET', variable_get('socialshareprivacy_widget'));
define('SOCIALSHAREPRIVACY_DEFAULT_VALUE_SERVICES', serialize(array('facebook' => 'facebook', 'twitter' => 'twitter', 'gplus' => 'gplus')));

/**
 * Implements hook_help().
 */
function socialshareprivacy_help($path, $arg) {
  switch ($path) {
    case 'admin/config/user-interface/socialshareprivacy':
    case 'admin/help#socialshareprivacy':
      return '<p>' . t('Adds social network buttons to content types and provides a <a href="@urlBlock">block</a> with the 2-click-method “<a href="@urlHeise" target="_blank">socialSharePrivacy</a>“ by Heise Zeitschriften Verlag. So the networks won\'t receive data unless the visitor wants to.', array('@urlBlock' => url('admin/structure/block/manage/socialshareprivacy/socialshareprivacy_block/configure'), '@urlHeise' => 'http://www.heise.de/extras/socialshareprivacy/')) . '</p>';
  }
}


/**
 * Implements hook_permission().
 */
function socialshareprivacy_permission() {
  return array(
    'administer socialshareprivacy' => array(
      'title' => t('administer socialSharePrivacy'),
    ),
    'access socialshareprivacy' => array(
      'title' => t('access socialSharePrivacy'),
    ),
  );
}

/**
 * Implements hook_menu().
 */
function socialshareprivacy_menu() {
    $items = array();

    $items['admin/config/user-interface/socialshareprivacy'] = array(
        'title' => 'socialSharePrivacy',
        'description' => 'Configure settings for socialSharePrivacy',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('socialshareprivacy_admin_settings'),
        'access arguments' => array('administer socialshareprivacy'),
        'weight' => -20,
        'file' => 'socialshareprivacy.admin.inc',
    );
    $items['admin/config/user-interface/socialshareprivacy/settings'] = array(
        'title' => 'Settings',
        'description' => 'Configure settings for socialSharePrivacy',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('socialshareprivacy_admin_settings'),
        'access arguments' => array('administer socialshareprivacy'),
        'weight' => -20,
        'type' => MENU_DEFAULT_LOCAL_TASK,
        'file' => 'socialshareprivacy.admin.inc',
    );
    $items['admin/config/user-interface/socialshareprivacy/fieldmgmt'] = array(
        'title' => 'Field Management',
        'description' => 'Add socialSharePrivacy fields to your contenttypes',
        'page callback' => 'socialshareprivacy_admin_fieldmgmt',
        'access arguments' => array('administer socialshareprivacy'),
        'weight' => -19,
        'type' => MENU_LOCAL_TASK,
        'file' => 'socialshareprivacy.admin.inc',
    );
    $items['admin/config/user-interface/socialshareprivacy/bulkupdate'] = array(
        'title' => 'Bulk Update',
        'description' => 'Update existing nodes',
        'page callback' => 'socialshareprivacy_admin_bulkupdate',
        'access arguments' => array('administer socialshareprivacy'),
        'weight' => -18,
        'type' => MENU_LOCAL_TASK,
        'file' => 'socialshareprivacy.admin.inc',
    );

    return $items;
}

/**
 * Implement hook_field_info().
 */
function socialshareprivacy_field_info() {
  return array(
    SOCIALSHAREPRIVACY_FIELD_TYPE => array(
      'label' => t('Placeholder for socialSharePrivacy'),
      'description' => t('Move this field to the position you want the socialSharePrivacy to be displayed in.'),
      'default_widget' => SOCIALSHAREPRIVACY_WIDGET,
      'default_formatter' => SOCIALSHAREPRIVACY_FORMATTER,
    ),
  );
}

/**
 * Implement hook_field_widget_info().
 */
function socialshareprivacy_field_widget_info() {
  return array(
    SOCIALSHAREPRIVACY_WIDGET => array(
      'label' => t('SSP Widget'),
      'field types' => array(SOCIALSHAREPRIVACY_FIELD_TYPE),
    ),
  );
}

/**
 * Implement hook_field_widget().
 *
 */
function socialshareprivacy_field_widget_form(&$form, &$form_state, $field,
  $instance, $langcode, $items, $delta = 0) {

  $element = array(
    '#type' => 'checkbox',
    '#prefix' => '<br/><strong>socialSharePrivacy</strong>',
    /* '#description' => t('Placeholder for socialSharePrivacy'), */
    '#title' => t('Display socialSharePrivacy'),
    '#description' => t('If this box is checked then socialSharePrivacy will be displayed on the view of this node.'),
    '#default_value' => (isset($items[0]) && isset($items[0]['value'])) ? $items[0]['value'] : 1,
    '#suffix' => '<br/>',
  );

  return $element;
}

/**
 * Implements hook_field_formatter_info().
 */
function socialshareprivacy_field_formatter_info() {
  return array(
    SOCIALSHAREPRIVACY_FORMATTER => array(
      'label' => t('SSP Formatter'),
      'field types' => array(SOCIALSHAREPRIVACY_FIELD_TYPE),
      'module' => 'socialshareprivacy',
    ),
  );
}

/**
 * Implement hoo_field_is_empty().
 */
function socialshareprivacy_field_is_empty($item, $field) {
  return FALSE;
}

function socialshareprivacy_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  if ($field['type'] == SOCIALSHAREPRIVACY_FIELD_TYPE) {
    foreach ($items as $delta => $item) {
      if (!is_array($item)) {
        $items[$delta] = array('value' => $item);
      }
    }
  }
}

/**
 * Implements hook_field_formatter_view().
 */
function socialshareprivacy_field_formatter_view($object_type, $object, $field, $instance, $langcode, $items, $display) {

  if (!_socialshareprivacy_has_access()) {
    return NULL;
  }

  $element = array();
  if ($field['type']==SOCIALSHAREPRIVACY_FIELD_TYPE) {
    switch ($display['type']) {
      case SOCIALSHAREPRIVACY_FORMATTER:
        foreach ($items as $delta => $item) {
          if ($item['value'] == "1") {
            $element[$delta]['#type'] = 'markup';

            $htmlNodeId = $field['field_name'] . '-' . $object->nid;
            $javascript = _socialshareprivacy_write_javascript($htmlNodeId, url('node/' . $object->nid, array('absolute' => TRUE)));
            $markup = _socialshareprivacy_get_markup($htmlNodeId);
            if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && drupal_strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
              $markup =  $markup . '<script type="text/javascript">' . $javascript . '</script>';
            }

            $element[$delta]['#markup'] = $markup;
          }
        }
        break;
    }
  }

  return $element;
}

/**
 * Implements hook_block_info().
 */
function socialshareprivacy_block_info() {
  $blocks['socialshareprivacy_block'] = array(
    // info: The name of the block.
    'info' => t('socialSharePrivacy'),
    // Block caching options (per role, per user, etc.)
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

/**
 * Implements hook_block_configure().
 */
function socialshareprivacy_block_configure($block_name = '') {
  if ($block_name == 'socialshareprivacy_block') {
    $form['help'] = array(
      '#markup' => t('Additional options can be set on the <a href="/admin/config/user-interface/socialshareprivacy">socialSharePrivacy configuration page</a>.'),
    );

    return $form;
  }
}

/**
 * Implements hook_block_view().
 */
function socialshareprivacy_block_view($delta = 0) {

  if (!_socialshareprivacy_has_access()) {
    return NULL;
  }

  return _socialshareprivacy_block($op='view');
}

/**
 * Gets the block.
 */
function _socialshareprivacy_block($op = 'list', $delta = 0, $edit = array()) {
  $block = array();

  if ($op == 'view') {
    $block['subject'] = t('socialSharePrivacy');
    $block['content'] = _socialshareprivacy_get_markup('socialshareprivacy-block');

    _socialshareprivacy_write_javascript('socialshareprivacy-block');
  }

  return $block;
}

/**
 * Return the path to the socialSharePrivacy plugin.
 */
function _socialshareprivacy_get_path() {
  static $library_path = NULL;

  // Try to locate the library path in any possible setup.
  if ($library_path == NULL) {
    // First check the default location.
    $path = variable_get('socialshareprivacy_path', SOCIALSHAREPRIVACY_PATH);
    if (is_dir($path . '/socialshareprivacy')) {
      $library_path = $path;
    }
    // Ask the libraries module as a fallback.
    elseif ($library_path == NULL && module_exists('libraries')) {
      if ($path = libraries_get_path('socialshareprivacy')) {
        $library_path = $path;
        variable_set('socialshareprivacy_path', $library_path);
      }
    }
    // HACK: If libraries api module is not installed but available, load it.
    elseif ($library_path == NULL && file_exists(dirname(__FILE__) . '/../libraries/libraries.module')) {
      require_once(dirname(__FILE__) . '/../libraries/libraries.module');
      if ($path = libraries_get_path('socialshareprivacy')) {
        $library_path = $path;
        variable_set('socialshareprivacy_path', $library_path);
      }
    }
    // If no path is found suggest the default one.
    elseif ($library_path == NULL) {
      $library_path = SOCIALSHAREPRIVACY_PATH;
    }
  }

  return $library_path;
}

/**
 * writes the javascript to the page
 */
function _socialshareprivacy_get_markup($nodeId = 'socialshareprivacy') {
  return '<div id="' . $nodeId . '" class="ssp_wrapper">&nbsp;</div>';
}

/**
 * writes the javascript to the page
 *
 *
 * @param $nodeId
 *   The unique javascript id.
 * @param $url
 *   The url to share.
 * @param $library_path
 *   The patch to SSP.
 */
function _socialshareprivacy_write_javascript($nodeId = 'socialshareprivacy', $url = '', $library_path = '') {

  $path = $library_path;
  if ($path == '') {
    $path = _socialshareprivacy_get_path();
  }

  $options = _socialshareprivacy_get_javascript_options($url, $library_path);

  $minFileNamePart = '.min';
  if (variable_get('socialshareprivacy_js_minified', 'true') == 'false') {
    $minFileNamePart = '';
  }

  if (variable_get('socialshareprivacy_reset_css', 'false') == 'true') {
    drupal_add_css(drupal_get_path('module', 'socialshareprivacy') . '/css/reset.css',
    array(
      'every_page' => TRUE,
    ));
  }

  drupal_add_css($path . '/socialshareprivacy/socialshareprivacy.css',
    array(
      'every_page' => TRUE,
    ));
  drupal_add_js($path . '/jquery.socialshareprivacy' . $minFileNamePart . '.js',
    array(
      'group' => JS_LIBRARY,
      'every_page' => TRUE,
    ));

  drupal_add_css(drupal_get_path('module', 'socialshareprivacy') . '/css/overlay_fix.css',
  array(
    'every_page' => TRUE,
  ));

  $inline_script = '(function ($) { jQuery(document).ready(function () { if(jQuery("#' . $nodeId . '").length > 0){ jQuery("#' . $nodeId . '").socialSharePrivacy(' . $options . ');' . _socialshareprivacy_external_link() . ' } }); })(jQuery);';

  drupal_add_js($inline_script,
    array(
      'type' => 'inline',
      'scope' => 'footer',
    ));

  return $inline_script;
}

/**
 * Return the javascript options
 *
 * @param $url
 *   The url to share.
 * @param $library_path
 *   The patch to SSP.
 */
function _socialshareprivacy_get_javascript_options($url = '', $library_path = '') {
  global $language;

  $path = $library_path;
  if ($path == '') {
    $path = _socialshareprivacy_get_path();
  }
  $facebook_dummy = base_path() . $path . '/socialshareprivacy/images/dummy_facebook_en.png';
  if (variable_get('socialshareprivacy_neutral_button', 'false') == 'true') {
    $facebook_dummy = base_path() . drupal_get_path('module', 'socialshareprivacy') . '/images/dummy_facebook.png';
  }
  elseif ($language->language == 'de' || variable_get('socialshareprivacy_force_german', 'false') == 'true') {
    $facebook_dummy = base_path() . $path . '/socialshareprivacy/images/dummy_facebook.png';
  }
  elseif ($language->language != 'en') {
    $facebook_dummy = base_path() . drupal_get_path('module', 'socialshareprivacy') . '/images/dummy_facebook.png';
  }

  /* use the german 'default' texts */
  if (variable_get('socialshareprivacy_force_german', 'true') == 'true') {
    $options = "{
          services : {
              facebook : {
                  'status' : '" . _socialshareprivacy_service_status("facebook") . "',
                  'dummy_img' : '" . $facebook_dummy . "',
                  'perma_option' : '" . _socialshareprivacy_service_permaoption_status("facebook") . "',
                  'referrer_track' : '" . _socialshareprivacy_get_referer_track() . "',
                  'action'         : '" . check_plain(variable_get('socialshareprivacy_facebook_action', 'recommend')) . "'
              },
              twitter : {
                  'status' : '" . _socialshareprivacy_service_status("twitter") . "',
                  'dummy_img' : '" . base_path() . $path . "/socialshareprivacy/images/dummy_twitter.png',
                  'perma_option' : '" . _socialshareprivacy_service_permaoption_status("twitter") . "',
                  'referrer_track' : '" . _socialshareprivacy_get_referer_track() . "'
              },
              gplus : {
                  'status' : '" . _socialshareprivacy_service_status("gplus") . "',
                  'dummy_img' : '" . base_path() . $path . "/socialshareprivacy/images/dummy_gplus.png',
                  'perma_option' : '" . _socialshareprivacy_service_permaoption_status("gplus") . "',
                  'referrer_track' : '" . _socialshareprivacy_get_referer_track() . "'
              }
          },
          'css_path': ''," . // setting css_path to an empty string disables loading the css in socialshareprivacy.js and we can use drupal_add_css() instead
"          'cookie_expires' : '" . variable_get('socialshareprivacy_cookie_expires', '365') . "',
          'info_link': '" . url(variable_get('socialshareprivacy_ext_link_target', 'http://www.heise.de/ct/artikel/2-Klicks-fuer-mehr-Datenschutz-1333879.html')) . "'";
  }
  else {
    $options = "{
          services : {
              facebook : {
                  'status' : '" . _socialshareprivacy_service_status("facebook") . "',
                  'dummy_img' : '" . $facebook_dummy . "',
                  'perma_option' : '" . _socialshareprivacy_service_permaoption_status("facebook") . "',
                  'language'       : '" . _socialshareprivacy_map_facebook_language($language->language) . "',
                  'txt_info'       : '" . _socialshareprivacy_escape_javascript(t('2 clicks for more privacy: Click here to activate the Facebook share button. Please note that activating the share button will already transfer data to Facebook. For more information please click on the <em>i</em>')) . "',
                  'referrer_track' : '" . _socialshareprivacy_get_referer_track() . "',
                  'action'         : '" . variable_get('socialshareprivacy_facebook_action', 'recommend') . "'
              },
              twitter : {
                  'status' : '" . _socialshareprivacy_service_status("twitter") . "',
                  'dummy_img' : '" . base_path() . $path . "/socialshareprivacy/images/dummy_twitter.png',
                  'perma_option' : '" . _socialshareprivacy_service_permaoption_status("twitter") . "',
                  'language'       : '" . $language->language . "',
                  'txt_info'       : '" . _socialshareprivacy_escape_javascript(t('2 clicks for more privacy: Click here to activate the Twitter share button. Please note that activating the share button will already transfer data to Twitter. For more information please click on the <em>i</em>')) . "',
                  'referrer_track' : '" . _socialshareprivacy_get_referer_track() . "'
              },
              gplus : {
                  'status' : '" . _socialshareprivacy_service_status("gplus") . "',
                  'dummy_img' : '" . base_path() . $path . "/socialshareprivacy/images/dummy_gplus.png',
                  'perma_option' : '" . _socialshareprivacy_service_permaoption_status("gplus") . "',
                  'language'       : '" . $language->language . "',
                  'txt_info'       : '" . _socialshareprivacy_escape_javascript(t('2 clicks for more privacy: Click here to activate the Google+ share button. Please note that activating the share button will already transfer data to Google. For more information please click on the <em>i</em>')) . "',
                  'referrer_track' : '" . _socialshareprivacy_get_referer_track() . "'
              }
          },
          'css_path': ''," . // setting css_path to an empty string disables loading the css in socialshareprivacy.js and we can use drupal_add_css() instead
"          'cookie_expires' : '" . (is_numeric(variable_get('socialshareprivacy_cookie_expires', '365')) ? variable_get('socialshareprivacy_cookie_expires', '365') : '365') . "',
          'txt_help'       : '" . _socialshareprivacy_escape_javascript(t('If you enable any of these options then the corresponding social network will receive and store data about your visit on this site. For more information please click on the <em>i</em>')) . "',
          'settings_perma' : '" . _socialshareprivacy_escape_javascript(t('Agree to permanent activation and thus data transfer:')) . "',
          'info_link': '" . url(variable_get('socialshareprivacy_ext_link_target', 'http://www.heise.de/ct/artikel/2-Klicks-fuer-mehr-Datenschutz-1333879.html')) . "'";
  }

  if ($url != '') {
    $options = $options . ",
    'uri' : '" . $url . "'";
  }

  $options = $options . "
          }";

  return $options;
}

/**
 * Checks if the directory in $form_element exists and contains a file named
 * 'jquery.socialshareprivacy.js'. If validation fails, the form element is flagged
 * with an error from within the file_check_directory function.
 *
 * @param $form_element
 *   The form element containing the name of the directory to check.
 */
function _socialshareprivacy_admin_settings_check_plugin_path($form_element) {
  $library_path = $form_element['#value'];
  if (!is_dir($library_path) || !(file_exists($library_path . '/jquery.socialshareprivacy.js') && file_exists($library_path . '/jquery.socialshareprivacy.min.js'))) {
    form_set_error($form_element['#parents'][0], t('You need to download the <a href="@urlSSP" target="_blank">socialSharePrivacy</a> and extract the entire contents of the archive into the %path folder of your server.', array('@urlSSP' => 'http://www.heise.de/extras/socialshareprivacy/', '%path' => $library_path)));
  }

  return $form_element;
}

/**
 * Get the status on/off for a service.
 */
function _socialshareprivacy_service_status($service) {
    $settings = variable_get('socialshareprivacy_services', unserialize(SOCIALSHAREPRIVACY_DEFAULT_VALUE_SERVICES));
    if (array_key_exists($service, $settings) && $settings[$service] !== 0) {
        return "on";
    }
    return "off";
}

/**
 * Get the status on/off for a perma option.
 */
function _socialshareprivacy_service_permaoption_status($service) {
    $settings = variable_get('socialshareprivacy_services_permaoption', unserialize(SOCIALSHAREPRIVACY_DEFAULT_VALUE_SERVICES));
    if (array_key_exists($service, $settings) && $settings[$service] !== 0) {
        return "on";
    }
    return "off";
}

/**
 * Translates and escapes '.
 */
function _socialshareprivacy_escape_javascript($text) {
    return addslashes(filter_xss($text));
}

/**
 * Gets the plain referer track string.
 */
function _socialshareprivacy_get_referer_track() {
    return check_plain(variable_get('socialshareprivacy_referrertrack', ''));
}

/**
 * Get the external link JS.
 */
function _socialshareprivacy_external_link() {
    $setting = variable_get('socialshareprivacy_ext_link', '');
    if ($setting == 'remove') {
        return " setTimeout('(function ($) { $(\'div.settings_info_menu > a\').click(function(){ return false; }); })(jQuery);', 300);";
    }
    elseif ($setting == 'blank') {
        return " setTimeout('(function ($) { $(\'div.settings_info_menu > a\').attr(\'target\', \'_blank\'); })(jQuery);', 300);";
    }
    return "";
}

/**
 * maps drupal language code to facebook langauge code
 */
function _socialshareprivacy_map_facebook_language($language) {
  $lang_map = array(
    'af' => 'af_ZA',
    'ar' => 'ar_AR',
    'ay' => 'ay_BO',
    'az' => 'az_AZ',
    'be' => 'be_BY',
    'bg' => 'bg_BG',
    'bn' => 'bn_IN',
    'bs' => 'bs_BA',
    'ca' => 'ca_ES',
    'ck' => 'ck_US',
    'cs' => 'cs_CZ',
    'cy' => 'cy_GB',
    'da' => 'da_DK',
    'de' => 'de_DE',
    'el' => 'el_GR',
    'en' => 'en_US',
    'eo' => 'eo_EO',
    'es' => 'es_ES',
    'et' => 'et_EE',
    'eu' => 'eu_ES',
    'fa' => 'fa_IR',
    'fb' => 'fb_FI',
    'fb' => 'fb_LT',
    'fi' => 'fi_FI',
    'fo' => 'fo_FO',
    'fr' => 'fr_CA',
    'fr' => 'fr_FR',
    'ga' => 'ga_IE',
    'gl' => 'gl_ES',
    'gn' => 'gn_PY',
    'gu' => 'gu_IN',
    'he' => 'he_IL',
    'hi' => 'hi_IN',
    'hr' => 'hr_HR',
    'hu' => 'hu_HU',
    'hy' => 'hy_AM',
    'id' => 'id_ID',
    'is' => 'is_IS',
    'it' => 'it_IT',
    'ja' => 'ja_JP',
    'jv' => 'jv_ID',
    'ka' => 'ka_GE',
    'kk' => 'kk_KZ',
    'km' => 'km_KH',
    'kn' => 'kn_IN',
    'ko' => 'ko_KR',
    'ku' => 'ku_TR',
    'la' => 'la_VA',
    'li' => 'li_NL',
    'lt' => 'lt_LT',
    'lv' => 'lv_LV',
    'mg' => 'mg_MG',
    'mk' => 'mk_MK',
    'ml' => 'ml_IN',
    'mn' => 'mn_MN',
    'mr' => 'mr_IN',
    'ms' => 'ms_MY',
    'mt' => 'mt_MT',
    'nb' => 'nb_NO',
    'ne' => 'ne_NP',
    'nl' => 'nl_BE',
    'nl' => 'nl_NL',
    'nn' => 'nn_NO',
    'pa' => 'pa_IN',
    'pl' => 'pl_PL',
    'ps' => 'ps_AF',
    'pt' => 'pt_PT',
    'qu' => 'qu_PE',
    'rm' => 'rm_CH',
    'ro' => 'ro_RO',
    'ru' => 'ru_RU',
    'sa' => 'sa_IN',
    'se' => 'se_NO',
    'sk' => 'sk_SK',
    'sl' => 'sl_SI',
    'so' => 'so_SO',
    'sq' => 'sq_AL',
    'sr' => 'sr_RS',
    'sv' => 'sv_SE',
    'sw' => 'sw_KE',
    'sy' => 'sy_SY',
    'ta' => 'ta_IN',
    'te' => 'te_IN',
    'tg' => 'tg_TJ',
    'th' => 'th_TH',
    'tl' => 'tl_PH',
    'tl' => 'tl_ST',
    'tr' => 'tr_TR',
    'tt' => 'tt_RU',
    'uk' => 'uk_UA',
    'ur' => 'ur_PK',
    'uz' => 'uz_UZ',
    'vi' => 'vi_VN',
    'xh' => 'xh_ZA',
    'yi' => 'yi_DE',
    'zh' => 'zh_CN',
    'zu' => 'zu_ZA',
  );
  $return = @$lang_map[$language];
  if (empty($return)) $return = 'en_US';
  return $return;
}

function _socialshareprivacy_has_access() {
  return user_access('access socialshareprivacy');
}
