<?php
include_once "tadtools_header.php";
include_once "jquery.php";



//自動轉連結
if(!function_exists('autolink')){

  function autolink( &$text, $target='_blank', $nofollow=true )
  {
    // grab anything that looks like a URL...
    $urls  =  _autolink_find_URLS( $text );
    if( !empty($urls) ) // i.e. there were some URLS found in the text
    {
      array_walk( $urls, '_autolink_create_html_tags', array('target'=>$target, 'nofollow'=>$nofollow) );
      $text  =  strtr( $text, $urls );
    }
    return $text;
  }

  function _autolink_find_URLS( $text )
  {
    // build the patterns
    $scheme         =       '(http:\/\/|https:\/\/)';
    $www            =       'www\.';
    $ip             =       '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
    $subdomain      =       '[-a-z0-9_]+\.';
    $name           =       '[a-z][-a-z0-9]+\.';
    $tld            =       '[a-z]+(\.[a-z]{2,2})?';
    $the_rest       =       '\/?[a-z0-9._\/~#&=;%+?-]+[a-z0-9\/#=?]{1,1}';
    $pattern        =       "$scheme?(?(1)($ip|($subdomain)?$name$tld)|($www$name$tld))$the_rest";

    $pattern        =       '/'.$pattern.'/is';
    $c              =       preg_match_all( $pattern, $text, $m );
    unset( $text, $scheme, $www, $ip, $subdomain, $name, $tld, $the_rest, $pattern );
    if( $c )
    {
      return( array_flip($m[0]) );
    }
    return( array() );
  }

  function _autolink_create_html_tags( &$value, $key, $other=null )
  {
    $target = $nofollow = null;
    if( is_array($other) )
    {
      $target      =  ( $other['target']   ? " target=\"$other[target]\"" : null );
      // see: http://www.google.com/googleblog/2005/01/preventing-comment-spam.html
      $nofollow    =  ( $other['nofollow'] ? ' rel="nofollow"'            : null );
    }
    $value = "<a href=\"$key\"$target$nofollow>$key</a>";
  }
}


//推文工具
if(!function_exists('push_url')){
  function push_url($css="width:auto;margin:10px;float:right;"){
    /*
    $main="
    <!-- AddThis Button BEGIN -->
    <div class='addthis_toolbox addthis_default_style ' style='$css'>
    <a class='addthis_button_facebook_like' fb:like:layout='button_count'></a>
    <a class='addthis_button_tweet'></a>
    <a class='addthis_button_google_plusone' g:plusone:size='medium'></a>
    <a class='addthis_counter addthis_pill_style'></a>
    </div>
    <script type='text/javascript' src='http://s7.addthis.com/js/300/addthis_widget.js#pubid=ra-4eeaf5210e9f814b'></script>
    <!-- AddThis Button END -->
    <div style='clear:both;'></div>
    ";
    */

    

  //第一代
    $main="<div style='$css'>
    <table summary='push_url' style='width:auto'>
    <tr><td style='vertical-align:top;padding:2px;'>
    <a title='add to Twitter' href='http://twitter.com/home/?status=http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}' target='_blank'><img src='".TADTOOLS_URL."/images/twitter.png' alt='add to Twitter' title='add to Twitter' align='top' style='border:0px;margin:0px;'></a>
    </td><td style='vertical-align:top;padding:2px;'>
    <a title='add to Plurk' href='http://www.plurk.com/?qualifier=shares&amp;status=http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}' target='_blank'><img src='".TADTOOLS_URL."/images/plurk.png' alt='add to Plurk' title='add to Plurk' align='top' style='border:0px;margin:0px;'></a>
    </td><td style='vertical-align:top;padding:2px;'>
    <a title='add to FaceBook' href='http://www.facebook.com/share.php?u=http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}' target='_blank'><img src='".TADTOOLS_URL."/images/facebook.png' alt='add to FaceBook' title='add to FaceBook' align='absmiddle'></a>

    </td><td style='vertical-align:top;padding:2px;'>
    <script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='small'></g:plusone>

    </td><td style='vertical-align:top;padding:0px;'>
    <script src='http://connect.facebook.net/zh_TW/all.js#xfbml=1'></script><fb:like href='{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}' layout='button_count' show_faces='false' width='50' font=''></fb:like>
    </td>
    </tr>
    </table>
    </div>
    <div style='clear:both;'></div>";

    return $main;
  }
}


//facebook的留言
if(!function_exists('facebook_comments')){
  function facebook_comments(){

    $xoopsModuleConfig=TadToolsXoopsModuleConfig();
    if(empty($xoopsModuleConfig['facebook_comments_width']))return;
    
    $main="<div id=\"fb-root\"></div><script src=\"http://connect.facebook.net/zh_TW/all.js#appId=189441632170&xfbml=1\"></script><fb:comments href=\"{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}\" num_posts=\"10\" width=\"{$xoopsModuleConfig['facebook_comments_width']}\"></fb:comments>";
    return $main;

  }
}


//單選回復原始資料函數
if(!function_exists('chk')){
  function chk($DBV=null,$NEED_V="",$defaul="",$return="checked='checked'"){
  	if($DBV==$NEED_V){
  		return $return;
  	}elseif(empty($DBV) && $defaul=='1'){
  		return $return;
  	}
  	return "";
  }
}

//複選回復原始資料函數
if(!function_exists('chk2')){
  function chk2($default_array="",$NEED_V="",$default=0){
  	if(in_array($NEED_V,$default_array)){
  		return "checked";
  	}elseif(empty($default_array) && $default=='1'){
  		return "checked";
  	}

  	return "";
  }
}

//細部權限判斷
if(!function_exists('power_chk')){
  function power_chk($perm_name="",$psn=""){
  	global $xoopsUser,$xoopsModule;

  	//取得目前使用者的群組編號
  	if($xoopsUser) {
  		$groups = $xoopsUser->getGroups();
  	}else{
  		$groups = XOOPS_GROUP_ANONYMOUS;
  	}

  	//取得模組編號
  	$module_id = $xoopsModule->getVar('mid');
  	//取得群組權限功能
  	$gperm_handler =& xoops_gethandler('groupperm');

  	//權限項目編號
  	$perm_itemid = intval($psn);
  	//依據該群組是否對該權限項目有使用權之判斷 ，做不同之處理
  	if($gperm_handler->checkRight($perm_name, $perm_itemid, $groups, $module_id)) {
  		return true;
  	}
  	return false;
  }
}


//建立目錄
if(!function_exists('mk_dir')){
  function mk_dir($dir=""){
    //若無目錄名稱秀出警告訊息
    if(empty($dir))redirect_header("index.php", 3,_TAD_NO_DIRNAME);
    //若目錄不存在的話建立目錄
    if (!is_dir($dir)) {
      umask(000);
      //若建立失敗秀出警告訊息
      if(!mkdir($dir, 0777)){
        redirect_header("index.php", 3,sprintf(_TAD_MKDIR_ERROR,$dir));
      }
    }
  }
}

//刪除整個目錄
if(!function_exists('rrmdir')){
  function rrmdir($path)
  {
    return is_file($path)?
      @unlink($path):
      array_map('rrmdir',glob($path.'/*'))==@rmdir($path)
    ;
  }
}
//取得分頁工具
if(!function_exists('getPageBar')){
  function getPageBar($sql="",$show_num=20,$page_list=10,$to_page="",$url_other=""){
    global $xoopsDB;
    if(empty($show_num))$show_num=20;
    if(empty($page_list))$page_list=10;
  	$result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],10, mysql_error()."<br>$sql");
  	$total=$xoopsDB->getRowsNum($result);

  	$navbar = new PageBar($total, $show_num, $page_list);
    if(!empty($to_page)){
      $navbar->set_to_page($to_page);
    }

    if(!empty($url_other)){
      $navbar->set_url_other($url_other);
    }
  	$mybar = $navbar->makeBar();
  	$main['bar']= sprintf(_TAD_TOOLBAR,$mybar['total'],$mybar['current'])."{$mybar['left']}{$mybar['center']}{$mybar['right']}";
  	$main['sql']=$sql.$mybar['sql'];
  	$main['total']=$total;

  	return $main;
  }
}


//分頁物件
if(!class_exists('PageBar')){
  class   PageBar{
  	// 目前所在頁碼
  	var $current;
  	// 所有的資料數量 (rows)
  	var $total;
  	// 每頁顯示幾筆資料
  	var $limit;
  	// 目前在第幾層的頁數選項？
  	var $pCurrent;
  	// 總共分成幾頁？
  	var $pTotal;
  	// 每一層最多有幾個頁數選項可供選擇，如：3 = {[1][2][3]}
  	var $pLimit;
  	var $prev;
  	var $next;
  	var $prev_layer = ' ';
  	var $next_layer = ' ';
  	var $first;
  	var $last;
  	var $bottons = array();
  	// 要使用的 URL 頁數參數名？
  	var $url_page = "g2p";
  	// 要使用的 URL 讀取時間參數名？
  	var $url_loadtime = "loadtime";
  	// 會使用到的 URL 變數名，給 process_query() 過濾用的。
  	var $used_query = array();
  	// 目前頁數顏色
  	var $act_color = "#990000";
  	var $query_str; // 存放 URL 參數列
  	//指定頁面
  	var $to_page;
  	//其他連結參數
    var $url_other;

  	function PageBar($total, $limit, $page_limit){
  		$mydirname = basename( dirname( __FILE__ ) ) ;
  		$this->prev = "<img src='".TADTOOLS_URL."/images/1leftarrow.gif' alt='"._TAD_BACK_PAGE."' align='absmiddle' hspace=3>"._TAD_BACK_PAGE;
  		$this->next = "<img src='".TADTOOLS_URL."/images/1rightarrow.gif' alt='"._TAD_NEXT_PAGE."' align='absmiddle' hspace=3>"._TAD_NEXT_PAGE;
  		$this->first = "<img src='".TADTOOLS_URL."/images/2leftarrow.gif' alt='"._TAD_FIRST_PAGE."' align='absmiddle' hspace=3>"._TAD_FIRST_PAGE;
  		$this->last = "<img src='".TADTOOLS_URL."/images/2rightarrow.gif' alt='"._TAD_LAST_PAGE."' align='absmiddle' hspace=3>"._TAD_LAST_PAGE;
      $this->to_page = $_SERVER['PHP_SELF'];
  		$this->limit = $limit;
  		$this->total = $total;
  		$this->pLimit = $page_limit;
  	}

  	function init(){
  		$this->used_query = array($this->url_page, $this->url_loadtime);
  		$this->query_str = $this->processQuery($this->used_query);
  		$this->glue = ($this->query_str == "")?'?':
  		'&';
      
  		$this->current = (isset($_GET["$this->url_page"]))? intval($_GET["$this->url_page"]):
  		1;
  		if($this->current < 1)$this->current=1;
  		$this->pTotal = ceil($this->total / $this->limit);
  		$this->pCurrent = ceil($this->current / $this->pLimit);
  	}

  	//初始設定
  	function set($active_color = "none", $buttons = "none"){
  		if ($active_color != "none"){
  			$this->act_color = $active_color;
  		}

  		if ($buttons != "none"){
  			$this->buttons = $buttons;
  			$this->prev = $this->buttons['prev'];
  			$this->next = $this->buttons['next'];
  			$this->prev_layer = $this->buttons['prev_layer'];
  			$this->next_layer = $this->buttons['next_layer'];
  			$this->first = $this->buttons['first'];
  			$this->last = $this->buttons['last'];
  		}
  	}

  	// 處理 URL 的參數，過濾會使用到的變數名稱
  	function processQuery($used_query){
  		// 將 URL 字串分離成二維陣列
  		$QUERY_STRING=htmlspecialchars($_SERVER['QUERY_STRING']);
  		$vars = explode("&", $QUERY_STRING);
  		for($i = 0; $i < count($vars); $i++){
  			$var[$i] = explode("=", $vars[$i]);
  		}

  		// 過濾要使用的 URL 變數名稱
  		for($i = 0; $i < count($var); $i++){
  			for($j = 0; $j < count($used_query); $j++){
  				if (isset($var[$i][0]) && $var[$i][0] == $used_query[$j]) $var[$i] = array();
  			}
  		}

  		// 合併變數名與變數值
  		for($i = 0; $i < count($var); $i++){
  			$vars[$i] = implode("=", $var[$i]);
  		}

  		// 合併為一完整的 URL 字串
  		$processed_query = "";
  		for($i = 0; $i < count($vars); $i++){
  			$glue = ($processed_query == "")?'?':
  			'&';
  			// 開頭第一個是 '?' 其餘的才是 '&'
  			if ($vars[$i] != "") $processed_query .= $glue.$vars[$i];
  		}
  		return $processed_query;
  	}

  	// 製作 sql 的 query 字串 (LIMIT)
  	function sqlQuery(){
  		$row_start = ($this->current * $this->limit) - $this->limit;
  		$sql_query = " LIMIT {$row_start}, {$this->limit}";
  		return $sql_query;
  	}


  	function set_to_page($page=""){
      $this->to_page=$page;
  	}

  	function set_url_other($other=""){
      $this->url_other=$other;
  	}


  	// 製作 bar
  	function makeBar($url_page = "none"){
  		if ($url_page != "none"){
  			$this->url_page = $url_page;
  		}
  		$this->init();

  		// 取得目前時間
  		$loadtime = '&loadtime='.time().$this->url_other;

  		// 取得目前頁框(層)的第一個頁數啟始值，如 6 7 8 9 10 = 6
  		$i = ($this->pCurrent * $this->pLimit) - ($this->pLimit - 1);

  		$bar_center = "";
  		while ($i <= $this->pTotal && $i <= ($this->pCurrent * $this->pLimit)){
  			if ($i == $this->current){
  				$bar_center = "{$bar_center}<font color='{$this->act_color}'>[{$i}]</font>";
  			}else{
  				$bar_center .= " <a href='{$this->to_page}{$this->query_str}{$this->glue}{$this->url_page}={$i}{$loadtime}'' title='{$i}'>{$i}</a> ";
  			}
  			$i++;
  		}
  		$bar_center = $bar_center . "";

  		// 往前跳一頁
  		if ($this->current <= 1){
  			$bar_left = " {$this->prev} ";
  			$bar_first = " {$this->first} ";
  		}	else{
  			$i = $this->current-1;
  			$bar_left = " <a href='{$this->to_page}{$this->query_str}{$this->glue}{$this->url_page}={$i}{$loadtime}' title='"._TAD_BACK_PAGE."'>{$this->prev}</a> ";
  			$bar_first = " <a href='{$this->to_page}{$this->query_str}{$this->glue}{$this->url_page}=1{$loadtime}' title='"._TAD_FIRST_PAGE."'>{$this->first}</a> ";
  		}

  		// 往後跳一頁
  		if ($this->current >= $this->pTotal){
  			$bar_right = " {$this->next} ";
  			$bar_last = " {$this->last} ";
  		}	else{
  			$i = $this->current + 1;
  			$bar_right = " <a href='{$this->to_page}{$this->query_str}{$this->glue}{$this->url_page}={$i}{$loadtime}' title='"._TAD_NEXT_PAGE."'>{$this->next}</a> ";
  			$bar_last = " <a href='{$this->to_page}{$this->query_str}{$this->glue}{$this->url_page}={$this->pTotal}{$loadtime}' title='"._TAD_LAST_PAGE."'>{$this->last}</a> ";
  		}

  		// 往前跳一整個頁框(層)
  		if (($this->current - $this->pLimit) < 1){
  			$bar_l = " {$this->prev_layer} ";
  		}	else{
  			$i = $this->current - $this->pLimit;
  			$bar_l = " <a href='{$this->to_page}{$this->query_str}{$this->glue}{$this->url_page}={$i}{$loadtime}' title='".sprintf($this->pLimit,_TAD_GO_BACK_PAGE)."'>{$this->prev_layer}</a> ";
  		}

  		//往後跳一整個頁框(層)
  		if (($this->current + $this->pLimit) > $this->pTotal){
  			$bar_r = " {$this->next_layer} ";
  		}	else{
  			$i = $this->current + $this->pLimit;
  			$bar_r = " <a href='{$this->to_page}{$this->query_str}{$this->glue}{$this->url_page}={$i}{$loadtime}' title='".sprintf($this->pLimit,_TAD_GO_NEXT_PAGE)."'>{$this->next_layer}</a> ";
  		}

  		$page_bar['center'] = $bar_center;
  		$page_bar['left'] = $bar_first . $bar_l . $bar_left;
  		$page_bar['right'] = $bar_right . $bar_r . $bar_last;
  		$page_bar['current'] = $this->current;
  		$page_bar['total'] = $this->pTotal;
  		$page_bar['sql'] = $this->sqlQuery();
  		return $page_bar;
  	}
  }
}
?>