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

  /*===================================================
    ShowFormAddUrl()
  ===================================================*/

  function ShowFormAddUrl() {

    // vars global configuration
    global $dbConn, $category_separator, $theme_path, $paid_link_day_period, 
             $paid_link_price_factor;

    // vars url & form
    global $cat;

    // vars messages
    global $msg;

    // vars template
    global $error_msg, $title, $url, $description, $category, $contact_name, 
             $email, $add_cat1, $add_cat2, $keywords, $reciprocal_url, 
             $custom_field_form, $sponsored_listing_period, 
             $premium_listing_period, $basic_listing_price, 
             $available_payment_systems, $periodprice, $currency_symbol,
             $logged_in;

    $title = $_POST['title'];

    if (empty($cat)) {
      DisplayTemplate($theme_path . "add_error.html");
    }
    else {
      if (empty($url))
        $url = "http://";

      // get category path
      $category_obj = new clsCategory;
      $category_obj->table_name      = "idx_category";
      $category_obj->link_table_name = "idx_link";
      $category_obj->separator       = $category_separator;
      $category                      = $category_obj->GetCategoryPath($cat);
      $category                     .= "\n<input type=\"hidden\" name=\"cat\" value=\"$cat\" />";

      // additional category
      $add_cat1     = (!$add_cat1) ? -1 : $add_cat1;
      $add_cat1     = str_replace("<select name=\"cat\">", "<select name=\"add_cat1\">",
                                  $category_obj->DisplayCategoryListBox($add_cat1));
      $add_cat1     = str_replace("<option value=\"\">", "<option value=\"0\">", $add_cat1);
      $add_cat2     = (!$add_cat2) ? -1 : $add_cat2;
      $add_cat2     = str_replace("<select name=\"cat\">", "<select name=\"add_cat2\">",
                                  $category_obj->DisplayCategoryListBox($add_cat2));
      $add_cat2     = str_replace("<option value=\"\">", "<option value=\"0\">", $add_cat2);

      $title          = htmlspecialchars(stripslashes($title));
      $url            = htmlspecialchars(stripslashes($url));
      $description    = htmlspecialchars(stripslashes($description));
      $contact_name   = htmlspecialchars(stripslashes($contact_name));
      $email          = htmlspecialchars(stripslashes($email));
      $keywords       = htmlspecialchars(stripslashes($keywords));
      $reciprocal_url = htmlspecialchars(stripslashes($reciprocal_url));

      // generate custom field
      $links_obj                                    = new clsLink;
      $links_obj->table_name                        = "idx_link";
      $links_obj->category_table_name               = "idx_category";
      $links_obj->autogenerate_form_text            = $msg["00001"];
      $links_obj->autogenerate_form_textarea        = $msg["00002"];
      $links_obj->autogenerate_form_image_add       = $msg["00005"];
      $links_obj->autogenerate_form_file_add        = $msg["00005"];
      $links_obj->autogenerate_form_select          = $msg["00007"];
      $links_obj->autogenerate_form_multiselect     = $msg["00008"];
      $links_obj->autogenerate_form_checkbox        = $msg["00009"];
      $links_obj->autogenerate_form_radio           = $msg["00010"];
      $links_obj->autogenerate_form_date            = $msg["00011"];
      $links_obj->autogenerate_form_datetime        = $msg["00012"];
      $links_obj->autogenerate_form_template        = $theme_path . "custom_field_form_rows.html";

      // make globals for custom fields data
      $fields                                       = $links_obj->GetFields();

      $i                                            = 30; // custom field start offset
      
      $count_fields = @count($fields);
      while ($i < $count_fields) {
        $field  = $fields[$i];
        global $$field;
        if (!is_array($$field)) {
          $$field = htmlspecialchars(stripslashes($$field));
        }
        $custf .= ",\$$field";
        $i++;
      }

      $custom_field_form                            = $links_obj->GenerateCustomFieldForm(true);

      // get payment system
      $query    = "select sponsored_price, premium_price, basic_price 
                   from idx_category where category_id = '$cat'";
      $result   = $dbConn->Execute($query);
      $sponsored_price = $result->Fields("sponsored_price");
      $premium_price   = $result->Fields("premium_price");
      $basic_price     = $result->Fields("basic_price");

      // period and price factor
      $period       = @explode(',', $paid_link_day_period);
      $price_factor = @explode(',', $paid_link_price_factor);
      $i = 0;
      
      while (list($k, $v) = @each($period)) {
        if ($k == 0) {
          $default_day = $v;
        }
        if ($sponsored_price) {
          $price_no_disc                          = ($v / $default_day) * $sponsored_price;
          $sponsored_listing_period[$k]['period'] = $v;
          $sponsored_listing_period[$k]['price']  = $price_factor[$k] * $sponsored_price;
          $sponsored_listing_period[$k]['disc']   = sprintf("%01.2f", ($price_no_disc - $sponsored_listing_period[$k]['price']) / $price_no_disc * 100);
          $sponsored_listing_period[$k]['save']   = $price_no_disc - $sponsored_listing_period[$k]['price'];
          if ($periodprice == "SPONSORED|$v|{$sponsored_listing_period[$k][price]}") {
            $sponsored_listing_period[$k]['selected']  = 'selected="selected"';
          }
        }

        if ($premium_price) {
          $price_no_disc                          = ($v / $default_day) * $premium_price;
          $premium_listing_period[$k]['period']   = $v;
          $premium_listing_period[$k]['price']    = $price_factor[$k] * $premium_price;
          $premium_listing_period[$k]['disc']     = sprintf("%01.2f", ($price_no_disc - $premium_listing_period[$k]['price']) / $price_no_disc * 100);
          $premium_listing_period[$k]['save']     = $price_no_disc - $premium_listing_period[$k]['price'];
          if ($periodprice == "PREMIUM|$v|{$premium_listing_period[$k][price]}") {
            $premium_listing_period[$k]['selected']  = 'selected="selected"';
          }
        }
        $i++;
      }

      $basic_listing_price = $basic_price;

      $currency_symbol = $dbConn->Lookup("currency_symbol", "idx_invoice_config", "0 = 0");
      $available_payment_systems = GetPaymentSystems();
      
      DisplayTemplate($theme_path . "add_form.html",
                      "\$error_msg,\$title,\$url,\$description,\$category,\$contact_name,\$email,\$add_cat1,\$add_cat2,\$keywords,\$reciprocal_url,\$custom_field_form,\$sponsored_listing_period,\$premium_listing_period,\$basic_listing_price,\$currency_symbol,\$available_payment_systems"
                        . $custf);
    }
  }


  /*===================================================
    ProcessFormAddUrl()
  ===================================================*/

  function ProcessFormAddUrl() {

    // vars global configuration
    global $dbConn, $site_url, $theme_path, $category_separator, $new_limit, $email_address;

    // vars url & form
    global $cat;

    // vars messages
    global $msg;

    // vars template
    global $error_msg, $password, $link_id, $title, $url, $description, $contact_name, $email, $bid, $category,
             $add_cat1, $add_cat2, $keywords, $reciprocal_url, $reciprocal_check, 
             $periodprice, $gateway;

    $title = $_POST['title'];

    // verify input

    if (empty($_POST['captcha_key']) || empty($_SESSION['captcha_key']))
      $error_msg = $msg["10120"];
    elseif ($_POST['captcha_key'] != $_SESSION['captcha_key'])
      $error_msg = $msg["10120"];
    elseif (empty($title))
      $error_msg = $msg["10101"];
    elseif (empty($url) || $url == 'http://')
      $error_msg = $msg["10102"];
    elseif (empty($description))
      $error_msg = $msg["10103"];
    elseif (empty($contact_name))
      $error_msg = $msg["10104"];
    elseif (empty($email))
      $error_msg = $msg["10105"];
    elseif (!IsEmailAddress($email))
      $error_msg = $msg["10106"];
    elseif (!empty($bid) && !Ismoney($bid))
      $error_msg = $msg["10107"];
    elseif ($cat == $add_cat1 || $cat == $add_cat2)
      $error_msg = $msg['10118'];
    elseif (!empty($add_cat1) && !empty($add_cat2) && $add_cat1 == $add_cat2)
      $error_msg = $msg['10118'];
    elseif ($reciprocal_check) {
      if (!IsValidReciprocalURL($url, $reciprocal_url)) {
        $error_msg = $msg['10119'];
      }
    }


    if (empty($error_msg)) {
      
      // clear captcha key to prevent repetitive submission
      $_SESSION['captcha_key'] = "";

      list($listing_type, $listing_period, $listing_price) = @explode('|', $periodprice);

      // get field
      $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";
      $links_obj->new_limit           = $new_limit;
      if ($listing_price > 0) {
        $add_result                   = $links_obj->Add(true);
      }
      else {
        $add_result                   = $links_obj->Add();
      }

      $category_obj = new clsCategory;
      $category_obj->table_name = "idx_category";
      $category_obj->user_table_name = "idx_users";
      $category_obj->separator  = $category_separator;
      $category                 = $category_obj->GetCategoryPath($cat);

      $users_obj = new clsUsers;
      $users_obj->table_name = "idx_users";

      // successfully added

      $title                 = stripslashes($title);
      $description           = stripslashes($description);
      $contact_name          = stripslashes($contact_name);

      if ($add_result == 0) {

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

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

        // send email to all editors, subscribers and admin
        $emails   = $links_obj->GetEditorEmail($cat);
        $emails[] = $email_address;
        $subscriber_emails =  $category_obj->GetSubscriberEmail($cat);

        while (list(, $v) = @each($emails)) {
          $body = EvalTemplate($theme_path . "mail/add_ok_editor.mail", $links_obj->email_template_fields);
          $from = $email_address;
          @mail($v, $msg["10113"], $body, "From: $from \nX-Mailer: INDEXU_X-Mailer/1.0");
        }

        while (list(, $v) = @each($subscriber_emails)) {
          $body = EvalTemplate($theme_path . "mail/add_ok_subscriber.mail", $links_obj->email_template_fields);
          $from = $email_address;
          @mail($v, $msg["10113"], $body, "From: $from \nX-Mailer: INDEXU_X-Mailer/1.0");
        }
        
        if ($listing_price > 0) {
          // temporary suspend link (activate it back again after payment received)
          $query  = "update idx_link set suspended = 1 where link_id = '$link_id'";
          $result = $dbConn->Execute($query);

          // prepare var
          $total         = $listing_price;
          $currency_code = $dbConn->Lookup("currency_code", "idx_invoice_config", "0 = 0");
          $custom        = "{$_COOKIE[COOKIE_USERNAME]}&{$listing_type}&{$link_id}&{$listing_period}";
          $item_name     = "{$listing_type} LISTING (ID: {$link_id})";
          $notify_url    = $site_url . "/payment/{$gateway}.check-upgrade.php";
          if ($_COOKIE['COOKIE_USERNAME']) {
            $return_url = $site_url . "/cp/mylisting.php";
            $cancel_url = $site_url . "/cp/mylisting.php";
          }
          else {
            $return_url = $site_url . "/paynow.php?res=ok&s=upgrade";
            $cancel_url = $site_url . "/index.php";
          }

          // route to selected payment system
          include "payment/" . $gateway . ".inc.php";
          include "payment/" . $gateway . ".php";
          RunPostFilter(__FILE__);
        }
        else {
          DisplayTemplate($theme_path . "add_ok.html");
        }

      }

      // pending

      elseif ($add_result == 1) {

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

        // send email to all editors and admin
        $emails   = $links_obj->GetEditorEmail($cat);
        $emails[] = $email_address;

        while (list(, $v) = @each($emails)) {
          $body = EvalTemplate($theme_path . "mail/add_pending_editor.mail", $links_obj->email_template_fields . ",\$site_url");
          $from = $email_address;
          @mail($v, $msg["10117"], $body, "From: $from \nX-Mailer: INDEXU_X-Mailer/1.0");
        }

        DisplayTemplate($theme_path . "add_pending.html");
      }

      // not allowed

      elseif ($add_result == 2) {
        DisplayTemplate($theme_path . "add_not_allowed.html");
      }

      elseif($add_result == -1) {
        ShowFormAddUrl();
      }
    }
    else {
      ShowFormAddUrl();
    }
  }

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

  include "application.php";
  
  RunPreFilter(__FILE__);

  if ($only_registered_can_add_link == 1) {
    ExecuteFilter("validate_user");
  }

  if (empty($cat)) {
    DisplayTemplate($theme_path . "add_error.html");
    RunPostFilter(__FILE__);
  }
  else {
    //get all id
    $category_obj = new clsCategory;
    $category_obj->table_name = "idx_category";
    $arr_cat                  = $category_obj->GetChildren(0);
    $dummy                    = array_shift($arr_cat); // remove 0

    if (!in_array($cat, $arr_cat)) {
      DisplayTemplate($theme_path . "add_error.html");
      RunPostFilter(__FILE__);
    }
  }

  // get category permission
  $query      = "select permission from idx_category where category_id = '$cat'";
  $result     = $dbConn->Execute($query);
  $permission = $result->Fields('permission');

  if ($permission == 2) {
    DisplayTemplate($theme_path . "add_not_allowed.html");
    RunPostFilter(__FILE__);
  }

  if (empty($pflag)) {
    ShowFormAddUrl();
  }
  elseif ($pflag == 'add') {
    ProcessFormAddUrl();
  }

  RunPostFilter(__FILE__);

?>