<?php
/**
 * appRain CMF
 *
 * LICENSE
 *
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.opensource.org/licenses/mit-license.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@apprain.com so we can send you a copy immediately.
 *
 * @copyright  Copyright (c) 2010 appRain, Team. (http://www.apprain.com)
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 *
 * HELP
 *
 * Official Website
 * http://www.apprain.com/
 *
 * Download Link
 * http://www.apprain.com/download
 *
 * Documents Link
 * http ://www.apprain.com/docs
 */


/**
 * $this->informationset($type)->find()
 * $this->informationset($type)->findAll()
 * $this->informationset($type)->findByFieldname()
 * $this->informationset($type)->findAllFieldname()
 * $this->informationset($type)->oneDArray()
 * $this->informationset($type)->Tag()
 * $this->informationset($type)->Save()
 * $this->informationset($type)->Delete()
 * $this->informationset($type)->idToName()
 * $this->informationset($type)->Listing()
 * $this->informationset($type)->get_information()
 *
 * # Example
 * $this->InformationSet("editorial-post")->findAll("id=1",Array("ioption='title' AND ivalue LIKE '%A%'")
 */

class appRain_Base_Modules_InformationSet extends appRain_Base_Objects
{
    private $default_condition = '=';
    private $idbprifix = "";

    public function __construct()
    {
        $this->idbprifix = App::Model('Information')->DBprefix();
    }
    
    /**
     * Base function to call information set
     *
     * @param $type String
     * @return $this Object
     */
    public function InformationSet($type = NULl)
    {
        $this->setFetchtype('informationset');
        if( isset($type))
        {
            $this->setInformationSetFetchType($type);
        }
        return $this;
    }

    /**
     * Manage all Information Set Call Back functions
     *
     * @param method String
     * @parame params String
     * @return Array
    */
    public function callInformationSetByFiled( $method = NULL, $params = NULL)
    {
        if( ($field = str_replace( "findby","",strtolower($method))) != strtolower($method)){

            switch( $field ){
                case "id":
                            $_i = App::Model('Information')->findById($params[0]);
                            if( !empty($_i)) $this->setInformationSetFetchType($_i['type']);
                            else return Array();
                case "adminref": case "last_modified": case "entry_date": case "fkey": case "generic":
                            return  $this->InformationSet()->find("Information.{$field} ='{$params[0]}'");
                            break;
                default:
                            return $this->InformationSet()->find(array("ioption = '{$field}' AND ivalue ='{$params[0]}'"));
                             break;

            }
        }
        else if( ($field = str_replace( "findallby","",strtolower($method))) != strtolower($method)){
            switch( $field ){
                case "id":
                            $_i = App::Model('Information')->findById($params[0]);
                            if( !empty($_i)) $this->setInformationSetFetchType($_i['type']);
                            else return Array();
                case "adminref": case "last_modified": case "entry_date": case "fkey": case "generic":
                            $_data = $this->InformationSet()->findAll("Information.{$field} ='{$params[0]}'");
                            break;
                default:
                            $_data = $this->InformationSet()->findAll(array("ioption = '{$field}' AND ivalue ='{$params[0]}'"));
                            break;

            }
            return $_data;
        }
        else if( ($field = str_replace( "findall","",strtolower($method))) != strtolower($method)){
            $c1 = isset($params[0]) ? $params[0] : "1";
            $c2 = isset($params[1]) ? $params[1] : array();

            if(!is_array($c1) ) $_data = $this->get_information($this->getInformationSetFetchType(),array("c1" => "AND $c1","c2"=>$c2));
            else $_data = $this->get_information($this->getInformationSetFetchType(),array("c2" => $c1));

            return $_data;
        }
        else if( ($field = str_replace( "find","",strtolower($method))) != strtolower($method)){
            $c1 = isset($params[0]) ? $params[0] : "1";
            $c2 = isset($params[1]) ? $params[1] : array();

            if(!is_array($c1) ) $_data = $this->get_information($this->getInformationSetFetchType(),array("c1" => "AND $c1","c2"=>$c2));
            else $_data = $this->get_information($this->getInformationSetFetchType(),array("c2" => $c1));

            return isset($_data['data'][0]) ? $_data['data'][0] : Array();
        }
    }


   /**
    * Fetch value from an Informationset and Return a with a 2D array format
    * Note: This function is usefull to use a part of information in droupdown box
    *
    * @parame skey String
    * @parame sval String
    * @parame option Array
    * @return Array
    * @example $this->informationSetBy1DArray("editorial_poat","id","title",array("ioptions='status' AND ivalue='Active'"));
    */
    public function oneDArray($skey = 'id', $sval = NULL,$option = array() )
    {
        $tmp_data = $this->get_information($this->getInformationSetFetchType(),$option);
        $tmp = array();
        foreach( $tmp_data['data'] as $key => $val ){
            if(isset($val[$skey]) && isset($val[$sval])){
                $tmp[$val[$skey]] = $val[$sval];
            }
        }
        return $tmp;
    }

   /**
    * Create a HTML input element with Information Set Data
    *
    * @parame name String
    * @parame information_type String
    * @parame value String
    * @parame paramater Array
    * @parame options Array
    * @return String
    */
    public function Tag( $name = NULL, $value = NULL,$paramater = NULL, $options = NULL)
    {
        if( $this->getFetchtype() == 'categoryset'){
            return $this->categorysetTag($name, $value,$paramater, $options);
        }
        else{
           $paramater['key']	=	isset($paramater['key'])		?	$paramater['key'] : "id";
            $paramater['val']	=	isset($paramater['val'])		?	$paramater['val'] : "id";
            $c2['option']		=	isset($paramater['option'])		?	$paramater['option'] : array();
            $inputType			=	isset($paramater['inputType'])	?	$paramater['inputType'] : "selectTag";
            $name				=	($inputType == "checkboxTag")	?	$name . "[checkbox][]" : $name;

            /* Set filter */
            App::$__userStatusId = isset($parameter['user']) ? $parameter['user'] : App::USERSTATUSRESETID;
            $data_arr = $this->InformationSet($this->getInformationSetFetchType())->OneDArray($paramater['key'],$paramater['val'],$c2['option']);

            /* Reset usr filter */
            $fetch = isset($parameter['fetch']) ? $parameter['fetch'] : App::$__userStatusId;
            if( strtolower($fetch) == 'all') App::$__userStatusId = NULL;
            else App::$__userStatusId = $fetch;

            return App::load("Helper/Html")->$inputType( $name , $data_arr , $value, $options);
        }
    }

    public function save($data = NULL)
    {
        return $this->quick_save_informationset($data);
    }

   /**
    * Update Information Set
    *
    * @param data Array
    * @return Boolean
    */
    public function quick_save_informationset($data = NULL)
    {
        $data = isset($data) ? $data : $this->__data;
        $data2save = $this->get_information_formated_data($data);

        return $this->save_information( $data2save );
    }

    /**
     * Format Information Set Data before save
     *
     * @parameter id Integer
     * @parameter new_data Array
     * @return Array
     */
    private function get_information_formated_data($new_data )
    {
        $new_data = isset($new_data) ? $new_data : $this->__data;

        $info_data = array();
        $new_data['id'] = isset($new_data['id']) ? $new_data['id'] : "";
        $type = isset($new_data['type']) ? $new_data['type'] : $this->getInformationSetFetchType();

        $definition = App::__def()->getInformationSetDefinition($type);

        $old_data = $this->InformationSet($type)->findById($new_data['id']);

        foreach( $definition['fields'] as $def_key => $def_val ){
            if( !isset($new_data[$def_key])){
                 $info_data["Option"][$def_key] = isset($old_data[$def_key]) ? $old_data[$def_key] : "";
            }
            else
            {
                $info_data["Option"][$def_key] = $new_data[$def_key];
            }
        }

        if( !isset($new_data["id"])) $info_data["Information"]["id"] = isset($old_data["id"]) ? $old_data["id"] : "";
        else $info_data["Information"]["id"] = $new_data["id"];

        if( !isset($new_data["user_id"])) $info_data["Information"]["user_id"] = isset($old_data["user_id"]) ? $old_data["user_id"] : "";
        else  $info_data["Information"]["user_id"] = $new_data["user_id"];

        if( !isset($new_data["fkey"])) $info_data["Information"]["type"] = isset($old_data["fkey"]) ? $old_data["fkey"] : "";
        else  $info_data["Information"]["fkey"] = $new_data["fkey"];

        if( !isset($new_data["type"])) $info_data["Information"]["type"] = isset($old_data["type"]) ? $old_data["type"] : $type;
        else  $info_data["Information"]["type"] = $new_data["type"];

        if( !isset($new_data["generic"])) $info_data["Information"]["generic"] = isset($old_data["generic"]) ? $old_data["generic"] : "";
        else  $info_data["Information"]["generic"] = $new_data["generic"];

        if( !isset($new_data["entry_date"])) $info_data["Information"]["entry_date"] = isset($old_data["entry_date"]) ? $old_data["entry_date"] : $this->get_date('Y-m-d H:i:s');
        else  $info_data["Information"]["entry_date"] = $new_data["entry_date"];

        return $info_data;
    }

    /**
     * Base function to save Information Set Data
     *
     * @param data Array
     * @return Integer
     * @uses This function return Information Set Id after save Complete
     */
    public function save_information( $data = NULL)
    {
        $data = isset($data) ? $data : $this->data;

        $errors = $this->validatedInformationSet($data);

        if(empty($errors)){

            /**
             * The information definition
             */
            $definition = app::__def()->getInformationSetDefinition($data['Information']['type']);

            /**
             * Set id and submit date
             */
            $user = App::Load("Module/Session")->read('User');

            $data['Information']['adminref'] =  isset($user['adminref']) ? $user['adminref'] : 0;
            $data['Information']['id'] =  isset($data['Information']['id']) ? $data['Information']['id'] : '';
            $data['Information']['entry_date'] = isset($data['Information']['entry_date']) ? $data['Information']['entry_date'] : App::Load("Helper/Date")->getDate('Y-m-d H:i:s');
            $data['Information']['last_modified'] = App::Load("Helper/Date")->getDate('Y-m-d H:i:s');

            /**
             * Save information part one
             */
            $result = App::Model('Information')->Save($data);

            /**
             * Set the the information id
             */
            $pid = $result->getId();

            /**
             * Run loop untill definition
             */
            foreach( $definition['fields'] as $key => $val ){
                /**
                 * In any group input type set. like check box
                 */
                $inputtype = isset( $definition['fields'][$key]["type"] ) ? $definition['fields'][$key]["type"] : "";
                $data['Option'][$key] = isset($data['Option'][$key]) ? $data['Option'][$key] : "";
                /**
                 * Combine checkbox elements
                 */
                if( is_array($data['Option'][$key])){
                    if( isset($data['Option'][$key]['checkbox']) ){
                        $data['Option'][$key] =  implode(",",$data['Option'][$key]['checkbox']);
                    }
                    else{
                        $data['Option'][$key] = implode(",",$data['Option'][$key]);
                    }
               }

                /**
                 * Set the value of the information data
                 */
                $value = isset( $data['Option'][$key] ) ? $data['Option'][$key] : "";
                $optionarr = array("Infodata" => array( "pid" => $pid, "ioption" => $key, "ivalue" => $value ));

                /**
                 * Save information data
                 */
                $infodata_niddle = App::Model('Infodata')->find("pid=$pid AND ioption='$key'");

                if( !empty($infodata_niddle) ){
                    /**
                     * Update infodata
                     */
                    App::Model('Infodata')->Save($optionarr, "pid=$pid AND ioption='$key'");
                }
                else{	
					/**
                     * Add new infor data
                     */
                    App::Model('Infodata')->Save($optionarr);
                }
            }

            /**
             * Return information id
             */
            $this->setId($pid);
            $this->setQueryStatus("Success");
        }
        else{
            $this->setQueryStatus("Failed");
            $this->setErrorInfo($errors);
        }

        return $this;
    }

    public function delete($id = NULL)
    {
        $this->delete_informationset($id);
    }

    /**
     * Delete Information By Id
     *
     * @param id Integer
     * @return Boolean
     */
    public function delete_informationset( $id = NULL)
    {
        if( !isset($id)) pre("Information Set id is requird to delete!");

        $data = $this->InformationSet()->findById($id);

        if( !empty($data)){
            App::Helper('Log')
				->setLogType('DataDeleted')
				->setLogSaveMode('Db')
				->setFkey(App::getUserStatusId())
				->Write($data);

            $this->clear_information_data($id);
            $query = "DELETE t1, t2  FROM " . $this->idbprifix ."information AS t1, " . $this->idbprifix ."infodata AS t2   WHERE t1.id=t2.pid AND t1.id='$id';";
            $arr = App::Model('Information')->custom_query($query);
        }

        return $this;
    }

    public function validatedInformationSet($data)
    {
        if(isset($data['Information']['type']))  $type = $data['Information']['type'];
        else return false;

        $fieldValues = $data["Option"];
        $fieldValues["generic_field"] = isset($data["Information"]["generic"]) ? $data["Information"]["generic"] : "" ;
        $id = isset($data["Information"]["id"])?$data["Information"]["id"]:null;

        $definition = app::__def()->getInformationSetDefinition($type);

        if(strtolower($definition["base"]["generic_field"]['enabled']) == 'yes'){
            $definition["fields"]["generic_field"] = $definition["base"]["generic_field"];
            $data["Option"]["generic_field"] = isset($data["Information"]["generic"]) ? $data["Information"]["generic"] : "";
        }

        $errors = Array();
        foreach($definition['fields'] as $fieldName => $fieldInfo){
            if(isset($fieldInfo["validation"]) && !empty($fieldInfo["validation"])){
                foreach($fieldInfo["validation"] as $validation){
                    $rule = $validation['type'];
                    $validation["options"]["_list"] =$validation["list"];
                    $validation["options"]["type"] = $type;
                    $validation["options"]["fieldname"] = $fieldName;
                    $validation["options"]["id"] = $id;

                    $fieldValues[$fieldName] = isset($fieldValues[$fieldName])?$fieldValues[$fieldName]:"";

                    if(is_array($fieldValues[$fieldName])){
                        if(isset($fieldValues[$fieldName]['checkbox'])){
                            $fieldValues[$fieldName] = (!empty($fieldValues[$fieldName]['checkbox'])) ? implode(',',$fieldValues[$fieldName]['checkbox']) : "";
                        }
                        else{
                            $fieldValues[$fieldName] = (!empty($fieldValues[$fieldName])) ? implode(',',$fieldValues[$fieldName]) : "";
                        }
                    }

                    if(!App::Load("Helper/Validation")->$rule($fieldValues[$fieldName],$validation["options"])){
                        $errors[]=$validation["message"];
                    }
                }
            }
        }
        return $errors;
    }

    /**
     * Clear External Data  of Information
     *
     * @param Id Integer
     */
    public function clear_information_data($id = NULL)
    {
        $data = $this->InformationSet()->findById($id);
        $type = $data["type"];

        /* Call back public function before delete information set*/
        $this->_on_information_set_delete(array("type"=>"$type","id"=>"$id"));

        $definition = app::__def()->getInformationSetDefinition($type);
        foreach( $definition["fields"] as $key => $val ){
            switch($val["type"]){
                case "fileTag" :
                                    $data[$key] = isset($data[$key]) ? $data[$key] : "";
                                    if($data[$key]!=""){
                                        App::$__userStatusId = $data["fkey"];
                                        $filemanager_path = App::load("Helper/Config")->get('filemanager_base_dir');
                                        App::$__userStatusId = App::USERSTATUSRESETID;
                                        $path = $filemanager_path . "/" . $data[$key];
                                        if( file_exists($path)) @unlink($path);
                                    }
                                    break;
            }
        }
    }


    /**
     * Get Information Set Value By Id
     *
     * @param ids String
     * @param title_key String
     * @param h_link String
     * @param options Array
     * @return String
     */
    public function idToName($ids = NULL ,$title_key = 'id', $h_link = 'No',$options=NULL)
    {
        if( $ids == "" ) return "";

        if( $this->getFetchtype() == 'categoryset'){
            return App::CategorySet()->IdToName( $ids, $title_key, $h_link, $options );
        }
        else{
            $a = array();
            foreach( explode(',',$ids) as $id ){
                $info_arr = $this->InformationSet()->findById( $id);
				if(!empty($info_arr)){
					if( strtolower($h_link) == 'yes' ){
						if( isset($options['link-url'])){
							$a[] = app::Load("Helper/Html")->linkTag(str_replace("[id]",$id,$options['link-url']),$info_arr[$title_key]);
						}
						else{
							$a[] = app::Load("Helper/Html")->linkTag(App::Helper('Config')->baseurl("/information/manage/" . $info_arr['type'] . "/view/$id"),$info_arr[$title_key]);
						}
					}
					else{
						$a[] = $info_arr[$title_key];
					}
				}
            }
            return  join(',',$a);
        }
    }

    /**
     * Delete Garbaze data from information module
     *
     * @return null
     */
    public function clear_garbaze_if_exists( $type )
    {
        $definition = app::__def()->getInformationSetDefinition($type);

        $c =("ioption NOT IN ('" . implode("','",array_keys($definition['fields'])) . "')");
        $sql = "SELECT count(*) as total FROM " . $this->idbprifix ."information as Information left join " . $this->idbprifix ."infodata as Infodata   on Information.id = Infodata.pid where Information.type='$type' AND $c";
        $cnt = App::Model('Information')->custom_query( $sql );

        if( $cnt[0]['total'] > 0 ){
            $sql = "SELECT * FROM " . $this->idbprifix ."information as Information left join " . $this->idbprifix ."infodata as Infodata   on Information.id = Infodata.pid where Information.type='$type' AND $c";
            $tmp = App::Model('Information')->custom_query( $sql );
            foreach( $tmp as $val ){
                App::Model('Infodata')->deleteById( $val['id'] );
            }
        }
    }

    /**
     * $options["c1"] = "ORDER BY Information.id ASC";
     * $options["c2"] = array("ioption='blog-post-title' and ivalue like '%a%'",'OR',"ioption='blog-post-desc' and ivalue like '%b%'");
     * $options["pagination"] = "Yes";
     * $options["limit"] = "2";
     * $options["paging_caption"] = array("Next","Previouse");
     * $data = $this->get_information('blog-post',$options);
     *
     * @param $type String
     * @param $options Array
     * @return array
     */
    public function get_information( $type = NULL, $options = NULL)
    {
        /* Clear Garbaze */
        $this->clear_garbaze_if_exists($type);

        /* Get current user */
        $current_user_id = App::getUserStatusId();
        $filter_by_user = isset($current_user_id) ? " AND fkey = $current_user_id" : "";

        /*  Rest the perameters  */
        $page_var_name = isset($options['page_var_name']) ? $options['page_var_name'] : "page";

        $smartPaging = $this->getSmartPaging();
        $smartPaging = isset($smartPaging) ? $smartPaging : false;

        if($smartPaging){
			$page = $this->getPage();
        }
		
        $hrp = isset($_GET[$page_var_name]) ? $_GET[$page_var_name] : 1;
        $page = isset($page) ? $page : $hrp;
        $page = is_numeric($page) ? $page : 1;

        $c1 = isset( $options['c1'] ) ? $options['c1'] : "Order by Information.id ASC";
        $c2 = isset( $options['c2'] ) ? $options['c2'] : Array();


        $ispagination = isset($options["pagination"]) ? $options["pagination"] : $this->getPagination();
        $ispagination = isset($ispagination) ? $ispagination : "No";
        if($this->getHLink())$options["h_link"] = $this->getHLink();
        $h_link = isset($options["h_link"]) ? $options["h_link"] : "?";

        if($this->getPrevCaption())$options['paging_caption'][1] = $this->getPrevCaption();
        $prev_caption = isset($options['paging_caption'][1] ) ? $options['paging_caption'][1] : PREVIOUS_PAGE;
        if($this->getNextCaption())$options['paging_caption'][0] = $this->getNextCaption();
        $next_caption = isset($options['paging_caption'][0] ) ? $options['paging_caption'][0] : NEXT_PAGE;

        /* Generate filter Query  */
        $c_str = '1';
        if( !empty($options['c2'])){
            $c_str = "";
            foreach( $options['c2'] as $key => $val){
                $valStr = is_string($val) ? $val : $this->value2str($val);

                if(in_array(strtoupper($valStr),Array('(',')','AND',')AND(','OR',')OR('))){
                     $c_str .=  strtoupper(" $valStr ");
                }
                else{
                    $c_str .= " Information.id in (  Select pid  from " . $this->idbprifix ."infodata where  " . $valStr . " order by id)";
                }
            }
        }

        /* Count total rows */
        $sql = "SELECT  count(*) as total FROM " . $this->idbprifix ."information as Information WHERE Information.type='$type' $filter_by_user AND ( $c_str ) $c1";
        $tmpdata = App::Model('Information')->custom_query( $sql );
        $total =  isset($tmpdata[0]['total']) ? $tmpdata[0]['total'] : 0;

        if($this->getLimit()){
			$options['limit'] = $this->getLimit();
        }
		$listing_per_page = isset( $options['limit'] ) ? $options['limit'] : $total;

        $tpage = ($listing_per_page != 0 ) ? ceil($total/$listing_per_page) : 0;
        $spage = ($tpage==0) ? $tpage+1 : $tpage;
        $startfrom = ($page-1) * $listing_per_page;
        $endto = ($page) * $listing_per_page;
        $page_no = "";

        /* Page set by five */
        $s =$page-5;
        if( $s < 1){
            $s =1;
        }

        /* Paging link */
        $sp_link ="";
        for( $i=$s; $i<=$page+5 && $i<=$tpage; $i++ ){
            if($smartPaging){
                $page_no .= ($i==$page) ? app::Load("Helper/Html")->getTag('strong',array("class"=>"pages"),$i) : " " . app::Load("Helper/Html")->linkTag($this->replaceSmartPage($h_link,$i),$i) . " ";
            }
            else{
                $page_no .= ($i==$page) ? app::Load("Helper/Html")->getTag('strong',array("class"=>"pages"),$i) : " " . app::Load("Helper/Html")->linkTag($h_link .  "&amp;{$page_var_name}=" . $i,$i) . " ";
            }

            $sp_link .= ($i==$page) ? "<li class=\"current\">{$i}</li>" : '<li><a href="' . $h_link .  '&page=' . $i . '">' .$i. '</a> </li>';
        }

        $link = ($page_no!="") ? "Showing Results " . ($startfrom+1) . "-$endto of $total" : "";


        $paging ='';
        $sp_prev = '<li class="disabled">' . PREVIOUS_PAGE . '</li>';
        $sp_next = '<li class="disabled">' . NEXT_PAGE . '</li>';
        if($tpage>1){
            $nextpage=$page+1;
            $prevpage=$page-1;

            if($smartPaging){
                $prevlink= app::Load("Helper/Html")->linkTag($this->replaceSmartPage($h_link,$prevpage), $prev_caption);
                $nextlink= app::Load("Helper/Html")->linkTag($this->replaceSmartPage($h_link,$nextpage), $next_caption);
            }
            else{
                $prevlink= app::Load("Helper/Html")->linkTag($h_link . "&amp;{$page_var_name}=" . $prevpage, $prev_caption);
                $nextlink= app::Load("Helper/Html")->linkTag($h_link . "&amp;{$page_var_name}=" . $nextpage, $next_caption);
            }


            if($page==$tpage){
                $paging="$prevlink";
                $sp_prev = "<li>$paging</li>";
                $sp_next = '<li class="disabled">' . NEXT_PAGE . '</li>';
            }
            elseif($tpage>$page && $page>1){
                    $paging="$prevlink | $nextlink";

                    $sp_prev = "<li>$prevlink</li>";
                    $sp_next = "<li>$nextlink</li>";
            }
            elseif($tpage>$page && $page<=1){
                    $paging="$nextlink";

                    $sp_prev = '<li class="disabled">' . PREVIOUS_PAGE . '</li>';
                    $sp_next = "<li>$paging</li>";
            }
        }

        if( $ispagination == 'Yes' ) {
			$sql = "SELECT  * FROM " . $this->idbprifix ."information as Information WHERE Information.type='$type' $filter_by_user AND ( $c_str ) $c1 LIMIT $startfrom ,$listing_per_page";
        }
		else{
			$sql = "SELECT  * FROM " . $this->idbprifix ."information as Information WHERE Information.type='$type' $filter_by_user AND ( $c_str ) $c1";
		}
        $tmpdata = App::Model('Information')->custom_query( $sql );
        $data = $this->infoData2SortedData($tmpdata);

        /* Prepare return dataformat */
        $gross['data'] = $data;

        if( strtolower($ispagination) != "no" ){
            $gross['paging'] = $paging;
            $gross['link'] = $link . " " . $paging;
            $gross['total'] = $total;
            $gross['page'] = $page;
            $gross['next_link'] = "";
            $gross['previouse_link'] = "";
            $gross['paging_str'] = '<div class="pagination pagination-left">
                            <div class="results">
                                <span>' . $link . '</span>
                            </div>
                            <ul class="pager">
                                ' . $sp_prev . '
                                ' . $sp_link . '
                                ' . $sp_next . '
                            </ul>
                        </div>';

            if($smartPaging){
                if(isset($prevpage))$gross['next_link'] = ($prevpage > 0) ? $this->replaceSmartPage($h_link,$prevpage) : "";
                if(isset($nextpage))$gross['previouse_link'] = ($nextpage < $total) ? $this->replaceSmartPage($h_link,$nextpage) : "";
            }
            else{
                if(isset($prevpage))$gross['next_link'] = ($prevpage > 0) ? $h_link . "&amp;{$page_var_name}=" . $prevpage : "";
                if(isset($nextpage))$gross['previouse_link'] = ($nextpage < $total) ? $h_link . "&amp;{$page_var_name}=" . $nextpage : "";
            }
        }

        return  $gross;
    }

    private function replaceSmartPage($l = NULL,$p = NULL)
    {
        if(isset($l) && isset($p)){
            return (strstr($l,'[page]')) ? str_replace("[page]",$p,$l) : "{$l}/{$p}";
        }
        else{
            return "?";
        }
    }

    public function value2str( $sustr = NULL)
    {
        $cnd = isset($sustr['cnd']) ? $sustr['cnd'] : $this->default_condition;
        unset($sustr['cnd']);

        list($field,$value) = each($sustr);

        return "ioption='{$field}' AND ivalue {$cnd} '{$value}'";
    }

    /**
     * Form Information Set Data
     *
     * @param tmp_data Array
     * @return array
     */
    public function infoData2SortedData( $tmp_data = NULL)
    {
        $data = array();
        foreach( $tmp_data as $key => $val ){
            $row = Array();
            $row['id'] = $val['id'];
            $row['adminref'] = $val['adminref'];
            $row['fkey'] = $val['fkey'];
            $row['generic'] = $val['generic'];
            $row['type'] = $val['type'];
            $row['entry_date'] = $val['entry_date'];
            $row['last_modified'] = $val['last_modified'];

            $dt = App::Model('Infodata')->findAllByPid($val["id"]);
            foreach( $dt['data'] as $dtval ){
                $row[$dtval['ioption']] = $dtval['ivalue'];
            }
            $data[] =  $row;
        }
        $data = isset($per_page) ?  array_slice($data,0,$per_page) : $data;
        return $data;
    }

    /**
     * Export Information Set
     *
     * Return Mix
     */
    public function export($download=false)
    {
        $info_arr = $this->InformationSet($this->getInformationSetFetchType())->findAll();

        switch(strtolower($this->getExporttype())){
            case 'csv':
				$data = App::Load("Helper/Utility")->convertArrayToCsvString(array_keys($info_arr['data'][0]),',');
				foreach($info_arr['data'] as $val){
					$data .= App::Load("Helper/Utility")->convertArrayToCsvString($val,',');
				}
				break;
            case 'xml':
				$data = App::Load("Helper/Utility")->convertArrayToXML($info_arr['data']);
				break;
        }

        if( $download === true){
            App::Load("Helper/Utility")->downloadInline($data,$this->getInformationSetFetchType() . '.' . $this->getExporttype());
        }
        else{
            return $data;
        }
    }

    public function Listing($options = NULL)
    {
        return $this->get_information(
			$this->getInformationSetFetchType(),
			$options
		);
    }
}