<?php /* -*- mode: php; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */

global $UTIL_DIR;

include_once($UTIL_DIR . "/mail.php");
include_once($UTIL_DIR . "/convert.php");

class Mailinglist extends _Mailinglist {
	private $file;
  public $unsubscribe_url;

	public function write()
	{
		$fp = fopen($this->file, "w");
		fwrite($fp, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");

		fwrite($fp, "<mailinglist subj_prefix=\"" . xmlenc($this->subj_prefix) . "\"\n");
    fwrite($fp, "             sender=\"" . xmlenc($this->sender) . "\"\n");
    fwrite($fp, "             replyto=\"" . xmlenc($this->replyto) . "\"\n");
    fwrite($fp, "             unsubscribe_url=\"" . xmlenc($this->unsubscribe_url) . "\">\n");
    fwrite($fp, "  <footer>" .  xmlenc($this->footer) . "</footer>\n");
		foreach($this->mailinglist as $email) {
			fwrite($fp, "  <email email=\"" . xmlenc($email->email) . "\"\n");
 			fwrite($fp, "         timestamp=\"" . xmlenc($email->timestamp) . "\">\n");
			fwrite($fp, "  </email>\n");
		}
		fwrite($fp, "</mailinglist>\n");

		fclose($fp);
	}
	
	private function read()
	{
		$dom = new DomDocument;
		$dom->preserveWhiteSpace = FALSE;
		$dom->load($this->file);

		$nl = $dom->documentElement;

    $this->subj_prefix = $nl->getAttribute('subj_prefix');
    $this->sender = $nl->getAttribute('sender');
    $this->replyto = $nl->getAttribute('replyto');
    $this->unsubscribe_url = $nl->getAttribute('unsubscribe_url');
    $footers = $dom->getElementsByTagName('footer');
    if($footers) {
      foreach($footers as $f) {
        $this->footer = $f->textContent;
      }
    }

		$params = $dom->getElementsByTagName('email');

		foreach ($params as $param) {
			$email = new Email($param->getAttribute('email'),
												 $param->getAttribute('timestamp'));
			$this->add($email);
		}
	}

	public function subscribe($emailaddr)
	{
		$str = "";
		if($emailaddr == "your@email.here") return "";
		$email = new EMail($emailaddr, time());
		if($this->add($email)) {
			$this->write();
			$str .= "<div class=\"newsletter_message\">The email: " .
        $emailaddr . " has now been subscribed.</div>";
		} else {
			$str .= "<div class=\"newsletter_message\">The email: " .
        $emailaddr . " is already subscribed.</div>";
		}
		return $str;
	}

	public function unsubscribe($emailaddr)
	{
		$str = "";
		if($this->remove($emailaddr)) {
			$this->write();
			$str .= "<div class=\"newsletter_message\">The email: " .
        $emailaddr . " has now been unsubscribed.</div>";
		} else {
			$str .= "<div class=\"newsletter_message\">The email: " .
        $emailaddr . " is not subscribed.</div>";
		}
		return $str;
	}

  /**
   * Overrides the postSingle method in the _Mailinglist class.
   */
	public function postSingle($email, $subject, $message)
	{
    $subject = "[".$this->subj_prefix."] " . $subject;

    $message .= "\n\n".$this->footer;
    $message .= "\n\nTo stop receiving this newsletter, click the following link: ".
      $this->unsubscribe_url."&action=unsubscribe&email=". $email->email . "\n";

    $email->send($subject, $message, $this->sender, $this->replyto);
  }

	public function Mailinglist($file)
	{
		$this->file =  $file;
		if(file_exists($file)) $this->read();
	}
}

class Newsletter {

  private $file;
  private $mailinglist;

  // Admin config
  public $admin_title = "Newsletter";
  public $admin_submodules = array("Send newsletter" => "send",
                                   "Config" => "config",
                                   "View list" => "view");

  public function admin_send($action, $vars)
	{
		global $UID, $ICONS_DIR;

		switch($action) {
		case "send":
      $this->mailinglist->post($vars["subject"], $vars["content"]);
			break;
			
		case "preview":
			$testmail = new Email($vars["testaddr"], 0);
			echo "<div class=\"preview\">\n";
			$this->mailinglist->postSingle($testmail, $vars["subject"], $vars["content"]);
			echo "A test mail has been sent to ".$vars["testaddr"]."</div>\n";
			echo "<p>Looking ok?</p>";
			$form = new Form("send");
			$form->addWidget(new Hidden($vars));
			$form->addWidget(new Button("yes"));
			$form->render();

			$form = new Form("retry");
			$form->addWidget(new Hidden($vars));
			$form->addWidget(new Button("no"));
			$form->render();
			break;
			
		case "retry":
			$testaddr = $vars["testaddr"];
			$subject = $vars["subject"];
			$content = $vars["content"];
		default:
			$form = new Form("preview");
			$form->addWidget(new LineEdit("Test address:", "testaddr", $testaddr));
			$form->addWidget(new LineEdit("Subject:", "subject", $subject));
			$form->addWidget(new TextEdit("Content:", "content", $content));
			$form->addWidget(new Button("Send"));
			$form->render();
			break;
		}
	}

  public function admin_config($action, $vars)
  {
    switch($action) {
    case "update":
      $this->mailinglist->subj_prefix = $vars["subj_prefix"];
      $this->mailinglist->sender = $vars["sender"];
      $this->mailinglist->replyto = $vars["replyto"];
      $this->mailinglist->footer = $vars["footer"];
      $this->mailinglist->unsubscribe_url = $vars["unsubscribe_url"];
			$this->mailinglist->write();
			break;
			
    default:
      $form = new Form("update");
      //http://www.executionroom.com/?page=news
      $form->addWidget(new LineEdit("Subject prefix:", "subj_prefix", $this->mailinglist->subj_prefix));
      $form->addWidget(new LineEdit("Sender:", "sender", $this->mailinglist->sender));
      $form->addWidget(new LineEdit("Reply to:", "replyto", $this->mailinglist->replyto));
      $form->addWidget(new TextEdit("Footer:", "footer", $this->mailinglist->footer));
      $form->addWidget(new LineEdit("Unsubscribe URL::", "unsubscribe_url", $this->mailinglist->unsubscribe_url));
      $form->addWidget(new Button("Update"));
      $form->render();
      break;
    }
  }

  public function admin_view($action, $vars)
  {
    switch($action) {
    default:
      echo "<p>There are " . sizeof($this->mailinglist->mailinglist) . " receivers:</p>\n";
      echo "<ul>\n";
      foreach($this->mailinglist->mailinglist as $m) {
        echo "  <li>".xmlenc($m->email)." (added ".date("M jS, Y - H:i:s", $m->timestamp).")</li>\n";
      }
      echo "</ul>\n";
      break;
    }
  }

  public function admin($sub, $action, $vars)
  {
    switch($sub) {
    case "send":
			$this->admin_send($action, $vars);
      break;

    case "config":
			$this->admin_config($action, $vars);
      break;

    case "view":
			$this->admin_view($action, $vars);
      break;
    }
  }

  public function run($params)
  {
		global $page;
		global $newsletter_action;
		global $_POST, $GLOBALS;
		$email = $_POST["newsletter_email"]; // get from lineedit.
		if($email == "") $email = $GLOBALS["newsletter_email"]; // get from link.

		$str = "";

		$str .= "<div class=\"newsletter\">\n";
		$str .= "  <form class=\"newsletter_form\" " .
			"action=\"?page=".$page."&amp;newsletter_action=subscribe\" " .
			"method=\"post\">\n";
		$str .= "    <div>\n";
		$str .= "      <input name=\"newsletter_email\" value=\"your@email.here\"/>\n";
		$str .= "      <button type=\"submit\">Subscribe</button>\n";
		$str .= "    </div>\n";
		$str .= "  </form>\n";
		$str .= "</div>\n";

		if($newsletter_action == "subscribe") {
			$str .= $this->mailinglist->subscribe($email);
		}

		if($newsletter_action == "unsubscribe") {
			$str .= $this->mailinglist->unsubscribe($email);
		}

		return $str;
  }

  private function read()
  {
		$this->mailinglist = new Mailinglist($this->file);
  }

  public function Newsletter($file)
  {
    $this->file =  $file;
    if(file_exists($file)) $this->read();
  }
}


function newsletter_init()
{
  global $DATA_DIR;
  return new Newsletter($DATA_DIR . "/newsletter.xml");
}

?>