<?php

/**
 * @file
 * Displays Printer-friendly versions of Drupal pages.
 *
 * @ingroup print
 */

define('PRINTMAIL_PATH', 'printmail');

define('PRINT_MAIL_FORMAT', 'mail');

define('PRINT_MAIL_LINK_POS_DEFAULT', 'link');
define('PRINT_MAIL_LINK_TEASER_DEFAULT', 0);
define('PRINT_MAIL_SHOW_LINK_DEFAULT', 1);
define('PRINT_MAIL_NODE_LINK_VISIBILITY_DEFAULT', 0);
define('PRINT_MAIL_NODE_LINK_PAGES_DEFAULT', '');
define('PRINT_MAIL_LINK_CLASS_DEFAULT', 'print-mail');
define('PRINT_MAIL_SYS_LINK_VISIBILITY_DEFAULT', 1);
define('PRINT_MAIL_SYS_LINK_PAGES_DEFAULT', '');
define('PRINT_MAIL_LINK_USE_ALIAS_DEFAULT', 0);
define('PRINT_MAIL_BOOK_LINK_DEFAULT', 1);
define('PRINT_MAIL_HOURLY_THRESHOLD', 3);
define('PRINT_MAIL_TEASER_DEFAULT_DEFAULT', 1);
define('PRINT_MAIL_TEASER_CHOICE_DEFAULT', 0);
define('PRINT_MAIL_SEND_OPTION_DEFAULT', 'sendpage');
define('PRINT_MAIL_JOB_QUEUE_DEFAULT', 0);

/**
 * Implementation of hook_perm().
 */
function print_mail_perm() {
  return array('access send to friend');
}

/**
 * Implementation of hook_theme().
 */
function print_mail_theme() {
  return array(
    'print_mail_format_link' => array(
      'arguments' => array(),
    ),
    'print_mail_form' => array(
      'arguments' => array('form' => NULL),
      'file' => 'print_mail.inc',
    ),
  );
}

/**
 * Implementation of hook_menu().
 */
function print_mail_menu() {
  $items = array();

  $items[PRINTMAIL_PATH] = array(
    'title' => variable_get('print_mail_text_title', 'Send page by e-mail'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('print_mail_form'),
    'access callback' => '_print_mail_access',
    'access arguments' => array('access send to friend'),
    'type' => MENU_CALLBACK,
    'file' => 'print_mail.inc',
  );
  $items[PRINTMAIL_PATH .'/'. PRINTMAIL_PATH] = array(
    'access callback' => FALSE,
  );
  $items['admin/settings/print/email'] = array(
    'title' => 'e-mail',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('print_mail_settings'),
    'access arguments'  => array('administer print'),
    'weight' => 2,
    'type' => MENU_LOCAL_TASK,
    'file' => 'print_mail.admin.inc',
  );
  $items['admin/settings/print/email/options'] = array(
    'title' => 'Options',
    'weight' => 1,
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
  $items['admin/settings/print/email/strings'] = array(
    'title' => 'Text strings',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('print_mail_strings_settings'),
    'access arguments'  => array('administer print'),
    'weight' => 2,
    'type' => MENU_LOCAL_TASK,
    'file' => 'print_mail.admin.inc',
  );

  return $items;
}

/**
 * Implementation of hook_block().
 */
function print_mail_block($op = 'list', $delta = 0, $edit = array()) {
  switch ($op) {
    case 'list':
      $block[0]['info'] = t('Most emailed');
      $block[0]['cache'] = BLOCK_CACHE_GLOBAL;
      return $block;
      break;
    case 'configure':
      return '';
    case 'save':
      return;
    case 'view':
      switch ($delta) {
      case 0:
        $block['subject'] = t('Most emailed');
        $result = db_query_range("SELECT path FROM {print_mail_page_counter} ORDER BY sentcount DESC", 0, 3);
        if (db_affected_rows()) {
          $block['content'] = '<div class="item-list"><ul>';
          while ($obj = db_fetch_object($result)) {
            $block['content'] .= '<li>'. l(_print_get_title($obj->path), $obj->path) .'</li>';
          }
          $block['content'] .= '</ul></div>';
        }
        break;
      }
      return $block;
      break;
    }
}

/**
 * Implementation of hook_link().
 */
function print_mail_link($type, $node = NULL, $teaser = FALSE) {
  $print_mail_link_pos = variable_get('print_mail_link_pos', array(PRINT_MAIL_LINK_POS_DEFAULT => PRINT_MAIL_LINK_POS_DEFAULT));
  $print_mail_link_use_alias = variable_get('print_mail_link_use_alias', PRINT_MAIL_LINK_USE_ALIAS_DEFAULT);
  $allowed_type = print_mail_link_allowed(array('type' => $type, 'node' => $node, 'teaser' => $teaser));
  if (($allowed_type) && !empty($print_mail_link_pos['link'])) {
    drupal_add_css(drupal_get_path('module', 'print') .'/css/printlinks.css');
    $links = array();
    $format = theme('print_mail_format_link');

    // Show book link
    if ($allowed_type === PRINT_ALLOW_BOOK_LINK) {
      $links['book_mail'] = array('href' => PRINTMAIL_PATH .'/book/export/html/'. $node->nid,
                                 'title' => $format['text'],
                                 'attributes' => $format['attributes'],
                                 'html' => $format['html'],
      );

      return $links;
    }
    elseif ($allowed_type === PRINT_ALLOW_NORMAL_LINK) {
      $query_arr = $_GET;
      if ($type == 'comment') {
        $query_arr['comment'] = $node->cid;
      }
      $query = print_query_string_encode($query_arr, array('q'));
      if (empty($query)) $query = NULL;

      if ($print_mail_link_use_alias) {
        $path = drupal_get_path_alias('node/'. $node->nid);
      }
      else {
        $path = $node->nid;
      }

      $links['print_mail'] = array('href' => PRINTMAIL_PATH .'/'. $path,
                                  'title' => $format['text'],
                                  'attributes' => $format['attributes'],
                                  'html' => $format['html'],
                                  'query' => $query,
      );

      return $links;
    }
  }
  else {
    return;
  }
}

/**
 * Implementation of hook_help().
 */
function print_mail_help($path, $arg) {
  $print_mail_link_pos = variable_get('print_mail_link_pos', array(PRINT_MAIL_LINK_POS_DEFAULT => PRINT_MAIL_LINK_POS_DEFAULT));
  if (($path !== 'node/%') && !(empty($print_mail_link_pos['link']) && empty($print_mail_link_pos['corner']))) {
    static $output = FALSE;

    if ($output === FALSE) {
      $output = TRUE;

      $link = print_mail_insert_link();
      if ($link) {
        return "<span class='print-syslink'>$link</span>";
      }
    }
  }
}

/**
 * Implementation of hook_nodeapi().
 */
function print_mail_nodeapi(&$node, $op = 'view', $teaser, $page) {
  switch ($op) {
    case 'view':
      // Insert content corner links
      $print_mail_link_pos = variable_get('print_mail_link_pos', array(PRINT_MAIL_LINK_POS_DEFAULT => PRINT_MAIL_LINK_POS_DEFAULT));
      if (($teaser === FALSE) && !empty($print_mail_link_pos['corner']) &&
          isset($node->build_mode) && ($node->build_mode === NODE_BUILD_NORMAL)) {
        $node->content['print_links']['#value'] .= print_mail_insert_link(NULL, $node);
      }
      break;
    case 'load':
      _print_mail_set_node_fields($node);
      break;
    case 'insert':
    case 'update':
      if (user_access('administer print') || user_access('node-specific print configuration')) {
        if ($node->print_mail_display === NULL) $node->print_mail_display = variable_get('print_mail_display_'. $node->type, PRINT_TYPE_SHOW_LINK_DEFAULT);
        if ($node->print_mail_display_comment === NULL) $node->print_mail_display_comment = variable_get('print_mail_display_comment_'. $node->type, PRINT_TYPE_COMMENT_LINK_DEFAULT);
        if ($node->print_mail_display_urllist === NULL) $node->print_mail_display_urllist = variable_get('print_mail_display_urllist_'. $node->type, PRINT_TYPE_URLLIST_DEFAULT);

        _print_mail_node_conf_modify($node->nid, $node->print_mail_display, $node->print_mail_display_comment, $node->print_mail_display_urllist);
      }
      break;
    case 'delete':
      db_query("DELETE FROM {print_mail_node_conf} WHERE nid = %d", $node->nid);
      db_query("DELETE FROM {print_mail_page_counter} WHERE path = 'node/%d'", $node->nid);
      break;
  }
}

/**
 * Implementation of hook_form_alter().
 */
function print_mail_form_alter(&$form, $form_state, $form_id) {
  // Add the node-type settings option to activate the mail version link
  if ((user_access('administer print') || user_access('node-specific print configuration')) && (($form_id == 'node_type_form') ||
      (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] .'_node_form' == $form_id))) {
    $form['print']['mail_label'] = array(
      '#type' => 'markup',
      '#value' => '<p><strong>'. t('Send by e-mail') .'</strong></p>',
    );

    $form['print']['print_mail_display'] = array(
      '#type' => 'checkbox',
      '#title' => t('Show link'),
    );
    $form['print']['print_mail_display_comment'] = array(
      '#type' => 'checkbox',
      '#title' => t('Show link in individual comments'),
    );
    $form['print']['print_mail_display_urllist'] = array(
      '#type' => 'checkbox',
      '#title' => t('Show Printer-friendly URLs list'),
    );

    if ($form_id == 'node_type_form') {
      $form['print']['print_mail_display']['#default_value'] = variable_get('print_mail_display_'. $form['#node_type']->type, PRINT_TYPE_SHOW_LINK_DEFAULT);
      $form['print']['print_mail_display_comment']['#default_value'] = variable_get('print_mail_display_comment_'. $form['#node_type']->type, PRINT_TYPE_COMMENT_LINK_DEFAULT);
      $form['print']['print_mail_display_urllist']['#default_value'] = variable_get('print_mail_display_urllist_'. $form['#node_type']->type, PRINT_TYPE_URLLIST_DEFAULT);
    }
    else {
      $node = $form['#node'];
      $form['print']['print_mail_display']['#default_value'] = isset($node->print_mail_display) ? $node->print_mail_display : variable_get('print_mail_display_'. $node->type, PRINT_TYPE_SHOW_LINK_DEFAULT);
      $form['print']['print_mail_display_comment']['#default_value'] = isset($node->print_mail_display_comment) ? $node->print_mail_display_comment : variable_get('print_mail_display_comment_'. $node->type, PRINT_TYPE_COMMENT_LINK_DEFAULT);
      $form['print']['print_mail_display_urllist']['#default_value'] = isset($node->print_mail_display_urllist) ? $node->print_mail_display_urllist : variable_get('print_mail_display_urllist_'. $node->type, PRINT_TYPE_URLLIST_DEFAULT);
    }
  }
}

/**
 * Implementation of hook_job_queue_functions().
 */
function print_mail_job_queue_functions() {
  $functions['print_mail'] = array(
   'title' => t('Send to friend'),
  );
  return $functions;
}

/**
 * Access callback to check a combination of user_acess() and page access
 *
 * @param $permission
 *   permission required to view the page
 * @return
 *   TRUE if the user has permission to view the page, FALSE otherwise
 */
function _print_mail_access($permission) {
  $page_access = TRUE;
  $parts = explode('/', $_GET['q']);
  if ($parts[0] == PRINTMAIL_PATH) {
    if (count($parts) > 1) {
      unset($parts[0]);
      $path = implode('/', $parts);
      if (ctype_digit($parts[1])) {
        if (drupal_lookup_path('source', $path)) {
          // This is a numeric alias
          $path = drupal_get_normal_path($path);
        }
        else {
          // normal nid
          $path = 'node/' . $path;
        }
      }
      else {
        $path = drupal_get_normal_path($path);
      }
      // If the destination page is not accessible, don't show the form
      if (!($router_item = menu_get_item($path)) || (!$router_item['access'])) {
        $page_access = FALSE;
      }
    }
  }

  return (user_access($permission) && $page_access);
}

/**
 * Auxiliary function to assign the per-node settings to the node object fields
 *
 * @param $node
 *   node to be modified
 */
function _print_mail_set_node_fields(&$node) {
  if (isset($node->nid)) {
    $res = db_fetch_object(db_query("SELECT link, comments, url_list FROM {print_mail_node_conf} WHERE nid = %d", $node->nid));
  }
  else {
    $res = FALSE;
  }
  $node->print_mail_display = $res ? intval($res->link) : variable_get('print_mail_display_'. $node->type, PRINT_TYPE_SHOW_LINK_DEFAULT);
  $node->print_mail_display_comment = $res ? intval($res->comments) : variable_get('print_mail_display_comment_'. $node->type, PRINT_TYPE_COMMENT_LINK_DEFAULT);
  $node->print_mail_display_urllist = $res ? intval($res->url_list) : variable_get('print_mail_display_urllist_'. $node->type, PRINT_TYPE_URLLIST_DEFAULT);
}

/**
 * Update the print_mail_node_conf table to reflect the given attributes
 * If updating to the default values, delete the record.
 *
 * @param $nid
 *   value of the nid field (primary key)
 * @param $link
 *   value of the link field (0 or 1)
 * @param $comments
 *   value of the comments field (0 or 1)
 * @param $url_list
 *   value of the url_list field (0 or 1)
 */
function _print_mail_node_conf_modify($nid, $link, $comments, $url_list) {
    db_query("UPDATE {print_mail_node_conf} SET link = %d, comments = %d, url_list = %d WHERE nid = %d", $link, $comments, $url_list, $nid);
    if (!db_affected_rows()) {
      @db_query("INSERT INTO {print_mail_node_conf} (nid, link, comments, url_list) VALUES (%d, %d, %d, %d)", $nid, $link, $comments, $url_list);
    }
}

/**
 * Format the send by e-mail link
 *
 * @return
 *   array of formatted attributes
 * @ingroup themeable
 */
function theme_print_mail_format_link() {
  $print_mail_link_class  = variable_get('print_mail_link_class', PRINT_MAIL_LINK_CLASS_DEFAULT);
  $print_mail_show_link = variable_get('print_mail_show_link', PRINT_MAIL_SHOW_LINK_DEFAULT);
  $print_mail_link_text = filter_xss(variable_get('print_mail_link_text', t('Send to friend')));

  $img = drupal_get_path('module', 'print') .'/icons/mail_icon.gif';
  $title = t('Send this page by e-mail.');
  $class = strip_tags($print_mail_link_class);
  $new_window = FALSE;
  $format = _print_format_link_aux($print_mail_show_link, $print_mail_link_text, $img);

  return array('text' => $format['text'],
               'html' => $format['html'],
               'attributes' => print_fill_attributes($title, $class, $new_window),
              );
}

/**
 * Auxiliary function to display a formatted send by e-mail link
 *
 * Function made available so that developers may call this function from
 * their defined pages/blocks.
 *
 * @param $path
 *   path of the original page (optional). If not specified, the current URL
 *   is used
 * @param $node
 *   an optional node object, to be used in defining the path, if used, the
 *   path argument is irrelevant
 * @return
 *   string with the HTML link to the printer-friendly page
 */
function print_mail_insert_link($path = NULL, $node = NULL) {
  if ($node !== NULL) {
    $nid = $node->nid;
    $path = 'node/'. $nid;
    $allowed_type = print_mail_link_allowed(array('node' => $node));
  }
  else {
    if ($path === NULL) {
      $nid = preg_replace('!^node/!', '', $_GET['q']);
      $path = $_GET['q'];
    }
    else {
      $nid = NULL;
    }
    $allowed_type = print_mail_link_allowed(array('path' => $path));
  }

  if ($allowed_type) {
    if ($nid !== NULL) {
      if ($allowed_type === PRINT_ALLOW_BOOK_LINK) {
        $path = 'book/export/html/'. $nid;
      }
      else {
        if (variable_get('print_mail_link_use_alias', PRINT_MAIL_LINK_USE_ALIAS_DEFAULT)) {
          $path = drupal_get_path_alias($path);
        }
        else {
          $path = $nid;
        }
      }
      $path = PRINTMAIL_PATH .'/'. $path;
      $query = print_query_string_encode($_GET, array('q'));
      if (empty($query)) {
        $query = NULL;
      }
    }
    else {
      $query = NULL;
    }
    drupal_add_css(drupal_get_path('module', 'print') .'/css/printlinks.css');
    $format = theme('print_mail_format_link');
    return '<span class="print_mail">'. l($format['text'], $path, array('attributes' => $format['attributes'], 'query' => $query, 'absolute' => TRUE, 'html' => $format['html'])) .'</span>';
  }
  else {
    return FALSE;
  }
}

/**
 * Determine a the link to send by e-mail is allowed depending on all possible settings
 *
 * @param $args
 *   array containing the possible parameters:
 *    teaser, node, type, path
 * @return
 *   FALSE if not allowed
 *   PRINT_ALLOW_NORMAL_LINK if a normal link is allowed
 *   PRINT_ALLOW_BOOK_LINK if a link is allowed in a book node
 */
function print_mail_link_allowed($args) {
  if ((!empty($args['teaser']) && !variable_get('print_mail_link_teaser', PRINT_MAIL_LINK_TEASER_DEFAULT))
      || !user_access('access send to friend')) {
    // If the teaser link is disabled or the user is not allowed
    return FALSE;
  }
  if (!empty($args['path'])) {
    $nid = preg_replace('!^node/!', '', drupal_get_normal_path($args['path']));
    if (ctype_digit($nid)) {
      $args['node'] = node_load($nid);
    }
  }
  if (!empty($args['node'])) {
    static $node_type = FALSE;

    $node = $args['node'];
    if (isset($node->type)) {
      $node_type = $node->type;
    }
    // Node
    $print_mail_node_link_visibility = variable_get('print_mail_node_link_visibility', PRINT_MAIL_NODE_LINK_VISIBILITY_DEFAULT);
    $print_mail_node_link_pages = variable_get('print_mail_node_link_pages', PRINT_MAIL_NODE_LINK_PAGES_DEFAULT);

    if (!_print_page_match($print_mail_node_link_visibility, "node/". $node->nid, $print_mail_node_link_pages)) {
      // Page not in visibility list
      return FALSE;
    }
    elseif (isset($args['type']) && ($args['type'] == 'comment') && isset($node_type)) {
      // Link is for a comment, return the configured setting
      // Cache this statically to avoid duplicate queries for every comment.
      static $res = array();
      if (!isset($res[$node->nid])) {
        $res[$node->nid] = db_fetch_object(db_query("SELECT comments FROM {print_mail_node_conf} WHERE nid = %d", $node->nid));
      }
      $print_display_comment = $res ? intval($res[$node->nid]->comments) : variable_get('print_mail_display_comment_'. $node_type, PRINT_TYPE_COMMENT_LINK_DEFAULT);
      if ($print_display_comment) {
        return PRINT_ALLOW_NORMAL_LINK;
      }
    }
    else {
      // Node link
      if (!$node->print_mail_display) {
        // Link for this node is disabled
        return FALSE;
      }
      elseif (isset($node->book)) {
        // Node is a book;
        $print_mail_book_link = variable_get('print_mail_book_link', PRINT_MAIL_BOOK_LINK_DEFAULT);
        switch ($print_mail_book_link) {
          case 1:
            if (user_access('access printer-friendly version')) {
              return PRINT_ALLOW_BOOK_LINK;
            }
            break;
          case 2:
            return PRINT_ALLOW_NORMAL_LINK;
        }
      }
      else {
        return PRINT_ALLOW_NORMAL_LINK;
      }
    }
  }
  else {
    // 'System' page
    $print_mail_sys_link_visibility = variable_get('print_mail_sys_link_visibility', PRINT_MAIL_SYS_LINK_VISIBILITY_DEFAULT);
    $print_mail_sys_link_pages = variable_get('print_mail_sys_link_pages', PRINT_MAIL_SYS_LINK_PAGES_DEFAULT);

    return _print_page_match($print_mail_sys_link_visibility, $_GET['q'], $print_mail_sys_link_pages);
  }
  return FALSE;
}
