<?php 
// ++++++++++++++++++++++++++++++++++++++++++++
//                                             
// FileName:split_page.php                    +
//
//
// 功能:分頁類                                +
//
// 時間:11/08/2005                            +
// ++++++++++++++++++++++++++++++++++++++++++++
  class split_page {
    var $page_view_num; //每頁顯示的記錄數
	var $curr_page;     //當前頁碼
	var $sql_query;     //SQL語句
    var $total_page;    //總頁數
	var $total_record;  //總共記錄數
	var $url;           //提交的網址
	var $start_limit;   
	var $multi_page;    //分頁函數得出的代碼
	var $query;         //新的sql語句
//構造函數,用於分析SQL語句
		function split_page($sql,$page,$url,$page_view_num="") {
			global $DB;
			  if (!isset($page_view_num) || ($page_view_num == "")) {
				 $this->page_view_num = 10;
			  }else {
				 $this->page_view_num = $page_view_num;
			  }
				 $this->sql_query = $sql;
				 $this->total_record = $DB->num_rows($DB->query($this->sql_query));
				 $this->total_page = ceil($this->total_record/$this->page_view_num);
				 $this->parse_page($page);
				 $this->url = $url;
				 $this->multi_page = $this->multi();
				 $this->get_start_limit();
				 $this->query = $this->sql_query." limit ".$this->start_limit.",".$this->page_view_num;
		}
//驗證page
		function parse_page($page) {
			if (!isset($page) || (!preg_match("/^[0-9]+$/",$page)) || ($page == 0)) {
				$this->curr_page = 1;
			}else {
				if ($page > $this->total_page) {
				  $this->curr_page = $this->total_page;
				}else {
				   $this->curr_page = $page;	
				}
			
			}
			
		}
//分頁函數
		function multi() {
			$multipage = '';
		if($this->total_record > $this->page_view_num) {
			$page = 10;
			$offset = 2;

			$pages = $this->total_page;
			$from = $this->curr_page - $offset;
			$to = $this->curr_page + $page - $offset - 1;
			if($page > $pages) {
			  $from = 1;
			  $to = $pages;
			} else {
				if($from < 1) {
					$to = $this->curr_page + 1 - $from;
					$from = 1;
					if(($to - $from) < $page && ($to - $from) < $pages) {
						$to = $page;
				}
				} elseif($to > $pages) {
					$from = $this->curr_page - $pages + $to;
					$to = $pages;
						if(($to - $from) < $page && ($to - $from) < $pages) {
							$from = $pages - $page + 1;
					}
				}
		}
		$multipage .= "<a href=\"$this->url&page=1\"><Font color=#000000 face=webdings>9</font></a>  ";
		for($i = $from; $i <= $to; $i++) {
			if($i != $this->curr_page) {
				$multipage .= "<a href=\"$this->url&page=$i\"><font color=#000000>[$i]</font></a> ";
			} else {
				$multipage .= '<u><b><font color=#000000>['.$i.']</font></b></u> ';
			}
		}
		$multipage .= $pages > $page ? " ... <a href=\"$this->url&page=$pages\"> $pages <Font color=#000000 face=webdings>:</font></a>" : " <a href=\"$this->url&page=$pages\"><Font color=000000 face=webdings>:</font></a>";
	}
	return $multipage;
}
 	
		function get_start_limit() {
			$this->start_limit = (intval($this->curr_page)-1)*$this->page_view_num;
		}
}

?>