Location: PHPKode > scripts > Yet Another Pager > yet-another-pager/CYap_clsSearch.php
<?PHP
/**
 * CYap_clsSearch.php
 *
 * Base widgets base class.
 *
 * @copyright CYap_clsSearch is part of Yap project {@link http://www.andrioli.com/en/yap.html} and it is LGPL
 * @author    Andrioli Darvin <darvin (inside) andrioli (dot) com>
 * @version   $Header: d:\cvs/classistd/yap/CYap_clsSearch.php,v 1.15 2008/03/10 12:15:46 darvin Exp $
 * @package CYap
 */
/*
 * +-------------------------------------------------------------------------+
 * | Yap                                                                     |
 * +-------------------------------------------------------------------------+
 * | Copyright (c) 2003-2008 Andrioli Darvin                                 |
 * | Email         hide@address.com                                       |
 * | Web           http://www.andrioli.com/en/yap.html                       |
 * | Download      http://www.phpclasses.org/browse.html/package/1391.html   |
 * |                                                                         |
 * +-------------------------------------------------------------------------+
 * | This library is free software; you can redistribute it and/or modify    |
 * | it under the terms of the GNU Lesser General Public License as          |
 * | published by the Free Software Foundation; either version 2 of the      |
 * | License, or (at your option) any later version.                         |
 * |                                                                         |
 * | This library is distributed in the hope that it will be useful, but     |
 * | WITHOUT ANY WARRANTY; without even the implied warranty of              |
 * | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU        |
 * | Lesser General Public License for more details.                         |
 * |                                                                         |
 * | You should have received a copy of the GNU Lesser General Public        |
 * | License along with this library; if not, write to the Free Software     |
 * | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
 * +-------------------------------------------------------------------------+
 */
/**
 *
 */
/**
 * Main search class. This class manages the logic to build the query form.
 * It maintains the collection of all search fields, and acts as interface
 * between those fields and the world outside.
 *
 * @package CYap
 *
 */
class CYap_clsSearch
{
/**
 * Array of CYap_clsSearchField objects.
 * It is an associative array indexed by the field name.
 */
var $tblFields;
/**
 * Same as $tblFields, but it keeps the order of the fields
 * @see $tblFields
 * @var array of CYAP_clsSearchField
 */
var $tblFieldsOrder;
/**
 * Language strings.
 *
 * @var string[]
 */
var $Lang;

var $LayoutClass;

var $LayoutObject;

/**
 * Class to use to create the submit button
 * If not set from parameter, it assumes CYAP_ViewSubmitButton
 * Note the class must be extend CYAP_Control class
 * @var string
 */
var $SubmitClass;
/**
 * Instanced object used to draw the submit button.
 * Set by CYap_clsSearch::SetSumitObject
 * @see CYap_clsSearch::SetSumitObject
 * @var CYAP_Control
 */
var $SubmitObject;
/**
 * Class constructor
 *
 * @param array $search_field Configuration data gievn to CYap or read from config file
 * @param array $language String translation table to the selected language
 * @return CYap_clsSearch
 * @access public
 * @since 2.1.0
 */
function CYap_clsSearch($search_field,$language)
{
/*
 * Parse the configuration data. This is the startup configuration.
 * Those parameters may be changed at runtime
 */
$this->tblFields=array();
$this->tblFieldsOrder=array();
$this->LayoutObject=null;
$this->SubmitObject=null;
// Default value
$this->LayoutClass='CYAP_clsSearchLayout';
$this->SubmitClass='CYAP_ViewSubmitButton';
$this->Lang=$language;
$this->LoadCfg($search_field);
}

/**
 * Check and load the configuration information about the search box
 * coming from the caller
 *
 * @param string[] $info parameters from the caller
 * @access public
 * @since 2.1.0
 */
function LoadCfg($info)
{
$index=count($this->tblFieldsOrder);
foreach($info as $FieldOrder => $FieldCfg)
   {
   if(is_array($FieldCfg))
      {
      // Field parameters
      $FieldClass=(array_key_exists("fieldclass",$FieldCfg))?$FieldCfg['fieldclass']:'CYap_clsSearchTxt';
      if(array_key_exists($FieldOrder,$this->tblFields))
        {
        // FieldName should be unique
        die("Duplicated fieldname: " . $FieldOrder. ".Check the search parameters");
        }
     else
        {
        eval('$this->tblFields[$FieldOrder]=new '.$FieldClass.'($FieldCfg,$FieldOrder);');
        $this->tblFieldsOrder[$index]=&$this->tblFields[$FieldOrder];
        $this->tblFields[$FieldOrder]->SetProperty('FieldOrder',$index);
        $index++;
        }
     }
   else
     {
     // Filter's parameters
     $this->LayoutClass=$this->GetParameter('layoutclass',$info,'CYAP_clsSearchLayout');
     $this->SubmitClass=$this->GetParameter('submitclass',$info,'CYAP_ViewSubmitButton');
     }
   }
}
/**
 * utility used to extract the request parameter from the configuration
 * array.
 *
 * @param string $paramName
 * @param string[] $cfg
 * @param string $default
 * @return string
 * @access private
 */
function GetParameter($paramName,$cfg,$default)
{
return((array_key_exists($paramName,$cfg))?
                $cfg[$paramName]:
                $default);
}
/**
 * Get the requested seacrh field
 * It return null, if the requested field doesn't exists
 * @param string $FieldName
 * @return CYAP_clsSearchField
 * @access public
 */
function &GetSearchField($FieldName)
{
if(array_key_exists($FieldName,$this->tblFields))
  return($this->tblFields[$FieldName]);
else
  return(null);
}
/**
 * Add the custom made field object. It allows the user to create
 * programmatically some field to add to the form.
 *
 * @param CYAP_clsSearchField $Field
 * @param string $FieldName
 * @return void
 * @access public
 */
function AddSearchField(&$Field,$FieldName)
{
$index=count($this->tblFieldsOrder);
if(array_key_exists($FieldName,$this->tblFields))
  {
  // FieldName should be unique
  die("Duplicated fieldname: " . $FieldName. ".Check the search parameters");
  }
else
  {
  $this->tblFields[$FieldName]=&$Field;
  $this->tblFieldsOrder[$index]=&$Field;
  $this->tblFields[$FieldName]->SetProperty('FieldOrder',$index);
  }
}
/**
 * Remove the requested field from the field list.
 *
 * @param string $FieldName
 * @access public
 * @return void
 */
function RemoveSearchField($FieldName)
{
if(array_key_exists($FieldName,$this->tblFields))
  {
  // The field exist, remove it
  $index=$this->tblFields[$FieldName]->GetProperty('FieldOrder');
  unset($this->tblFieldsOrder[$index]);
  unset($this->tblFields[$FieldName]);
  }
}
/**
 * Pass an instanced layout class to the search class.
 * When thr form will be draws, the class will use the provided layout object
 *
 * @param CYAP_clsSearchLayout $layout
 * @access public
 * @return void
 */
function SetLayoutObject(&$layout)
{
$this->LayoutObject=&$layout;
}
/**
 * It gives the layout class name to instance to draw the form
 *
 * @param string $ClassName
 */
function SetLayoutClass($ClassName)
{
$this->LayoutClass=$ClassName;
}
/**
 *
 *
 * @param CYAP_Control $Submit
 * @access public
 * @return void
 */
function SetSubmitObject(&$Submit)
{
$this->SubmitObject=&$Submit;
}
/**

 * @param string $ClassName
 */
function SetSubmitClass($ClassName)
{
$this->SubmitClass=$ClassName;
}

/**
 * Should I show the search box? If there isn't any field set to
 * filter the output, the search form is not show
 * Function called by CYap to knows whether display or not the box
 *
 * @return boolean True: do not display the form
 * @access public
 * @since 2.1.0
 */
function NoSearchBox()
{
return(count($this->tblFieldsOrder)<2);
}

/**
 * Read data from search form. Each field retrieves its own value
 * Called by CYap::AnalizeRequest (@see CYAP::AnalizeRequest)
 * @return void
 * @since 2.1.0
 * @access public
 */
function ReadFormData()
{
foreach($this->tblFields as $FieldName => $Field)
   {
   $this->tblFields[$FieldName]->ReadFormData();
   }
}
/**
 * Store the fields status into session. Called by CYAP::AnalizeRequest
 * @param string $prefix Text to prepend to session variable name
 * @access public
 * @since 2.1.0
 */
function StoreInformation($prefix)
{
// Tell to all fields to store its own information.
foreach($this->tblFields as $FieldName => $Field)
   {
   $this->tblFields[$FieldName]->StoreInformation($prefix);
   }
// I've not any informztion to save, yet...
}
/**
 * Load the fields status into session
 * @param string $prefix Text to prepend to session variable name
 * @access public
 * @since 2.1.0
 */
function LoadInformation($prefix)
{
// Tell to all fields to store its own information.
foreach($this->tblFields as $FieldName => $Field)
   {
   $this->tblFields[$FieldName]->LoadInformation($prefix);
   }
// I've not any informztion to load, yet...
}
/**
 * Remove all information from session array
 * @param string $prefix Text to prepend to session variable name
 * @access public
 * @since 2.1.0
 */
function CleanSessionInfo($prefix)
{
foreach($this->tblFields as $FieldName => $Field)
   {
   $this->tblFields[$FieldName]->CleanSessionInfo($prefix);
   }
}
/**
 * Build the condition to retrieve the rows. It returns the text to append the sql
 * the sql statement used to retrieve the data to display
 * @param CYap_Db $db_class
 * @return String
 * @access public
 * @since 2.1.0
 */
function GetWhereCondition($db_class)
{
$where="";
foreach($this->tblFields as $FieldName => $Field)
   {
   $risp=$this->tblFields[$FieldName]->GetWhereCondition($db_class);
   if($risp!='')
   	  $where.=' and '.$risp;
   }
return($where);
}
/**
 * Get the page size. Called by Cyap to retrieve the value of the field
 * PageSize
 *
 * @return string
 * @access public
 * @since 2.1.0
 */
function GetPageSize()
{
// Set the number of rows to show. If
$nRows=($this->NoSearchBox())?1000:$this->tblFields['PagSize']->GetValue();
return($nRows);
}

/**
 * Add the control to ask the number of rows per page to tblfield
 * Function called by CYAP::Cyap
 * @see CYap::CYap
 * @param $nRows Integer Number of\rows per page (default value)
 * @return void
 * @access public
 */
function AddRowPerPage()
{
$this->tblFields['PagSize']=new CYap_clsSearchPageSize(array(),"PagSize");
$this->tblFields['PagSize']->SetLabel($this->Lang['PageLen']);
$this->tblFields['PagSize']->SetDefaultValue(15);
$this->tblFieldsOrder[199]=&$this->tblFields['PagSize'];
}

/**
 * Javascript code to validate the search box form.
 *
 * @access private
 * @return void
 * @see show_form()
 */
function JsSearchFormValidate()
{
echo '
<script type="text/javascript">
function CheckSearchBox(TheForm)
{';
$JsCode='';
foreach($this->tblFields as $FieldName => $Field)
   {
   $JsCode.=$this->tblFields[$FieldName]->JsSearchFieldValidate();
   }
echo $JsCode;
echo '
return true
}
</script>';
}

/**
 * Draw the form.
 * It istances the object SearchLayout and order it to build the HTML code
 * required to display the form.
 * It return the HTML statements required to display the form.
 * @return string
 * @access public
 * @since 2.1.0
 */
function Draw()
{
// Place any required javascript code
// Start the form
$txt="<h3>".$this->Lang['NewSearch']."</h3>
      <form action=".$_SERVER["PHP_SELF"] ." method=post onsubmit='return CheckSearchBox(this)' name='yapfilter'>\n
      <input type=hidden name=daquery value=1>\n
      <input type=hidden name=ev value=YAP_SEARCH>\n";
/*
 * If any layout object is provided I use it, otherwise
 * I instance a new one.
 */
if (is_null($this->LayoutObject))
   eval('$LayoutObj=new ' . $this->LayoutClass .'();');
else
   $LayoutObj=$this->LayoutObject;
$txt.=$LayoutObj->Start();
ksort($this->tblFieldsOrder);
$txt.=$LayoutObj->Draw($this->tblFieldsOrder);
if (is_null($this->SubmitObject))
   eval('$subObj=new ' . $this->SubmitClass .'();');
else
   $subObj=$this->SubmitObject;
$subObj->SetControlLabel($this->Lang['Search']);
$txt.=$LayoutObj->DrawElement($subObj);
$txt.=$LayoutObj->End();
$txt.="</Form>";
$txt.=$LayoutObj->GetJsCode();
return ($txt);
}

} // CYAP_clsSearch

/**
 ***********************************************************************
 *  C Y A P _ c l s L A Y O U T
 **********************************************************************
 * @package CYap
 *
 */
class CYap_clsSearchLayout
{
var $JsCode;
function CYap_clsSearchLayout()
{
$this->JsCode='';
}
/**
 * Begin the job
 *
 * @return string
 */
function Start()
{
return('<table border=0 align=center>');
}
/**
 * End job. Close all pending tags
 *
 * @return string
 */
function End()
{
return('</table>');
}

/**
 * Draw the fields listed by $tblFields
 *
 * @param CYap_clsSearchField $tblFields table of fields to be draw. Passed by reference
 * @return string
 * @access public
 * @since 2.1.0
 */
function Draw($tblFields)
{
$Html='';
foreach($tblFields as $FieldName => $Field)
   {
   if(is_subclass_of($tblFields[$FieldName],'CYap_clsSearchField'))
      $drawObject=$tblFields[$FieldName]->GetDrawObject();
   else
      $drawObject=$tblFields[$FieldName];
   if(!is_subclass_of($drawObject,'CYAP_Control'))
     die('Error: the control object given does not extend the class CYAP_Control');
   $Html.=$this->_DoDraw($drawObject);
   $this->JsCode.=$drawObject->GetJsCode();
   }
return($Html);
}
/**
 * Build the HTML code required to draw the given search field
 *
 * @param CYAP_clsSearchField $element
 * @return string
 * @access public
 * @since 2.1.0
 */
function DrawElement(&$element)
{
   if(is_subclass_of($element,'CYap_clsSearchField'))
      $drawObject=$element->GetDrawObject();
   else
      $drawObject=$element;
   if(!is_subclass_of($drawObject,'CYAP_Control'))
     die('Error: the control object given does not extend the class CYAP_Control');
   $Html=$this->_DoDraw($drawObject);
   return($Html);
}
/**
 * Build the HTML code required to draw the given search field
 *
 * @param CYAP_clsSearchField $element
 * @return string
 * @access public
 * @since 2.1.0
 */
function _DoDraw($DrawObject)
{
$Html="<tr><td>\n";
$Html.=$DrawObject->DrawLabel(false)."\n";
$Html.="</td><td>\n";
$Html.=$DrawObject->Draw(false)."\n";
$Html.="</td></tr>\n";
return($Html);
}

function GetJsCode()
{
return($this->JsCode);
}
}

/***********************************************************************
 *  C Y A P _ c l s 2 C O L U M N L A Y O U T
 ***********************************************************************/
/**
 * @package CYap
 */
class CYAP_cls2ColumnLayout extends CYAP_clsSearchLayout
{
/**
 * Item counter
 *
 * @var integer
 */
var $ElementNo;
function CYAP_cls2ColumnLayout()
{
    parent::CYAP_clsSearchLayout();
    $this->ElementNo=0;
}

function _DoDraw($DrawObject)
{
$this->ElementNo++;
$Html='';
if(is_subclass_of($DrawObject,'CYAP_ViewSubmitButton'))
   {
   // submit button
   if($this->ElementNo>1)
     $Html.="</td></tr>\n";
   $Html.="<tr><td colspan=4>\n";
   $Html.=$DrawObject->Draw(false)."\n";
   $Html.="</td></tr>\n";
   }
else
   {
   // Filter field
   if($this->ElementNo%2)
     $Html.="<tr><td>\n";
   else
     $Html.="</td><td>\n";
   $Html.=$DrawObject->DrawLabel(false)."\n";
   $Html.="</td><td>\n";
   $Html.=$DrawObject->Draw(false)."\n";
   if(!$this->ElementNo%2)
      $Html.="</td></tr>\n";
   }
return($Html);
}

}

/***********************************************************************
 *  C Y A P _ c l s S E A R C H F I E L D
 ***********************************************************************/

/**
 * Base search field definition
 *
 * @package CYap
 *
 */
class CYap_clsSearchField
{

var $Type;
var $PaddingChar;
var $Padding;
var $UseRegex;
var $Label;
/**
 * Field name used to assign a name to input tag on the form
 * @var string
 */
var $MyName;
/**
 * Column name to look for in the database
 * @var string
 */
var $DbField;
/**
 * Display size
 * @var integer
 */
var $Size;
/**
 * Raw value from $_REQUEST array
 * @var string
 */
var $RequestValue;
/**
 * Class used to build the HTML code required to display this field.
 * @var string
 */
var $ViewClass;
/**
 * Istance of $this->Viewclass
 * @var CYap_Control
 */
var $ViewObj;
/**
 * Default value form the field, if any is supplied
 * @var mixed $DefaultValue
 */
var $DefaultValue;
/**
 * @var integer
 */
var $FieldOrder;
/**
 * Enter description here...
 *
 * @param array $cfg Configuration parameters
 * @param string $FieldName
 * @return CYap_clsSearchField
 * @access public
 */
function CYap_clsSearchField($cfg,$FieldName)
{
$this->MyName=$FieldName;
$this->DefaultValue='';
$this->ViewObj=null;
$this->_Initialize();
$this->LoadCFg($cfg);
}
/**
 * utility used to extract the request parameter from the configuration
 * array.
 *
 * @param string $paramName
 * @param string[] $cfg
 * @param string $default
 * @return string
 * @access private
 */
function GetParameter($paramName,$cfg,$default)
{
return((array_key_exists($paramName,$cfg))?
                $cfg[$paramName]:
                $default);
}
/**
 * Set the properties to the default value
 * @access private
 *
 */
function _Initialize()
{
$this->Type='';
$this->DbField=' ';
$this->PaddingChar=' ';
$this->Padding='none';
$this->UseRegex='0';
$this->Size=0;
$this->ViewClass='CYAP_ViewTextBox';
$this->Label=' ';
}
/**
 * Parse and load the configuration parameters
 *
 * @param string[] $cfg
 * @access public
 * @return void
 */
function LoadCFg($cfg)
{
if(array_key_exists("type",$cfg))
   $this->Type=$cfg["type"];
if(array_key_exists("fieldname",$cfg))
   $this->DbField=$cfg["fieldname"];
if(array_key_exists("paddingchar",$cfg))
   $this->PaddingChar=$cfg["paddingchar"];
if(array_key_exists("padding",$cfg))
   $this->Padding=$cfg["padding"];
if(array_key_exists("useregex",$cfg))
   $this->UseRegex=$cfg["useregex"];
if(array_key_exists("size",$cfg))
   $this->Size=$cfg["size"];
if(array_key_exists("viewclass",$cfg))
   $this->ViewClass=$cfg["viewclass"];
if(array_key_exists("description",$cfg))
   $this->Label=$cfg["description"];
}
/**
 * Set the default value. Used the value from $_REQUEST is null
 * It set the variable CYap_clsSearchField::DefaultValue
 *
 * @param string $value
 * @access public
 * @return void
 */
function SetDefaultValue($value)
{
$this->DefaultValue=$value;
}
function SetLabel($value)
{
$this->Label=$value;
}
/**
 * Generic function to set the paramters without create many set function
 * as the property declared by each control
 * @param Property string
 * @param Value mixed
 * @access public
 */
function SetProperty($Property,$value)
{
// TODO check whether the property exists
eval('$this->'.$Property.'=$value;');
}
/**
 * Get the value of the requested property
 *
 * @param string $Property
 * @return mixed
 * @access public
 */
function GetProperty($Property)
{
// TODO check whether the property exists
eval('return($this->'.$Property.');');
}
/**
 *
 * @param CYap_Db $db_class
 * @return String
 * @access public
 * @since 2.1.0
 */
function GetWhereCondition($db_class)
{
Return("");
}
/**
 * Return the field value. It may be the data read from the form, if any,
 * or the default value
 *
 * @return string
 * @access public
 */
function GetValue()
{
if($this->RequestValue!='' && !is_null($this->RequestValue))
   return($this->RequestValue);
else
   return($this->DefaultValue);
}

/**
 * All other info are retrievd from cfg file. Only the value posted from the form
 * needs to be saved.
 *
 * @param string $prefix
 * @access public
 * @return void
 */
function StoreInformation($prefix)
{
$_SESSION[$prefix."F".$this->MyName]=$this->RequestValue;
}
/**
 * Load the field value from session.
 * @see StoreInformation
 * @param string $prefix
 * @access public
 * @return void
 */
function LoadInformation($prefix)
{
if(array_key_exists($prefix."F".$this->MyName,$_SESSION))
    {
	$this->RequestValue=$_SESSION[$prefix."F".$this->MyName];
	if(is_null($this->RequestValue))
      $this->RequestValue=$this->DefaultValue;
    }
else
    $this->RequestValue=$this->DefaultValue; // if any
}

function CleanSessionInfo($prefix)
{
if(isset($_SESSION[$prefix."F".$this->MyName]))
   unset($_SESSION[$prefix."F".$this->MyName]);
}
/**
 * Read data from search form. Each field retrieves its own value.
 * If the value is not found, the default value is assumed.
 */
function ReadFormData()
{
if(isset($_REQUEST["F".$this->MyName])&&$_REQUEST["F".$this->MyName]!='')
  {
   $this->RequestValue=$_REQUEST["F".$this->MyName];
   if(is_null($this->RequestValue))
      $this->RequestValue=$this->DefaultValue;
   }
else
   $this->RequestValue=$this->DefaultValue;
}

/**
 * Js code to validate the field value called by CYAP_clsSearch
 * Abstract
 * @access public
 * @return void
 * @see show_form()
 */
function JsSearchFieldValidate()
{
return('');
}
/**
 * Draw the field.
 * @access public
 * @return CYap_Control object
 */
function &GetDrawObject()
{
}

/**
 * Istance of ViewClass
 * @access public
 * @return CYAP_Control object
 */
function _MakeViewObj()
{
if(is_null($this->ViewObj))
   {
   $this->ViewObj=new $this->ViewClass();
   $this->ViewObj->SetControlLabel($this->Label);
   $this->ViewObj->SetControlName('F'.$this->MyName);
   $this->ViewObj->SetValue($this->GetValue());
   }
return($this->ViewObj);
}
}  // CYAP_clsSearchField


/**
 * @package CYap
 */
class CYap_clsSearchTxt extends CYap_clsSearchField
{


function CYap_clsSearchTxt($cfg,$FieldName)
{
parent::CYap_clsSearchField($cfg,$FieldName);
}
/**
 *
 * @param CYap_Db $db_class
 * @return String
 * @access public
 * @since 2.1.0
 */
function GetWhereCondition($db_class)
{
$RetValue="";	
// Field not required
if($this->RequestValue=='')
  {
  return($RetValue);
  }

// variabile inserita
if ($this->Type=="A")
   {
   // Uso regex? Se si alzo il flag del campo FieldUseRegex, se no eseguo il padding del campo
   if($this->UseRegex=="1")
     {
     $RetValue=$db_class->DbRegexCond($this->DbField,$db_class->DBEscape($this->RequestValue)).' ';
     }
   else
     {
     $LookFor=$this->var_padding($this->Size,$this->Padding,$this->PaddingChar,$this->RequestValue);
     $RetValue=$this->DbField.'=\''.$db_class->DBEscape($LookFor).'\' ';
     }
   }
else
   {
   // numeric field
   $LookFor=$this->RequestValue;
   $RetValue=$this->DbField.'='.$db_class->DBEscape($LookFor).' ';
   }
return($RetValue);
}

/**
 * Pad the given field to match the requested size
 *
 * @param integer the output size
 * @param string type of pad (none,left,right,center)
 * @param string char to use to pad
 * @param string input text
 * @return string the 'padded' string
 * @access private
 */
function var_padding($size,$padding,$paddingchar,$text)
{
if($padding=='none') { return($text); }
switch($padding)
    {
    case 'left': $cmd=STR_PAD_LEFT;
                 break;
    case 'right': $cmd=STR_PAD_RIGHT;
                 break;
    case 'center': $cmd=STR_PAD_BOTH;
                 break;
    default:
            trigger_error('ERROR: invalid padding value '.$padding,E_USER_ERROR);
            break;
    }
$dimTesto=strlen($text);
// se la dimensione è sufficiente restituisco la stringa
if ($dimTesto<$size) { return(str_pad($text, $size, $paddingchar, $cmd)); }
else {return($text); }
}
/**
 * Draw the field.
 * @access public
 * @return CYap_Control object
 */
function &GetDrawObject()
{
$ViewObj=$this->_MakeViewObj();
$ViewObj->SetProperty('Size',$this->Size);
return($ViewObj);
}
}
/**
 * @package CYap
 */
class CYap_clsSearchPageSize extends CYap_clsSearchField
{
function CYap_clsSearchPageSize($cfg,$FieldName)
{
parent::CYap_clsSearchField($cfg,$FieldName);
$this->Size=4;
}
/**
 * The PageSize doesn't return any where condition
 * 
 *
 * @param CYap_Db $db_class
 * @return String
 * @access public
 * @since 2.1.0
 */
function GetWhereCondition($db_class)
{
return('');
}

/**
 * Draw the field.
 * @access public
 * @return CYap_Control object
 */
function &GetDrawObject()
{
$ViewObj=$this->_MakeViewObj();
$ViewObj->SetProperty('Size',$this->Size);
return($ViewObj);
}

}

/**
 * Class that allows the user to tell whether look for the
 * exact given text or use the regular expression statement.
 * It is usefull mainly due performance reason. The like statement
 * is more resource expensive and it requires more time to return the answer.
 * So if your user doesn't need to use the pattern match feature,
 * he may disable and get more quickly answer.
 *
 * @package CYap
 *
 */
class CYap_clsSearchRegexOpt extends CYap_clsSearchTxt
{

var $RegexValue;
function CYap_clsSearchRegexOpt($cfg,$FieldName)
{
parent::CYap_clsSearchTxt($cfg,$FieldName);
}
/**
 * Set the properties to the default value
 * @access private
 *
 */
function _Initialize()
{
parent::_Initialize();
$this->ViewClass='CYap_ViewOptRegex';
}
/**
 * Parse and load the configuration parameters
 *
 * @param string[] $cfg
 * @access public
 * @return void
 */
function LoadCfg($cfg)
{
parent::LoadCFg($cfg);
if(!is_subclass($this->ViewClass,'CYap_ViewOptRegex'))
  die('Error: the provided view class '.$this->ViewClass.' is not subclass of CYap_ViewOptRegex');
$this->RegexValue=$this->UseRegex;
}
/**
 *
 */
function GetWhereCondition($Db_Class)
{
// Field not required
if($this->RequestValue=='')
  {
  return('');
  }

// variabile inserita
if ($this->Type=="A")
   {
   // Uso regex? Se si alzo il flag del campo FieldUseRegex, se no eseguo il padding del campo
   if($this->RegexValue=="1")
     return($Db_Class->DbRegexCond($this->DbField,$Db_Class->DBEscape($this->RequestValue)).' ');
   else
      {
     $LookFor=$this->var_padding($this->Size,$this->Padding,$this->PaddingChar,$this->RequestValue);
     return($this->DbField.'=\''.$Db_Class->DBEscape($LookFor).'\' ');
     }
   }
else
   {
   // numeric field
   $LookFor=$this->RequestValue;
   return($this->DbField.'='.$Db_Class->DBEscape($LookFor).' ');
   }
}
/**
 * Read data from search form. Each field retrieves its own value.
 * If the value is not found, the default value is assumed.
 */
function ReadFormData()
{
// The text is retrieved by the standard function
parent::ReadFormData();
// Now I retrieve the 'complete word flag
if(isset($_REQUEST["F".$this->MyName."_compWord"])&&$_REQUEST["F".$this->MyName."_compWord"]!='')
  {
  /**
   * Note: when checked, the checkbox means 'exact macth' so it doesn't need the
   *       regular expression therefore RegexValue=0
   *       On the contrary, if the checkbox is not set, the partial match is given.
   */
   $this->RegexValue=($_REQUEST["F".$this->MyName."_compWord"]=='on')?'0':'1';
   }
else
   $this->RegexValue=$this->UseRegex;
}
/**
 * Draw the field.
 * @access public
 * @return CYap_Control object
 */
function &GetDrawObject()
{
$ViewObj=$this->_MakeViewObj();
$ViewObj->SetProperty('Size',$this->Size);
$ViewObj->SetProperty('UseRegex',$this->RegexValue);
return($ViewObj);
}

/**
 * All other info are retrievd from cfg file. Only the value posted from the form
 * needs to be saved.
 *
 * @param string $prefix
 * @access public
 * @return void
 */
function StoreInformation($prefix)
{
parent::StoreInformation($prefix);
$_SESSION[$prefix."F".$this->MyName.'_regex']=$this->RegexValue;
}
/**
 * Load the field value from session.
 * @see StoreInformation
 * @param string $prefix
 * @access public
 * @return void
 */
function LoadInformation($prefix)
{
parent::LoadInformation($prefix);
if(array_key_exists($prefix."F".$this->MyName.'_regex',$_SESSION))
    {
	$this->RegexValue=$_SESSION[$prefix."F".$this->MyName.'_regex'];
	if(is_null($this->RegexValue))
      $this->RegexValue=$this->UseRegex;
    }
else
    $this->RegexValue=$this->UseRegex; // if any
}

function CleanSessionInfo($prefix)
{
parent::CleanSessionInfo($prefix);
if(isset($_SESSION[$prefix."F".$this->MyName.'_regex']))
   unset($_SESSION[$prefix."F".$this->MyName.'_regex']);
}
}



/**
 * @package CYap
 */
class CYap_clsSearchSelectBox extends CYap_clsSearchField
{
/**
 * Options list. The keys are the option and the values are the
 * value returned by the selected option
 * @var string[]
 */
var $OptionList;

function CYap_clsSearchSelectBox($cfg,$FieldName)
{
parent::CYap_clsSearchField($cfg,$FieldName);
}
/**
 * Set the properties to the default value
 * @access private
 *
 */
function _Initialize()
{
parent::_Initialize();
$this->OptionList=array();
$this->ViewClass='CYap_SelectBox';
$this->DefaultValue='NOFILTER';
}
/**
 * Parse and load the configuration parameters
 *
 * @param string[] $cfg
 * @access public
 * @return void
 */
function LoadCfg($cfg)
{
parent::LoadCFg($cfg);
if(array_key_exists("optionlist",$cfg))
   $this->OptionList=$cfg["optionlist"];
if(!is_subclass($this->ViewClass,'CYap_SelectBox'))
  die('Error: the provided view class '.$this->ViewClass.' is not subclass of CYap_SelectBox');
$this->RegexValue=$this->UseRegex;
}
/**
 * Add the options to choose from.
 *
 * @param string $Text Option label
 * @param string $Value Value returned by the option
 * @access public
 * @return void
 */
function AddOption($Text,$Value)
{
$this->OptionList[$Value]=$Text;
}
/**
 * @param CYap_Db $db_class
 * @return String
 * @access public
 * @since 2.1.0
 */
function GetWhereCondition($Db_Class)
{
// Field not required
/**
 * Special values ALL and NOFILTER tell the class to not apply any filter
 */
if($this->RequestValue==''||$this->RequestValue=='ALL'||$this->RequestValue=='NOFILTER')
  {
  return('');
  }
$LookFor=$this->RequestValue;
if ($this->Type=="A")
   // Search as text
   return($this->DbField.'=\''.$Db_Class->DBEscape($LookFor).'\' ');
else
   // Search as number
   return($this->DbField.'='.$Db_Class->DBEscape($LookFor).' ');
}
/**
 * Draw the field.
 * @access public
 * @return CYap_Control object
 */
function &GetDrawObject()
{
$ViewObj=$this->_MakeViewObj();
$ViewObj->SetProperty('Choices',$this->OptionList);
return($ViewObj);
}
}

/**
 * @package CYap
 */
class CYap_clsSearchRangeTxt extends CYap_clsSearchField
{
/*
 * Some rules:
 *
 * $RequestValue is assumed as from,
 * $RequestValueTo is the to field
 * $DefaultValue is assumed as from
 * $DefaultValueTo is the 'to' default
 * if only the from, or only the to RequestValue (or DefaultValue) is filled
 * the 'to' and the 'from' values are set equal
 */

var $RequestValueTo;
var $DefaultValueTo;

function CYap_clsSearchRangeTxt($cfg,$FieldName)
{
parent::CYap_clsSearchField($cfg,$FieldName);
$this->UseRegex='0';
if(is_null($this->DefaultValueTo))
  $this->DefaultValueTo=$this->DefaultValue;
}
/**
 * Set the properties to the default value
 * @access private
 *
 */
function _Initialize()
{
parent::_Initialize();
$this->DefaultValueTo='';
$this->ViewClass='CYAP_ViewTextRange';
}
/**
 * Parse and load the configuration parameters
 *
 * @param string[] $cfg
 * @access public
 * @return void
 */
function LoadCfg($cfg)
{
parent::LoadCFg($cfg);
if(array_key_exists("defaultto",$cfg))
   $this->DefaultValueTo=$cfg["defaultto"];
if(!is_subclass($this->ViewClass,'CYAP_ViewTextRange'))
  die('Error: the provided view class '.$this->ViewClass.' is not subclass of CYAP_ViewTextRange');
}
/**
 * @param CYap_Db $db_class
 * @return String
 * @access public
 * @since 2.1.0
 */
function GetWhereCondition($Db_Class)
{
// Field not required
if($this->RequestValue=='')
  {
  return('');
  }

// variabile inserita
if ($this->Type=="A")
   {
   $LookForFrom=$this->var_padding($this->Size,$this->Padding,$this->PaddingChar,$this->RequestValue);
   $LookForTo=$this->var_padding($this->Size,$this->Padding,$this->PaddingChar,$this->RequestValueTo);
   return($Db_Class->DbBetweenCond($this->DbField,$Db_Class->DBEscape($this->RequestValue),$Db_Class->DBEscape($this->RequestValueTo),'DB_TEXT').' ');
   }
else
   {
   // numeric field
   $LookForFrom=$this->RequestValue;
   $LookForTo=$this->RequestValueTo;
   return($Db_Class->DbBetweenCond($this->DbField,$Db_Class->DBEscape($this->RequestValue),$Db_Class->DBEscape($this->RequestValueTo),'DB_NUMBER').' ');
   }
}

/**
 * Pad the given field to match the requested size
 *
 * @param integer the output size
 * @param string type of pad (none,left,right,center)
 * @param string char to use to pad
 * @param string input text
 * @return string the 'padded' string
 * @access private
 */
function var_padding($size,$padding,$paddingchar,$text)
{
if($padding=='none') { return($text); }
switch($padding)
    {
    case 'left': $cmd=STR_PAD_LEFT;
                 break;
    case 'right': $cmd=STR_PAD_RIGHT;
                 break;
    case 'center': $cmd=STR_PAD_BOTH;
                 break;
    default:
            trigger_error('ERROR: invalid padding value '.$padding,E_USER_ERROR);
            break;
    }
$dimTesto=strlen($text);
// se la dimensione è sufficiente restituisco la stringa
if ($dimTesto<$size) { return(str_pad($text, $size, $paddingchar, $cmd)); }
else {return($text); }
}

/**
 * Read data from search form. Each field retrieves its own value.
 * If the value is not found, the default value is assumed.
 */
function ReadFormData()
{
if(isset($_REQUEST["F".$this->MyName])&&$_REQUEST["F".$this->MyName]!='')
  {
   $this->RequestValue=$_REQUEST["F".$this->MyName];
   if(is_null($this->RequestValue))
      $this->RequestValue=$this->DefaultValue;
   }
else
   $this->RequestValue=$this->DefaultValue;
if(isset($_REQUEST["F".$this->MyName."_To"])&&$_REQUEST["F".$this->MyName."_To"]!='')
  {
   $this->RequestValueTo=$_REQUEST["F".$this->MyName."_To"];
   if(is_null($this->RequestValueTo))
      $this->RequestValueTo=$this->DefaultValueTo;
   }
else
   $this->RequestValueTo=$this->DefaultValueTo;
if((is_null($this->RequestValue)||$this->RequestValue=='')&&!is_null($this->RequestValueTo))
  $this->RequestValue=$this->RequestValueTo;
elseif(!is_null($this->RequestValue)&&(is_null($this->RequestValueTo)||$this->RequestValueTo==''))
  $this->RequestValueTo=$this->RequestValue;
}
/**
 * Return the field value. It may be the data read from the form, if any,
 * or the default value
 *
 * @return string
 * @access public
 */
function GetValueTo()
{
if($this->RequestValueTo!='' && !is_null($this->RequestValueTo))
   return($this->RequestValueTo);
else
   return($this->DefaultValueTo);
}
/**
 * Set the default value. Used the value from $_REQUEST is null
 * It set the variable CYap_clsSearchField::DefaultValue
 *
 * @param string $value
 * @access public
 * @return void
 */
function SetDefaultValueTo($value)
{
$this->DefaultValueTo=$value;
}
/**
 * All other info are retrievd from cfg file. Only the value posted from the form
 * needs to be saved.
 *
 * @param string $prefix
 * @access public
 * @return void
 */
function StoreInformation($prefix)
{
parent::StoreInformation($prefix);
$_SESSION[$prefix."F".$this->MyName."_To"]=$this->RequestValueTo;
}
/**
 * Load the field value from session.
 * @see StoreInformation
 * @param string $prefix
 * @access public
 * @return void
 */
function LoadInformation($prefix)
{
parent::LoadInformation($prefix);
if(array_key_exists($prefix."F".$this->MyName."_To",$_SESSION))
    {
	$this->RequestValueTo=$_SESSION[$prefix."F".$this->MyName."_To"];
	if(is_null($this->RequestValueTo))
      $this->RequestValueTo=$this->DefaultValueTo;
    }
else
    $this->RequestValueTo=$this->DefaultValueTo; // if any
}

function CleanSessionInfo($prefix)
{
parent::CleanSessionInfo($prefix);
if(isset($_SESSION[$prefix."F".$this->MyName."_To"]))
   unset($_SESSION[$prefix."F".$this->MyName."_To"]);
}
/**
 * Draw the field.
 * @access public
 * @return CYap_Control object
 */
function &GetDrawObject()
{
$ViewObj=$this->_MakeViewObj();
$ViewObj->SetValueTo($this->GetValueTo());
$ViewObj->SetProperty('Size',$this->Size);
$ViewObj->SetControlNameTo('F'.$this->MyName.'_To');
return($ViewObj);
}
}

/**
 * @package CYap
 */
class CYap_clsSearchDate extends CYap_clsSearchField
{
/*
 * Some rules:
 * The value is archived as timestamp, but it is shown according to the
 * given format
 */

var $ShowFormat;
var $WhereFormat;

function CYap_clsSearchDate($cfg,$FieldName)
{
parent::CYap_clsSearchField($cfg,$FieldName);
}
/**
 * Set the properties to the default value
 * @access private
 *
 */
function _Initialize()
{
parent::_Initialize();
$this->ShowFormat='d-m-Y';
$this->WhereFormat='Ymd';
$this->ViewClass='CYAP_ViewDate';
}
/**
 * Parse and load the configuration parameters
 *
 * @param string[] $cfg
 * @access public
 * @return void
 */
function LoadCfg($cfg)
{
parent::LoadCFg($cfg);
if(array_key_exists("showformat",$cfg))
   $this->ShowFormat=$cfg["showformat"];
if(array_key_exists("showformat",$cfg))
   $this->WhereFormat=$cfg["filterformat"];
if(!is_subclass($this->ViewClass,'CYap_ViewDate'))
  die('Error: the provided view class '.$this->ViewClass.' is not subclass of CYAP_ViewDate');
}
/**
 * @param CYap_Db $db_class
 * @return String
 * @access public
 * @since 2.1.0
 */
function GetWhereCondition($Db_Class)
{
// Field not required
if($this->RequestValue=='')
  {
  return('');
  }
// variabile inserita
if ($this->Type=="A")
   {
   if($this->WhereFormat==strtoupper('TIMESTAMP'))
      $cond= $this->DbField.'= \''.$this->RequestValue.'\'';
   else
      $cond= $this->DbField.'= \''.date($this->WhereFormat,$this->RequestValue).'\'';
   }
else
   {
   if($this->WhereFormat==strtoupper('TIMESTAMP'))
      $cond= $this->DbField.'='.$this->RequestValue.' ';
   else
      $cond= $this->DbField.'= '.date($this->WhereFormat,$this->RequestValue).' ';
   }
return($cond);
}

/**
 * Read data from search form. Each field retrieves its own value.
 * If the value is not found, the default value is assumed.
 */
function ReadFormData()
{
if(isset($_REQUEST["F".$this->MyName])&&$_REQUEST["F".$this->MyName]!='')
  {
   $InsertValue=$_REQUEST["F".$this->MyName];
   if(is_null($InsertValue))
      $this->RequestValue=$this->DefaultValue;
   else
     {
      // Convert $this->ShowFormat to Format string accepted by parseDate
      $cond='/([dmYHM])/';
      $replace='%${1}';
      $Format=preg_replace($cond,$replace,$this->ShowFormat);
      $this->RequestValue=@strtotime($this->parseDate($InsertValue,$Format));
      if($this->RequestValue===false)
        {
        // Invalid date . TODO show some message
        $this->RequestValue=$this->DefaultValue;
        }
     }
   }
else
   $this->RequestValue=$this->DefaultValue;
}

/**
 * Returns a formatted date from a string based on a given format
 * (from PHP Manual)
 * Supported formats
 *
 * %Y - year as a decimal number including the century
 * %m - month as a decimal number (range 1 to 12)
 * %d - day of the month as a decimal number (range 1 to 31)
 *
 * %H - hour as decimal number using a 24-hour clock (range 0 to 23)
 * %M - minute as decimal number
 * %s - second as decimal number
 * %u - microsec as decimal number
 * @param string date  string to convert to date
 * @param string format expected format of the original date
 * @return string rfc3339 w/o timezone YYYY-MM-DD YYYY-MM-DDThh:mm:ss YYYY-MM-DDThh:mm:ss.s
 */
function parseDate( $date, $format ) {
  // Builds up date pattern from the given $format, keeping delimiters in place.
  if( !preg_match_all( "/%([YmdHMsu])([^%])*/", $format, $formatTokens, PREG_SET_ORDER ) ) {
   return false;
  }
  $datePattern='';
  foreach( $formatTokens as $formatToken ) {
   if(array_key_exists(2,$formatToken))
      $delimiter = preg_quote( $formatToken[2], "/" );
   else
      $delimiter='';
   if($formatToken[1] == 'Y') {
     $datePattern .= '(.{1,4})'.$delimiter;
   } elseif($formatToken[1] == 'u') {
     $datePattern .= '(.{1,5})'.$delimiter;
   } else {
     $datePattern .= '(.{1,2})'.$delimiter;
   }
  }

  // Splits up the given $date
  if( !preg_match( "/".$datePattern."/", $date, $dateTokens) ) {
   return false;
  }
  $dateSegments = array();
  for($i = 0; $i < count($formatTokens); $i++) {
   $dateSegments[$formatTokens[$i][1]] = $dateTokens[$i+1];
  }

  // Reformats the given $date into rfc3339

  if( $dateSegments["Y"] && $dateSegments["m"] && $dateSegments["d"] ) {
   if( ! checkdate ( $dateSegments["m"], $dateSegments["d"], $dateSegments["Y"] )) { return false; }
   $dateReformated =
     str_pad($dateSegments["Y"], 4, '0', STR_PAD_LEFT)
     ."-".str_pad($dateSegments["m"], 2, '0', STR_PAD_LEFT)
     ."-".str_pad($dateSegments["d"], 2, '0', STR_PAD_LEFT);
  } else {
   return false;
  }
  /*
  if( $dateSegments["H"] && $dateSegments["M"] ) {
   $dateReformated .=
     "T".str_pad($dateSegments["H"], 2, '0', STR_PAD_LEFT)
     .':'.str_pad($dateSegments["M"], 2, '0', STR_PAD_LEFT);

   if( $dateSegments["s"] ) {
     $dateReformated .=
       ":".str_pad($dateSegments["s"], 2, '0', STR_PAD_LEFT);
     if( $dateSegments["u"] ) {
       $dateReformated .=
       '.'.str_pad($dateSegments["u"], 5, '0', STR_PAD_RIGHT);
     }
   }
  } */

  return $dateReformated;
}


/**
 * Draw the field.
 * @access public
 * @return CYap_Control object
 */
function &GetDrawObject()
{
$ViewObj=$this->_MakeViewObj();
$ViewObj->SetProperty('ShowFormat',$this->ShowFormat);
return($ViewObj);
}
}
?>
Return current item: Yet Another Pager