You are here

zopim.module in Zopim Live Chat 6.2

Same filename and directory in other branches
  1. 8 zopim.module
  2. 6 zopim.module
  3. 7 zopim.module

File

zopim.module
View source
<?php

/*
 * @file
 * Drupal Module: zopim
 * Adds the required Javascript for Zopim chat to the bottom of all your Drupal pages
 */
define('ZOPIM_SCRIPT_DOMAIN', "zopim.com");
define('ZOPIM_BASE_URL', "https://www.zopim.com/");
define('ZOPIM_GETACCOUNTDETAILS_URL', ZOPIM_BASE_URL . "plugins/getAccountDetails");
define('ZOPIM_SETDISPLAYNAME_URL', ZOPIM_BASE_URL . "plugins/setDisplayName");
define('ZOPIM_IMINFO_URL', ZOPIM_BASE_URL . "plugins/getImSetupInfo");
define('ZOPIM_IMREMOVE_URL', ZOPIM_BASE_URL . "plugins/removeImSetup");
define('ZOPIM_LOGIN_URL', ZOPIM_BASE_URL . "plugins/login");
define('ZOPIM_SIGNUP_URL', ZOPIM_BASE_URL . "plugins/createTrialAccount");
define('ZOPIM_THEMES_LIST', "http://zopim.com/assets/dashboard/themes/window/plugins-themes.txt");
define('ZOPIM_COLORS_LIST', "http://zopim.com/assets/dashboard/themes/window/plugins-colors.txt");
define('ZOPIM_LANGUAGES_URL', "http://translate.zopim.com/projects/zopim/");
define('ZOPIM_DASHBOARD_URL', "http://dashboard.zopim.com/");
define('ZOPIM_SMALL_LOGO', "http://zopim.com/assets/branding/zopim.com/chatman/online.png");
define('ZOPIM_IM_LOGOS', "http://www.zopim.com/static/images/im/");
define('ZOPIM_THEMES_URL', "http://");
define('ZOPIM_COLOURS_URL', "http://");
function zopim_help($path, $arg) {
  switch ($path) {
    case 'admin/settings/zopim':
      return;
  }
}
function zopim_perm() {
  return array(
    'administer zopim',
    'use PHP for zopim visibility',
  );
}
function zopim_menu() {
  $includes = drupal_get_path('module', 'zopim') . '/includes';

  // Account settings
  $items['admin/settings/zopim'] = array(
    'title' => 'Zopim',
    'description' => t('Configuration for the Zopim module.'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'zopim_admin_settings_form',
    ),
    'access arguments' => array(
      'administer zopim',
    ),
    'file' => 'zopim-account.admin.inc',
    'file path' => $includes,
    'type' => MENU_NORMAL_ITEM,
  );

  // Setup default local task, same as normal item, with a few exceptions.
  $items['admin/settings/zopim/account'] = $items['admin/settings/zopim'];
  $items['admin/settings/zopim/account']['title'] = 'Account Settings';
  $items['admin/settings/zopim/account']['description'] = t('Configure the account settings for your Zopim account.');
  $items['admin/settings/zopim/account']['type'] = MENU_DEFAULT_LOCAL_TASK;
  $items['admin/settings/zopim/account']['weight'] = 0;

  // Visibility settings
  $items['admin/settings/zopim/visibility'] = array(
    'title' => 'Visibility',
    'description' => "Configure the settings used to determine the widget's visibility.",
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'zopim_admin_settings_form',
    ),
    'access arguments' => array(
      'administer zopim',
    ),
    'file' => 'zopim-visibility.admin.inc',
    'file path' => $includes,
    'type' => MENU_LOCAL_TASK,
    'weight' => 1,
  );

  // Widget customization
  $items['admin/settings/zopim/customize'] = array(
    'title' => 'Customize Widget',
    'description' => 'Configure the settings used to generate your Zopim code.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'zopim_admin_settings_form',
    ),
    'access arguments' => array(
      'administer zopim',
    ),
    'file' => 'zopim-customize.admin.inc',
    'file path' => $includes,
    'type' => MENU_LOCAL_TASK,
    'weight' => 2,
  );
  return $items;
}
function zopim_init() {
  global $user;
  $settings = zopim_get_settings();
  if (!empty($settings['general']['account_key']) && $settings['visibility']['enabled'] && _zopim_visibility_pages() && _zopim_visibility_user($user)) {
    $domain = ZOPIM_SCRIPT_DOMAIN;
    if (!empty($settings['general']['salt']) && $settings['general']['account'] === 1 && $settings['visibility']['enabled'] === 1) {
      $js_settings = $settings;
      unset($js_settings['general']['username'], $js_settings['general']['password']);

      // If user is logged in then setup his info in the settings array.
      if (!user_is_anonymous() && $settings['widget']['use_user_info'] === 1) {
        if ($user->name != '') {
          $js_settings['user']['name'] = $user->name;
        }
        if ($user->mail != '') {
          $js_settings['user']['email'] = $user->mail;
        }
      }
      drupal_add_js(array(
        'zopim' => $js_settings,
      ), 'setting');
    }
  }
}
function zopim_footer($main = 0) {

  // 1. Check if the Zopim account number has a value.
  // 2. Add JS based on visibility value.
  // 3. Check if we should add the JS for the currently active user's role.
  global $user;
  $settings = zopim_get_settings();
  if (!empty($settings['general']['account_key']) && $settings['visibility']['enabled'] && _zopim_visibility_pages() && _zopim_visibility_user($user)) {
    if (!empty($settings['general']['salt']) && $settings['general']['account'] === 1 && $settings['visibility']['enabled'] === 1) {
      $script = "\n  var zopimSettings = Drupal.settings.zopim;\n  // Start of Zopim Live Chat Script\n  window.\$zopim||(function(d,s){var z=\$zopim=function(c){z._.push(c)},\$=\n  z.s=d.createElement(s),e=d.getElementsByTagName(s)[0];z.set=function(o\n  ){z.set._.push(o)};\$.setAttribute('charset','utf-8');\$.async=!0;z.set.\n  _=[];\$.src='//v2.zopim.com/?'+zopimSettings.general.account_key;\$.type='text/java'+s;z.\n  t=+new Date;z._=[];e.parentNode.insertBefore(\$,e)})(document,'script')\n  // End of Zopim Live Chat Script\n\n  // Start Zopim Live Chat customizations\n  \$zopim(function() {\n    if (zopimSettings.widget.language != '--') {\n      \$zopim.livechat.setLanguage(zopimSettings.widget.language);\n    }\n    if (zopimSettings.user.name) {\n      \$zopim.livechat.setName(zopimSettings.user.name);\n    }\n    if (zopimSettings.user.email) {\n      \$zopim.livechat.setEmail(zopimSettings.user.email);\n    }\n    \$zopim.livechat.button.setPosition(zopimSettings.widget.position);\n    if (zopimSettings.customization.widget === 1) {\n      \$zopim.livechat.window.setTheme(zopimSettings.theming.theme);\n    }\n    if (zopimSettings.customization.color === 1) {\n      \$zopim.livechat.window.setColor(zopimSettings.theming.color);\n    }\n    if (zopimSettings.help_bubble.display == 'show') {\n      \$zopim.livechat.bubble.show(true);\n    }\n    if (zopimSettings.help_bubble.display == 'hide') {\n      \$zopim.livechat.bubble.hide(true);\n    }\n    if (zopimSettings.help_bubble.title != '') {\n      \$zopim.livechat.bubble.setTitle(zopimSettings.help_bubble.title);\n    }\n    if (zopimSettings.help_bubble.message != '') {\n      \$zopim.livechat.bubble.setText(zopimSettings.help_bubble.message);\n    }\n    if (zopimSettings.greeting_messages.enabled === 1) {\n      \$zopim.livechat.setGreetings({\n        'online' : [zopimSettings.greeting_messages.chatbar.online, zopimSettings.greeting_messages.panel.online],\n        'offline' : [zopimSettings.greeting_messages.chatbar.offline, zopimSettings.greeting_messages.panel.offline],\n        'away' : [zopimSettings.greeting_messages.chatbar.away, zopimSettings.greeting_messages.panel.away]\n      });\n    }\n    if (zopimSettings.widget.hide_when_offline === 1) {\n      \$zopim.livechat.button.setHideWhenOffline(true);\n    }\n  });\n  // End Zopim Live Chat customizations\n  ";
      drupal_add_js($script, 'inline', 'footer');
    }
  }
}

/**
 * Implementation of hook_requirements().
 */
function zopim_requirements($phase) {
  $settings = zopim_get_settings();
  $requirements = array();
  if ($phase == 'runtime') {

    // Raise warning if Zopim user account has not been set yet.
    if ($settings['general']['account'] === 0) {
      $requirements['zopim'] = array(
        'title' => t('Zopim module'),
        'description' => t('Zopim module has not been configured yet. Please configure its settings from the <a href="@url">Zopim settings page</a>.', array(
          '@url' => url('admin/settings/zopim'),
        )),
        'severity' => REQUIREMENT_ERROR,
        'value' => t('Not configured'),
      );
    }
  }
  return $requirements;
}

/**
 * Based on visibility setting this function returns TRUE if Zopim code should
 * be added to the current page and otherwise FALSE.
 */
function _zopim_visibility_pages() {
  $settings = zopim_get_settings();
  static $page_match;

  // Cache visibility setting in hook_init for hook_footer.
  if (!isset($page_match)) {
    $visibility = $settings['visibility']['page']['mode'];
    $pages = $settings['visibility']['page']['pages'];

    // Match path if necessary.
    if (!empty($pages)) {
      if ($visibility < 2) {
        $path = drupal_get_path_alias($_GET['q']);

        // Compare with the internal and path alias (if any).
        $page_match = drupal_match_path($path, $pages);
        if ($path != $_GET['q']) {
          $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
        }

        // When $visibility has a value of 0, the block is displayed on
        // all pages except those listed in $pages. When set to 1, it
        // is displayed only on those pages listed in $pages.
        $page_match = !($visibility xor $page_match);
      }
      else {
        $page_match = drupal_eval($pages);
      }
    }
    else {
      $page_match = TRUE;
    }
  }
  return $page_match;
}

/**
 * Tracking visibility check for an user object.
 *
 * @param $account
 *   A user object containing an array of roles to check.
 * @return boolean
 *   A decision on if the current user is being tracked by Zopim.
 */
function _zopim_visibility_user($account) {
  $enabled = FALSE;

  // Is current user a member of a role that should be tracked?
  if (_zopim_visibility_roles($account)) {
    $enabled = TRUE;
  }
  return $enabled;
}

/**
 * Based on visibility setting this function returns TRUE if Zopim code should
 * be added for the current role and otherwise FALSE.
 */
function _zopim_visibility_roles($account) {
  $settings = zopim_get_settings();
  $enabled = TRUE;
  $roles = $settings['visibility']['role'];
  if (array_sum($roles) > 0) {

    // One or more roles are selected for tracking.
    foreach (array_keys($account->roles) as $rid) {

      // Is the current user a member of one role selected in admin settings?
      if (isset($roles[$rid]) && $rid == $roles[$rid]) {

        // Current user is a member of a role that is selected in admin settings.
        $enabled = FALSE;
        break;
      }
    }
  }
  return $enabled;
}
function zopim_post_request($url, $data, $ssl = NULL) {
  $ssl = $ssl ? $ssl : variable_get('zopim_use_ssl', '1');
  $headers = array(
    'Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8',
  );
  $url = $ssl === 1 ? $url : str_replace("https", "http", $url);
  $data = drupal_query_string_encode($data);
  $request = drupal_http_request($url, $headers, 'POST', $data);
  return drupal_parse_json($request->data);
}
function zopim_get_account_details($salt = '') {
  $settings = zopim_get_settings();
  $salt = empty($salt) ? $settings['general']['salt'] : $salt;
  if (empty($salt)) {
    return 'unconfigured';
  }
  else {
    $data = array(
      'salt' => $salt,
    );
    return zopim_post_request(ZOPIM_GETACCOUNTDETAILS_URL, $data);
  }
}

/**
 * Utility function to return all settings in one call.
 * @return array
 *   An array of settings.
 */
function zopim_get_settings() {
  $defaults = array(
    'general' => array(
      'username' => FALSE,
      'password' => FALSE,
      'salt' => FALSE,
      'agreement' => 0,
      'use_ssl' => 1,
      'account' => 0,
      'account_key' => FALSE,
      'customization' => array(
        'color' => FALSE,
        'widget' => FALSE,
      ),
    ),
    'widget' => array(
      'language' => '--',
      'position' => 'br',
      'use_user_info' => 1,
      'hide_when_offline' => 0,
    ),
    'theming' => array(
      'color' => '#FFFFFF',
      'theme' => 'alphacube',
    ),
    'help_bubble' => array(
      'display' => 'default',
      'title' => '',
      'message' => '',
    ),
    'greeting_messages' => array(
      'enabled' => 0,
      'chatbar' => array(
        'online' => '',
        'away' => '',
        'offline' => '',
      ),
      'panel' => array(
        'online' => '',
        'away' => '',
        'offline' => '',
      ),
    ),
    'visibility' => array(
      'enabled' => 1,
      'role' => array(),
      'page' => array(
        'mode' => 0,
        'pages' => '',
      ),
    ),
  );
  return array_replace_recursive($defaults, variable_get('zopim', $defaults));
}
function zopim_set_settings($form, &$form_state) {
  foreach ($form_state['values'] as $key => $value) {
    if (!is_array($value)) {
      unset($form_state['values'][$key]);
    }
  }
  $settings = zopim_get_settings();
  $form_state['values'] = array_replace_recursive(array(
    'zopim' => $settings,
  ), array(
    'zopim' => $form_state['values'],
  ));
}

/**
 * Function stolen and reused from json_server module.
 */
if (!function_exists('drupal_parse_json')) {
  function drupal_parse_json($v) {

    // PHP 5 only
    if (function_exists('json_decode')) {
      return json_decode($v);
    }
    if ($v[0] == '"') {
      $v = substr($v, 1, -1);
    }
    elseif ($v[0] == '{') {
      $var = explode(",", substr($v, 1, -2));
      $v = array();
      foreach ($var as $value) {
        $va = explode(":", $value);
        $v[$va[0]] = drupal_parse_json($va[1]);
      }
    }
    elseif ($v[0] == '[') {
      $var = explode(",", substr($v, 1, -2));
      $v = array();
      foreach ($var as $value) {
        $v[] = drupal_parse_json($va[0]);
      }
    }
    return $v;
  }
}
if (!function_exists('array_replace_recursive')) {
  function array_replace_recursive($array, $array1) {
    if (!function_exists('recurse')) {
      function recurse($array, $array1) {
        foreach ($array1 as $key => $value) {

          // create new key in $array, if it is empty or not an array
          if (!isset($array[$key]) || isset($array[$key]) && !is_array($array[$key])) {
            $array[$key] = array();
          }

          // overwrite the value in the base array
          if (is_array($value)) {
            $value = recurse($array[$key], $value);
          }
          $array[$key] = $value;
        }
        return $array;
      }
    }

    // handle the arguments, merge one by one
    $args = func_get_args();
    $array = $args[0];
    if (!is_array($array)) {
      return $array;
    }
    for ($i = 1; $i < count($args); $i++) {
      if (is_array($args[$i])) {
        $array = recurse($array, $args[$i]);
      }
    }
    return $array;
  }
}

Functions

Namesort descending Description
zopim_footer
zopim_get_account_details
zopim_get_settings Utility function to return all settings in one call.
zopim_help
zopim_init
zopim_menu
zopim_perm
zopim_post_request
zopim_requirements Implementation of hook_requirements().
zopim_set_settings
_zopim_visibility_pages Based on visibility setting this function returns TRUE if Zopim code should be added to the current page and otherwise FALSE.
_zopim_visibility_roles Based on visibility setting this function returns TRUE if Zopim code should be added for the current role and otherwise FALSE.
_zopim_visibility_user Tracking visibility check for an user object.

Constants