<?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 clsCategory {

    var $table_name             = "category";
    var $link_table_name        = "link";
    var $number_of_columns      = 2; // choose 1,2,3, and 4
    var $number_of_subcats      = 3;
    var $default_image          = "images/folder.gif";
    var $show_image             = true;
    var $show_subcat            = false;
    var $show_description       = false;
    var $number_of_links_format = "";
    var $cat_description_format = "";
    var $cat_link_style         = "";
    var $subcat_link_style      = "";
    var $cat_cellspacing        = 2;
    var $cat_table_width        = 400;
    var $parent                 = 0;
    var $separator              = "::";
    var $header                 = "";
    var $image_path             = "";
    var $query                  = "";
    var $type_of_list           = "STANDART_LIST"; // STANDART_LIST
    var $bold                   = true;            // SEARCH RESULT
    var $keywords               = "";
    var $bold_format            = "<b><%keyword%></b>";

    // internal use only


    // method to add new category
    // return :   0: success
    //            1: sql error
    // ----------------------------------------

    function Add($name, $parent_id, $description, $image, $content, $visible, 
                   $permission, $meta_keyword, $meta_description, 
                   $registered_only, $header, $footer, $related, $page_title, 
                   $price_sponsored, $price_premium, $price_basic) {
      global $dbConn;

      $query = "insert into $this->table_name
                (name, parent_id, description, image, content, visible, links, permission, meta_keyword, meta_description, registered_only, header, footer, related, page_title, sponsored_price, premium_price, basic_price)
                values ('$name', $parent_id, '$description', '$image', '$content', $visible, 0, $permission, '$meta_keyword', '$meta_description', $registered_only, '$header', '$footer', '$related', '$page_title', '$price_sponsored', '$price_premium', '$price_basic')";
      $result = $dbConn->Execute($query);

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

    // method to edit category
    // return :   0: success
    //            1: sql error
    // ----------------------------------------

    function Edit($category_id, $name, $parent_id, $description, $image, 
                    $content, $visible, $permission, $meta_keyword,
                    $meta_description, $registered_only, $header, $footer, 
                    $related, $page_title, $order_num, $sponsored_price, 
                    $premium_price, $basic_price) {
      global $dbConn;

      $query  = "update $this->table_name 
                 set name = '$name',
                     parent_id = $parent_id,
                     description = '$description',
                     image = '$image',
                     content = '$content',
                     visible = '$visible',
                     permission = '$permission',
                     meta_keyword = '$meta_keyword',
                     meta_description = '$meta_description',
                     registered_only = '$registered_only',
                     header = '$header',
                     footer = '$footer',
                     related = '$related',
                     page_title = '$page_title',
                     order_num = $order_num,
                     sponsored_price = '$sponsored_price',
                     premium_price = '$premium_price',
                     basic_price = '$basic_price'
                 where category_id = '$category_id'";
      $result = $dbConn->Execute($query);

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


    // method to delete category
    // return :   0: success
    //            1: category is not empty
    // ----------------------------------------

    function Delete($cat_id) {
      global $dbConn;

      // do it have links

      $query  = "select link_id from $this->link_table_name where category_id = '$cat_id'";
      $result = $dbConn->Execute($query);
      $total  = $result->RecordCount();

      // if so, do not delete the category
      if ($total != 0)
        return 1;
      else {

        // get the parent_id
        $query     = "select parent_id from $this->table_name where category_id = '$cat_id'";
        $result    = $dbConn->Execute($query);
        $parent_id = $result->Fields("parent_id");

        // do it has children?
        $query     = "select category_id from $this->table_name where parent_id = '$cat_id'";
        $result    = $dbConn->Execute($query);

        // if so, assign parent_id to their grandparent

        while (!$result->EOF) {
          $category_id = $result->Fields("category_id");
          $query       = "update $this->table_name set
                          parent_id = '$parent_id'
                          where category_id = '$category_id'";
          $result2     = $dbConn->Execute($query);
          $result->MoveNext();
        }

        // now delete the category
        $query  = "delete from $this->table_name where category_id = '$cat_id'";
        $result = $dbConn->Execute($query);

        return 0;
      }
    }


    // method to get in ordered categories
    // -----------------------------------

    function GetInOrderCategory($categories) {
      $total = count($categories);
      $i     = 0;

      while ($i < $total) {
        $cat_id           = $categories[$i];
        $array["$cat_id"] = $this->GetCategoryPath($cat_id);
        asort($array);
        $i++;
      }

      if ($total > 0)
        $keys = array_keys($array);

      // return arrays of category_id
      return $keys;
    }


    // method to get number of links in specific category
    // --------------------------------------------------

    function GetNumberOfLinks($cat) {
      global $dbConn;
      $queue = $this->GetChildren($cat);
      @reset($queue);
      $query = "select count(link_id) as count from $this->link_table_name 
                where suspended = 0
                      and (0!=0 ";

      while (list($key, $cat) = @each($queue)) {
        $query .= " or category_id = $cat or cat1 = $cat or cat2 = $cat";
      }
      $query .= ")";

      $result = $dbConn->Execute($query);
      $val = $result->Fields("count");
      $result->Close();

      return $val;
    }


    // method to display the category path
    // -----------------------------------

    function CalculateCategoryPath($cat, $file = "") {
      global $dbConn, $cat_path_link_style, $site_url;
      $parents   = ";";
      $parent_id = 10;

      while ($parent_id) {

        // read name and parent_id
        $query     = "select parent_id, name from $this->table_name where category_id = '$cat'";
        $result    = $dbConn->Execute($query);

        $parent_id = $result->Fields("parent_id");
        $name      = $result->Fields("name");

        $parents  .= "$parent_id;";

        if (GetModRewriteStatus()=='1') {
          $name2               = SEOReplace($name);
          $mod_rewrite_pattern = GetModRewritePatternCategory();
          $mod_rewrite_pattern = str_replace('{$cat_name}',$name2,$mod_rewrite_pattern);
          $mod_rewrite_pattern = str_replace('{$cat_id}',$cat,$mod_rewrite_pattern);
          $mod_rewrite_pattern = str_replace('{$page}','1',$mod_rewrite_pattern);
          $href                = strtolower($mod_rewrite_pattern);
        }
        else {
          $href = strtolower("browse.php?cat=$cat");
        }
        
        $href                = "<a href=\"{$href}\" name=\"cat_$cat\" style=\"$cat_path_link_style\">";
        $close_href          = "</a>";

        // write path
        if (empty($path)) {
          $path  = $name;
          $path2 = $href . $name . $close_href;
        }
        else {
          $path  = $name . $this->separator . $path;
          $path2 = $href . $name . $close_href . $this->separator . $path2;
        }

        // next looping
        $cat = $parent_id;
      }

      if (GetModRewriteStatus()=='1') {
        if (strpos($mod_rewrite_pattern, '{$cat_path}') !== FALSE) {
          // rebuild path with url from path
          $paths = explode($this->separator, $path);
          $path2s = explode($this->separator, $path2);
          while (list($k, $v) = @each($paths)) {
            $mod_rewrite_pattern = GetModRewritePatternCategory();
            $mod_rewrite_pattern = substr($mod_rewrite_pattern, 0, strrpos($mod_rewrite_pattern, '/'));
            $cat_path .= strtolower(SEOReplace($v)) . '/';
            $mod_rewrite_pattern = str_replace('{$cat_path}',$cat_path,$mod_rewrite_pattern);
            $mod_rewrite_pattern = str_replace('//','/',$mod_rewrite_pattern);
            $path2s[$k] = preg_replace('/<a href=".*?"/', "<a href=\"{$site_url}/$mod_rewrite_pattern\"", $path2s[$k]);
          }
          $path2 = implode($this->separator, $path2s);
        }
      }
	  
      return $path . "<----break---->" . $path2 . "<----break---->" . $parents;
    }


    // method to display the category path
    // -----------------------------------

    function GetCategoryPath($cat, $with_url = FALSE) {
      global $dbConn;
      if (!$with_url) {
        $path   = $dbConn->Lookup("path", "idx_category_path", "category_id = '$cat'");
      }
      else {
        $path   = $dbConn->Lookup("path_with_url", "idx_category_path", "category_id = '$cat'");
      }
      return $path;
    }


    // method to display the top parent category
    // -----------------------------------------

    function GetTopParentCategory($cat) {
      global $dbConn;

      $parents = $dbConn->Lookup('parents', 'idx_category_path', "category_id = '$cat'");
      $parent_arr = @explode(';', $parents);
      $parent_id = $parent_arr[@count($parent_arr) - 3];

      if (empty($parent_id)) {
        $parent_id = 0; // top level category
      }

      return $parent_id;
    }


    // method to display search result from search category
    // ----------------------------------------------------

    function DisplaySearchResult($query, $file = "") {
      global $dbConn;
      $parent_id = 100000;

      while ($parent_id) {

        // read name and parent_id
        $query     = "select parent_id, name from $this->table_name where category_id = '$cat'";
        $row       = $dbConn->FetchOne($query);
        $parent_id = $row["parent_id"];
        $name      = $row["name"];

        if (!empty($file)) {
          $href       = "<a href=\"$file?cat=$cat\" name=\"cat_$cat\">";
          $close_href = "</a>";
        }

        // write path
        if (empty($path)) {
          $path = $href . $name . $close_href;
        }
        else {
          $path = $href . $name . $close_href . $this->separator . $path;
        }

        // next looping
        $cat = $parent_id;
      }

      return $path . " ";
    }


    // method to get access permission
    // -------------------------------

    function GetAccessPermission($cat) {
      global $dbConn;
      return $dbConn->Lookup("registered_only", $this->table_name, "category_id = '$cat'");
    }


    // method to get content of category
    // ---------------------------------

    function GetContent($cat) {
      global $dbConn;
      $content = $dbConn->Lookup("content", $this->table_name, "category_id = '$cat'");
      if ($content) {
        $tpl = new Template;
        $tpl->assign('cat', $cat);
        $content = $tpl->fetch('var:' . $content);
      }
      return $content;
    }


    // method to get meta keyword
    // --------------------------

    function GetMetaKeyword($cat) {
      global $dbConn;
      return $dbConn->Lookup("meta_keyword", $this->table_name, "category_id = '$cat'");
    }


    // method to get meta description
    // ------------------------------

    function GetMetaDescription($cat) {
      global $dbConn;
      return $dbConn->Lookup("meta_description", $this->table_name, "category_id = '$cat'");
    }


    // method to display categories
    // ----------------------------

    function Display() {
      global $dbConn, $number_of_links_format_search_result, $site_url;

      $tpl = new Template();

      // get main category
      if (empty($this->query))
        $query = "select category_id from $this->table_name where (parent_id = '$this->parent' and visible = 1) order by name";
      else
        $query = $this->query;

      $result = $dbConn->Execute($query);
      while (!$result->EOF) {
        $cats_id[] = $result->Fields("category_id");
        $result->MoveNext();
      }

      // get related category
      $query2       = "select category_id from $this->table_name where (related <> 0 and visible = 1 and  related = '$this->parent')";
      $result2 = $dbConn->Execute($query2);
      $related = array ();
      while (!$result2->EOF) {
        $related[] = $cats_id[] = $result2->Fields("category_id");
        $result2->MoveNext();
      }

      // okay.. get all them and short it

      if (@count($cats_id)) {
        $query = "select a.*, b.path, b.path_with_url
                  from $this->table_name a
                       left join {$this->table_name}_path b on (a.category_id = b.category_id)
                  where 0 != 0 ";
        while (list($k, $v) = @each($cats_id)) {
          $query .= "or a.category_id = '$v' ";
        }
        $query .= "order by order_num, name";
        @reset($cats_id);
      }

      $result   = $dbConn->Execute($query);
      $num_cats = $result->RecordCount();

      if ($num_cats != 0) {
        $category = $this->header;
        $category .= "<table width=\"$this->cat_table_width\" cellspacing=\"$this->cat_cellspacing\">\n";
        $category .= "<tr>";

        $st_min = floor($num_cats / $this->number_of_columns);
        $st_max = ceil($num_cats / $this->number_of_columns);
        $st_burst = $num_cats % $this->number_of_columns;

        $k = 0;
        while ($k < $this->number_of_columns) {
          $width = 100 / $this->number_of_columns;
          $category .= "<td width=\"$width" . "%\" valign=\"top\">\n";

          $max_loop = ($st_burst > 0) ? $st_max : $st_min;
          $st_burst--;

          $i = 0;
          while ($i < $max_loop) {
            $cat_id = $result->Fields("category_id");
            $cat_name = $result->Fields("name");
            $cat_description = $result->Fields("description");
            $cat_image = $result->Fields("image");
            $cat_path = $result->Fields("path");
            $cat_path_with_url = $result->Fields("path_with_url");
            $nl = $result->Fields("links");
            $result->MoveNext();

            // if related category put @ after its name
            if (in_array($cat_id, $related))
              $cat_name .= "@";

            if ($this->show_image == false)
              $image = "";
            else {
              if ($cat_image == "")
                $cat_image = $this->default_image;
              else
                $cat_image = $this->image_path . $cat_image;

              $image = "<img src=\"$cat_image\" border=\"0\" alt=\"\" />";

              if ($this->default_image == "" && $cat_image == "")
                unset($image);
            }

            $tpl->assign('number_of_links', $nl);
            $number_of_links = $tpl->fetch('var:' . $this->number_of_links_format);

            $tpl->assign('cat_description', $cat_description);
            $cat_desc = $tpl->fetch('var:' . $this->cat_description_format);

            if (GetModRewriteStatus()=='1') {
              $cat_name2 = SEOReplace($cat_name);
              $mod_rewrite_pattern = GetModRewritePatternCategory();
              $mod_rewrite_pattern = str_replace('{$cat_name}',$cat_name2,$mod_rewrite_pattern);
              $mod_rewrite_pattern = str_replace('{$cat_id}',$cat_id,$mod_rewrite_pattern);
              $mod_rewrite_pattern = str_replace('{$page}','1',$mod_rewrite_pattern);
              if (strpos($mod_rewrite_pattern, '{$cat_path}') !== FALSE) {
                $mod_rewrite_pattern = substr($mod_rewrite_pattern, 0, strrpos($mod_rewrite_pattern, '/') + 1);
                $cat_path2 = SEOReplace(str_replace($this->separator, 'indexuslash', $cat_path));
                $cat_path2 = str_replace('indexuslash', '/', $cat_path2);
                $mod_rewrite_pattern = str_replace('{$cat_path}',$cat_path2,$mod_rewrite_pattern);
                $mod_rewrite_pattern = str_replace('//', '/', $mod_rewrite_pattern);
              }
              $cat_url   = strtolower($mod_rewrite_pattern);
            }
            else {
              $cat_url   = strtolower("browse.php?cat=$cat_id");
            }
            $cat_url = $site_url . "/" . $cat_url;

            if ($this->type_of_list == "STANDART_LIST") {
              $category .= "<p />";

              if (!empty($image)) {
                $category .= "<a href=\"$cat_url\" style=\"$this->cat_link_style\" name=\"cat_$cat_id\">$image</a> \n";
              }

              $category .= "<b><a href=\"$cat_url\" style=\"$this->cat_link_style\" name=\"cat_$cat_id\">$cat_name</a></b> $html_number_of_links \n";
              $category .= "$number_of_links\n";

              if ($this->show_description) {
                if (!empty($cat_description))
                  $category .= "<br />";

                $category .= "$cat_desc \n";
              }

              if ($this->show_subcat)
                $category .= "<br />";
            }

            if ($this->type_of_list == "SEARCH_RESULT") {
              $tpl->assign('number_of_links', $nl);
              $number_of_links = $tpl->fetch('var:' . $number_of_links_format_search_result);

              $category .= "<br />";
              $category .= $this->GetCategoryPath($cat_id, TRUE);
              $category .= "$number_of_links\n";
            }


            // get sub category

            if ($this->show_subcat) {
              $query      = "select a.category_id, a.name, b.path, b.path_with_url
                             from $this->table_name a
                                  left join {$this->table_name}_path b on (a.category_id = b.category_id)
                             where parent_id = '$cat_id' and visible = 1
                             order by order_num, name";
              $result_sub = $dbConn->Execute($query);
              $num_subs   = $result_sub->RecordCount();
              $j          = 0;

              while (!$result_sub->EOF && ($j < $this->number_of_subcats)) {
                $sub_id   = $result_sub->Fields("category_id");
                $sub_name = $result_sub->Fields("name");
                $sub_path = $result_sub->Fields("path");
                $result_sub->MoveNext();

                if (GetModRewriteStatus()=='1') {
                  $sub_name2 = SEOReplace($sub_name);
                  $mod_rewrite_pattern = GetModRewritePatternCategory();
                  $mod_rewrite_pattern = str_replace('{$cat_name}',$sub_name2,$mod_rewrite_pattern);
                  $mod_rewrite_pattern = str_replace('{$cat_id}',$sub_id,$mod_rewrite_pattern);
                  $mod_rewrite_pattern = str_replace('{$page}','1',$mod_rewrite_pattern);
                  if (strpos($mod_rewrite_pattern, '{$cat_path}') !== FALSE) {
                    $mod_rewrite_pattern = substr($mod_rewrite_pattern, 0, strrpos($mod_rewrite_pattern, '/') + 1);
                    $sub_path2 = SEOReplace(str_replace($this->separator, 'indexuslash', $sub_path));
                    $sub_path2 = str_replace('indexuslash', '/', $sub_path2);
                    $mod_rewrite_pattern = str_replace('{$cat_path}',$sub_path2,$mod_rewrite_pattern);
                    $mod_rewrite_pattern = str_replace('//', '/', $mod_rewrite_pattern);
                  }
                  $sub_url   = strtolower($mod_rewrite_pattern);
                }
                else {
                  $sub_url   = strtolower("browse.php?cat=$sub_id");
                }
                $sub_url = $site_url . "/" . $sub_url;

                $category .= "<a href=\"$sub_url\" style=\"$this->subcat_link_style\" name=\"cat_$sub_id\">$sub_name</a>, ";

                $j++;

                if ($j == $this->number_of_subcats || $result_sub->EOF) {
                  $category = substr(trim($category), 0, -1);
                  if ($j < $num_subs) {
                    $category .= "....";
                  }
                }
              }
              $category .= "\n";
            }

            $i++;
          }

          $k++;
          $category .= "</td>\n\n";
        }

        $category .= "</tr></table><br />";
      }

      // bold it
      if ($this->type_of_list == "SEARCH_RESULT") {
        $tpl->assign('keyword', "\\3");
        $replace = $tpl->fetch('var:' . $this->bold_format);
        $replace = "\\1\\2" . $replace . "\\4\\5";

        if ($this->bold) {
          $keywords = $this->keywords;
          $category = preg_replace("/<a href=\"(.*?)\"/mse", "'<a href=\"'.base64_encode('\\1').'\"'", $category);
          while (list(, $word) = @each($keywords)) {
            $pattern  = "/(<a href=.*?>)(.*?)(" . $word . ")(.*?)(<\/a>)/iU";
            $category = preg_replace($pattern, $replace, $category);
          }
          $category = preg_replace("/<a href=\"(.*?)\"/mse", "'<a href=\"'.base64_decode('\\1').'\"'", $category);
        }
      }

      return $category;
    }


    // method to update number of links in all categories
    // --------------------------------------------------

    function UpdateNumberOfLinksInAllCategories() {
      global $dbConn;
      // get all categories
      $query  = "select category_id from $this->table_name";
      $result = $dbConn->Execute($query);
      while ($row = $result->FetchRow()) {
        $cat_id  = $row["category_id"];
        $nl      = $this->GetNumberOfLinks($cat_id);
        $query   = "update $this->table_name set links = '$nl' where category_id = '$cat_id'";
        $dbConn->Execute($query);
      }
    }


    // method to update number of links in specific category
    // -----------------------------------------------------

    function UpdateNumberOfLinksInCategory($cat_id) {
      global $dbConn;
      $nl     = $this->GetNumberOfLinks($cat_id);
      $query  = "update $this->table_name set links = '$nl' where category_id = '$cat_id'";
      $result = $dbConn->Execute($query);
    }


    // method to get category's add permission
    // ---------------------------------------

    function GetAddLinkPermission($cat) {
      global $dbConn;
      return $dbConn->Lookup("permission", $this->table_name, "category_id = '$cat'");
    }


    // method to get category's name
    // -----------------------------

    function GetCategoryName($cat) {
      global $dbConn;
      return $dbConn->Lookup("name", $this->table_name, "category_id = '$cat'");
    }


    // method to get category's description
    // -----------------------------

    function GetCategoryDescription($cat) {
      global $dbConn;
      return $dbConn->Lookup("description", $this->table_name, "category_id = '$cat'");
    }


    // method to display select category's list box
    // --------------------------------------------

    ////// build tree use depth first alg. Recursive!! //////

    var $not_allowed_cat         = array ();
    var $exclude_not_allowed_cat = 0;

    function BuildTreeRec($cat_id = 0, $lv = 0) {
      global $cat_list, $category_list, $selected_cat, $category_separator;

      if (!isset($this->not_allowed_cat))
        $this->not_allowed_cat = array ();

      // prepare to stop recursive, if has no value then go to next node
      if (!isset($cat_list[$cat_id]))
        return false;

      // do recursive on each node
      foreach ($cat_list[$cat_id] as $key => $cat_node) {

        // assign var
        $name        = $cat_node['name'];
        $category_id = $cat_node['category_id'];
        $order_num   = $cat_node['order_num'];
        $path        = $cat_node['path'];


        if (in_array($category_id, $this->not_allowed_cat) && $this->exclude_not_allowed_cat) { }
        else {
          $category_list .= "<option value=\"$category_id\" ";

          if ($category_id == $selected_cat)
            $category_list .= " selected=\"selected\"";

          if ($path) {
            $cpath = $path;
          }
          else {
            $cpath = $this->GetCategoryPath($category_id);
          }
          $arr = explode($this->separator, $cpath);
          $cpath = str_repeat('&nbsp; ', (@count($arr) - 1) * 3) . $arr[@count($arr) - 1];

          $category_list .= ">" . $cpath . "</option>\n";
        }

        // this will go to next first child node
        $this->BuildTreeRec($cat_node['category_id'], $lv + 1);
      }

      unset($cat_list[$category_id]);
    }


    function DisplayCategoryListBox($cat, $show_main_category = false, $admin = 0) {
      global $dbConn, $cat_list, $category_list, $selected_cat;

      $selected_cat = $cat;

      // exclude not allowed submission
      $query  = "select category_id from idx_category where permission = 2";
      $result = $dbConn->Execute($query);
      while ($row = $result->FetchRow()) {
        if ($cat != $row['category_id']) {
          $this->not_allowed_cat[] = $row['category_id'];
        }
      }
      $result->Close();

      $category_list = "<select name=\"cat\">";

      if ($cat == 0 || $show_main_category)
        $category_list .= "<option value=\"0\">Main Category</option>";
      else
        $category_list .= "<option value=\"\"></option>";

      if ($admin == 1) {
        $query = "select a.category_id, a.parent_id, a.name, b.path
                  from idx_category a
                       left join idx_category_path b on (a.category_id = b.category_id)
                  order by a.name";

        if (!empty($this->query))
          $query = $this->query;

        $this->exclude_not_allowed_cat = 0;
      }
      else {
        $query = "select a.category_id, a.parent_id, a.name, b.path
                  from idx_category a
                       left join idx_category_path b on (a.category_id = b.category_id)
                  where visible = 1
                  order by a.name";

        if (!empty($this->query))
          $query = $this->query;

        $this->exclude_not_allowed_cat = 1;
      }

      $result = $dbConn->Execute($query);
      // build array of node data
      while ($row = $result->FetchRow()) {
        $cat_list[$row['parent_id']][$row['category_id']] = $row;
      }

      if ($admin == 0 || $admin == 1) {
        if (sizeof($cat_list) != 0) {
          $this->BuildTreeRec();
        }
      }
      // editor
      elseif ($admin == 2) {
        $result->MoveFirst();
        while ($row = $result->FetchRow()) {
          $category_id = $row['category_id'];
          $category_list .= "<option value=\"$category_id\" ";
          if ($category_id == $selected_cat) $category_list .= " selected=\"selected\"";
          $cpath = $this->GetCategoryPath($category_id);
          $arr = explode($this->separator, $cpath);
          $cpath = str_repeat('&nbsp; ', (@count($arr) - 1) * 3) . $arr[@count($arr) - 1];
          $category_list .= ">" . $cpath . "</option>\n";
        }
      }

      $category_list .= "</select>";
      unset($this->not_allowed_cat);
      return $category_list;
    }


    // method to get hidden categories
    // -------------------------------
    function GetHiddenCategories() {
      global $dbConn;
      $query  = "select category_id from $this->table_name where visible = 0";
      $result = $dbConn->Execute($query);
      while (!$result->EOF) {
        $cat_id[] = $result->Fields("category_id");
        $result->MoveNext();
      }
      $result->Close();
      return $cat_id;
    }


    // method to get member only categories
    // ------------------------------------
    function GetMemberOnlyCategories() {
      global $dbConn;
      $query  = "select category_id from $this->table_name where registered_only = 1";
      $result = $dbConn->Execute($query);
      while (!$result->EOF) {
        $cat_id[] = $result->Fields("category_id");
        $result->MoveNext();
      }
      $result->Close();
      return $cat_id;
    }


    // method to get children
    // ----------------------

    function GetChildren($cat) {
      global $dbConn;
      $query  = "select category_id from idx_category_path
                 where parents like '%;$cat;%'";
      $result = $dbConn->Execute($query);
      $children[] = $cat;
      while (!$result->EOF) {
        $children[] = $result->Fields("category_id");
        $result->MoveNext();
      }
      $result->Close();
      return $children;
    }


    // method to make hidden its children
    // ----------------------------------

    function HideChildren($cat) {
      global $dbConn;
      $c = $this->GetChildren($cat);
      $i = 1;

      $count_c = @count($c);
      while ($i < $count_c) {
        $cat    = $c[$i];
        $query  = "update $this->table_name set visible = 0 where category_id = '$cat'";
        $result = $dbConn->Execute($query);
        $i++;
      }
    }


    // method to make unhidden its children
    // ----------------------------------

    function UnhideChildren($cat) {
      global $dbConn;
      $c = $this->GetChildren($cat);
      $i = 1;

      $count_c = @count($c);
      while ($i < $count_c) {
        $cat    = $c[$i];
        $query  = "update $this->table_name set visible = 1 where category_id = '$cat'";
        $result = $dbConn->Execute($query);
        $i++;
      }
    }


    // method to set member only to children
    // -------------------------------------

    function SetMemberOnlyToChildren($cat) {
      global $dbConn;
      $c = $this->GetChildren($cat);
      $i = 1;

      $count_c = @count($c);
      while ($i < $count_c) {
        $cat    = $c[$i];
        $query  = "update $this->table_name set registered_only = 1 where category_id = '$cat'";
        $result = $dbConn->Execute($query);
        $i++;
      }
    }


    // method to unset member only to children
    // ---------------------------------------

    function UnsetMemberOnlyToChildren($cat) {
      global $dbConn;
      $c = $this->GetChildren($cat);
      $i = 1;

      $count_c = @count($c);
      while ($i < $count_c) {
        $cat    = $c[$i];
        $query  = "update $this->table_name set registered_only = 0 where category_id = '$cat'";
        $result = $dbConn->Execute($query);
        $i++;
      }
    }


    // method to get html header of category
    // -------------------------------------

    function GetHeader($cat) {
      global $dbConn, $cat;
      $header = $dbConn->Lookup("header", $this->table_name, "category_id = '$cat'");
      if ($header) {
        $tpl = new Template;
        $tpl->assign('cat', $cat);
        $header = $tpl->fetch('var:' . $header);
      }
      return $header;
    }


    // method to get html footer of category
    // -------------------------------------

    function GetFooter($cat) {
      global $dbConn, $cat;
      $footer = $dbConn->Lookup("footer", $this->table_name, "category_id = '$cat'");
      if ($footer) {
        $tpl = new Template;
        $tpl->assign('cat', $cat);
        $footer = $tpl->fetch('var:' . $footer);
      }
      return $footer;
    }


    // method to get category page's title
    // -----------------------------------

    function GetPageTitle($cat) {
      global $dbConn;
      $page_title = $dbConn->Lookup("page_title", $this->table_name, "category_id = '$cat'");
      return $page_title;
    }


    // method to get subscriber emails for this category and below
    // -----------------------------------

    function GetSubscriberEmail($cat) {
      global $dbConn;
      $query   = "select parents from idx_category_path where category_id = '$cat'";
      $result  = $dbConn->Execute($query);
      $parents = @explode(';', $result->Fields("parents"));

      while (list($k, $v) = @each($parents)) {
        if ($v == '') {
          unset($parents[$k]);
        }
      }

      $cats   = $parents;
      $cats[] = $cat;
      $query  = "select distinct(username) from idx_notification
                 where category_id in ('".@implode("', '", $cats)."')";
      $result = $dbConn->Execute($query);

      $user_obj = new clsUsers;
      $user_obj->table_name = $this->user_table_name;

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

      $result->Close();

      return $email;
    }


    function ParseCategoryPath() {
      global $dbConn, $site_url;
      $path = $_SERVER['REQUEST_URI'];
      if (!get_magic_quotes_gpc()) {
        $path = addslashes($path);
      }
      $paths = explode('/', $path);
      $page = 1;
      if (strpos($path, '.html') !== FALSE) {
        $last_path = $paths[count($paths) - 1];
        $page = preg_replace('/[^0-9]/', '', $last_path);
        unset($paths[count($paths) - 1]);
      }
      while (list($k, $v) = @each($paths)) {
        $path = implode('/', $paths);
        if ($id || !$path) {
          break;
        }
		$path = $site_url . "/" . $path;
        $id   = $dbConn->Lookup('category_id', 'idx_category_path', "path_with_url like '%\"$path%' order by path asc");
        unset($paths[$k]);
      }
      return array($id, $page);
    }

  }
?>