<?php

/**
 *
 * INDEXU
 * Copyright(C), Nicecoder, 2000-2006, All Rights Reserved.
 *
 * INDEXU(tm) is protected by Indonesia and International copyright laws.
 * Unauthorized use or distribution of INDEXU(tm) is strictly prohibited,
 * violators will be prosecuted. To obtain a license for using INDEXU(tm),
 * please register at Nicecoder home page at http://www.nicecoder.com
 *
 * Author:
 *    Dody Rachmat Wicaksono (dody@nicecoder.com)
 *    M. Zuber (zubby@nicecoder.com)
 *
 */

  class clsMailingList {

    var $table_name         = "mailing_list";
    var $message_table_name = "message";
    var $query              = "";
    var $date_format        = "d-M-Y";
    var $max_rows           = "";
    var $header             = "";
    var $paging             = false;
    var $pg_size            = "10";
    var $href               = "";
    var $more_param         = "";
    var $template_file      = "";
    var $code;
    var $email_from         = "";

    // output only
    var $pagination;
    var $num_rows;

    // internal use only


    // method to get fields name
    // return :   array of field name
    // ------------------------------

    function GetFields() {
      global $dbConn;

      // get link fields information
      $query      = "select * from $this->table_name where username = ''";
      $result     = $dbConn->Execute($query);
      $num_fields = $result->FieldCount();

      if ($result) {
        $i = 0;

        while ($i < $num_fields) {
          $fld      = $result->FetchField($i);
          $fields[] = $fld->name;
          $i++;
        }
      }

      // return array
      return $fields;
    }


    // method to handle subscription
    // input :    $email = email address
    //            $confirm = email address confirmation
    // return :   0: success
    //            1  pending
    //            2: email address already exist
    // set : var code
    // ------------------------------------------------

    function Subscribe($email, $confirm = false) {
      global $dbConn;

      // is already exist?
      $query  = "select email from $this->table_name where status=1 and email = '$email'";
      $result = $dbConn->Execute($query);

      if ($result->RecordCount() > 0)
        return 2;
      else {
        if (!$confirm) {
          $query  = "insert into $this->table_name (email,code,status) values
          ('$email','',1)";
          $result = $dbConn->Execute($query);

          return 0;
        }
        else {

          // generate code
          mt_srand((double)microtime() * 1000000);
          $code       = mt_rand();
          $code       = substr($code, -4, 4);
          $this->code = $code;

          $query      = "insert into $this->table_name (email,code,status) values
          ('$email','$code',0)";
          $result     = $dbConn->Execute($query);

          return 1;
        }
      }
    }


    // method to handle unsubscription
    // input :    $email = email address
    // return :   0: success
    //            1: email address does not exist
    // ------------------------------------------

    function Unsubscribe($email) {
      global $dbConn;

      // is already exist?
      $query  = "select email from $this->table_name where status=1 and email = '$email'";
      $result = $dbConn->Execute($query);

      if ($result->RecordCount() == 0)
        return 1;
      else {
        $query  = "delete from $this->table_name where status=1 and email = '$email'";
        $result = $dbConn->Execute($query);

        return 0;
      }
    }


    // method to handle unsubscription
    // input :    $email = email address
    //            $code = validation code
    // return :   0: success
    //            1: invalid code
    // ------------------------------------------

    function Confirm($email, $code) {
      global $dbConn;

      // is exist?
      $query  = "select email from $this->table_name where status=0 and email = '$email' and code = '$code'";
      $result = $dbConn->Execute($query);

      if ($result) {
        if ($result->RecordCount() == 0)
          return 1;
        else {
          $query  = "update $this->table_name set status = 1 where code = '$code' and email = '$email'";
          $result = $dbConn->Execute($query);

          $query  = "delete from $this->table_name where status=0 and email = '$email'";
          $result = $dbConn->Execute($query);

          return 0;
        }
      }
      else
        return 1;
    }


    // method to create new message
    // input :    $subject = message subject
    //            $body = message subject
    // return :   0: success
    //            1: sql error
    // ------------------------------------------

    function CreateMessage($subject, $body) {
      global $dbConn;

      $query  = "insert into $this->message_table_name 
                 (subject,body,date) values 
                 ('$subject','$body', now())";
      $result = $dbConn->Execute($query);

      if ($result)
        return 0;
      else
        return 1;
    }


    // method to view message
    // return :   html
    // ------------------------------------------

    function ViewMessage() {
      global $dbConn, $admin_template_path;

      $msg_icon = "../admin_tpl/images/message.gif";
      $msg_icon = "<img src=$msg_icon border=0> ";

      $tpl    = new Template();

      $query  = "select date, message_id, subject from $this->message_table_name
                 order by subject";
      $result = $dbConn->Execute($query);
      $total  = $result->RecordCount();

      $i        = 0;

      while (!$result->EOF) {
        $subject    = $result->Fields("subject");
        $message_id = $result->Fields("message_id");
        $date       = $result->Fields("date");
        $date       = date($this->date_format, @strtotime($date));

        $tpl->assign('subject', $subject);
        $tpl->assign('message_id', $message_id);
        $tpl->assign('date', $date);

        if ($i % 2)
          $tbl_class = "tbl_light";
        else
          $tbl_class = "tbl_light2";

        $tpl->assign('tbl_class', $tbl_class);
        $tpl->assign('msg_icon', $msg_icon);
        $line .= $tpl->fetch($this->template_file);

        $i++;
        $result->MoveNext();
      }

      return $line;
    }


    // method to view subscriber
    // return :   html
    // set : $this->num_rows
    // ------------------------------------------

    function ViewSubscriber() {
      global $dbConn, $admin_template_path;

      $user_icon      = "../admin_tpl/images/people.gif";
      $user_icon      = "<img src=$user_icon border=0> ";

      $tpl            = new Template();

      $query          = "select email from $this->table_name
                         where status = 1";
      $result         = $dbConn->Execute($query);
      $total          = $result->RecordCount();
      $this->num_rows = $total;

      $i              = 0;

      while (!$result->EOF) {
        $email = $result->Fields("email");
        $tpl->assign('email', $email);

        if ($i % 2)
          $tbl_class = "tbl_light";
        else
          $tbl_class = "tbl_light2";

        $tpl->assign('tbl_class', $tbl_class);
        $tpl->assign('user_icon', $user_icon);

        $line .= $tpl->fetch($this->template_file);

        $i++;
        $result->MoveNext();
      }

      return $line;
    }


    // method to edit message
    // input :    $message_id
    //            $status : "display_form"
    //                      "process_form"
    //            $subject
    //            $body
    // return :   0: success
    //            1: sql error
    // ------------------------------------------

    function EditMessage($status, $message_id, $subject = "", $body = "") {
      global $dbConn;

      $tpl = new Template();

      if ($status == 'display_form') {
        $query   = "select * from $this->message_table_name where message_id = '$message_id'";
        $result  = $dbConn->Execute($query);
        $subject = $result->Fields("subject");
        $body    = $result->Fields("body");

        $tpl->assign('message_id', $message_id);
        $tpl->assign('subject', $subject);
        $tpl->assign('body', $body);

        $line .= $tpl->fetch($this->template_file);

        return $line;
      }
      elseif ($status == 'process_form') {
        $query  = "update $this->message_table_name 
                   set subject = '$subject',
                       body = '$body',
                       date = now()
                   where message_id = $message_id";
        $result = $dbConn->Execute($query);

        if ($result)
          return 0;
        else
          return 1;
      }
    }


    // method to delete message
    // input :    $message_id
    // return :   0: success
    //            1: sql error
    // ------------------------------------------

    function DeleteMessage($message_id) {
      global $dbConn;
      $query  = "delete from $this->message_table_name where message_id = $message_id";
      $result = $dbConn->Execute($query);

      if ($result)
        return 0;
      else
        return 1;
    }


    // method to send message
    // input :    $message_id
    //            $status : "confirm_form"
    //                      "process_form"
    // return :   0: success
    //            1: sql error
    // ------------------------------------------

    function SendMessage($status, $message_id, $emails = array(), $type = "", $test_only = FALSE) {
      global $dbConn, $base_path, $category_separator;

      $tpl     = new Template();

      $query   = "select * from $this->message_table_name where message_id = '$message_id'";
      $result  = $dbConn->Execute($query);
      $subject = $result->Fields("subject");
      $body    = $result->Fields("body");

      if ($status == 'confirm_form') {
        include_once $base_path . "key.php";
        $tpl->assign('message_id', $message_id);
        $tpl->assign('subject', $subject);
        $tpl->assign('body', str_replace(array('<%', '%>'), array('&lt;%', '%&gt;'), $body));
        $tpl->assign('hash', '');
        $line .= $tpl->fetch($this->template_file);
        return $line;
      }
      elseif ($status == 'process_form') {
        if (strpos($type, "webmaster") !== FALSE) {
          $links_obj = new clsLink;
          $links_obj->table_name = "idx_link";
          $fields = $links_obj->GetFields();

          $category_obj = new clsCategory;
          $category_obj->table_name = "idx_category";
          $category_obj->separator = $category_separator;
        }
        if (strpos($type, "registered_user") !== FALSE || strpos($type, "editor") !== FALSE) {
          $users_obj = new clsUsers;
          $users_obj->table_name = "idx_users";
          $fields = $users_obj->GetFields();
        }

        $recipient_list = "";
        $i = 0;
        while (list(, $v) = @each($emails)) {
          if (trim($v)) {
            $i++;
            $from = $this->email_from;
            if (strpos($type, "webmaster") !== FALSE) {
              list($email, $link_id) = explode("|", $v);
              $row = $dbConn->FetchOne("select * from idx_link where link_id = '$link_id'");
              $tpl = new Template;
              while (list($k, $v) = @each($fields)) {
                $tpl->assign($v, $row[$v]);
              }
              $more_info = "($row[url])";
              $tpl->assign("category", $category_obj->GetCategoryPath($row["category_id"]));
              $mail_body = $tpl->fetch('var:' . $body);
              unset($tpl);
              @reset($fields);
            }
            elseif (strpos($type, "registered_user") !== FALSE || strpos($type, "editor") !== FALSE) {
              list($email, $username) = explode("|", $v);
              $row = $dbConn->FetchOne("select * from idx_users where username = '$username'");
              $tpl = new Template;
              while (list($k, $v) = @each($fields)) {
                $tpl->assign($v, $row[$v]);
              }
              $more_info = "($username)";
              $mail_body = $tpl->fetch('var:' . $body);
              unset($tpl);
              @reset($fields);
            }
            elseif (strpos($type, "mailing_list_subscriber") !== FALSE) {
              $email = $v;
              $tpl = new Template;
              $tpl->assign("email", $email);
              $mail_body = $tpl->fetch('var:' . $body);
              unset($tpl);
            }
            elseif (strpos($type, "all") !== FALSE) {
              $email = $v;
              $tpl = new Template;
              $mail_body = $tpl->fetch('var:' . $body);
              unset($tpl);
            }
            if (!$test_only) {
              @mail($email, $subject, $mail_body, "From: $from \nX-Mailer: INDEXU_X-Mailer/1.0");
            }
            $recipient_list .= "$i. $email $more_info<br>";
          }
        }
        return $recipient_list;
      }
    }


    // method to get all subscriber
    // return :   array
    // ------------------------------------------

    function GetAllSubscriber($query_filter = "") {
      global $dbConn;
      $query          = "select email from $this->table_name
                         where status = 1
                               $query_filter";
      $result         = $dbConn->Execute($query);
      $total          = $result->RecordCount();
      $this->num_rows = $total;

      while (!$result->EOF) {
        $emails[] = $result->Fields("email");
        $result->MoveNext();
      }

      return $emails;
    }


    // method to delete subscriber
    // input :    $message_id
    // return :   0: success
    //            1: sql error
    // ------------------------------------------

    function DeleteSubscriber($email) {
      global $dbConn;
      $query  = "delete from $this->table_name where email = '$email' and status = 1";
      $result = $dbConn->Execute($query);

      if ($result)
        return 0;
      else
        return 1;
    }
  }
?>
