<?php
/* $Id: emailpage.module,v 1.3.4.2 2006/03/13 21:56:31 deekayen Exp $ */

define('EMAILPAGE_SUBJECT_LINE', variable_get('emailpage_subject_line', t("thought you'd like to see this")));
define('EMAILPAGE_TITLE', t('Email this page to a friend'));
define('EMAILPAGE_MESSAGE', variable_get('emailpage_message', t('%someone thought you would like this page')."\n"));

function emailpage_help($section) {
  if ($section == 'admin/modules#description') {
    return t('Provides and "email this page" link to all nodes');
  }
}

function emailpage_perm() {
  return array('administer emailpage'); 
}

function emailpage_menu($may_cache) {
  global $user;
  $items=array();
  if ($may_cache) {
    $items[]=array('path' => 'emailpage', 'title' => t('email this page'), access => 1, 'type' => MENU_CALLBACK, 'callback' => 'emailpage_page');
  }
  return $items;
}

function emailpage_link($type, $node=0, $main=0) {
  return theme('emailpage_link', $type, $node, $main);
}

function theme_emailpage_link($type, $node=0, $main=0) {
  $links=array();

  // This var is set in the settings section under the admin/modules/emailpage section
  // It shows 'email this $nodetype' or 'email this page'
  $e_l_t = variable_get('emailpage_link_type', 0);
  if($e_l_t) {
    if($type == 'comment') {
      $e_l_t = 'comment';
      $links[] = l(t('email this %type', array('%type' => t($e_l_t))), "emailpage&nid=$node->nid&cid=$node->cid", array('title' => EMAILPAGE_TITLE), NULL);
      return $links;
    }
    $e_l_t=$node->type;
  } else {
    $e_l_t="page";
  }
    
  if($main) {  // not on an index page
    if(variable_get('emailpage_show_on_main', 0)) {  
      $links[] = l(t('email this %type', array('%type' => t($e_l_t))), "emailpage&nid=$node->nid", array('title' => EMAIL_PAGE_TITLE), NULL);
      return $links;
    }
  } else { // not on a main page
    $links[] = l(t("email this ".$e_l_t), "emailpage&nid=$node->nid", array("title" => EMAILPAGE_TITLE), NULL);                                                                          return $links;
  }
}

function emailpage_page() {
  global $base_url;

  // first we check to see if they have reached the emailpage_flood_control limit
  // which is set in the settings.
  if($_COOKIE['emailpage_flood_count'] >= variable_get('emailpage_flood_control', 10)) {
    $content = variable_get('emailpage_flood_error_msg', t('Sorry, you have reached the maximum number of emails allowed per user. Please try again later'));
    print theme('page', $content);
    return;
  }

  $host = parse_url($base_url);

  // Check we have the $node-nid needed to send the page
  // and the comment fragment if they email a comment
  if(!$_COOKIE['referer']) {
    if($_GET['nid']) {
      if($_GET['cid']) {  // this takes care of links to specific comments
        $nodelink = $base_url .'/'. url('node/'. $_GET['nid'] ."#comment-". $_GET['cid']);
      } else {
        $nodelink = $base_url .'/'. url('node/' .$_GET['nid']);
      }
      // Set the refering page in a cookie
      // 5mins should be enuf for anyone to put in a valid email address ;-)
      setcookie('referer', $nodelink, time()+300, '/', '.'.$host['host']);
    } else {
      $nodelink = $base_url;
    }
  }



  //  we need to check if the form has been posted..
  if($_POST) {
    if(!user_validate_mail($_POST['edit']['emailpage_addy']) && $_POST['edit']['emailpage_sender'] && $_COOKIE['referer']) {  // all is well, so lets send it!
      $headers = 'Reply-To: '. variable_get('emailpage_sender_addy', ''). "\r\nFrom: ". variable_get('emailpage_sender_addy', ''). "\r\n";
      $headers = "MIME-Version: 1.0\nContent-Type: text/plain; charset=UTF-8; format=flowed\nContent-transfer-encoding: 8Bit\n" . $headers;
      mail($_POST['edit']['emailpage_addy'], $_POST['edit']['emailpage_sender'].' '. mime_header_encode(EMAILPAGE_SUBJECT_LINE), $_COOKIE['referer']. "\n\n". wordwrap(str_replace('%someone', $_POST['edit']['emailpage_sender'], EMAILPAGE_MESSAGE), 72), $headers);

      // Delete the cookie
      // If we dont do this, sending other pages becomes messy.
      setcookie('referer', '', time()-3600, '/', '.'.$host['host']);

      // Increase the emailpage_flood_control cookie (check settings)
      setcookie('emailpage_flood_count', $_COOKIE['emailpage_flood_count']+1, time()+7200, '/', ".".$host['host']);

      $content=variable_get('emailpage_success_msg', t('Success!'));
      variable_set('emailpage_total', variable_get('emailpage_total', 0)+1);
    	drupal_goto();
      return;
      
    } else {
    
      $error="<p class=\"error\">You must supply your name and a valid email address</p>";

      $form["emailpage_sender"] = array(
        '#type' => 'textfield',
        '#title' => t("Your Name"),
        '#default_value' => $_POST['edit']['emailpage_sender'],
        '#size' => 20,
        '#maxlength' => 30,
      );
      $form["emailpage_addy"] = array(
        '#type' => 'textfield',
        '#title' => t("Address to send to"),
        '#default_value' => $_POST['edit']['emailpage_addy'],
        '#size' => 20,
        '#maxlength' => 30,
      );
      $form["emailpage_submit"] = array(
        '#type' => 'submit',
        '#value' => t("Send it Now!"),
      );

      $content .= $error;
      $form['#method'] = "post";
      $form['#action'] = url("emailpage");
      $content .= '<h2>'. t('Example Email')."</h2>\n";
      $content .= '<p><strong>'. t('Subject'). ': </strong>['. t('Your Name').'] '.EMAILPAGE_SUBJECT_LINE."</p>\n\n<p>".$nodelink."</p>\n\n<p>[".t('Your Name').'] '.nl2br(EMAILPAGE_MESSAGE).'</p>';
      $form['emailpage_stuff'] = array('#type' => 'markup', '#value' => $content, '#weight' => -1);
      return drupal_get_form('emailpage', $form);

    }
  } 

  if(!$_POST) {
    $content .= '<h2>'. t('Example  Email'). "</h2>\n";
    $content .= '<p><strong>'. t('Subject'). ': </strong>['. t('Your Name'). '] '. EMAILPAGE_SUBJECT_LINE. "</p>\n\n<p>". $nodelink. "</p>\n\n<p>[". t('Your Name'). '] '. nl2br(EMAILPAGE_MESSAGE). '</p>';

    $form['emailpage_stuff'] = array('#type' => 'markup', '#value' => $content);
    $form["emailpage_sender"] = array(
      '#type' => 'textfield',
      '#title' => t("Your Name"),
      '#default_value' => $_POST['edit']['emailpage_sender'],
      '#size' => 20,
      '#maxlength' => 30,
    );
    $form["emailpage_addy"] = array(
      '#type' => 'textfield',
      '#title' => t("Address to send to"),
      '#default_value' => $_POST['edit']['emailpage_addy'],
      '#size' => 20,
      '#maxlength' => 30,
    );
    $form["emailpage_submit"] = array(
      '#type' => 'submit',
      '#value' => "Send it Now!",
    );

    return drupal_get_form('emailpage', $form);

  }
}

function emailpage_settings() {
  global $base_url;

  // only administrators can access this module
  if (!user_access('administer emailpage')) {
    return drupal_set_message(t('You are not allowed to access this page'), 'error');
  }
  $host = parse_url($base_url);

  $stuff = "<p>Total emails sent to date: <strong>".variable_get('emailpage_total', 1)."</strong></p>";
  $form['emailpage'] = array(
      '#type' => 'fieldset',
      '#title' => t('Emailpage settings'),
      '#tree' => TRUE,
    );

  $form['emailpage']['emailpage_stuff'] = array('#type' => 'markup', '#value' => $stuff);
  $form['emailpage']['emailpage_total'] = array(
    '#type' => 'radios',
    '#title' => 'Reset the Counter?',
    '#default_value' => variable_get('emailpage_total', 0),
    '#options' => array(1 => "Yes", variable_get('emailpage_total', 0) => "No")
    );
  $form['emailpage']['emailpage_link_type'] = array(
    '#type' => 'radios',
    '#title' => 'Use node type to create link?',
    '#default_value' => variable_get('emailpage_link_type', 0),
    '#options' => array(1 => "Yes", 0 => "No"),
    '#description' => t("If yes, the link will read &quot;email this <em>nodetype</em>&quot;, if no, it will just read &quot;email this page&quot;.")
  );
  $form['emailpage']['emailpage_show_on_main'] = array(
    '#type' => 'radios',
    '#title' => 'Show link on index pages?',
    '#default_value' => variable_get('emailpage_show_on_main', 0),
    '#options' => array(1 => "Yes", 0 => "No"),
    '#description' => t("If yes, the email this page link will show on all teasers on the index pages as well as the individual nodes.")
  );
  $form['emailpage']['emailpage_flood_control'] = array(
    '#type' => 'select',
    '#title' => "Flood Control",
    '#default_value' => variable_get('emailpage_flood_control', 10),
    '#options' => array(1 => "1", 2 => "2", 3 => "3", 4 => "4", 5 => "5", 6 => "6", 7 => "7", 8 => "8", 9 => "9", 10 => "10"),
    '#description' => "How many times a user can use the form in a 2hr period. This prevents abusers from sending out unlimited amounts of unwanted mail from the emailpage module."
  );

  $form['emailpage']['emailpage_sender_addy'] = array(
    '#type' => 'textfield',
    '#title' => t("Sender Address"),
    '#default_value' => variable_get('emailpage_sender_addy', "NoReply@".$host['host']),
    '#size' => 30,
    '#maxlength' => 40,
    '#description' => "The address to send FROM.",
  );
  $form['emailpage']['emailpage_subject_line'] = array(
    '#type' => 'textfield',
    '#title' => t("Subject Line"),
    '#default_value' => EMAILPAGE_SUBJECT_LINE,
    '#size' => 30,
    '#maxlength' => 40,
    '#description' => "The subject line will start with the senders name as the first word, you can edit the rest of the line above."
  );

  $form['emailpage']['emailpage_message'] = array(
    '#type' => 'textarea',
    '#title' => t("Message"),
    '#default_value' => EMAILPAGE_MESSAGE,
    '#cols' => 40,
    '#rows' => 10,
    '#description' => t("The senders name will appear as the first word followed by the text in the textarea above.")
  );

  $form['emailpage']['emailpage_flood_error_msg'] = array(
    '#type' => 'textarea',
    '#title' => t("Flood Control Error Msg"),
    '#default_value' => variable_get('emailpage_flood_error_msg', t("Sorry, you have reached the maximum number of emails allowed per user. Please try later.")),
    '#cols' => 40,
    '#rows' => 10,
    '#description' => t("This text appears if a user tries to email a page but has exceeded the flood control limit.")
  );
  return $form;
}


?>