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

   // ----- show radio button -----
  // $var_name = the name of form field
  // $list_text = comma delimited string of text that will be displayed
  // $list_value = comma delimited string of value associated with $list_text
  // $checked = one of item that in $list_value that will be checked

  function ShowRadioButton($var_name, $list_text, $list_value, $checked) {
    $array_text  = explode(",", $list_text);
    $array_value = explode(",", $list_value);
    while (list($k, $v) = @each($array_value)) {
      $value = $array_value[$k];
      $text  = $array_text[$k];
      if ($value == $checked) {
        $output .= "<input type=\"radio\" name=\"$var_name\" value=\"$value\" checked=\"checked\">$text&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
      }
      else {
        $output .= "<input type=\"radio\" name=\"$var_name\" value=\"$value\">$text&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
      }
    }
    return $output;
  }


  // ----- show drop down -----
  // $var_name = the name of form field
  // $list_text = comma delimited string of text that will be displayed
  // $list_value = comma delimited string of value associated with $list_text
  // $selected = one of item that in $list_value that will be selected

  function ShowDropDown($var_name, $list_text, $list_value, $selected) {
    $array_text  = explode(",", $list_text);
    $array_value = explode(",", $list_value);
    $output = "<select name=$var_name>";
    while (list($k, $v) = @each($array_value)) {
      $value = $array_value[$k];
      $text  = $array_text[$k];
      if ($value == $selected) {
        $output .= "\n <option value=\"$value\" selected=\"selected\">$text</option>";
      }
      else {
        $output .= "\n <option value=\"$value\">$text</option>";
      }
    }
    $output .= "\n</select>";
    return $output;
  }


  // return in array
  //   $ret[0] total online users
  //   $ret[1] members
  //   $ret[2] guest
  //   $ret[3..x] username of who's online

  function GetWhosOnline($exp = 600) {
    global $dbConn, $whosonline;

    if (!empty($whosonline))
      $exp = $whosonline;

    $expired = time() - $exp;

    // get total users online
    $query   = "select data from idx_sessions where expiry > $expired
                order by expiry desc";
    $result  = $dbConn->Execute($query);
    
    $ret[0] = 0;
    $ret[1] = 0;
    $ret[2] = 0;
    $ip_arr = array();
    while (!$result->EOF) {
      $data = $result->Fields(data);
      $data = urldecode($data);

      // parse session data
      $data = substr($data, 0, strlen($data) - 1);
      $str  = explode(";", $data);

      $dump = array ();

      foreach ($str as $key => $val) {
        $str1 = explode("|", $val);
        foreach ($str1 as $key1 => $val1) {
          if (preg_match("/s:/i", $val1))
            $dump[$vkey] = unserialize($val1);
          else
            $vkey = $val1;
        }
      }

      if (!in_array($dump[indexu_session_ip], $ip_arr)) {
        $ip_arr[] = $dump[indexu_session_ip];
        $username = $dump[indexu_session_username];
        if (!empty($username)) {
          $ret[] = $username;
          $ret[1]++;
        }
        else {
          $ret[2]++;
        }
        $ret[0]++;
      }

      $result->MoveNext();
    }

    // fix $_SESSION bug
    if ($ret[0] == 0) {
      $ret[0] = 1;   // total

      if (isset($_COOKIE['COOKIE_USERNAME'])) {
        $ret[1] = 1; // member
        $ret[3] = $_COOKIE['COOKIE_USERNAME'];
      }
      else
        $ret[2] = 1; // guest
    }

    return $ret;
  }


  // ----- recursifely remove directory -----

  function RemoveDir($file) {
    global $base_path;

    if (file_exists($file)) {

      if (is_dir($file)) {
        $handle = opendir($file);

        while (false !== ($filename = readdir($handle))) {
          if ($filename != "." && $filename != "..") {
            RemoveDir($file . "/" . $filename);
          }
        }

        closedir($handle);

        if ($file != $base_path . 'cache' 
              && $file != $base_path . 'cache/dummy.txt'
              && $file[0] != '.') {
          @rmdir($file);
        }
      }
      else {
        if ($file != $base_path . 'cache' 
              && $file != $base_path . 'cache/dummy.txt'
              && $file[0] != '.') {
          @unlink($file);
        }
      }
    }
  }


  // ----- recursifely create directory -----

  function CreateDir($path, $permission) {
    global $base_path;

    if (ini_get('safe_mode')) {
      return;
    }

    $dirs = explode("/", $path);
    $dir  = "";

    while (list($k, $current) = @each($dirs)) {
      $dir .= ($k == 0 && ereg(':', $current)) ? $current : "/$current";

      if (!is_dir("$base_path/$dir")) {
        mkdir("$base_path/$dir", $permission);
      }
    }
  }


  // ----- IsValidReciprocalURL -----

  function IsValidReciprocalURL($url, $reciprocal_url) {
    global $site_url;
    $p_url = parse_url($url);
    $p_reciprocal_url = parse_url($reciprocal_url);
    if ($p_url['host'] != $p_reciprocal_url['host']) {
      return FALSE;
    }
    $content = HttpRequest($reciprocal_url);
    if (!ereg($site_url, $content['html'])):
      return FALSE;
    endif;
    return TRUE;
  }


  // ----- CheckUrl -----

  function CheckUrl($loc) {
    flush();
    $url = parse_url($loc);
    if(!$url[port]) $url[port] = "80";
    if(!$url[path]) $url[path] = "/";

    $fp = @fsockopen($url[host], $url[port], $errno, $errstr, 30);
		if(!$fp){
  	  echo "ERROR: $errstr ($errno)<br>\n";
	  }
		else {
  	  $str  = "GET $url[path] HTTP/1.1\r\n";
  		$str .= "User-Agent: INDEXU Spider Link Checker (http://www.indexu.com)\r\n";
  		$str .= "Host: $url[host]\r\n\r\n";

      fputs($fp,$str);
      $res = fgets($fp,50);
	    fclose($fp);

			//$res = substr($res,-3,3);
			return $res;
		}
  }


  // ----- SEOReplace -----

  function SEOReplace($string) {
    $seo_replacement_str_arr = array (
      ' ',
      '-',
      '/',
      '\\',
      ',',
      '.',
      '#',
      ':',
      ';',
      '\'',
      '"',
      '[',
      ']',
      '{',
      '}',
      ')',
      '(',
      '|',
      '`',
      '~',
      '!',
      '@',
      '%',
      '$',
      '^',
      '&',
      '*',
      '=',
      '?',
      '+'
    );
    $string = str_replace($seo_replacement_str_arr, '-', $string);
    $string = preg_replace(array('/-+/', '/-$/', '/-indexuslash/'), 
                           array('-', '', 'indexuslash') , $string);
    $string = urlencode(strtolower($string));
    return $string;
  }


  // ----- RemoveEvilTags -----

  function RemoveEvilTags($string, $allowed_tags = '') {
    if (is_array($string)) {
      $texts = $string;
    }
    else {
      $texts[0] = $string;
    }
    while (list($k, $text) = @each($texts)) {
      while ($text != strip_tags($text, $allowed_tags)) {
        $text = strip_tags($text, $allowed_tags);
      }
      $bad_protocols = '/(\'|")(about|chrome|data|disk|hcp|help|javascript|livescript|lynxcgi|lynxexec|ms-help|ms-its|mhtml|mocha|opera|res|resource|shell|vbscript|view-source|vnd.ms.radio|wysiwyg):.*?\\1/msi';
      $bad_attribs = '/on(Load|Click|DblClick|DragStart|KeyDown|KeyPress|KeyUp|MouseDown|MouseMove|MouseOut|MouseOver|SelectStart|Blur|Focus|Scroll|Select|Unload|Change|Submit)\s*=\s*(\'|").*?\\2/msi';
      while ($text != preg_replace($bad_protocols, '""', $text)) {
        $text = preg_replace($bad_protocols, '""', $text);
      }
      while ($text != preg_replace($bad_attribs, '', $text)) {
        $text = preg_replace($bad_attribs, '', $text);
      }
      $texts[$k] = $text;
    }
    if (is_array($string)) {
      return $texts;
    }
    return $texts[0];
  }


  // ----- JSEncode -----

  function JSEncode($value) {
    $type = gettype($value);
    if ($type == "boolean") {
      return ($value) ? "Boolean(true)" : "Boolean(false)";
    } 
    elseif ($type == "integer") {
      return "parseInt($value)";
    } 
    elseif ($type == "double") {
      return "parseFloat($value)";
    } 
    elseif ($type == "array" || $type == "object" ) {
      $s = "{ ";
      if ($type == "object") {
        $value = get_object_vars($value);
      } 
      foreach ($value as $k=>$v) {
        $esc_key = JSEscape($k);
        if (is_numeric($k)) 
          $s .= "$k: " . JSEncode($v) . ", ";
        else
          $s .= "\"$esc_key\": " . JSEncode($v) . ", ";
      }
      if (count($value))
        $s = substr($s, 0, -2);
      return $s . " }";
    } 
    else {
      $esc_val = JSEscape($value);
      $s = "\"$esc_val\"";
      return $s;
    }
  }


  // ----- JSEscape -----

  function JSEscape($val)
  {
    $val = str_replace("\\", "\\\\", $val);
    $val = str_replace("\r", "\\r", $val);
    $val = str_replace("\n", "\\n", $val);
    $val = str_replace("'", "\\'", $val);
    return str_replace('"', '\\"', $val);
  }


  // ----- Redirect -----

  function Redirect($url, $run_post_filter = TRUE) {
    if (substr($_SERVER["SERVER_SOFTWARE"], 0, 6) == "Apache") {
      header("Location: $url");
    }
    else {
      echo "<META HTTP-EQUIV='refresh' CONTENT='0'; URL=$url>";
    }
    if ($run_post_filter) {
      RemoveFilter("runtime");
      RunPostFilter();
    }
  }

?>