<?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)
 *
 */

  /*===================================================
    ShowFormEditLink()
  ===================================================*/

  function ShowFormEditLink() {

    // vars global configuration
    global $dbConn, $category_separator, $admin_template_path, $no_image_file;

    // vars url & form
    global $id;

    // vars messages
    global $msg;

    // vars template
    global $has_next, $has_prev;

    $tpl = new Template();

    if ($dbConn->Lookup('count(*)', 'idx_link_temp', "vid > '$id'")) {
      $tpl->assign('has_next', 1);
    }
    if ($dbConn->Lookup('count(*)', 'idx_link_temp', "vid < '$id'")) {
      $tpl->assign('has_prev', 1);
    }

    $links_obj = new clsLink;
    $links_obj->table_name = "idx_link_temp";    // temp table
    $links_obj->category_table_name = "idx_category";
    $links_obj->custom_field_offset++;


    $category_obj = new clsCategory;
    $category_obj->table_name = "idx_category";
    $category_obj->separator = $category_separator;


    $fields = $links_obj->GetFields();

    $i = 0;
    $count_fields = @count($fields);
    while ($i < $count_fields) {
      $field = $fields[$i];
      global $$field;
      $i++;
    }

    // get values
    $query = "select * from idx_link_temp where vid = '$id'";
    $result = $dbConn->Execute($query);

    // generate custom field
    $links_obj->autogenerate_form_text            = $msg["30001"];
    $links_obj->autogenerate_form_textarea        = $msg["30002"];
    $links_obj->autogenerate_form_image           = $msg["30004"];
    $links_obj->autogenerate_form_file            = $msg["30006"];
    $links_obj->autogenerate_form_select          = $msg["30007"];
    $links_obj->autogenerate_form_multiselect     = $msg["30008"];
    $links_obj->autogenerate_form_checkbox        = $msg["30009"];
    $links_obj->autogenerate_form_radio           = $msg["30010"];
    $links_obj->autogenerate_form_date            = $msg["30011"];
    $links_obj->autogenerate_form_datetime        = $msg["30012"];
    $links_obj->autogenerate_form_template        = $admin_template_path . "link_custom_field_form.html";
    $links_obj->template_file                     = $admin_template_path . "link_validate_edit_form.html";
    $links_obj->header                            = $msg["20061"];

    // fetch
    $i = 0;
    $count_fields = @count($fields);
    while ($i < $count_fields) {
      $$fields[$i] = htmlspecialchars($result->Fields("$fields[$i]"));
      if($links_obj->fields_type[$i]=="IMAGE")
        if($$fields[$i]=="")
          $$fields[$i] = $no_image_file;

      $tpl->assign($fields[$i], $$fields[$i]);
      $i++;
    }

    global $category;
    $category = $category_obj->DisplayCategoryListBox($category_id,0,1);
    $tpl->assign('category', $category);
    $tpl->assign('error_msg', $error_msg);

    $add_cat1 = str_replace("<select name=\"cat\">","<select name=\"add_cat1\">",$category_obj->DisplayCategoryListBox($cat1,0,1));
    $add_cat1 = str_replace("<option value=\"\">","<option value=\"0\">",$add_cat1);
    $add_cat1 = str_replace("Main Category","",$add_cat1);
    $add_cat2 = str_replace("<select name=\"cat\">","<select name=\"add_cat2\">",$category_obj->DisplayCategoryListBox($cat2,0,1));
    $add_cat2 = str_replace("<option value=\"\">","<option value=\"0\">",$add_cat2);
    $add_cat2 = str_replace("Main Category","",$add_cat2);
    $tpl->assign('add_cat1', $add_cat1);
    $tpl->assign('add_cat2', $add_cat2);

    $custom_field_form = $links_obj->GenerateCustomFieldForm();
    if(!empty($custom_field_form)) $custom_field_form = $links_obj->header . $custom_field_form;
    $tpl->assign('custom_field_form', $custom_field_form);
    $line = $tpl->fetch($links_obj->template_file);

    print $line;
  }


  /*===================================================
    ProcessFormEditLink()
  ===================================================*/

  function ProcessFormEditLink() {

    // vars global configuration
    global $dbConn, $category_separator, $admin_template_path;

    global $allowed_file_extension, $base_path;
    $folder = 'upload_files';

    // vars url & form
    global $id, $title, $url, $description, $cat, $contact_name, $email, $bid,
      $password, $add_cat1, $add_cat2, $reciprocal_url;

    // vars messages
    global $msg;

    // vars template
    global $message;

    // verify input

    if(empty($title)) $error_msg = $msg["20071"];
    elseif(empty($url)) $error_msg = $msg["20072"];
    elseif(empty($cat)) $error_msg = $msg["20073"];
    elseif (!empty($email) && !IsEmailAddress($email)) $error_msg = $msg["20074"];
    elseif (!empty($bid) && !IsMoney($bid)) $error_msg = $msg["20075"];


    if(empty($error_msg)) {

      $links_obj = new clsLink;
      $links_obj->table_name = "idx_link_temp";
      $links_obj->category_table_name = "idx_category";
      $links_obj->custom_field_offset++;

      $fields = $links_obj->GetFields();

      $i = 0;
      $count_fields = @count($fields);
      while ($i < $count_fields) {
        $field = $fields[$i];
        global $$field;
        $i++;
      }

      $sql_old = "select * from $links_obj->table_name where vid = '$id'";
      $result_old = $dbConn->Execute($sql_old);

      // build query

      $query = "update $links_obj->table_name set ";

      $i = 1;
      $count_fields = @count($fields);
      while ($i < $count_fields) {
        $field = $fields[$i];
        $old[$field] = $result_old->Fields($field);
        global $$field;

        if($links_obj->fields_type[$i]=="IMAGE" || $links_obj->fields_type[$i]=="FILE") {
          if ($links_obj->fields_file_extension[$i]) {
            $allowed_file_extensionx = explode(",", $links_obj->fields_file_extension[$i]);
          }
          else {
            $allowed_file_extensionx = explode(",", $allowed_file_extension);
          }
          if(!empty($_FILES[$field]['name'])) {
            // get file extension
            $temp = explode(".",$_FILES[$field]['name']);
            $last = count($temp)-1;
            $file_ext = $temp[$last];
            $field_name = $field;

            $file_obj['src'] = $_FILES[$field]['tmp_name'];
            $file_obj['dst'] = $base_path . $folder. "/". $field ."_ID.". $file_ext;
            $file_queue[$field] = $file_obj;
          }
        }

        if($field != "link_id" && $field != "hits" && $field != "votes" && $field != "rating" &&
          $field != "hot" && $field != "new" && $field != "pick" && $field != "top_rated" &&
          $field != "updated" && $field != "date" && $field != "password" &&
          $field != "avg_review" && $field != "reviews" && $field!='last_updated') {

          if($field=='category_id') $value = "$cat";
          else $value = $$field;

          if($field=='cat1') $value = "$add_cat1";
          if($field=='cat2') $value = "$add_cat2";

          if($field=='last_updated')
            $query .= "$field = $value, ";
          elseif($links_obj->fields_type[$i]=="IMAGE" || $links_obj->fields_type[$i]=="FILE") {
            $file_del = "{$field}_del";
            global $$file_del;
            if ($$file_del) {
              $query .= "$field = '', ";
              @unlink("{$base_path}$old[$field]");
            }
            else {
              if ($file_queue[$field]) {
                @unlink("{$base_path}$old[$field]");
                $v = $file_queue[$field];
                $k = $field;
                $v['dst'] = str_replace('ID', 'temp'.$id, $v['dst']);
                if (@copy($v['src'],$v['dst'])) {
                  $relatif_path = $folder. "/". $k ."_temp". $id .".". $file_ext;
                  $query .= "$k = '$relatif_path', ";
                }
              }
              else {
                $query .= "$field = '$old[$field]', ";
              }
            }
          }
          else {
            if (!is_array($value)) {
              $query .= "$field = '$value', ";
            }
            else {
              $query .= "$field = '".@implode(',', $value)."', ";
            }
          }
        }

        $i++;
      }

      $query = substr($query, 0, strlen($query)-2); // delete last ', '

      $query .= " where vid = '$id'";
      $result = $dbConn->Execute($query);

      $message = $msg["20101"];
    }
    else $message = $error_msg;

    DisplayTemplate($admin_template_path . "message.html", "\$message");

  }


  /*===================================================
    ProcessFormEditApproveLink()
  ===================================================*/

  function ProcessFormEditApproveLink() {

    // vars global configuration
    global $dbConn, $category_separator, $admin_template_path, $email_address,
             $theme_path, $active_theme;

    global $allowed_file_extension, $base_path;
    $folder = 'upload_files';

    // vars url & form
    global $id, $title, $url, $description, $cat, $contact_name, $email, $bid,
      $password, $add_cat1, $add_cat2, $reciprocal_url;

    // vars messages
    global $msg;

    // vars template
    global $message, $back;

    // verify input

    if(empty($title)) $error_msg = $msg["20071"];
    elseif(empty($url)) $error_msg = $msg["20072"];
    elseif(empty($cat)) $error_msg = $msg["20073"];
    elseif (!empty($email) && !IsEmailAddress($email)) $error_msg = $msg["20074"];
    elseif (!empty($bid) && !IsMoney($bid)) $error_msg = $msg["20075"];


    if(empty($error_msg)) {

      $links_obj = new clsLink;
      $links_obj->table_name = "idx_link_temp";
      $links_obj->category_table_name = "idx_category";
      $links_obj->custom_field_offset++;

      $fields = $links_obj->GetFields();

      $i = 0;
      $count_fields = @count($fields);
      while ($i < $count_fields) {
        $field = $fields[$i];
        global $$field;
        $i++;
      }

      $sql_old = "select * from $links_obj->table_name where vid = '$id'";
      $result_old = $dbConn->Execute($sql_old);

      // build query

      $query = "update $links_obj->table_name set ";

      $i = 1;
      $count_fields = @count($fields);
      while ($i < $count_fields) {
        $field = $fields[$i];
        $old[$field] = $result_old->Fields($field);
        global $$field;

        if($links_obj->fields_type[$i]=="IMAGE" || $links_obj->fields_type[$i]=="FILE") {
          if ($links_obj->fields_file_extension[$i]) {
            $allowed_file_extensionx = explode(",", $links_obj->fields_file_extension[$i]);
          }
          else {
            $allowed_file_extensionx = explode(",", $allowed_file_extension);
          }
          if(!empty($_FILES[$field]['name'])) {
            // get file extension
            $temp = explode(".",$_FILES[$field]['name']);
            $last = count($temp)-1;
            $file_ext = $temp[$last];
            $field_name = $field;

            $file_obj['src'] = $_FILES[$field]['tmp_name'];
            $file_obj['dst'] = $base_path . $folder. "/". $field ."_ID.". $file_ext;
            $file_queue[$field] = $file_obj;
          }
        }

        if($field != "link_id" && $field != "hits" && $field != "votes" && $field != "rating" &&
          $field != "hot" && $field != "new" && $field != "pick" && $field != "top_rated" &&
          $field != "updated" && $field != "date" && $field != "password" &&
          $field != "avg_review" && $field != "reviews" && $field!='last_updated') {

          if($field=='category_id') $value = "$cat";
          else $value = $$field;

          if($field=='cat1') $value = "$add_cat1";
          if($field=='cat2') $value = "$add_cat2";

          if($field=='last_updated')
            $query .= "$field = $value, ";
          elseif($links_obj->fields_type[$i]=="IMAGE" || $links_obj->fields_type[$i]=="FILE") {
            $file_del = "{$field}_del";
            global $$file_del;
            if ($$file_del) {
              $query .= "$field = '', ";
              @unlink("{$base_path}$old[$field]");
            }
            else {
              if ($file_queue[$field]) {
                @unlink("{$base_path}$old[$field]");
                $v = $file_queue[$field];
                $k = $field;
                $v['dst'] = str_replace('ID', 'temp'.$id, $v['dst']);
                if (@copy($v['src'],$v['dst'])) {
                  $relatif_path = $folder. "/". $k ."_temp". $id .".". $file_ext;
                  $query .= "$k = '$relatif_path', ";
                }
              }
              else {
                $query .= "$field = '$old[$field]', ";
              }
            }
          }
          else {
            if (!is_array($value)) {
              $query .= "$field = '$value', ";
            }
            else {
              $query .= "$field = '".@implode(',', $value)."', ";
            }
          }
        }

        $i++;
      }

      $query = substr($query, 0, strlen($query)-2); // delete last ', '

      $query .= " where vid = '$id'";
      $result = $dbConn->Execute($query);

      // approve link

      $tpl = new Template();

      $theme_path = $theme_path . $active_theme;

      $links_obj = new clsLink;
      $links_obj->table_name = "idx_link";
      $links_obj->category_table_name = "idx_category";
      $links_obj->editor_table_name = "idx_editor";
      $links_obj->user_table_name = "idx_users";

      $category_obj = new clsCategory;
      $category_obj->table_name = "idx_category";
      $category_obj->user_table_name = "idx_users";

      $query = "select link_id, title from idx_link_temp where vid = '$id'";
      $result = $dbConn->Execute($query);
      $lid = $result->Fields("link_id");
      $title = $result->Fields("title");

      if(empty($lid)) $flag = 0;
      else $flag = 1;

      $links_obj->ApproveLink($id,$flag);
      $mark=1;

      $message .= $msg["20121"];
      $tpl->assign('title', $title);
      $message = $tpl->fetch('var:' . $message);

      // update new flag
      if($flag==0) $links_obj->UpdateNewFlag();

      // update updated flag
      elseif($flag==1) $links_obj->UpdateUpdatedFlag();

      // send email submitter
      $body = EvalTemplate($theme_path . "/mail/approved.mail", $links_obj->email_template_fields);
      $from = $email_address;
      mail($email, $msg["20131"], $body, "From: $from \nX-Mailer: INDEXU_X-Mailer/1.0");

      // send email to all editors
      $emails = $links_obj->GetEditorEmail($category_id);
      $j = 0;
      $count_emails = @count($emails);
      while ($j < $count_emails) {
        $body = EvalTemplate($theme_path . "/mail/approved_editor.mail", $links_obj->email_template_fields);
        $from = $email_address;
        mail($emails[$j], $msg["20133"], $body, "From: $from \nX-Mailer: INDEXU_X-Mailer/1.0");
        $j++;
      }

      // send email to all subscriber
      $subscribe_emails = $category_obj->GetSubscriberEmail($category_id);
      $j = 0;
      $count_subscribe_emails = @count($subscribe_emails);
      while ($j < $count_subscribe_emails) {
        $body = EvalTemplate($theme_path . "/mail/approved_subscriber.mail", $links_obj->email_template_fields);
        $from = $email_address;
        mail($subscribe_emails[$j], $msg["20133"], $body, "From: $from \nX-Mailer: INDEXU_X-Mailer/1.0");
        $j++;
      }

      $message = $msg["30015"];

      $back = "<a href=link_validate.php>Back</a>";

    }
    else $message = $error_msg;

    DisplayTemplate($admin_template_path . "message.html", "\$message,\$back");
  }


  /*===================================================
    ShowFormPrevEditLink()
  ===================================================*/

  function ShowFormPrevEditLink() {

    // vars global configuration
    global $dbConn;

    // vars url & form
    global $id;

    // vars messages
    global $msg;

    // vars template

    $query = "select vid from idx_link_temp
              where vid < '$id'
              order by vid desc
              limit 1";
    $result = $dbConn->Execute($query);
    $vid = $result->Fields("vid");

    Redirect("link_validate_edit.php?id=$vid");
  }


  /*===================================================
    ShowFormNextEditLink()
  ===================================================*/

  function ShowFormNextEditLink() {

    // vars global configuration
    global $dbConn;

    // vars url & form
    global $id;

    // vars messages
    global $msg;

    // vars template
    
    $query = "select vid from idx_link_temp
              where vid > '$id'
              order by vid asc
              limit 1";
    $result = $dbConn->Execute($query);
    $vid = $result->Fields("vid");
    
    Redirect("link_validate_edit.php?id=$vid");
  }


  /*===================================================
    main
  ===================================================*/

  include "../application.php";

  RunPreFilter(__FILE__);

  if (empty($pflag)) {
    DisplayTemplate($admin_template_path . "header.html");
    ShowFormEditLink();
  }
  elseif ($pflag == 'edit') {
    DisplayTemplate($admin_template_path . "header.html");
    ProcessFormEditLink();
  }
  elseif ($pflag == 'editapprove') {
    DisplayTemplate($admin_template_path . "header.html");
    ProcessFormEditApproveLink();
  }
  elseif ($pflag == 'prev') {
    ShowFormPrevEditLink();
  }
  elseif ($pflag == 'next') {
    ShowFormNextEditLink();
  }
  DisplayTemplate($admin_template_path . "footer.html");

  RunPostFilter(__FILE__);

?>