/**
* @author Gianluca GIMIGLIANO
* @package myFields
*/
/**#@+ @ignore */
if (!class_exists('mySessions')) include_once(dirname(__FILE__).'/mySessions.php');
if (!class_exists('myCSS')) include_once(dirname(__FILE__).'/myCSS.php');
if (!class_exists('myDizionario')) include_once(dirname(__FILE__).'/myDizionario.php');
if (!class_exists('myArrayObject')) include_once(dirname(__FILE__).'/myArrayObject.php');
if (!class_exists('myJQuery')) include_once(dirname(__FILE__).'/myJQuery.php');
if (!class_exists('mySecurizer')) include_once(dirname(__FILE__).'/myPlugins/mySecurizer.php');
if (!class_exists('myAjaxFileManagerPlugin')) include_once(dirname(__FILE__).'/myPlugins/myAjaxFileManagerPlugin.php');
/**#@-*/
/** @ignore */
class Data {
public $errore,$formato,$mask,$value;
function Data ($formato="gma",$val='') {
$formato=strtolower($formato);
$this->errore=null;
if (strlen($formato)!=3 || strpos($formato,'g')===false
|| strpos($formato,'m')===false || strpos($formato,'a')===false
) $this->errore="Formato errato";
else {$this->formato=$formato;
$this->mask[0]=$formato[0];
$this->mask[1]=$formato[1];
$this->mask[2]=$formato[2];
$this->mask=array_flip($this->mask);
$this->check_value($val);
$this->set_value($val);
}
}
function get_expr () {
if ($this->formato[0]=='g' || $this->formato[0]=='m') $x.='[0-9]{1,2}[/.-]';
if ($this->formato[0]=='a') $x.='[0-9]{4}[/.-]';
$x.='[0-9]{1,2}[/.-]';
if ($this->formato[2]=='g' || $this->formato[2]=='m') $x.='[0-9]{1,2}';
if ($this->formato[2]=='a') $x.='[0-9]{4}';
return "^$x\$|^[0-9]{8}\$";
}
function set_value($val){
if (preg_match('/[0-9]{8}/S',$val)) $val="$val[0]$val[1]/$val[2]$val[3]/$val[4]$val[5]$val[6]$val[7]";
$this->value=str_replace(array('\\','.','-'),array('/','/','/'),$val);
}
function check_value($val='') {
unset($this->errore);
if ($val=='') return $val;
if (!preg_match("#{$this->get_expr()}#S",$val)) $this->errore=" è scorretto, il formato data ammesso è ".$this->get_format();
else {
if (preg_match('/[0-9]{8,8}/S',$val)) $val="$val[0]$val[1]/$val[2]$val[3]/$val[4]$val[5]$val[6]$val[7]";
$val=preg_split('~[/.-]~',str_replace('\\','-',$val));
$ok=@checkdate ((int) $val[$this->mask['m']],(int) $val[$this->mask['g']],(int) $val[$this->mask['a']]);
if (!$ok) $this->errore="Data errata";
}
}
function anglo($x) {
if ($x=='g') return 'd';
if ($x=='m') return 'm';
if ($x=='a') return 'Y';
}
function get_format () {
$x=$this->formato[0].'/'.$this->formato[1].'/'.$this->formato[2];
$x=str_replace('g','gg',$x);
$x=str_replace('m','mm',$x);
return str_replace('a','aaaa',$x);
}
function get_value_formatted($formato='gma',$sep='/') {
if (!$this->value) return '';
$val=explode("/",$this->value);
$mask[0]=$formato[0];
$mask[1]=$formato[1];
$mask[2]=$formato[2];
foreach ($mask as $va) $x[]=sprintf('%02d',$val[$this->mask[$va]]);
return implode($sep,$x);
}
function check ($data) {
$this->check_value($data);
return $this->errore;
}
}
######################################################################################################################
/**
* @package myFields
*
* Classe base per produrre un tag html,
* es.
*
* echo new MyTag('a',array('href'=>'#'), //tag Anchor che ha come attributo href=#
* new MyTag('b','','link') //contenuto dell'Anchor è un tag Bold che contiene la stringa 'link'
* );
* echo new MyTag('hr'); //mostra un filetto hr
*
* il risultato sarà:
* <a href="#" ><b >link</b></a>
* <hr />
*
*
* echo new MyTag('a',array('href'=>'#'), //tag Anchor che ha come attributo href=#
* new MyTag('b','','link') //contenuto dell'Anchor è un tag Bold che contiene la stringa 'link'
* );
* echo new MyTag('hr'); //mostra un filetto hr
*
* Stesso risultato se si scrive
*
* echo new MyTag("",'',
* new MyTag('b','','link') //contenuto dell'Anchor è un tag Bold che contiene la stringa 'link'
* );
* echo new MyTag('hr'); //mostra un filetto hr
*
*/
class MyTag implements ArrayAccess {
/**#@+ @ignore */
protected $attributi=array(),$javascript='',$tagName='',$contenuto=null,$id_istance;
protected static $id_istanza=1;
public function offsetSet($offset, $value) {
$this->set_attributo($value,$offset);
}
public function offsetExists($offset) {
return $this->get_attributo($offset)!='';
}
public function offsetUnset($offset) {
$this->unset_attributo($offset);
}
public function offsetGet($offset) {
return $this->get_attributo($offset);
}
public static function crea_id_istanza() {
return ++self::$id_istanza;
}
/**#@-*/
/**
* Costruttore
*
* @param string $nome può essere il nome, o anche semplicemente l'html del tag da creare (in questo caso vanno omessi gli altri due parametri)
* @param array $attributi array con gli attributi del tag
* @param string/object $contenuto eventuale contenuto del tag può essere una stringa o un oggetto che implementa __toString es lo stesso myTga o estensioni
*/
function __construct($nome='',$attributi=array(),$contenuto=null) {
$this->id_istanza=self::crea_id_istanza();
$nome=trim($nome);
if(preg_match('#^[a-z]*$#iS',$nome,$m)) $this->tagName=strtolower($nome);
else {
if(!preg_match('#^<([a-z]+)#iS',$nome,$m)) $this->tagName=strtolower($m[1]);
$this->importa_attributi($nome);
}
$this->attributi+=array_change_key_case((array) $attributi);
$this->contenuto=$contenuto;
}
/** assegna un JS ad un evento, di default è onclick
* @param string $JS E' lo JavaScript da lanciare
* @param string $evento Il nome dell'evento su cui attivare lo JS
* @param boolean $sostituisci sostituisce eventuali eventi precedenti
*/
function SetJS($JS,$evento='onclick',$sostituisci=true) {
$prec=$this->get_attributo(strtolower($evento));
if(!$sostituisci && $prec) $JS="$prec;$JS";
$this->set_attributo(strtolower($evento),str_replace('"','\\"',$JS));
return $this;
}
/**
* alias di @see setjs
*/
function set_js($JS,$evento='onclick',$sostituisci=true) {
return $this->setjs($JS,$evento,$sostituisci);
}
/** Restituisce il campo in html pronto per la visualizzazione
* @return string
*/
function get_Html () {
if (!trim($this->tagName)) return $this->stringa_attributi();
else return $this->jsAutotab().
($this->contenuto===null)?"<$this->tagName {$this->stringa_attributi()} />":
"<$this->tagName {$this->stringa_attributi()}>{$this->contenuto}$this->tagName>";
}
function get_id_istanza(){
return $this->id_istance;
}
/** @ignore*/
function Nonhtmlentities( $string ){
if (is_callable('html_entity_decode')) return html_entity_decode($string,ENT_QUOTES,'ISO-8859-1');
// replace numeric entities
$string = preg_replace('~([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $string);
$string = preg_replace('~([0-9]+);~e', 'chr(\\1)', $string);
// replace literal entities
$trans_tbl = get_html_translation_table(HTML_ENTITIES);
$trans_tbl = array_flip($trans_tbl);
return strtr($string, $trans_tbl);
}
/** @ignore*/
function __call($f,$a){
}
/** @ignore*/
function __toString(){
return $this->get_html();
}
/**
* Imposta un attributo, inserendo la coppia (nome_attributo,valore)
* oppure un insieme di attributi se il primo campo è un array
* associativo con tutti gli attributi ed il relativo valore
*
* @param array|string $primo
* @param string $valore
*/
function set_attributo ($primo,$valore='') {
//echo "$primo=$valore ";
if (is_array($primo)) foreach ($primo as $nome=>$valore)
{$nome=trim(strtolower($nome));
/* if ($nome=='style') $this->set_style($valore);
else */
$this->attributi[$nome]=(is_array($valore)?$valore:trim($valore));
}
elseif ($valore!==null) { $primo=trim(strtolower($primo));
/*if ($primo=='style') $this->set_style($valore);
else */
$this->attributi[$primo]=(!is_scalar($valore)?$valore:trim($valore));
}
// else $this->unset_attributo('value');
return $this;
}
/**
* @param string $nome
*/
function unset_attributo ($nome) { unset ($this->attributi[$nome]); return $this;}
/**
* @param string $nome
* @return string
*/
function get_attributo($nome) {return $this->attributi[$nome]; }
/**
* @return string
*/
function get_attributi () {return $this->attributi; }
static function unid(){
return session_id().'.'.microtime(1).'.'.rand(1,99999);
}
/**
* Imposta una proprietà css e relativo valore es:
*
* $f->set_style('color','red'); //imposta colore rosso
* $f->set_style('font-weight','bold'); //imposta grassetto
*
* //si può sostituire con
* $f->set_attributo('style','color:red;font-weight:bold'); //ma cochcio alla sintassi
*
*
* @param string $proprieta
* @param string $valore
*/
function set_style($proprieta,$valore){
$css=new myCSS();
$valori=$css->parseStyle($this->attributi['style']);
if (strlen(trim($valore))==0) unset($valori[$proprieta]);
else $valori[$proprieta]=$valore;
$css->add_classe($valori,'classe');
$this->attributi['style']=$css->UnparseStyle('classe',true);
return $this;
}
/**
* Effettua il parsing del html passato
* es
* $x= myTag::parse_attributi_tag(' 'valore1',
* 'secondo' => ' val"ore ',
* 'terzo' => ' " \' " ')
*
* @param string $html è l'HTML da importare
* @param boolean $decode_htmlentities se true le entità html vengono decodificate
*/
static function parse_attributi_tag($html,$decode_htmlentities=true) {
$parametri=array();
$x=trim($html);
if ($x{0}=='<') {$x=explode(' ',$x,2);
$x=$x[1];
}
$x=explode('>',$x,2);
$x=$x[0];
do {$x=explode('=',$x,2);
$x[0]=explode(' ',trim($x[0]));
$parametro=$x[0][count($x[0])-1];
if(!$parametro) break;
$x[1]=trim($x[1]);
if (!$x[1]) break;
$i=1;
$p=-1;
$j=-1;
if ($x[1]{0}=='"') do {$p=strpos($x[1],'"',$i);
if ($p!==false && $x[1]{$p-1}!='\\') break;
$i=$p+1;
} while ($p!==false);
elseif ($x[1]{0}=="'") do {$p=strpos($x[1],"'",$i);
if ($p!==false && $x[1]{$p-1}!='\\') break;
$i=$p+1;
} while ($p!==false);
else {$x[1].=' ';
$j=strpos($x[1]," ");
}
if($j!=-1) {$v=stripslashes(substr($x[1],0,$j));
if ($decode_htmlentities) $v=html_entity_decode($v);
$parametri[trim($parametro)]=$v;
$x=substr($x[1],$j,strlen($x[1])-$j);
}
elseif($p!=-1)
{
$v=stripslashes(substr($x[1],1,$p-1));
if ($decode_htmlentities) $v=html_entity_decode($v);
$parametri[trim($parametro)]=$v;
$x=substr($x[1],$p+1,strlen($x[1])-$p);
}
else break;
} while(true);
return $parametri;
}
/**
* Importa gli attributi espressi sotto forma di stringa
* es
*
* $x= new myTag('a',array('target'=>'_blank'),'click qui');
* $x->importa_attributi(" href=link title='ciao' ");
* echo $x;
* //otterremo:
* click qui
*
*/
function importa_attributi($html) {
$this->attributi+=self::parse_attributi_tag($html);
}
/** @ignore*/
function stringa_attributi ($v=array(),$Esclusi=true,$novalue=false) {
if (!$this->attributi) return '';
$v=@array_flip((array) $v);
foreach ($this->attributi as $nome=>$valore)
if (!is_array($valore) && (abs($Esclusi-isset($v[$nome]))) && $nome!='value' )
{
if ($nome=='style' && trim($valore))
{
$css=new myCSS();
$css->add_classe($css->parseStyle($valore),'classe');
$valore=$css->UnparseStyle('classe',true);
}
if ($nome) $out.=strtolower($nome)."=\"".str_replace('"','"',$valore)."\" ";
else $out.=$valore.' ';
}
if (isset($this->attributi['value']))
{
if (!$Esclusi && isset($v['value'])) $out.='value="'.htmlentities(trim(/*$this->Nonhtmlentities*/(string)$this->attributi['value'])).'"';
elseif ($Esclusi && !isset($v['value']) && !$novalue) $out.='value="'.htmlentities(trim(/*$this->Nonhtmlentities*/(string)$this->attributi['value'])).'"';
}
return $out;
}
/** @ignore */
function clonami() {
if (PHP_VERSION >= 5) return clone($this);
else return $this;
}
/** @ignore */
function __clone(){
if($this->campi)
foreach ($this->campi as $i=>$f) if( is_object($f)) $this->campi[$i]=clone $f;
}
}
/**
* @package myFields
*/
class MyField extends myTag{
/**#@+ @ignore */
public $myFields=array(),$Richiede_tag_label=true, $Prevede_label=true,$con_js=true;
protected
$notnull=null, $controllo_regExp=null, $maxlength,$minlength,$min,$max,
$MyType='',
$Formula=false, $autotab=false, $javascript=false,
$Metodo_ridefinito,
$myJQueries=array(),
$traduzioni,$dizionario,$numerico=false,$notrasl,$xml=array('tag'=>null,'case'=>'','header'=>''),$abilitaXML=true,$facoltativoXML=false;
public function offsetSet($offset, $value) {
if (!$offset) return $this->set_value($value);
else return $this->set_attributo($offset, $value);
}
public function offsetGet($offset) {
if (!$offset) return $this->get_value();
else return $this->get_attributo($offset);
}
/**#@-*/
/**
* Invocato quando questa form viene aggiunta ad una myForm
* con add_campo, eventualmente da ridefinire
**/
function __onAdded(){
}
/**
* Costruttore di classe
*
* @access public
* @param string $nome E' il nome del campo
* @param array|string $valore Valore da assegnare come defaulto array (non assoc) di valori nel caso di campo multivalori
*/
function MyField ($nome='',$valore='')
{self::$id_istanza++;
$this->id_istance=self::$id_istanza;
static $MyField;
$this->myFields= & $MyField;
$this->AbsPath();
if(!isset($this->myFields['static'])) $this->myFields['static']=array();
if(!isset($this->myFields['campo__istanze'])) $this->myFields['campo__istanze']=array();
if(!isset($this->myFields['myForms'])) $this->myFields['myForms']=array();
// if ($nome=='LIVELLO_AUTH') {echo "
$nome ";print_r($this->myFields['campo__istanze']); }
if(!$nome) $nome='myField_'.(++$this->myFields['names']);
if (is_array($nome)) $this->set_attributo($nome);
else {$this->set_name($nome);
$this->set_value($valore);
}
// if ($nome=='LIVELLO_AUTH') {print_r($this->myFields['campo__istanze']); echo "";}
}
/** @ignore*/
protected function AbsPath(){
if (!$_SERVER['myFields']['PathSito'])
{
$_SERVER['myFields']['PathSito']=str_replace('\\','/',$_SERVER['DOCUMENT_ROOT']);
if(substr($_SERVER['DOCUMENT_ROOT'],-1)!='/') $_SERVER['myFields']['PathSito'].='/';
$_SERVER['myFields']['MyFormsPath']=str_replace('//','/',str_ireplace($_SERVER['myFields']['PathSito'],'',str_replace('\\','/',dirname(__FILE__)))).'/';
}
}
/**
* Restituisce tag per il carivcamento di js di utilità
*
*/
function get_js_common() {
return "";
}
function set_abilitazione_js($stato=false) {
$this->con_js=$stato;
return $this;
}
/** Imposta i percorsi da far usare al package, ove non riesca a reperirli in automatico
* @param string $PathSito E' la path assoluta del sito es "c:\wwwwpublic\htdocs"
* @param string $MyFormsPath la path assoluta delle myforms rispetto alla root del sito esl "/librerie/myform"
*/
function setAbsPath($PathSito='',$MyFormsPath='') {
$MyFormsPath=preg_replace('|^/|','',$MyFormsPath);
if($PathSito) $_SERVER['myFields']['PathSito']=str_replace('//','/',"$PathSito/");
if($MyFormsPath) $_SERVER['myFields']['MyFormsPath']=$MyFormsPath.'/';
}
function get_PathSito() {
MyField::AbsPath();
return $_SERVER['myFields']['PathSito'];
}
/**
* Restituisce un booleano che dice se contiene più valori contemporaneamente
* @return boolean
*/
function isMultiple(){
return false;
}
function get_MyFormsPath() {
MyField::AbsPath();
return $_SERVER['myFields']['MyFormsPath'];
}
/**
* Dice se e' numerico questo campo
*
* @param boolean $numerico se omesso restituisce il fatto che sia numerico, se valorizzato setta la caratteristica
* @return boolean
*/
function is_numeric($numerico='')
{if ($numerico!=='') $this->numerico=$numerico;
return $this->numerico;
}
/**
* Imposta una lingua da usare (carica dizionario predefinito dalle myForms)
*
* @param string(2) $lingua codice lingua
*/
function set_lingua($lingua='en') {
if (!$lingua) return ;
$this->dizionario[0]=new myDizionario($lingua);
return $this;
}
/**
* Aggiunge un dizionario alternativo (da usare solo dopo solo dopo myFields::set_lingua)
*
* @param myDizionario $dizionario
* @param string(2) $lingua eventuale codice lingua
*/
function add_dizionario(&$dizionario,$lingua='') {
if ($this->dizionario) {
if (!$lingua) $this->dizionario[]=&$dizionario;
else $this->dizionario[$lingua]=&$dizionario;
}
else die("add_dizionario solo dopo set_lingua");
}
/**
*
* Restituisce l'elenco di tutti i dizionari attivi.
* @return array
*/
function get_dizionario() {
if (!$this->dizionario) return array();
elseif (!is_array($this->dizionario)) return array($this->dizionario);
else return $this->dizionario;
}
/** @ignore */
function trasl($messaggio,$parole='') {
if (!$this->dizionario || $this->notrasl) {
if (!$parole) return $messaggio;
else return strtr($messaggio,$parole);
}
$esito=false;
foreach ($this->dizionario as $i=>&$dizionario)
{
$tradotto=$dizionario->trasl($messaggio,$parole,$esito);
if ($esito && $tradotto) return $tradotto;
}
return $messaggio;
}
/** Restituisce un messaggio se l'attributo value non soddisfa condizioni di notnull,maxlength,minlength
* @return string
*/
function Errore() {
$errore=$this->get_errore_diviso();
if (!is_array($errore)) return $this->trasl($errore);
else { $mess=array_shift($errore);
foreach($errore as $i=>&$v) $messaggi['%'.($i+1).'%']=&$v;
return $this->trasl($mess,$messaggi);
}
}
function get_js_chk(){
$js="
valore=trim(''+document.getElementById('{$this->get_id()}').value);
";
// $js.="alert(valore+'>');";
if ($this->notnull)
$js.="if(strlen(valore)==0) return \"{$this->trasl('non può essere nullo')}\";\n";
else $js.="if(strlen(valore)==0) return ;\n";
if ($this->controllo_regExp['exp']) {
$exp=$this->controllo_regExp['exp'];
$js.="if(valore!='' && valore.match(/{$exp}/)==null) return \"{$this->trasl($this->controllo_regExp['mess'])}\";\n";
}
If (strlen($this->max)>0)
$js.="if (valore!='' && valore>\"{$this->max}\") return \"{$this->trasl('non può essere maggiore di %1%',array('%1%'=>$this->max))}\";\n";
if (strlen($this->min)>0)
$js.="if (valore!='' && valore<\"{$this->min}\") return \"{$this->trasl('non può essere minore di %1%',array('%1%'=>$this->min))}\";\n";
if (strlen($this->maxlength)>0)
$js.="if (valore!='' && strlen(valore)>{$this->maxlength}) return \"{$this->trasl('non può contenere più di %1% caratteri',array('%1%'=>$this->maxlength))}\";\n";
if (strlen($this->minlength)>0)
$js.="if (valore!='' && strlen(valore)<{$this->minlength}) return \"{$this->trasl('deve contenere almeno %1% caratteri',array('%1%'=>$this->minlength))}\";\n";
//$js.="alert(valore+'ok');";
return $js;
}
function get_errore_diviso() {
$valore=$this->get_attributo('value');
if ($this->notnull && strlen(trim((string) $valore))==0) return 'non può essere nullo';
if ($valore && $this->controllo_regExp['exp'] && !preg_match("~{$this->controllo_regExp['exp']}~",$valore)) return $this->controllo_regExp['mess'];
$valore=$this->get_value();
If ($this->maxlength && strlen($valore)>$this->maxlength) return array('non può contenere più di %1% caratteri',$this->maxlength);
if ($valore && $this->minlength && strlen($valore)<$this->minlength) return array('deve contenere almeno %1% caratteri',$this->minlength);
}
/**
* restituisce true se l'oggetto è sottoclasse del parametro
*
* @param string $classe nome della classe
* @param boolean $oppure_e se true restituisce true anche se l'oggetto è istanza di $classe
* @return boolean
*/
function Estende($classe,$oppure_e=false) {
if($oppure_e && $this instanceof $classe) return true;
return is_subclass_of($this,$classe);
}
/**@ignore**/
protected function jsAutotab() {
if (!$this->autotab || $this->myFields['static']['autotab']) return '';
$this->myFields['static']['autotab']=1;
return '';
}
/** Setta la autotabulazione del campo **/
function set_autotab () {
$this->autotab=true;
return $this;
}
/** @ignore*/
function my_js_documentwrite($html,$quote=true) {
$tags=explode('>',$html);
for ($i=0;$i';
if(strlen($testo)>50) {$out.='document.write("'.($quote?str_replace('"','\\"',$testo):$testo)."\");\n";
$testo='';
}
}
$testo.=$tags[count($tags)-1];
return $out.='document.write("'.($quote?str_replace('"','\\"',$testo):$testo)."\");\n";
}
/** Restituisce il nome del tipo del campo
*
* @return string
*/
function get_MyType() {return $this->MyType; }
/** @ignore*/
function set_MyType($nome) {$this->MyType=$nome; }
/** @ignore*/
function get_value_html() {
$valore=$this->get_value();
if (is_array($valore)) return count($valore);
if ($valore==='' || is_array($valore)) return '';
return htmlentities($this->Nonhtmlentities($valore));
}
function get_formula() {
return $this->Formula;
}
function set_formula($formula) {
if (trim($formula)) $this->Formula=$formula;
return $this;
}
/*
*
* @return string
*/
function get_value() {
return $this->get_attributo('value');
}
/** Restituisce l'attributo 'name'
* @return string
*/
function get_name() { return $this->get_attributo('name'); }
/**
*
* Restituisce il valore del minimo impostato
* @return int
*/
function get_min(){return $this->min;}
/**
*
* Restituisce il valore del massimo impostato
* @return int
*/
function get_max(){return $this->max;}
/** Elimina lo showonly
**/
function unset_showonly() {
/*$this->Prevede_label=true;
$this->Richiede_tag_label=true;*/
unset($this->Metodo_ridefinito['get_Html']['metodo']);
unset($this->Metodo_ridefinito['get_Html']['parametri']);
}
/** Imposta lo showonly
* @param $campo_nascosto se true si aggiunge un campo nascosto con il valore del campo se falso si scrive solo la descrizione (default è true)
**/
function set_showonly($campo_nascosto=true) {
/*$this->Prevede_label=true;
$this->Richiede_tag_label=true;*/
$this->Metodo_ridefinito['get_Html']['metodo']='_get_html_show';
$this->Metodo_ridefinito['get_Html']['parametri']=array('campo'=>$campo_nascosto);
return $this;
}
/**
* Stato showonly
*
* @return 0|1|2 = non attivo | campo nascosto | senza campo nascosto
*/
function get_showonly() {
if ($this->Metodo_ridefinito['get_Html']['parametri']['campo']) return 1;
if ($this->Metodo_ridefinito['get_Html']<>'') return 2;
return 0;
}
/** Disattiva lo set_hidden
**/
function unset_hidden() {
if ($this->Metodo_ridefinito['get_Html']['set_hidden'])
{
$this->Prevede_label=$this->Metodo_ridefinito['get_Html']['set_hidden'][0];
$this->Richiede_tag_label=$this->Metodo_ridefinito['get_Html']['set_hidden'][1];
}
unset($this->Metodo_ridefinito['get_Html']['metodo']);
unset($this->Metodo_ridefinito['get_Html']['parametri']);
}
/** Imposta il campo come nescosto
* @param $campo_nascosto se true si aggiunge un campo nascosto con il valore del campo se falso si scrive solo la descrizione (default è true)
**/
function set_hidden() {
$this->Metodo_ridefinito['get_Html']['metodo']='_get_html_hidden';
$this->Metodo_ridefinito['get_Html']['set_hidden']=array($this->Prevede_label, $this->Richiede_tag_label);
$this->Metodo_ridefinito['get_Html']['parametri']=array();
$this->Prevede_label=false;
$this->Richiede_tag_label=false;
return $this;
}
/**
* Restituisce true se hidden abilitato
*
* @return boolean
*/
function is_hidden() {
return $this->Metodo_ridefinito['get_Html']['metodo']=='_get_html_hidden' ||
// $this->get_showonly()===1 || showonly non è nascosto
$this->Estende('myHidden',true);
}
/** @ignore */
protected function _get_html_hidden($pars){
if (!$this->get_attributo['disabled']){
$x=new MyHidden($this->get_name(),$this->get_value());
$x->set_attributo('id',$this->get_id());
return "stringa_attributi()} />";
}
}
/**
* abilita/disabilita l'xml di quel campo
*
* @param abilita $boolean se true l'xml si vede se false non viene mostrato
*/
function set_abilita_xml($abilita=false){
$this->abilitaXML=$abilita;
return $this;
}
/**
* Imposta la facoltatività del tag, se facoltativo @see get_xml non restituirà nulla
* altrimenti si visualizza il tag vuoto
*
* @param abilita $boolean se true l'xml si vede se false non viene mostrato
*/
function set_xml_facoltativo($facoltativo=true){
$this->facoltativoXML=$facoltativo;
return $this;
}
/**
* restituisce il nome del tag XML corrente
* @param boolean $complex se false restituisce il tag; true restituisce un array associatico con chiavi 'tag'=> 'ridefinito'=>boolean che dice se impostato usando @see set_parametri_xml
* @return string
*/
public function get_xml_tag($complex=false){
$tag=($this->xml['']?$this->xml['']:$this->get_name());
$tag=explode('[',$tag,2);
$tag=$tag[0];
if(!$complex) return $tag;
else return array('tag'=>$tag,'ridefinito'=>$this->xml['']!='');
}
/**
* Imposta eventuali variazioni sull'XML prodotto da @see get_xml
*
* @param string $tagName è il tag name che verrà usato nell'xml al posto del nome del campo (se omesso si usa il nome del campo)
* @param array $attributi è l'array associativo che indica la trascodifica degli attributi da visualizzare, la chiave è il nome dell'attributo HTNL il valore è l'attributo XML da usare
* può anche non essere associativo, in quel caso indica gli attributi da visualizzare
*/
public function set_parametri_xml($tagName='',$attributi=array()){
if ($tagName) $this->xml['']=trim($tagName);
foreach ($attributi as $k=>&$v)
if(is_int($k)) $this->xml[$v]=$v;
elseif(strlen($k)>0) $this->xml[$k]=$v;
return $this;
}
/**
* Funzione estendibile per modificare il valore prodotto dall'XML m di default è un alias di @see get_html
*
* @return string
*/
function &get_xml_value() {
return $this->get_value();
}
/** Restituisce il campo in XML iin UTF-8 pronto per la visualizzazione, di default gli attributi non vengono presi in considerazione ed il nome del campo diventa il tag che lo racchiude mentre il contenuto è il valore restituito da @see get_xml per personalizzare gli attributi usare @see set_attributi_xml
* @return string
*/
function &get_xml() {
if(!$this->abilitaXML) return;
if(is_array($this->xml))
foreach ($this->xml as $nome=>$usare)
if ($nome && trim($this->parametri[$nome])) $parametri.=' '.strtolower($usare)."=\"".(htmlspecialchars($this->parametri[$nome],null,'UTF-8')).'"';
$tag=$this->get_xml_tag(false);
if(strlen($v=$this->get_xml_value()))
{if(strpos($v,'&')===false && strpos($v,'<')===false)
return "<$tag$parametri>".utf8_encode($v)."$tag>";
else return "<$tag$parametri>\n\n$tag>";
}
elseif(!$this->facoltativoXML) return "<$tag$parametri />";
}
/** @ignore */
protected function _get_html_show($pars){
if ($pars['campo'] && !$this->get_attributo['disabled']) $out=$this->_get_html_hidden($pars);
$attr=$this->stringa_attributi(array('class','style'),false)." id=\"myshow_only_{$this->get_attributo('id')}\"";
return "".$this->get_value()."".$out;
}
/** Restituisce l'attributo 'id'
* @return string
*/
function get_id() { return $this->get_attributo('id'); }
/** @ignore*/
function &get_value_DB() { return $this->get_attributo('value'); }
/**
* Imposta l'attributo 'value'
*
* @param array|string $valore Valore da assegnare come defaulto array (non assoc) di valori nel caso di campo multivalori
*/
function set_value($valore) {
if (is_array($valore)) foreach ($valore as $v) $val[]=stripslashes($v);
elseif (trim($valore)==='') $val='';
else $val=stripslashes(trim($valore));
$this->attributi['value']=$val;
return $this;
}
/** Setta l'attributo 'name'
* @param string $nome
* @param boolean $cambia_id se false l'id del campo non viene riassegnato
*/
function set_name($nome,$cambia_id=true) {
if (!$nome) return $this;
$this->attributi['name']=$nome;
$nome=explode('[',$nome,2);
$nome=$nome[0];
if(!isset($this->myFields['campo__istanze'][strtolower($nome)])) $this->myFields['campo__istanze'][strtolower($nome)]=0;
if($cambia_id) $this->attributi['id']=$nome.(($this->myFields['campo__istanze'][strtolower($nome)])?'_'.$this->myFields['campo__istanze'][strtolower($nome)]:"");
$this->myFields['campo__istanze'][strtolower($nome)]++;
return $this;
}
function set_attributo ($primo,$valore='') {
if (is_array($primo))
foreach ($primo as $nome=>$valore)
{if (strtolower($nome)=='name') $this->set_name($valore);
elseif(strtolower($nome)=='value') $this->set_value($valore);
else parent::set_attributo($nome,$valore);
}
elseif ($valore!==null)
{if (strtolower($primo)=='name') $this->set_name($valore);
elseif(strtolower($primo)=='value') $this->set_value($valore);
else parent::set_attributo($primo,$valore);
}
return $this;
}
/** Setta la caratteristica di notnull
* @param boolean $var se true=> not null false=> null
*/
function set_notnull($var=true) { $this->notnull=$var; return $this;}
/** Restituisce la caratteristica di notnull
* @param boolean $var se true=> notnull false=> nullable
*/
function get_notnull() { return $this->notnull; }
/** Setta l'espressione regolare da usare nel metodo Errore
* @param string $expr è l'espressione regolare
* @param string $messaggio è il messaggio da restituire se value non è confermato da $expr
*/
function set_regExp($expr,$messaggio='formalmente errato') {
$this->controllo_regExp['exp']=$expr;
$this->controllo_regExp['mess']=$messaggio;
return $this;
}
/** Setta la caratteristica di readonly
* @param bool $var se vero imposta readonly altrimenti lo toglie (default=true)
*/
function set_readonly($var=true){
if ($var==false) $this->unset_attributo('readonly');
else $this->set_attributo('readonly','readonly');
return $this;
}
/** Setta la caratteristica di disabled
*/
function set_disabled(){ $this->set_attributo('disabled','disabled'); return $this;}
/** Setta il Tooltip del campo
* @param string $testo è il testo
*/
function set_Tooltip ($testo) {
$this->set_attributo('title',$testo);
return $this;
// $this->setjs('this.title=\''.addslashes(htmlentities($this->Nonhtmlentities(strip_tags($testo)))).'\'','onmouseover');
}
function get_myJQueries(){
return (array) $this->myJQueries;
}
function add_myJQuery(myJQuery $myJQ) {
if(method_exists($myJQ, 'application')) $myJQ->application($this);
if(method_exists($myJQ, 'get_widget')) $k=$myJQ->get_widget();
else $k=spl_object_hash($myJQ);
unset($this->myJQueries[$k]);
return $this->myJQueries[$k]=$myJQ;
}
/**
* @ignore
*/
protected function send_html($html){
if($this->myJQueries && $this->myFields['CONTESTO']!='myForm::calcolo_dipendenze') foreach ($this->myJQueries as $myjq) $js.=$myjq->get_new_html($html);
return $html.$js;
}
/** Restituisce il campo in html pronto per la visualizzazione
* @return string
*/
function get_Html() {
if(!$this->myFields['static']['common']) {$jsCommon=$this->get_js_common();$this->myFields['static']['common']=true;}
if ($get_html=$this->Metodo_ridefinito['get_Html']['metodo']) return $jsCommon.$this->$get_html($this->Metodo_ridefinito['get_Html']['parametri']);
return $this->send_html((!$this->con_js?'':$jsCommon.$this->jsAutotab()).'stringa_attributi().' />');
}
}
/**
* @package myFields
*/
class MyText extends MyField {
/**#@+ @ignore */
protected $MaiMin='',$unsetstriptags=false;
/**#@-*/
/**
* Costruttore di classe
*
* @access public
* @param string $nome E' il nome del campo
* @param string $valore Valore da assegnare come default
* @param string $classe è la classe css da utilizzare
*/
function MyText ($nome,$valore='',$classe='') {
parent::MyField($nome,$valore);
$this->set_attributo('type','text');
if ($classe) $this->set_attributo('class',$classe);
$this->set_MyType('MyText');
}
/** Elimina l'impostazione Maiuscolo o Minuscolo
**/
function unset_MaiMin() {
$this->set_MaiMin('');
}
/** Imposta Maiuscolo o Minuscolo(tramite css)
* @param maiuscolo|minuscolo $modo
**/
function set_MaiMin($modo='maiuscolo') {
if (strtolower($modo)=='maiuscolo') {$this->set_style('text-transform','uppercase');
$this->MaiMin=$modo;
}
if (strtolower($modo)=='minuscolo') {$this->set_style('text-transform','lowercase');
$this->MaiMin=$modo;
}
if (strtolower($modo)=='') {$this->set_style('text-transform','');
$this->MaiMin=$modo;
}
return $this;
}
/** Setta la lunghezza max del campo, da verificare nel metodo Errore
* @param integer $maxlength è l'espressione regolare
* @param integer $size è la lunghezza effettiva del campo da visualizzare
*/
function set_maxlength($maxlength,$size="") {
$this->maxlength=$maxlength;
$this->set_attributo('maxlength',$maxlength);
if (!$size) $this->set_attributo('size',min((int) ($maxlength*1.2),70));
else $this->set_attributo('size',$size);
return $this;
}
/**
* restituisce la lunghezza del campo in caratteri
*
* @return int
*/
function get_size(){
return $this->get_attributo('size');
}
/** Setta la autotabulazione del campo **/
function set_autotab () {
parent::set_autotab();
if($this->myJQueries)
foreach ($this->myJQueries as $JQ)
if($JQ instanceof myJQMask) {$JQMask=true;break;}
if(!$JQMask) {$onKeyup=$this->get_attributo('onkeyup');
$onKeyup.="if(this.maxLength==this.value.length) MyTabulazione(this);";
$this->SetJS($onKeyup,'onkeyup',false);
}
else $JQ->set_oncomplete("function(){MyTabulazione(self.get(0));}",true);
return $this;
}
/**
* Disabilita completamente la pulizia dei tag
*
*/
function unset_striptags(){
$this->unsetstriptags=true;
}
/** @ignore*/
function striptags($testo) {
if ($this->unsetstriptags) return $testo;
else return strip_tags($testo);
}
Function &get_value_db() {
$valore= $this->striptags(parent::get_value_db());
if ($this->MaiMin=='maiuscolo') $valore=strtoupper($valore);
if ($this->MaiMin=='minuscolo') $valore=strtolower($valore);
return $valore;
}
function &get_value() {
$valore= $this->striptags(parent::get_value());
if ($this->MaiMin=='maiuscolo') $valore=strtoupper($valore);
if ($this->MaiMin=='minuscolo') $valore=strtolower($valore);
return $valore;
}
function set_value($valore) { $valore=trim($valore);
if ($this->MaiMin=='maiuscolo') $valore=strtoupper($valore);
if ($this->MaiMin=='minuscolo') $valore=strtolower($valore);
$this->attributi['value']=$this->striptags(stripslashes(trim($valore)));
return $this;
}
/** Restituisce la lunghezza max impostata
* @return integer
*/
function get_maxlength() { return $this->maxlength; }
/** Setta la lunghezza min del campo, da verificare nel metodo Errore
* @param integer $minlength è l'espressione regolare
*/
function set_minlength($minlength) { $this->minlength=$minlength; return $this;}
/** Restituisce la lunghezza min impostata
* @return integer
*/
function get_minlength() { return $this->minlength; }
}
/**
* @package myFields
*/
class MyPassword extends MyText {
/**
* Costruttore di classe
*
* @access public
* @param string $nome E' il nome del campo
* @param string $valore Valore da assegnare come default
* @param string $classe è la classe css da utilizzare
*/
function MyPassword ($nome,$valore='',$classe='') {
parent::MyText($nome,$valore,$classe);
$this->set_attributo('type','password');
$this->set_MyType('MyPassword');
}
}
/**
* @package myFields
*/
class MyEmail extends MyText {
/**#@+ @ignore */
protected $divisore,$molteplicita,$grafica,$maxlengthcomplessiva,$textarea;
/**#@-*/
/**
* Costruttore di classe
*
* @access public
* @param string $nome E' il nome del campo
* @param string $valore Valore da assegnare come default
* @param string $classe è la classe css da utilizzare
*/
function MyEmail ($nome,$valore='',$classe='') {
parent::MyText($nome,$valore,$classe);
$this->set_regexp('^[-_a-zA-Z0-9]+[-\\._a-zA-Z0-9]*[a-zA-Z0-9_-]+@[a-zA-Z0-9\-]{2,}[-_\.a-zA-Z0-9]{0,}\.([a-zA-Z]{2}|com|edu|net|org|biz|info|it|int|gov|eu|name|mil|mobi|aero|asia|jobs|museum)$',"non è in formato corretto");
$this->set_MyType('MyEmail');
$this->set_MaiMin('minuscolo');
}
function &get_value() {
return strtolower(parent::get_value());
}
function set_value($valore) {
parent::set_value(strtolower($valore));
return $this;
}
/** @ignore */
protected function get_errore_diviso_singolo(){
$esito=parent::get_errore_diviso();
if(!$esito && $_SERVER['LOCAL_ADDR']!='127.0.0.1' && $this->restrizioni_check && $this->get_value())
{$dominio=explode('@',$this->get_value());
if($this->restrizioni_check[1] && is_callable('getmxrr'))
$valido=@getmxrr($dominio[1],$hosts);
elseif($this->restrizioni_check[0] || !is_callable('getmxrr'))
$valido=@dns_get_record($dominio[1],'A');
if(!$valido) return 'non è accettabile';
}
return $esito;
}
/**
* Permette di rendere il check_errore più o meno restrittivo
* @param boolean $VerificaRecordDX Verifica l'esistenza di un record DX relativo a server mail
* @param boolean $VerificaDNS Verifica sulla rete che il dominio sia valido
*
*/
function set_restrizioni_check($VerificaRecordDX=true,$VerificaDNS=true){
$this->restrizioni_check=array($VerificaDNS,$VerificaRecordDX);
return $this;
}
function get_errore_diviso() {
if (!$this->divisore) return $this->get_errore_diviso_singolo();
else {
$mails=explode($this->divisore,str_replace("\r","",$this->get_value()));
foreach ($mails as $i=>&$mail) {$mail=trim($mail);
if (!$mail) unset($mails[$i]);
}
if ($this->molteplicita>0 && count($mails)>$this->molteplicita) return array("non può contenere più di %1% valori diversi",$this->molteplicita);
$originale=$this->get_value();
$mails=array_flip(array_flip($mails));
foreach ($mails as $mail) {$this->set_value($mail);
if($errore=$this->get_errore_diviso_singolo()) break;
}
if (!$errore) $this->set_value(implode($this->divisore,$mails));
else $this->set_value($originale);
}
if($errore) {if(!is_array($errore)) $errore=array($errore);
$errore[0].=' %'.count($errore).'%';
$errore[]=' '.$this->trasl('per ogni singolo valore');
}
elseif($this->maxlengthcomplessiva[0] &&
strlen($this->get_value())>$this->maxlengthcomplessiva[0]) return array('non può contenere più di %1% caratteri',$this->maxlengthcomplessiva[0]);
return $errore;
}
/**
* Imposta la possibilità di inserire più valori nello stesso campo
* Di default la lunghezza max per singolo valore diventa la lunghezza precedentemente impostata,
* e quella complessiva (se omessa) è la molteplicita * la lunghezza max (più i divisori).
*
* di conseguenza se un campo nasce di 50 caratteri e
* vogliamo metterci dentro 3 valori al più 20 cadauno,
* il che potrebbe portare ad una lunghezza max 60>50 e comunque inaccettabile
*
* $f=new myform();
* $f->add_campo(new myemail('email'))->set_maxlength(20) //max 20 per il campo
* ->set_molteplicita(3,',',50) //20 diventa la lunghezza del singolo valore e 50 complessivi (compresi divisori)
*
*
*
* @param int $max numero massimo di mail, se omesso o 0 non viene tenuto in considerazione
* @param char $divisore carattere da usare tra una mail e l'altra (se "\n" visualizza meccanismo con elenco in javascript)
* @param int $maxlengthComplessiva massima lunghezza complessiva contando tutti i valori e relativi divisori
* @param bool $textarea forza la visualizzazione in textarea (sorza il divisore a "\n")
*/
function set_molteplicita($max=0,$divisore=';',$maxlengthComplessiva='',$textarea=false){
$this->grafica=$grafica;
$this->molteplicita=$max;
if($textarea) {$divisore="\n";
$this->textarea=true;
}
$this->divisore=$divisore;
if (!$maxlengthComplessiva) $this->maxlengthcomplessiva=array($this->maxlength*$max+$max-1,$this->get_attributo('size'));
else $this->maxlengthcomplessiva=array($maxlengthComplessiva,$this->get_attributo('size'));
return $this;
}
function get_Html () {
if ($get_html=$this->Metodo_ridefinito['get_Html']['metodo']) return $this->$get_html($this->Metodo_ridefinito['get_Html']['parametri']);
$maxlength_singolo=$this->maxlength;
if ($this->maxlengthcomplessiva) $this->set_maxlength($this->maxlengthcomplessiva[0],$this->maxlengthcomplessiva[1]);
if ($this->divisore!="\n") return $this->send_html(parent::get_html());
else
{
$this->set_style('overflow-y','hidden');
$this->set_style('overflow-x','auto');
$this->set_value(str_replace("\n\n","\n",str_replace($this->divisore,$this->divisore."\n",$this->get_value())));
$textarea="
{$this->jsAutotab()}
";
if ($this->textarea) return $textarea;
if (!$this->myFields['static']['js_src'][get_class($this)])
{$js="
";
$this->myFields['static']['js_src'][get_class($this)]=1;
}
$this->set_hidden();
$valori=explode("\n",$this->get_value());
$testo=new MyText("_myMultiTextJS_$jsSent",$valori[0],$this->get_attributo('class'));
$testo->set_attributo('size',$this->get_attributo('size'))
->set_attributo('maxlength',$this->get_attributo('maxlength'))
->set_js("if (this.options[this.selectedIndex].text).replace(' ','')=='') this.value=this.options[this.selectedIndex].text",'onblur');
$x=new mySelect('',array(0),'',$this->get_attributo('class'));
for ($i=0;$i<$this->molteplicita;$i++)
{$blk.=' ';
$x->add_Opzione("$valori[$i]$blk",$i);
}
$x->set_attributo('size',$this->molteplicita)
->set_style('cursor','hand')
->set_tooltip('Click per editare')
->set_js("('{$testo->get_id()}').value=(this.options[this.selectedIndex].text).replace(' ','')",'onclick');
$output=addslashes(str_replace(array("\r","\n","\t"),'',$this->send_html(parent::get_html())."$testoget_id()}','{$x->get_id()}','{$this->get_id()}');\" alt=\"".$this->trasl('Inserisci nell\'elenco')."\"> ".$x->get_html()));
return $js."";
}
}
}
/**
* @package myFields
*
*/
/**
* @package myFields
*/
class MyHidden extends myField {
/**#@+ @ignore */
protected $errore,$secure;
/**#@-*/
/**
* Costruttore di classe
*
* @access public
* @param string $nome E' il nome del campo
* @param string $valore Valore da assegnare come default
* @param string $classe è la classe css da utilizzare
*/
function MyHidden ($nome,$valore='',$classe='') {
parent::myField($nome,$valore,$classe);
$this->set_attributo('type','hidden');
$this->set_MyType('MyHidden');
$this->Richiede_tag_label=false;
$this->Prevede_label=false;
$this->numerico=null;
}
/* function unsecure(mySecurizer $s){
$this->secure=$s;
$val=$this->get_value().'';
if($val!=='')
{
if(!$this->secure->is_secure($this->get_name(),$val))
{
$this->errore="Errore interno";
return $this;
}
$this->set_value($s->unsecure($this->get_name(),$val));
}
return $this;
}
*/
function set_secure(mySecurizer $s){
$this->secure=$s;
return $this;
}
function get_js_chk(){}
/**
* In questo campo non si verificano mai errori
*/
function get_errore_diviso() {
/*if($this->notnull &&
$this->secure &&
!$this->secure->is_secure($this->get_name(),$this->get_value())) return "Errore interno, riprovare prego";
*/
return null;
}
/** Non attiva in questa classe
*/
function set_autotab () {return $this;}
function get_Html () {
if($this->secure) return $this->send_html($this->jsAutotab()."secure->encode($this->get_name(),$this->get_value(),true)."\" ".$this->stringa_attributi(array('value','title','size','maxlength','onkeyup'))." />");
else return $this->send_html($this->jsAutotab()."stringa_attributi(array('title','size','maxlength','onkeyup'))." />");
}
}
class MyUUID extends MyHidden {
function &get_value(){
$v4=parent::get_value();
if(!$v4) $this->set_attributo('value',$v4=self::v4());
return $v4;
}
public static function v4() {
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
// 32 bits for "time_low"
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
// 16 bits for "time_mid"
mt_rand(0, 0xffff),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
mt_rand(0, 0x0fff) | 0x4000,
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
mt_rand(0, 0x3fff) | 0x8000,
// 48 bits for "node"
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
}
/**
* @package myFields
*/
Class MyDateTime extends MyHidden {
function set_value($valore) {
if ($valore && preg_replace('#\0|\-|\:| #','',$valore)!='')return parent::set_value($valore);
else return parent::set_value(date("Y-m-d H:i:s"));
}
/**
* Costruttore di classe
*
* @access public
* @param string $nome E' il nome del campo
* @param string $valore Valore da assegnare all'attributo 'value', SE NULL VIENE IMPOSTATO ALLA DATA DI SISTEMA
* @param string $classe è la classe css da utilizzare
*/
function MyDateTime ($nome,$valore='',$classe='') {
parent::MyHidden($nome,$valore,$classe);
$this->set_MyType('MyDateTime');
}
/**
* In questo campo non si verificano mai errori
*/
function get_errore_diviso() {return null;}
/**
* Restituiesce la parte del valore contenuto nel mydate
*
* @param 0|1 $quale se 0=>data 1=>ora
* @param boolean $oggetto se falso restituisce la parte come stringa, alttrimenti come oggetto myDate|myOrario a seconda della parte scelta
* @return oggetto|string
*/
function get_parte($quale,$oggetto=false) {
$v=explode(' ',$this->get_value());
if (!$oggetto) return $v[$quale];
if ($quale==0) return new myDate('',$v[0]);
else return new MyOrario('',$v[1]);
}
}
/**
* @package myFields
*/
Class MyTime extends MyText {
/**
* Costruttore di classe
*
* @access public
* @param string $nome E' il nome del campo
* @param string $valore Valore da assegnare come default ACCETTATE SIA IN FORMATO hh:mm:ss e hh.mm
* @param string $classe è la classe css da utilizzare
*/
function MyTime ($nome,$valore='',$classe='') {
parent::MyText($nome,$valore,$classe);
$this->set_attributo('maxlength','8');
$this->set_attributo('size','8');
$this->set_regExp('^[0-9]{1,2}[\.|\-|\:]{1}[0-9]{1,2}([\.|\-|\:]{1}[0-9]{1,2})?$',' errato, formati corretti hh.mm oppure hh.mm.ss');
$this->set_MyType('MyTime');
}
function set_value($valore) {
if ($valore && preg_match("#{$this->controllo_regExp['exp']}#",$valore))
{ $valore=preg_replace('#[\.\-]#',':',$valore);
foreach(explode(':',$valore) as $v) if ($v!=='') $n[]=sprintf('%02d',$v);
if (is_array($n)) $valore=implode(":",$n);
}
return parent::set_value($valore);
}
function &get_value() {
$valore=parent::get_value();
if ($valore) {foreach(explode(':',$valore) as $v) if ($v!=='') $n[]=sprintf('%02d',$v);
$valore=implode(":",$n);
}
return $valore;
}
/** @ignore*/
function &get_value_DB() {
$v=explode(':',$this->get_value());
if (count($v)==2) $v[]='00';
return implode(':',$v);
}
function get_errore_diviso() {
if ($errore=parent::get_errore_diviso()) return $errore;
$v=explode(':',$this->get_value());
if ($v[0]>23 || $v[1]>59 || $v[2]>59) return " non è un'ora valida";
}
}
/**
* @package myFields
*/
class MyInt extends MyText {
/**#@+ @ignore */
protected $min,$max,$numerico=true,$zeri=false;
/**#@-*/
/**
* Costruttore di classe
* @access public
* @param string $nome E' il nome del campo
* @param string $valore Valore da assegnare come default
* @param string $classe è la classe css da utilizzare
*/
function MyInt ($nome,$valore='',$classe='') {
parent::MyText($nome,$valore,$classe);
$this->set_regExp('^[\+|\-]{0,1}[0-9]*$','deve essere un numero intero');
$this->set_MyType('MyInt');
$this->min='';
$this->max='';
}
/**
* forza un cero numero di zeri davanti al numero inserito,
* agisce solo dopo verifica errore() quindi set_minlength continua ad essere valido
* es: se su un campo da 8 cifresi imposta una lunghezza minima di 5 e l'utente ne inserisce 3 da comunque errore
* se invece ne mette 6 le rimanenti 2 vengono copert con zeri davanti
*/
function set_zerofill($stato=true){$this->zeri=$stato;}
/** Setta il minimo valore numericamente accettabile
* @param integer $min
*/
function set_min($min) {
$this->min=$min;
return $this;
}
/** Setta il massimo valore numericamente accettabile
* @param integer $max
*/
function set_max($max) {
$this->max=$max;
$this->set_maxlength(max(strlen($this->max),strlen($this->min)));
return $this;
}
function &get_value(){
if (strlen(parent::get_value()) && $this->zeri)
return sprintf("%0{$this->maxlength}s",parent::get_value());
else return parent::get_value();
}
function errore(){
if($this->zeri) $this->set_value(parent::get_value());
$errore=parent::errore();
if($this->zeri) $this->set_value($this->get_value());
return $errore;
}
function get_errore_diviso() {
if ($errore=parent::get_errore_diviso()) return $errore;
$x=$this->get_value_html();
if (strlen($x) && strlen($this->min) && $x<$this->min) return array('non può essere minore di %1%',$this->min);
if (strlen($x) && strlen($this->max) && $x>$this->max) {
return array('non può essere maggiore di %1%',$this->max);
}
}
function get_js_chk(){
$js="valore=trim(''+document.getElementById('{$this->get_id()}'));";
if ($this->notnull)
$js.="if(strlen(valore)==0) return \"{$this->trasl('non può essere nullo')}\";";
if ($this->controllo_regExp['exp']) {
$this->controllo_regExp['exp']=stripslashes($this->controllo_regExp['exp']);
$js.="if(valore!='' && !valore.search(/{$this->controllo_regExp['exp']}/)) return \"{$this->controllo_regExp['mess']}\";";
}
If (strlen($this->max)>0)
$js.="if (valore!='' && parseFloat(valore)>{$this->max}) return \"{$this->trasl('non può essere maggiore di %1%',array('%1%'=>$this->max))}\";";
if (strlen($this->min)>0)
$js.="if (valore!='' && parseFloat(valore)<{$this->min}) return \"{$this->trasl('non può essere minore di %1%',array('%1%'=>$this->min))}\";";
if (strlen($this->maxlength)>0)
$js.="if (valore!='' && strlen(valore)>{$this->maxlength}) return \"{$this->trasl('non può contenere più di %1% caratteri',array('%1%'=>$this->maxlength))}\";";
if (strlen($this->minlength)>0)
$js.="if (valore!='' && strlen(valore)<{$this->minlength}) return \"{$this->trasl('deve contenere almeno %1% caratteri',array('%1%'=>$this->minlength))}\";";
return $js;
}
/** @ignore*/
function lettere_decine($n){
$numeri=array('zero','uno','due','tre','quattro','cinque','sei','sette',
'otto','nove','dieci','undici','dodici','tredici','quattordici',
'quindici','sedici','diciassette','diciotto','diciannove',
20=>'venti',30=>'trenta',40=>'quaranta',50=>'cinquanta',
60=>'sessanta',70=>'settanta',80=>'ottanta',90=>'novanta');
$vocali=array('a'=>1,'e'=>1,'i'=>1,'o'=>1,'u'=>1);
if($numeri[$n]!=null) return $numeri[$n];
else { //20<=$n<=99
$st=$n.'';
$unita=$numeri[$st[1]];
$decine=$numeri[10*$st[0]];
if($vocali[$unita[0]]==1) $decine=substr($decine,0,strlen($decine)-1);
return $decine.$unita;
}
}
/** @ignore*/
function lettere_centinaia ($n){
$numeri=array(100=>'cento',200=>'duecento',300=>'trecento',400=>'quattrocento',500=>'cinquecento',
600=>'seicento',700=>'settecento',800=>'ottocento',900=>'novecento');
$vocali=array('o'=>1);
if($numeri[$n]!=null) return $numeri[$n];
elseif($n<100) return self::lettere_decine($n);
else {$st=$n.'';
$centinaia=$numeri[$st[0]*100];
$decine=self::lettere_decine(substr($st,1)+0);
if($vocali[$decine[0]]==1) $centinaia=substr($centinaia,0,strlen($centinaia)-1);
return $centinaia.$decine;
}
}
/** @ignore*/
function lettere_n ($n) {
$grandezze=array('|0|1|2|3|'=>1,
'|4|5|6|'=>array('cifre'=>3,'singolare'=>'mille','plurale'=>'mila'),
'|7|8|9|'=>array('cifre'=>6,'singolare'=>'unmilione','plurale'=>'milioni'),
'|9|10|11|'=>array('cifre'=>9,'singolare'=>'unmiliardo','plurale'=>'miliardi')
);
foreach ($grandezze as $k=>$v) if (strpos($k,'|'.strlen($n).'|')!==false) break;
if(!is_array($v)) return self::lettere_centinaia($n);
else { $st=$n.'';
$primaParte=substr($st,0,strlen($st)-$v['cifre'])+0;
if($primaParte==1) $risultato=$v['singolare'];
else $risultato=Myint::lettere_n($primaParte).$v['plurale'];
$secondaParte=substr($st,-$v['cifre'])+0;
if($secondaParte>0) $risultato.=Myint::lettere_n($secondaParte);
return $risultato;
}
}
/** Restituisce il valore del campo in lettere
* @param int $numero è il numero da convertire, se omesso si usa il valore corrente dell'oggetto
* @return string
*/
function inlettere ($numero='') {
if ($numero==='') $n=(int) str_replace(',','.',$this->get_value());
else $n=(int) $numero;
if ($n<0) {
$segno='-';
$n=abs($n);
}
$v=explode('.',sprintf('%01.2f',$n));
return $segno.self::lettere_n($v[0]);
}
/**
* Converts a number to its roman numeral representation
*
* @param integer $num An integer between 0 and 3999
* inclusive that should be converted
* to a roman numeral integers higher than
* 3999 are supported from version 0.1.2
* Note:
* For an accurate result the integer shouldn't be higher
* than 5 999 999. Higher integers are still converted but
* they do not reflect an historically correct Roman Numeral.
*
* @param bool $html Enable html overscore required for
* integers over 3999. default true
* @return string $roman The corresponding roman numeral
*/
function inRomani($num='',$html = true)
{ if ($num==='') $num=$this->get_value();
if ($num < 0) return '';
$num = (int) $num;
$conv = array( 10 => array('X', 'C', 'M'), 5 => array('V', 'L', 'D'), 1 => array('I', 'X', 'C') );
$roman = '';
$digit = (int) ($num / 1000);
$num -= $digit * 1000;
while ($digit > 0) {
$roman .= 'M';
$digit--;
}
for ($i = 2; $i >= 0; $i--) {
$power = pow(10, $i);
$digit = (int) ($num / $power);
$num -= $digit * $power;
if (($digit == 9) || ($digit == 4)) $roman .= $conv[1][$i] . $conv[$digit+1][$i];
else {
if ($digit >= 5)
{
$roman .= $conv[5][$i];
$digit -= 5;
}
while ($digit > 0)
{
$roman .= $conv[1][$i];
$digit--;
}
}
}
/*
* Preparing the conversion of big integers over 3999.
* One of the systems used by the Romans to represent 4000 and
* bigger numbers was to add an overscore on the numerals.
* Because of the non ansi equivalent if the html output option
* is true we will return the overline in the html code if false
* we will return a _ to represent the overscore to convert from
* numeral to arabic we will always expect the _ as a
* representation of the html overscore.
*/
if ($html == true) {
$over = '';
$overe = '';
} elseif ($html == false) {
$over = '_';
$overe = '';
}
/*
* Replacing the previously produced multiple MM with the
* relevant numeral e.g. for 1 000 000 the roman numeral is _M
* (overscore on the M) for 900 000 is _C_M (overscore on both
* the C and the M) We initially set the replace to AFS which
* will be later replaced with the M.
*
* 500 000 is _D (overscore D) in Roman Numeral
* 400 000 is _C_D (overscore on both C and D) in Roman Numeral
* 100 000 is _C (overscore C) in Roman Numeral
* 90 000 is _X_C (overscore on both X and C) in Roman Numeral
* 50 000 is _L (overscore L) in Roman Numeral
* 40 000 is _X_L (overscore on both X and L) in Roman Numeral
* 10 000 is _X (overscore X) in Roman Numeral
* 5 000 is _V (overscore V) in Roman Numeral
* 4 000 is M _V (overscore on the V only) in Roman Numeral
*
* For an accurate result the integer shouldn't be higher then
* 5 999 999. Higher integers are still converted but they do not
* reflect an historically correct Roman Numeral.
*/
$roman = str_replace(str_repeat('M', 1000), $over.'AFS'.$overe, $roman);
$roman = str_replace(str_repeat('M', 900), $over.'C'.$overe.$over.'AFS'.$overe, $roman);
$roman = str_replace(str_repeat('M', 500), $over.'D'.$overe, $roman);
$roman = str_replace(str_repeat('M', 400), $over.'C'.$overe.$over.'D'.$overe, $roman);
$roman = str_replace(str_repeat('M', 100), $over.'C'.$overe, $roman);
$roman = str_replace(str_repeat('M', 90), $over.'X'.$overe.$over.'C'.$overe, $roman);
$roman = str_replace(str_repeat('M', 50), $over.'L'.$overe, $roman);
$roman = str_replace(str_repeat('M', 40), $over.'X'.$overe.$over.'L'.$overe, $roman);
$roman = str_replace(str_repeat('M', 10), $over.'X'.$overe, $roman);
$roman = str_replace(str_repeat('M', 5), $over.'V'.$overe, $roman);
$roman = str_replace(str_repeat('M', 4),'M'.$over.'V'.$overe, $roman);
/*
* Replacing AFS with M used in both 1 000 000
* and 900 000
*/
$roman = str_replace('AFS', 'M', $roman);
/*
* Make HTML output more readable by combining span tags
* where possible.
*/
if ($html == true) $roman = str_replace($overe.$over, '', $roman);
return $roman;
}
/**
* Restituisce il valore dell'oggetto in forma ordinale: primo, secondo ..
*
* @param int $numero se omesso restituisce l'ordinale del valore memorizzato nell'istanza
* @param boolean $genere se true il genere è maschile (es. primo) altrimenti femminile (prima)
* @param boolean $singolare se true è singolare (es. primo,prima) altrimenti plurale (primi,prime)
* @return string
*/
function ordinale ($numero=null,$genere=true,$singolare=true) {
if ($numero===null) $numero=(int) $this->get_value();
else $numero=(int) $numero;
if($numero<=0) return '';
$numeri=array(1=>'prim','second','terz','quart','quint','sest','settim','ottav','non','decim');
if ($numero<=10) $ordinale=$numeri[$numero];
else {
$ordinale=MyInt::inlettere($numero);
$numero=(string) $numero;
if ($ordinale{strlen($ordinale)-2}!='e') $ordinale=substr($ordinale,0,-1);
if ($numero{strlen($numero)-1}=='3') $ordinale.='e';
$ordinale.='esim';
}
if ($genere)
{
if($singolare) $ordinale.='o';
else $ordinale.='i';
}
else {
if($singolare) $ordinale.='a';
else $ordinale.='e';
}
return $ordinale;
}
}
/**
* @package myFields
*/
class MyIntPos extends MyInt {
/**
* Costruttore di classe
* @access public
*
* @param string $nome E' il nome del campo
* @param string $valore Valore da assegnare come default
* @param string $classe è la classe css da utilizzare
*/
function MyIntPos ($nome,$valore='',$classe='') {
parent::MyInt($nome,$valore,$classe);
$this->set_regExp('^[\+]{0,1}[0-9]*$','deve essere un numero intero positivo');
$this->set_MyType('MyIntPos');
$this->set_min(0);
}
}
/**
* @package myFields
*/
Class MyOrario extends MyInt {
/**
* Costruttore di classe, permette di memorizzare un generico orario positivo o negativo o maggiore di 24 ore
* si interfaccia con il DB memorizzando il valore espresso in minuti
*
* @access public
* @param string $nome E' il nome del campo
* @param string $valore Valore da assegnare come default ACCETTATE SIA IN FORMATO hh:mm e hh.mm
* @param string $classe è la classe css da utilizzare
*/
function MyOrario ($nome,$valore='',$classe='') {
parent::MyInt($nome,$valore,$classe);
$this->is_numeric(false);
$this->set_attributo('maxlength','5');
$this->set_attributo('size','5');
$this->set_regExp('^[\+|\-]{0,1}[0-9]{1,2}([\.\:\,]{1}[0-9]{1,2})?$',' errato, formato corretto hh.mm');
$this->set_MyType('MyOrario');
}
function set_value($valore) {
MyInt::set_value($valore);
if ($this->get_errore_diviso()) return $this;
if ($valore) {
if ($valore[0]=='-') {$segno=$valore[0];
$valore=substr($valore,1);
}
if (strlen($valore)==4 && preg_match('#^[0-9]+$#S',$valore)) $valore=substr($valore,0,2).':'.substr($valore,2,2);
$n=array();
foreach(preg_split('/\\:|\\.|\\,/',$valore) as $v) if ($v!=='' && preg_match('#^[0-9]+$#S',$v)) $n[]=sprintf('%02d',$v);
else $n[]=$v;
unset($n[2]);
if (preg_match('#^[0-9]+$#S',$n[0]) && !isset($n[1])) $n[1]='00';
$valore=implode(":",$n);
if ($segno) $valore=$segno.$valore;
}
return parent::set_value($valore);
}
function &get_value() {
$valore=parent::get_value();
if (strlen(trim($valore))=='') return '';
if (strlen($valore)==4 && preg_match('#^[0-9]+$#S',$valore)) $valore=substr($valore,0,2).':'.substr($valore,2,2);
$n=array();
foreach(preg_split('/\\:|\\.|\\,/',$valore) as $v) if ($v!=='' && preg_match('#^[0-9]+$#S',$v)) $n[]=sprintf('%02d',$v);
else $n[]=$v;
unset($n[2]);
if (preg_match('#^[0-9]+$#S',$n[0]) && !isset($n[1])) $n[1]='00';
$valore=implode(":",$n);
$this->attributi[value]=$valore;
/*if (preg_match('/(\d{2}):(\d{2})[:(\d{2})]/i',$valore))
{
foreach(explode(':',$valore) as $v) if ($v!=='') $n[]=sprintf('%02d',$v);
unset($n[2]);
$valore=implode(":",$n);
}*/
return $valore;
}
/** Ritorna il valore in minuti
* @param string $orario se omesso usa il valore memorizzato nel campo
* @return int numero_minuti
*/
function get_minuti($orario='') {
if ($orario=='') $orario=$this->get_value();
$v=preg_split('/\\.|\\:|\\,/',$orario);
return ($v[0]<0?-1:1)*(abs($v[0])*60+$v[1]);
}
/** Setta il valore del campo espresso in minuti
* @param string $orario
*/
function set_minuti($orario) {
$n[]=sprintf('%02d',(int)($orario/60));
$n[]=sprintf('%02d',abs($orario) % 60);
return parent::set_value(implode(':',$n));
}
function get_errore_diviso() {
if ($errore=parent::get_errore_diviso()){//print_r($errore); exit;
return $errore;}
$v=explode(':',$this->get_value());
if ($v[1]<0 || $v[1]>59 ) return " deve avere i minuti compresi tra 0 e 59";
}
}
/**
* @package myFields
*/
Class MyDate extends MyInt {
/**#@+ @ignore */
protected $calendar, $minmaxcal,$xmlFormat=array('amg','-');
/**#@-*/
/**
* Costruttore di classe
*
* @access public
* @param string $nome E' il nome del campo
* @param string $valore Valore da assegnare come default ACCETTATE SIA IN FORMATO GG/MM/AAAA CHE AAAA/MM/GG
* @param string $classe è la classe css da utilizzare
*/
function MyDate ($nome,$valore='',$classe='') {
parent::MyText($nome,$valore,$classe);
$this->is_numeric(false);
$this->set_maxlength(10,10);
$this->set_style('width','8em');
$this->set_MyType('MyDate');
}
/** Restituisce il numero di giorni di un certo mese
* @param int $month
* @param int $year
* @return int
*/
static function giorni_mese($month, $year)
{$daysInMonth = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
if ($month < 1 || $month > 12) return 0;
$d = $daysInMonth[$month - 1];
if ($month == 2)
{ if ($year%4 == 0)
{ if ($year%100 == 0)
{ if ($year%400 == 0) $d = 29;
}
else $d = 29;
}
}
return $d;
}
/** @ignore*/
function giorni_anno($anno) {
if (MyDate::giorni_mese(2,$anno)==29) return 366;
else return 365;
}
/** Restituisce una parte della data
* Es. volendo solo mese ed anno si può scrivere
*
* $x=new MyDate('data','1/2-2006');
* echo $x->get_parte(1).'/'.$x->get_parte(2);
*
* @param 0|1|2 $quale Se 0 restituisce il giorno se 1 restituisce il mese, se 2 restituisce l'anno
* @param string $data se esplicitato il calcolo si applica alla data indicata, altrimenti si prende in considerazione la data memorizzata nel campo
* @return int
*/
function get_parte($quale,$data='') {
if (!$data) $data=$this->get_value();
$x=explode('/',$data);
return intval(preg_replace('/^0/', '', $x[$quale]));
}
/** Restituisce il numero di anni tra due date
* @param string $dal E' la data di inizio nel formato gg/mm/aaaa (se omesso inizia dal 1/1/1900)
* @param string $al E' la data di arrivo nel formato gg/mm/aaaa (se omesso usa il dato dell'oggetto mydate)
* @return int
*/
FUNCTION calcola_anni($dal,$al=''){
if (!$al) $al=$this->get_value();
$d1=new MyDate('',$dal);
$d2=new MyDate('',$al);
$segno=1;
if($d1->get_formatted()>$d2->get_formatted())
{
$d1->set_value($al);
$d2->set_value($dal);
$segno=-1;
}
$anni=$d2->get_parte(2)-$d1->get_parte(2);
$mm1=$d1->get_parte(1);
$mm2=$d2->get_parte(1);
$gg1=$d1->get_parte(0);
$gg2=$d2->get_parte(0);
//inizio non inizia da 1 viene considerato parziale
if($mm2<$mm1 || ($mm2==$mm1 && $gg2<$gg1) ) //stesso anno stesso mese
{//
$anni--;
}
return $anni*$segno;
}
/** Restituisce il numero di giorni tra due date
* @param string $dal E' la data di inizio nel formato gg/mm/aaaa (se omesso inizia dal 1/1/1900)
* @param string $al E' la data di arrivo nel formato gg/mm/aaaa (se omesso usa il dato dell'oggetto mydate)
* @return int
*/
function &calcola_giorni($dal='1/1/1900',$al=''){
if (!$al) $al=$this->get_value();
//echo "$dal $al ";
$d1=new Data('gma',$dal);$d2=new Data('gma',$al);
if ($d1->errore || $d2->errore ) return null;
if ($d1->get_value_formatted('amg')<$d2->get_value_formatted('amg'))
{ $segno=1;
$dal=explode('/',$dal);
$al=explode('/',$al);
}
else {$Dal=$dal; $segno=-1;
$dal=explode('/',$al);
$al=explode('/',$Dal);
}
if ($dal[2]==$al[2]) {//stesso anno
if($dal[1]==$al[1]) return ($al[0]-$dal[0])*$segno;
else {$tot=MyDate::giorni_mese($dal[1],$dal[2])-$dal[0]; //numeri di giorni fino alla fine del mese di part
$dal[1]++; //passo al mese success a quello di partenza
while ($dal[1]<$al[1]) {$tot+=MyDate::giorni_mese($dal[1],$dal[2]);$dal[1]++;} //sommo i giorni fino a fine anno
}
}
else {//anni diversi
$tot+=MyDate::giorni_mese($dal[1],$dal[2])-$dal[0]; //numeri di giorni fino alla fine del mese di part
$dal[1]++; //passo al mese success a quello di partenza
while ($dal[1]<=12) {$tot+=MyDate::giorni_mese($dal[1],$dal[2]);$dal[1]++;} //sommo i giorni fino a fine anno
$dal[2]++;
while ($dal[2]<$al[2]) {$tot+=MyDate::giorni_anno($dal[2]);$dal[2]++;} //sommo i giorni fino all'anno corrente escl
$i=1;
while ($i<$al[1]) {$tot+=MyDate::giorni_mese($i,$al[2]);$i++; } //sommo i giorni dei mesi dell'anno corrente
}
$tot+=$al[0];
return $tot*$segno;
}
/** Restituisce il numero di mesi tra due date
* @param string $dal E' la data di inizio nel formato gg/mm/aaaa (se omesso inizia dal 1/1/1900)
* @param string $al E' la data di arrivo nel formato gg/mm/aaaa (se omesso usa il dato dell'oggetto mydate)
* @param 0|1|2 $considera_giorni se:
* 0 considera la differenza di mesi a prescindere dai giorni es. 1 == calcola_mesi('31/01/2012,'1/2/2012')
* 1 considera il mese di arrivo solo se il giorno e superiore al giorno di partenza es. 0 == calcola_mesi('31/01/2012','1/2/2012',1) e 0==calcola_mesi(31/01/2012','29/2/2012',1)
* 2 considera il mese di arrivo se il giorno e superiore al giorno di partenza o il mese di arrivo ha un numero di giorni del giorno di partenza ed il giorno di arrivo è l'ultimo di quel mese es. 1==calcola_mesi(30/01/2012','29/2/2012',2) e 0==calcola_mesi(30/01/2012','28/2/2012',2)
* @return int $classe è la classe css da utilizzare
*/
function calcola_mesi($dal='1/1/1900',$al='',$considera_giorni=0){
if (!$al) $al=$this->get_value();
$d1=new Data('gma',$dal);
$d2=new Data('gma',$al);
if ($d1->errore || $d2->errore ) return null;
if ($d1->get_value_formatted('amg')<$d2->get_value_formatted('amg'))
{ $segno=1;
$dal=explode('/',$d1->get_value_formatted('gma'));
$al=explode('/',$d2->get_value_formatted('gma'));
}
else {
$segno=-1;
$dal=explode('/',$d2->get_value_formatted('gma'));
$al=explode('/',$d1->get_value_formatted('gma'));
}
if($considera_giorni==2 && MyDate::giorni_mese($al[1],$al[2])==$al[0]) $al[0]=31;//se 2 e l'arrivo coincide con l'ultimo giorno del mese lo estendo a 31
if ($dal[2]==$al[2]) {//stesso anno
$tot=$al[1]-$dal[1]; //sommo i giorni fino a fine anno
}
else {//anni diversi
$dal[1]++; //passo al mese success a quello di partenza per non contarlo
while ($dal[1]<=12) {$tot++;$dal[1]++;} //incremento fine anno
$dal[2]++;
while ($dal[2]<$al[2]) {$tot+=12;$dal[2]++;} //sommo 12 mesi fino all'anno corrente escl
$tot+=$al[1]; //sommo i giorni dei mesi dell'anno corrente
}
$tot=(int) $tot;
return ($considera_giorni>0 && $al[0]<$dal[0] ? --$tot : $tot)*$segno;
}
/** Sposta una data di giorni mesi ed anni
* Es.
* Supponiamo di avere due MyDate $primo e $secondo e di voler far sì che il $secondo sia sempre maggiore del $primo di almeno un mese ed un giorno.
* Dovremo impostare il valore minimo del secondo pari alla data del primo MyDate incrementata di un mese ed un giorno
*
*
* $secondo->set_min( $primo->sposta_data(1,1,0) );
*
*
* IMPORTANTE: QUESTO METODO HA EFFETTO SOLO SE TUTTI I VALORI USATI HANNO LO STESSO SEGNO
* @param int $ngiorni Positivo o negativo indica il numro di giorni da sommare o sottrarre.
* @param int $nmesi Analogo ai giorni
* @param int $nanni Analogo ai mesi
* @param int $data a cui applicare lo spostamento, se omessa prende la data dell'oggetto
* @return string data spostata nel formata gg/mm/aaaa
*/
function sposta_data($ngiorni=0,$nmesi=0,$nanni=0,$data=''){
if (!$data && is_object($this)) $data=$this->get_value();
// echo "Data $data $ngiorni,$nmesi,$nanni ";
IF ($ngiorni*$nmesi<0 || $ngiorni*$nanni<0 || $nanni*$nmesi<0 ) return $data;
$data=explode('/',$data);
if ($ngiorni>0 && $ngiorni+$data[0]>MyDate::giorni_mese($data[1],$data[2]))
{
do{
$ngiorni-=$scalare;
// se mese corrente è genn o feb e anno corrente è di 366 scalo 366
// se mese corrente è succ a feb ma anno succ è bisestile scalo 366
if (($data[1]<=2 && MyDate::giorni_anno($data[2])==366) ||
($data[1]>2 && MyDate::giorni_anno($data[2]+1)==366)) $scalare=366;
else $scalare=365;
if ($ngiorni-$scalare>=0) $data[2]++;
}
while ($ngiorni-$scalare>=0);
$scalare=0;
while ($ngiorni+$data[0]>MyDate::giorni_mese($data[1],$data[2]))
{
$ngiorni-=MyDate::giorni_mese($data[1],$data[2]);
$data[1]++;
if ($data[1]==13) {$data[1]=1; $data[2]++;}
}
}
if ($ngiorni<0 && $data[0]+$ngiorni<=0)
{
do{
$ngiorni+=$scalare;
if (($data[1]<=2 && MyDate::giorni_anno($data[2]-1)==366) ||
($data[1]>2 && MyDate::giorni_anno($data[2])==366)) $scalare=366;
else $scalare=365;
if ($ngiorni+$scalare<=0) $data[2]--;
}
while ($ngiorni+$scalare<=0);
while ($ngiorni+$data[0]<=0)
{
$data[1]--;
if ($data[1]==0) {$data[1]=12; $data[2]--;}
$ngiorni+=MyDate::giorni_mese($data[1],$data[2]);
}
}
if (abs($nmesi)>12) {
$s=$nmesi/abs($nmesi);
$nanni+=$s* (int) (abs($nmesi) /12);
$nmesi=$s* (abs($nmesi) %12);
}
// echo "Diventa $ngiorni,$nmesi,$nanni ";
If ($ngiorni+$nmesi+$nanni>0) {
$data[0]+=$ngiorni;
if ($data[0]>MyDate::giorni_mese($data[1],$data[2]))
{$data[0]-=MyDate::giorni_mese($data[1],$data[2]);
$nmesi++;
}
$data[1]+=$nmesi;
if ($data[1]>12)
{$data[0]-=MyDate::giorni_mese($data[1],$data[2]);
}
$data[2]+=$nanni;
}
else {
$data[2]+=$nanni;
$data[1]+=$nmesi;
if ($data[1]<=0)
{ $data[2]--;
$data[1]+=12;
}
$data[0]+=$ngiorni;
if ($data[0]<=0) {$data[1]--;
if ($data[1]<=0) {
$data[2]--;
$data[1]+=12;
}
$data[0]+=MyDate::giorni_mese($data[1],$data[2]);
}
}
$data[2]=sprintf('%04s',$data[2]+(int) ($data[1]/13));
$data[1]=sprintf('%02s',($data[1]%12==0?12:$data[1]%12));
$giornimese=MyDate::giorni_mese($data[1],$data[2]);
if ($data[0]>$giornimese) $data[0]=$giornimese;
$data[0]=sprintf('%02s',$data[0]);
return implode('/',$data);
}
/** Restituisce la data odierna (del server web)
* @return string
*/
function get_oggi() {return date('d/m/Y'); }
/** Restituisce numero corrispondente al giorno della settimana
* @param string $data se esplicitato il calcolo si applica alla data indicata, altrimenti si prende in considerazione la data memorizzata nel campo
* @return int 0=>Domenica .. 6 =>Sabato
*/
function &get_numero_giorno_settimana($data) {
if (!$data) $data=$this->get_value();
$giorni=MyDate::calcola_giorni(MyDate::get_oggi(),$data);
if ($giorni===null) return null;
$giorni=$giorni %7;
if ($giorni<0) $giorni=7+$giorni;
$n=(date('w')+$giorni) %7;
return $n;
}
function &get_nome_giorno_settimana($data='') {
if (!$data) $data=$this->get_value();
$giorni=array();
foreach (array('domenica','lunedì','martedì','mercoledì','giovedì','venerdì','sabato') as $giorno) $giorni[]=$this->trasl($giorno);
$giorno=MyDate::get_numero_giorno_settimana($data);
if ($giorno===null) return null;
return $giorni[$giorno];
}
/** Restituisce un array con le parti della data desiderate espresse in lettere
* Es.
*
* $x=new MyDate('data');
* $x->set_value($x->get_oggi());
* $parti=$x->inlettere(array('s','g','m','a'));
* echo $parti['s'].', '.$parti->g.' '.$parti['m'].' '.$parti->a;
*
*
* oppure
*
*
* $parti=MyDate::inlettere(array('s','g','m','a'),MyDate::get_oggi());
* echo $parti['s'].', '.$parti->g.' '.$parti['m'].' '.$parti->a;
*
*
*
*
* @param array $parti è un array che indica le parti in lettere che si desiderano es. ('s','m') indica che si vuole il giorno della settimana e l'anno in lettere.
* I possibili valori sono:
*
* g=>numero del giorno espresso in lettere
* s=>Nome giorno settimana
* m=>Nome del mese
* mm=>numero del mese espresso in lettere
* a=>anno espresso in lettere
*
* @param string $data se esplicitato il calcolo si applica alla data indicata, altrimenti si prende in considerazione la data memorizzata nel campo
* @return myArrayObject
*/
function &inlettere($parti=array('g','s','m','mm','a'),$data='') {
if (!$data) $data=$this->get_value();
$mesi=array();
foreach (array('gennaio','febbraio','marzo','aprile','maggio','giugno','luglio','agosto','settembre','ottobre','novembre','dicembre') as $mese)
if (is_object($this)) $mesi[]=$this->trasl($mese);
else $mesi[]=$mese;
$v=new myArrayObject();
foreach ($parti as $p) {
if ($p=='m') {
$mese=MyDate::get_parte(1,$data);
$v['m']=$mesi[$mese-1];
}
if ($p=='mm') {
$mese=MyDate::get_parte(1,$data);
$v['mm']=MyInt::inlettere($mese);
}
if ($p=='g') {
$giorno=MyDate::get_parte(0,$data);;
$v['g']=MyInt::inlettere($giorno);
}
if ($p=='a') {
$anno=MyDate::get_parte(2,$data);
$v['a']=MyInt::inlettere($anno);
}
if ($p=='s') {
$v['s']=MyDate::get_nome_giorno_settimana($data);
}
}
return $v;
}
function set_value($valore='') {
if (!$valore || preg_replace('#\/|\.|\-|0#','',$valore)=='') $valore='';
$valore=substr($valore,0,10);
$data=new Data("gma",$valore);
if ($data->errore && $valore) {$dataAmg=new Data("amg",$valore);
if (!$dataAmg->errore) {$data->errore=null;
$data->value=$dataAmg->get_value_formatted();
}
}
if (!$data->errore) $this->attributi['value']=$data->get_value_formatted();
else $this->attributi['value']=$valore;
return $this;
}
/**
*
* Restituisce il valore del minimo impostato
* @param bool $del_calendario se true restituisce il valore relativo al calendario
* @return int
*/
function get_min($del_calendario=false){
if($del_calendario) return $this->minmaxcal['min'];
return $this->min;
}
/**
*
* Restituisce il valore del massimo impostato
* @param bool $del_calendario se true restituisce il valore relativo al calendario
* @return int
*/
function get_max($del_calendario=false){
if($del_calendario) return $this->minmaxcal['max'];
return $this->max;
}
/**
* @see MyInt::set_min()
* @param string $min data minima consentita
* @param bool se true il minimo impostato viene esteso anche all'eventuale calendario
*/
function set_min($min,$anche_calendario=true) {
if (preg_replace('#\/|\.|\-#','',$min)=='') $min='';
if ($min=='0') $min='';
$data=new Data("gma",$min);
if ($data->errore && $min)
{$dataAmg=new Data("amg",$min);
if (!$dataAmg->errore) {$data->errore=null;
$data->value=$dataAmg->get_value_formatted();
}
}
if (!$data->errore) {$this->min=$data->get_value_formatted('gma','/');
if($anche_calendario) $this->minmaxcal['min']=$this->min;
}
else $data->errore=array("Data Minima non valida: %1%",$min);
return $this;
}
/**
* @see MyInt::set_max()
* @param string $max data massima consentita
* @param bool se true il massimo impostato viene esteso anche all'eventuale calendario
*/
function set_max($max,$anche_calendario=true) {
if (preg_replace('#\/|\.|\-#','',$max)=='') $max='';
if ($max=='0') $max='';
$data=new Data("gma",$max);
if ($data->errore && $max) {$dataAmg=new Data("amg",$max);
if (!$dataAmg->errore) {$data->errore=null;
$data->value=$dataAmg->get_value_formatted();
}
}
if (!$data->errore) {$this->max=$data->get_value_formatted('gma','/');
if($anche_calendario) $this->minmaxcal['max']=$this->max;
}
else $data->errore= array("Data Massima non valida: %1%",$max);
return $this;
}
/** @ignore*/
function &get_value_DB() {
$data=new Data("gma",$this->get_value());
if ($data->errore || !$this->get_value()) return '';
return $data->get_value_formatted('amg','-');
}
/** Restituisce la data nel formato prescelto
* @param string $formato è il formato desiderato e può essere una tra 'gma','mga','amg','agm' , di default è 'amg'
* @param string $divisore è la stringa che deve dividere i vari campi, di default è '-'
* @param string $valore è la stringa in formato mydate accettabile (es gg/mm-aaaa) da formattare, se omesso usa il valore interno all'oggetto
*/
function get_formatted($formato='amg',$divisore='-',$valore='') {
if (!$formato) $formato='amg';
if (!$divisore) $divisore="-";
$formato=strtolower($formato);
if (strlen($valore)==0 && is_object($this)) $valore=$this->get_value();
$data=new Data("gma",$valore);
if ($data->errore && $valore) {$dataAmg=new Data("amg",$valore);
if (!$dataAmg->errore) {$data->errore=null;
$data->value=$dataAmg->get_value_formatted();
}
}
if (!$data->errore) return $data->get_value_formatted($formato,$divisore);
return false;
}
/** Imposta la visualizzazione del calendario
* @param JQ|popup $tipo setta il tipo di visualizzazione,se null non si visualizza calendario (default è JQuery)
* @param string $titolo titolo da far comparire nella finestra
* @param string $css css da usare (percorso assoluto)
*/
function set_calendar($tipo='JQ',$titolo='',$css='') {
$this->calendar=array('tipo'=>$tipo,'titolo'=>$titolo,'css'=>$css);
if ($tipo=='JQ') {$this->add_myJQuery(new myJQDatepicker());
$myJQMask=new myJQMask("#{$this->get_id()}");
$myJQMask->set_mask("d9/99/9999",'',array('d'=>"0123"));
$this->add_myJQuery($myJQMask);
}
return $this;
}
function get_js_chk(){
$js="valore=format_data(document.getElementById('{$this->get_id()}').value);
if(valore==null) return null;
";
if ($this->notnull)
$js.="if(strlen(valore)==0) return \"{$this->trasl('non può essere nullo')}\";";
If (strlen($this->max)>0)
$js.="if (valore!='' && valore>'{$this->get_formatted('amg','-',$this->max)}') return \"{$this->trasl('non può essere successiva al %1%',array('%1%'=>$this->max))}\";";
if (strlen($this->min)>0)
$js.="if (valore!='' && valore<'{$this->get_formatted('amg','-',$this->min)}') return \"{$this->trasl('non può essere antecedente al %1%',array('%1%'=>$this->min))}\";";
if (strlen($this->maxlength)>0)
$js.="if (valore!='' && strlen(valore)>{$this->maxlength}) return \"{$this->trasl('non può contenere più di %1% caratteri',array('%1%'=>$this->maxlength))}\";";
if (strlen($this->minlength)>0)
$js.="if (valore!='' && strlen(valore)<{$this->minlength}) return \"{$this->trasl('deve contenere almeno %1% caratteri',array('%1%'=>$this->minlength))}\";";
return $js;
}
/** Restituisce il campo in html pronto per la visualizzazione
* @return string
*/
function get_Html () {
if ($get_html=$this->Metodo_ridefinito['get_Html']['metodo']) return $this->$get_html($this->Metodo_ridefinito['get_Html']['parametri']);
$out= 'stringa_attributi().'/>';
if ($this->calendar['tipo']=='popup')
{
$docroot= $this->get_MyFormsPath();
$js=MyPopUp::js_always_top();
if (!$this->myFields['static']['js_src'][get_class($this)])
{
$js.='';
$this->myFields['static']['js_src'][get_class($this)]=1;
}
//$out.="$jsget_id()}\" onclick='return calendarioPopup(\"/$docroot"."calendar.php?id=".$this->get_attributo('id')."&tipo=".$this->calendar['tipo']."&titolo=".$this->calendar['titolo']."&css=".$this->calendar['css']."&value=".$this->get_value()."&lang=".($this->dizionario?$this->dizionario[0]->get_al():'it')."&max={$this->max}&min={$this->min}\")' onkeypress='return calendarioPopup(this,\"/$docroot"."calendar.php?id=".$this->get_attributo('id')."&tipo=".$this->calendar['tipo']."&titolo=".$this->calendar['titolo']."&css=".$this->calendar['css']."&value=".$this->get_value()."&max={$this->max}&min={$this->min}\")'>";
$out="$jsget_id()}\">$out trasl('Click qui per selezionare dal calendario')}\" href='#'
onclick='return calendarioPopup(\"{$this->get_id()}\",\"/{$docroot}calendar.php?id={$this->get_id()}&tipo={$this->calendar['tipo']}&titolo={$this->calendar['titolo']}&css={$this->calendar['css']}&value={$this->get_value()}&lang=".($this->dizionario?$this->dizionario[0]->get_al():'it')."&max={$this->max}&min={$this->min}\")'
onkeypress='return calendarioPopup(\"{$this->get_id()}\",\"/{$docroot}calendar.php?id={$this->get_id()}&tipo={$this->calendar['tipo']}&titolo={$this->calendar['titolo']}&css={$this->calendar['css']}&value={$this->get_value()}&lang=".($this->dizionario?$this->dizionario[0]->get_al():'it')."&max={$this->max}&min={$this->min}\")'
style='border:0px'/>trasl('Click qui per selezionare dal calendario')}\" style='border:0px' id=\"calend_icon_{$this->get_id()}\" />";
}
if(!$this->myFields['static']['common']) {$jsCommon=$this->get_js_common();$this->myFields['static']['common']=true;}
return $jsCommon.$this->jsAutotab().$this->send_html($out);
}
function get_errore_diviso() {
$valore=$this->get_value();
if ($this->notnull && $valore=='') return 'non può essere nullo';
if ($this->maxlength && strlen($valore)>$this->maxlength) return array('non può contenere più di %1% caratteri',$this->maxlength);
if ($this->minlength && strlen($valore)<$this->maxlength) return array('deve contenere almeno %1% caratteri',$this->minlength);
$d=new Data("gma",$valore);
if ($d->errore) return $d->errore;
$M=new MyDate("",$this->min);
if ($valore && $this->min) {
$mese=$M->inlettere(array('m'));
$min=intval($M->get_parte(0)).' '.$this->trasl($mese['m']).' '.intval($M->get_parte(2));
if ($d->get_value_formatted('amg','-')<$M->get_formatted()) return array('non può essere antecedente al %1%',$min);
}
if ($valore && $this->max) {
$M->set_value($this->max);
$mese=$M->inlettere(array('m'));
$max=intval($M->get_parte(0)).' '.$this->trasl($mese['m']).' '.intval($M->get_parte(2));
if ($d->get_value_formatted('amg','-')>$M->get_formatted()) return array( 'non può essere successiva al %1%',$max);
}
}
function get_xml_value(){
return $this->get_formatted($this->xmlFormat[0],$this->xmlFormat[1]);
}
function set_xml_format($formato='amg',$divisore='-'){
$this->xmlFormat=array($formato,$divisore);
}
}
/**
* @package myFields
*/
Class MyOra extends MyOrario {
/**#@+ @ignore */
protected $anche_secondi=true;
/**#@-*/
/**
* Costruttore di classe, permette di memorizzare una generica ora nell'ambito delle 24 ore giornaliere
* si interfaccia con il DB memorizzando il valore espresso in HH:MM:00, (specifico per mysql)
*
* @access public
* @param string $nome E' il nome del campo
* @param string $valore Valore da assegnare come default ACCETTATE SIA IN FORMATO hh:mm e hh.mm
* @param string $classe è la classe css da utilizzare
*/
function MyOra ($nome,$valore='',$classe='') {
parent::MyInt($nome,$valore,$classe);
$this->is_numeric(false);
$this->set_attributo('maxlength','5');
$this->set_attributo('size','5');
$this->set_regExp('^[0-9]{1,2}([\.\:\,]{1}[0-9]{1,2})?$',' errato, formato corretto hh.mm');
$this->set_MyType('MyOra');
}
/**
* Setta la proprietà di inserire fittiziamente anche i secondi quando salva su DB
*
* @param boolean $abilita disabilita/abilita tale proprietà
*/
function set_secs_mode($abilita=false) {
$this->anche_secondi=$abilita;
return $this;
}
/**
* Restituisce lo stato proprietà di inserire anche i secondi quando salva su DB
*
* @return boolean stato della proprieta
*/
function get_secs_mode($disabilita=true) {
return $this->anche_secondi;
}
function get_errore_diviso() {
// if(!preg_match('#^[0-9]{1,2}([\\.\\:\\,]{1}[0-9]{1,2})?$#',$this->get_value())) return "non è in formato corretto";
if ($errore=parent::get_errore_diviso()) return $errore;
$v=explode(':',$this->get_value());
if ($v[1]<0 || $v[1]>59 ) return " deve avere il numero di minuti compreso tra 0 e 59";
if ($v[0]<0 || $v[0]>23 ) return " deve avere l'ora compresa tra 0 e 23";
}
}
/**
* @package myFields
*/
class MyFloat extends MyInt {
/**#@+ @ignore */
protected $decimali='',$separatore='.';
/**#@-*/
/**
* Costruttore di classe
*
* @access public
* @param string $nome E' il nome del campo
* @param string $valore Valore da assegnare all'attributo 'value'
* @param string $classe è la classe css da utilizzare
*/
function MyFloat ($nome,$valore='', $classe='') {
$this->set_regExp('^(([\+\-]{0,1})[0-9]*([\\.\\,]{0,1}[0-9]*))$',"deve essere un numero");
parent::MyText($nome,$valore,$classe);
$this->set_decimali(0);
$this->set_MyType('MyFloat');
}
/** Setta il numero di cifre decimali accettabili
* @param integer $decimali
*/
function set_decimali($decimali){
$this->decimali=$decimali;
if (!$decimali)$this->set_regExp('^[\+\-]{0,1}[0-9]+([\\.\\,]{0,1}[0-9]+)?$',"deve essere un numero");
else $this->set_regExp('^[\+\-]{0,1}[0-9]+([\\.\\,]{0,1}[0-9]{1,'.$decimali.'})?$',array("deve essere un numero con al più %1% cifre decimali",$decimali));
if ($this->max) $maxl1=strlen(intval($this->max))+1+$this->decimali;
if ($this->min) $minl2=strlen(intval($this->min))+1+$this->decimali+($min<0);
$this->set_maxlength(max($maxl1,$minl2));
return $this;
}
function set_max($max) {
$this->max=$max;
$dec=strlen(strstr($max,$this->separatore))-1;
$this->set_decimali(max($dec,$this->decimali));
return $this;
}
function set_min($min) {
$this->min=$min;
$dec=strlen(strstr($min,$this->separatore))-1;
$this->set_decimali(max($dec,$this->decimali));
return $this;
}
function set_value($valore) {
$val=str_replace(',','.',$valore);
if (strlen($val) && $this->decimali && !preg_match("#{$this->controllo_regExp['exp']}#",$val))
parent::set_value(str_replace('.',$this->separatore,sprintf('%01.'.$this->decimali.'f',$val)));
else parent::set_value(str_replace('.',$this->separatore,$val));
return $this;
}
function &get_value() {
if (parent::get_value()!=0) $this->set_value(parent::get_value());
return parent::get_value();
}
/**
* Imposta il segno separatore dei decimali, sono accettati solo punto o virgola
* altrimenti non ha effetto
*
* @param ,|. $separatore
*/
function set_separatore($separatore='.') {
if ($separatore=='.' || $separatore==',') {
$this->separatore=$separatore;
$this->set_decimali($this->decimali);
}
return $this;
}
/**
* Restituisce il separature corrente
*
* @return ,|.
*/
function get_separatore() {
return $this->separatore;
}
/** Restituisce il valore del campo in lettere
* @param int $decimali numero di cifre decimali in forma letterale, se negativo si aggiungono sempre decimali anche se non significativi
* @param string $separatore_decimali indica la parola per il simbolo di interpunzione
* @param bool $numero è il numero da convertire, se omesso si usa il valore corrente dell'oggetto
* @return string
*/
function inlettere ($decimali=2,$separatore_decimali='virgola',$numero='') {
if ($numero==='') $n=(float) trim(str_replace(array(",",'.'),array($this->separatore,$this->separatore),$this->get_value()));
else $n=(float) $numero;
if (!$separatore_decimali) $separatore_decimali='virgola';
if ($n<0) {
$segno='-';
$n=abs($n);
}
$v=explode($this->separatore,round($numero,abs($decimali)));
if ($v[1] || $decimali<0) return $segno.myInt::inlettere($v[0]).$separatore_decimali.myInt::inlettere($v[1]);
else return $segno.myInt::inlettere($v[0]);
}
function get_html(){
$this->get_value();
return parent::get_html();
}
}
/**
* @package myFields
*/
class MyFloatPos extends MyFloat {
/**
* Costruttore di classe
* @access public
* @param string $nome E' il nome del campo
* @param string $valore Valore da assegnare come default
* @param string $classe è la classe css da utilizzare
*/
function MyFloatPos ($nome,$valore='', $classe='') {
parent::MyFloat($nome,$valore,$classe);
$this->set_min(0);
$this->set_MyType('MyFloatPos');
}
/*
function set_max($max) {
parent::set_max($max);
$this->set_maxlength(strlen($this->max)+1+$this->decimali);
}
*/
}
/**
* @package myFields
*/
Class MyEuro extends MyFloat {
/**
* Costruttore di classe
*
* @access public
* @param string $nome E' il nome del campo
* @param string $valore Valore da assegnare come default
* @param string $classe è la classe css da utilizzare
*/
function MyEuro($nome,$valore='', $classe='') {
parent::MyFloat($nome,'',$classe);
$this->set_decimali(2);
$this->set_value($valore);
$this->set_MyType('MyEuro');
$this->set_style("text-align","right");
}
/*
function get_value(){
if($this->separatore=',')
}
*/
function set_mask(){
$this->mask=new myJQMask("#{$this->get_id()}");
return $this;
}
/** Restituisce il valore del campo in lettere
* @param string $separatore_decimali indica il simbolo di separazione tra interi e decimali(in forma numerica) di default '/'
* @param float $numero è il numero da convertire, se omesso si usa il valore corrente dell'oggetto
* @return string
*/
function inlettere ($separatore_decimali='/',$numero='') {
if ($numero==='') $n=(float) trim(str_replace(array(",",'.'),array($this->separatore,$this->separatore),$this->get_value()));
else $n=(float) $numero;
if ($n<0) {
$segno='-';
$n=abs($n);
}
$v=explode('.',sprintf("%01.2f",$numero,2));
return $segno.myInt::inlettere($v[0]).$separatore_decimali.$v[1];
}
function set_value($x) {
if($this->mask) {
if($this->separatore=='.') $migliaia="'";
else $migliaia='.';
$x=trim(str_replace($migliaia,'',$x));
}
return parent::set_value($x);
}
function get_html(){
if(!$this->mask) return parent::get_html();
{$l=strlen(max(intval(abs($this->get_max())), intval(abs($this->get_min()))));
$m="{$this->separatore}99";
if($this->separatore=='.') $migliaia="'";
else $migliaia='.';
for ($i=0;$i<$l;$i++) {
if($i>0 && $i%3==0)
{$m=$migliaia.$m;
$punti++;
}
$m="9$m";
}
if($this->get_min()<0) {
$this->set_maxlength($l+$punti+4,$l+$punti+4);
$this->mask->set_mask("~$m",'_',array('~'=>'+ -'));
}
else {
$this->set_maxlength($l+$punti+3,$l+$punti+3);
$this->mask->set_mask($m);
}
$this->add_myJQuery($this->mask);
return parent::get_html();
}
}
}
/**
* @package myFields
*/
/**
* @package myFields
*/
/**
* @package myFields
*/
class MyURL extends MyEmail {
/**#@+ @ignore */
protected $componenti_fisse=array(),$controllo=false;
/**#@-*/
function MyURL ($nome,$valore='', $classe='') {
parent::MyEmail($nome,$valore,$classe);
$this->set_regExp('^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?');
$this->set_MyType('MyURL');
$this->set_MaiMin('');
}
/**
* Funzione inversa di get_componenti
* @see get_componenti
* @static
* @param array $componenti
*
*/
function ricomponi_componenti($componenti)
{
if (!is_array($componenti)) return false;
$uri = isset($componenti['scheme']) ? $componenti['scheme'].':'.((strtolower($componenti['scheme']) == 'mailto') ? '' : '//') : '';
$uri .= isset($componenti['user']) ? $componenti['user'].(isset($componenti['pass']) ? ':'.$componenti['pass'] : '').'@' : '';
$uri .= isset($componenti['host']) ? $componenti['host'] : '';
$uri .= isset($componenti['port']) ? ':'.$componenti['port'] : '';
if(isset($componenti['path']) && strtolower($componenti['scheme']) != 'mailto')
{
$uri .= (substr($componenti['path'], 0, 1) == '/') ? $componenti['path'] : ('/'.$componenti['path']);
}
if(isset($componenti['path']) && strtolower($componenti['scheme']) == 'mailto')
{
$uri .= $componenti['path'] ;
}
$uri .= isset($componenti['query']) ? '?'.$componenti['query'] : '';
$uri .= isset($componenti['fragment']) ? '#'.$componenti['fragment'] : '';
return $uri;
}
function get_errore_diviso() {
if ($errore=parent::get_errore_diviso()) return $errore;
$parse=$this->get_componenti();
if (!$parse) return ' '.$this->trasl("formalmente errato");
foreach ($this->componenti_fisse as $i=>$v) {
if ($v[valore] && !$parse[$i]) $parse[$i]=substr($v[valore],0,strpos($v[valore],'|')) ;
elseif(!$errore && $v[valore] && ($p=strpos("|$v[valore]|",'|'.$parse[$i].'|'))===false) $errore=$this->trasl("formato errato").", $v[mex]";
}
$this->set_value($this->ricomponi_componenti($parse));
return $errore;
}
/**
* Fissa delle componenti, le componenti fissate non potranno essere cambiate dell'utente e se omesse verranno aggiunte
* @param array $scheme
* @param array $host
* @param array $port
* @param array $path
* *
*
* $u=new myURL('nome');
* $u->fissa_componenti(array('http','https'),array('www.italia.it','www.italia.gov.it'));
* $u->set_value('www.prova.it');
* echo $u->Errore(); //Restituisce "formato errato, deve iniziare per: http oppure https
* echo $u->get_value(); //restituisce http://www.prova.it , all'host errato www.prova.it
* // (ma segnalato nell'errore) si aggiunge il primo
* // degli schemi di default
*
*/
function fissa_componenti($scheme='',$host='',$port='',$path='') {
if ($scheme) {$this->componenti_fisse[scheme][mex]=array($this->trasl("deve iniziare per: %1%"),implode(' '.$this->trasl('oppure').' ',$scheme));
$this->componenti_fisse[scheme][valore]=implode('|',$scheme);
}
if ($host) {$this->componenti_fisse[host][mex]=array($this->trasl("deve avere l'host: %1%"),implode(' '.$this->trasl('oppure').' ',$host));
$this->componenti_fisse[host][valore]=implode('|',$host);
}
if ($port) {$this->componenti_fisse[port][mex]=array($this->trasl("deve usare la porta: %1%"),implode(' '.$this->trasl('oppure').' ',$port));
$this->componenti_fisse[port][valore]=implode('|',$port);
}
if ($path) {$this->componenti_fisse[path][mex]=array($this->trasl("il percorso deve essere: %1%"),implode(' '.$this->trasl('oppure').' ',$path));
$this->componenti_fisse[path][valore]=implode('|',$path);
}
}
/**
* Restituisce le componenti della url
* @link http://it2.php.net/manual/it/function.parse-url.php
* @static
* @param string $url se omesso restituisce il parsing del valore corrente dell'istanza
* @return array con le componenti come chiavi
*
*
* $url = 'http://username:password@hostname/path?arg=value#anchor';
* print_r( myurl::get_componenti($url) );
*
* Il precedente esempio visualizzerà:
* Array
* (
* [scheme] => http
* [host] => hostname
* [user] => username
* [pass] => password
* [path] => /path
* [query] => arg=value
* [fragment] => anchor
* )
*
*/
function get_componenti($url='') {
if (!$url) $url=$this->get_value();
if (strpos($url,':')===false) $url='myfields://'.$url;
$p=(array) @parse_url($url);
foreach ($p as $i=>$v) if ($v=='myfields') unset($p[$i]);
return $p;
}
function &get_value() {
return myText::get_value();
}
function set_value($valore) {
myText::set_value($valore);
return $this;
}
/**
* Fa comparire l'icona per verificare la correttezza del link
*
*/
function set_controllo(){
$this->myFields['static']['js_src'][get_class($this)]="
";
$this->controllo="
";
/*
function ApriMyUrl(LINK){
if (LINK) {
finestrella=window.open('/".$this->get_MyFormsPath()."/js/tiny_mce/plugins/myadvlink/cercaUrl/index.php?parentid='+LINK, 'myURL', 'resizable=1,toolbar=0,menubar=0,location=0,scrollbars=yes,resize=1,width=800,height=400');
finestrella.focus();
}
}
";
$this->controllo="
";
*/
/*"
\n";
if ($this->reloadJSGET) {if($campo->get_name() && $this->reloadJSGET[$campo->get_value()])
{$urls=$this->build_reload_urls($this->reloadJSGET[$campo->get_value()][0],
str_replace('[]','',$campo->get_name()),
$this->reloadJSGET[$campo->get_value()][1],
'','',
$this->reloadJSGET[$campo->get_value()][2]
);
$url=$urls[$campo->get_value()];
}
}
elseif($this->showlinks) {if($campo->get_name())
{$fragment=explode('#',$this->showlinks[0],2);
if(count($fragment)==1)
$url=explode('?',$this->showlinks[0],2);
else $url=explode('?',$fragment[0],2);
$fragment=$fragment[1];
$urls=$this->build_reload_urls(
'parametro',
str_replace('[]','',$campo->get_name()),
$this->showlinks[1],
$url[0],
$url[1],
$fragment
);
$url=$urls[$campo->get_value()];
}
}
$link = new MyLink((!$url?'#':htmlentities($url)),$this->trasl('Click qui per scegliere l\'opzione'));
if ($attrLabel) $link->set_attributi($attrLabel);
$link->unset_attributo('name');
$link->unset_attributo('onclick');
$link->unset_attributo('onkeypress');
$link->unset_attributo('onchange');
if ($campo->get_checked())
{
$link->set_attributo('style','font-weight:bold');
$outLink="Scelto".($url?$link->get_html($this->trasl($nome_campo)):$this->trasl($nome_campo));
}
else $outLink=($url?$link->get_html($this->trasl($nome_campo)):$this->trasl($nome_campo));
if (isset($this->showlinks)) return $outLink;
else return ($outLink?"":'').$outScript;
}
}
/**
*
* Calcola le url usate nel mySelect::setReloadJS() nelle modalità GET,
* utile per eventuali overriding
*
* @param parametro|completo|azzera|submit $Tipo Il default è 'parametro'
* @param string $nome_campo nome del campo usato come riferimento per la costr. nuova url
* @param boolean $usa_random se true aggiunge tt randomico
* @param string $url eventuale url da usare, se string avuota o omesso si usa $_SERVER['PHP_SELF']
* @param string $query_string eventuale string di parametri se FALSE non si usa omesso o stringa vuota usa $_SERVER["QUERY_STRING"]
* @param string $fragment eventuale fragment
*
* @return string
*/
function build_reload_urls($Tipo,$nome_campo,$usa_random,$url='',$query_string='',$fragment=''){
$nuova=array();
if($query_string==='') $query_string=$_SERVER["QUERY_STRING"];
if($query_string) @parse_str($query_string,$parametri);
if(!$url) $url=$_SERVER['PHP_SELF'];
$parametri=(array) $parametri;
unset($parametri['ttt']);
unset($parametri['tt']);
static $build;
if($build[serialize(func_get_args())]) return $build[serialize(func_get_args())];
$secure=new mySecurizer();
if($parametri)
foreach ($parametri as $par=>$val)
{
if ($Tipo=='parametro' && $par==$nome_campo) break;
if ($par!=$nome_campo && (is_array($val) || trim($val)!==''))
$nuova[$par]=(mySecurizer::seemsSecurized($val) &&
($val=$secure->decode($par, $val,false))!==false
?$secure->encode($par, $val):$val);
}
if ($Tipo=='azzera') $nuova=array();
if($usa_random) $nuova['tt']=self::unid();
if($fragment) $fragment="#$fragment";
foreach ($this->get_Opzioni() as $titolo=>$val)
{$nuova[$nome_campo]=$val;
$valori[$val]=$url.'?'.http_build_query($nuova).$fragment;
}
return $build[serialize(func_get_args())]=$valori;
}
/** @ignore*/
function _get_html_show($pars=''){
if (count($this->opzioni)==0 || !($vals=$this->get_value())) return;
if (!is_array($vals)) $vals=array($vals);
$vals=array_flip($vals);
foreach ($this->campi as $nome=>$val)
if($nome && isset($vals[$val->get_value()]))
{ $opz[]=$nome;
$id=++$this->myFields['static']['ids_'.get_class($this)][$this->get_id()];
if ($pars['campo'] &&
!$val->get_attributo['disabled'])
{$x=new MyHidden($val->get_name(),$val->get_value());
$x->set_attributo('id',$this->get_id().'_'.$id);
$out.=$x->get_Html();
}
}
if (count($opz)==1) return $opz[0].$out;
return "
".implode('
',(array)$opz)."
$out";
}
/** @ignore */
protected function _get_html_hidden($pars){
$this->clean_value();
$v=(array)$this->get_value();
foreach ($v as $val) $out.=new MyHidden($this->get_name(),$val);
return $out;
}
function get_xml_value(){
$xmlTagCampo=$this->xmlTagCampo;
if (!$xmlTagCampo) {
$xmlTagCampo=explode('[',($this->xml['']?$this->xml['']:$this->get_name()));
$xmlTagCampo=$xmlTagCampo[0].'_valore';
}
$attr=$this->get_attributi();
$attributi_specifici_dele_singolo=array('name'=>1,'id'=>1,'value'=>1);
$valori=$this->get_value();
if (is_array($valori)) $valori=@array_flip($valori);
else $valori=array($valori=>1);
foreach ($this->campi as $v)
{
$campo=$v->clonami();
if ($attr) foreach ($attr as $n=>$v) if (!$campo->get_attributo($n) && !$attributi_specifici_dele_singolo[$n]) $campo->set_attributo($n,$v);
if (isset($valori[$campo->get_value()])) $campo->set_checked();
else $campo->set_unchecked();
$campo->set_parametri_xml($xmlTagCampo);
$out.=$campo->get_xml();
}
return $out;
}
/** Restituisce il campo in XML iin UTF-8 pronto per la visualizzazione, di default gli attributi non vengono presi in considerazione ed il nome del campo diventa il tag che lo racchiude mentre il contenuto è il valore restituito da @see get_xml per personalizzare gli attributi usare @see set_attributi_xml
* @return string
*/
function &get_xml() {
if(!$this->abilitaXML) return;
if (is_array($this->xml))
foreach ($this->xml as $nome=>$usare)
if ($nome && trim($this->parametri[$nome])) $parametri.=' '.strtolower($usare)."=\"".(htmlspecialchars($this->parametri[$nome],null,'UTF-8')).'"';
$tag=($this->xml['']?$this->xml['']:$this->get_name());
$tag=explode('[',$tag,2);
if(strlen($v=$this->get_xml_value()))
return "<$tag[0]$parametri>$v$tag[0]>";
elseif(!$this->facoltativoXML) return "<$tag[0]$parametri />";
}
/**
* Imposta eventuali variazioni sull'XML prodotto da @see get_xml
*
* @param string $tagName è il tag name che verrà usato nell'xml al posto del nome del campo (se omesso si usa il nome del campo
* @param array $attributi è l'array associativo che indica la trascodifica degli attributi da visualizzare, la chiave è il nome dell'attributo HTNL il valore è l'attributo XML da usare
* può anche non essere associativo, in quel caso indica gli attributi da visualizzare
* @param string $tagContenuto è il nome del tag da usare nei tag che rappresentano i valori
*/
public function set_parametri_xml($tagName='',$attributi=array(),$tagContenuto=''){
parent::set_parametri_xml($tagName,$attributi);
$this->xmlTagCampo=$tagContenuto;
return $this;
}
function get_campi_interni(){
return $this->campi;
}
function get_Html($noLabel=false,$attributi_td="") {
if(!$this->myFields['static']['common']) {$jsCommon=$this->get_js_common();$this->myFields['static']['common']=true;}
if(!$attributi_td)
{
if($this->posizionelabel=='d') $attributi_td=" style='text-align:left' ";
else $attributi_td=" style='text-align:right' ";
}
if (($get_html=$this->Metodo_ridefinito['get_Html']['metodo']))
return $jsCommon.$this->$get_html($this->Metodo_ridefinito['get_Html']['parametri']);
if (count($this->opzioni)==0) return;
$riga=0;
$i=0;
foreach ($this->campi as $nome=>&$val)
{if(!$nome) continue;
if ($this->autotab) $this->campi[$nome]->set_autotab();
$x[$riga][]=$this->get_html_singolo($nome,$noLabel);
if (++$i % $this->accapo==0) $riga++;
}
$out="
get_id()}\" >";
if (is_array($x)) foreach ($x as &$riga) $out.="
".implode("
",$riga)."
";
$out.="
".$this->get_html_Accessibilita($this->get_attributo('onclick'));
return $jsCommon.$out;
}
/**
* Passa in minuscolo (ma con la prima lettera di ogni parola maiuscola)
* facendo ovewriting di questo metodo si possono personalizzare le regole di "aggiustamento" delle opzioni
* @param string $cosa
*/
function Minuscolo ($cosa) {
$v=explode("_",trim($cosa));
for ($i=0; $iopzioni))
{
foreach ($this->opzioni as $nome=>$val) $v[$this->Minuscolo($nome)]=$val;
$this->opzioni=$v;
}
return $this;
}
/** se settato aggiunge il reload della pagina sull'evento passato, di default è onClick
* DA USARE SOLO DOPO AVER IMPOSTATO LE OPZIONI
* @param parametro|completo|azzera|submit $Tipo Il default è 'parametro'
* @param string $evento Il nome dell'evento su cui attivare il reload
* Supponiamo che questo selettore si chiami 'Tipo' e la url della pagina sia
* http://www.fdsf.it?abc=32432&Tipo=424&altro=12345
* con l'opzione 'parametro' si ricaricherà http://www.fdsf.it?abc=32432&Tipo=nuovo_valore
* con l'opzione 'completo' si ricaricherà http://www.fdsf.it?abc=32432&Tipo=nuovo_valore&altro=12345
* con l'opzione 'azzera' si ricaricherà http://www.fdsf.it?Tipo=nuovo_valore
* con l'opzione 'submit' effettua l'invio in POST del form così com'è
*
**/
function SetReloadJS($Tipo='parametro',$evento='onclick',$opzioni=array(),$fragment='',$usa_random=true,$sostituisci=false) {
if (!$opzioni || count($opzioni)==0) {
$opzioni=array_values($this->get_opzioni());
//print_r($this->get_opzioni());
}
// echo "
";print_r($this->nuovaUrl);
foreach ($this->campi as $opz=>&$campo)
if (in_array($campo->get_value(),$opzioni)!==false)
{
if ($Tipo=='submit') $this->campi[$opz]->set_attributo($evento,"submit()");
else { $this->reloadJSGET[$campo->get_value()]=array($Tipo,$usa_random,$fragment);
$this->campi[$opz]->set_js("location.href=myLinks_{$campo->get_id_istanza()}[this.value];",$evento,$sostituisci);
}
}
// echo "
";print_r($this->campi);
return $this;
}
/**
* alias di @see setreloadjs()
*/
function set_reloadjs($Tipo='parametro',$evento='onclick',$opzioni=array(),$fragment='',$usa_random=true,$sostituisci=false) {
return $this->setreloadjs($Tipo,$evento,$opzioni,$fragment,$usa_random,$sostituisci);
}
/** se assegna un JS ad un evento delle $opzioni di default è onClick
* DA USARE SOLO DOPO AVER IMPOSTATO LE OPZIONI
* @param array $opzioni E' un array con l'elenco delle CHIAVI su cui attivare l'evento, se vuoto si applica a tutte
* @param string $JS E' lo JavaScript da lanciare
* @param string $evento Il nome dell'evento su cui attivare lo JS
* @param boolean $sostituisci sostituisce eventuali eventi precedenti
*/
function SetJS($opzioni='',$JS,$evento='onclick',$sostituisci=true) {
if (!$opzioni || count($opzioni)==0) {parent::SetJS($JS,$evento);
return $this;
}
// foreach ($opzioni as $opz) if (isset($this->campi[$opz])) $this->campi[$opz]->SetJS($JS,$evento);
foreach ($this->campi as $opz=>&$v)
if (in_array($v->get_value(),$opzioni)!==false)
{
$this->campi[$opz]->SetJS($JS,$evento,$sostituisci);
}
return $this;
}
/**
* alias di @see setjs()
*/
function set_js($opzioni='',$JS,$evento='onclick',$sostituisci=true) {
return $this->setjs($opzioni,$JS,$evento,$sostituisci);
}
/** Setta le opzioni
* @param array $opzioni E' un array associativo con le opzioni Titolo=>valore
*/
function set_Opzioni($opzioni=array()) {
$this->opzioni=$opzioni;
$valori=$this->get_value();
if (is_array($valori)) $valori=@array_flip($valori);
else $valori=array($valori=>1);
unset($this->myFields['campo__istanze'][$this->get_name()]);
if (is_array($this->campi)) foreach ($this->campi as $i=>$v) $attr[$i]=$v->get_attributi();
$this->campi=array();
if ($opzioni) foreach ($opzioni as $val=>$key)
{
$this->campi[$val]=new MyCheck($this->get_attributo('name'),$key,$this->get_attributo('class'));
if ($attr[$val]) {unset($attr[$val]['id']);
$this->campi[$val]->set_attributo($attr[$val]);
}
if (isset($valori[$this->campi[$val]->get_value()]))
$this->campi[$val]->set_checked();
else $this->campi[$val]->set_unchecked();
$this->myFields['campo__istanze'][$this->get_name()]--; //altrimenti l'id cresce 2 volte
$this->campi[$val]->set_name($this->get_name().'[]');
}
return $this;
}
/** Aggiunge una singola opzione
* @param string $titolo è il titolo da visualizzare
* @param string $valore è il valore da associare al titolo
* @param boolean $fine se falso o omesso l'opzione si aggiunge in coda se true si aggiunge all'inizio
*/
function add_Opzione($titolo,$valore,$fine=false) {
$this->notrasl=true;
$opzioni=$this->get_Opzioni();
$this->notrasl=false;
if (!$fine) {$n_opzioni=$opzioni;
$n_opzioni[$titolo]=$valore;
}
else {$n_opzioni[$titolo]=$valore;
if (is_array($opzioni)) foreach ($opzioni as $id=>$val) $n_opzioni[$id]=$val;
}
$this->set_Opzioni($n_opzioni);
}
/**
* Setta le opzioni del selettore
*
* @param ADODBConnection $db è la connessione a DB da utilizzare
* @param string $qry la query da usare per reperire i dati in cui il primo campo è Titolo ed il secondo è il valore del selettore
* @param boolean $registra se true i valori vengono memorizzati in una variabile di sessione e la qry non si riesegue più
*/
function set_OpzioniQRY(&$db,$qry='',$registra=true) {
$this->qry=$qry;
IF ($_SESSION['myFields']['MyOpzioniRegistrate'][md5($this->qry)] && $registra)
{$this->opzioni=$_SESSION['myFields']['MyOpzioniRegistrate'][md5($this->qry)];
$opzioni=$this->opzioni;
}
else {
$v=&$db->getarray($qry);
for ($i=0;$iset_Opzioni($opzioni);
if ($registra) $this->registra_opzioni();
return $this;
}
/**
* Registra le opzioni in sessione
**/
function registra_opzioni() {
$_SESSION['myFields']['MyOpzioniRegistrate'][md5($this->qry)]=$this->opzioni;
}
/**
* Elimina le opzioni dalla sessione
**/
function deregistra_opzioni() {
unset($_SESSION['myFields']['MyOpzioniRegistrate'][md5($this->qry)]);
}
function get_errore_diviso() {
$valore=$this->get_value();
if ($this->notnull && !$valore) return 'non può essere nullo';
if(!$valore) $valore=array();
if($this->restrizioni_check && $valore)
{$opzioni=$this->get_Opzioni();
if(!$opzioni) $opzioni=array();
else $opzioni=array_values($opzioni);
if(array_diff($valore,$opzioni)) return 'non è accettabile';
}
}
function get_js_chk(){
if ($this->notnull) return "if(strlen(myGetValueCampo('{$this->get_id()}','radio',null))==0) return \"{$this->trasl('non può essere nullo')}\";";
}
}
/**
* @ignore
* @package myFields
*/
Class _MyRadio extends MyCheck {
var $valore;
function _MyRadio ($nome,$valore='',$classe='') {
parent::MyCheck($nome,$valore,$classe);
$this->set_attributo('type','radio');
}
function set_value($valore) {
$this->valore=$valore;
return parent::set_value($valore);
}
function &get_value() {
return $this->valore;
}
/** Non attiva in questa classe
*/
function set_autotab () {return $this; }
}
/**
* @package myFields
*/
Class MyRadio extends MyMultiCheck{
/**#@+ @ignore */
protected $accapo=5,$campi, $attributi_opzioni=array(),$restrizioni_check=true;
/**#@-*/
/**
* Costruttore di classe
* @access public
* @param string $nome E' il nome del campo
* @param int/string $valore da assegnare come default
* @param array $opzioni E' un array associativo con le opzioni Titolo=>valore
* @param string $classe è la classe css da utilizzare
*/
function MyRadio ($nome,$valore='',$opzioni=array(),$classe=''){
$this->set_MyType('MyRadio');
parent::MyField($nome,$valore,$classe);
if (is_array($nome) && $nome['opzioni']) $opzioni=$nome['opzioni'];
if (count($opzioni)>0) $this->set_Opzioni($opzioni);
$this->set_MyType('MyRadio');
$this->Richiede_tag_label=false;
}
/**
* Permette di rendere il check_errore più o meno restrittivo
*/
function set_restrizioni_check($stato){
$this->restrizioni_check=$stato;
return $this;
}
/** Non attiva in questa classe*/
function set_autotab () {return $this;}
function set_name($nome) {
MyField::set_name($nome);
if ($this->campi) foreach ($this->campi as $name=>$val) if ($this->campi[$name]->get_name()) $this->campi[$name]->set_name($nome);
return $this;
//echo "
"; print_r($this->campi);
}
function get_name() {
return MyField::get_name();
}
/** Restituisce il titolo associato al valore
* @param string $valore se omesso si usa il valore predefinito del selettore
* @return string $titolo è il titolo visualizzato
*/
function get_Titolo($valore='') {
$opzioni=array_flip($this->get_opzioni());
return $opzioni[($valore?$valore:$this->get_value())];
}
function set_Opzioni($opzioni=array()) {
$this->opzioni=$opzioni;
if (is_array($this->campi))
foreach ($this->campi as $i=>$v) $attr[$i]=$v->get_attributi();
unset($this->myFields['campo__istanze'][$this->get_name()]);
$this->campi=array();
if (is_array($opzioni)) {
foreach ($opzioni as $label=>&$valore)
if ($label)
{//unset($this->campo__istanze[$this->get_name()]);
// echo $this->get_name()." $label=>$valore ";
$this->campi[$label]=new _MyRadio($this->get_name(),$valore,$this->get_attributo('class'));
if ($attr[$label]) {unset($attr[$label]['id']);
unset($attr[$label]['value']);
$this->campi[$label]->set_attributo($attr[$label]);
$this->campi[$label]->set_attributo($this->attributi_opzioni[$label]);
}
if ($this->get_value()==$valore) $this->campi[$label]->set_checked();
}
}
return $this;
}
/** elimina dal/i valore/i impostati quelli non presenti nelle opzioni
* attenziene a non usarla prima di aver settato tutte le opzioni valide
* altrimenti si annulla il valore
*/
function clean_value() {
$opzioni=@array_flip($this->opzioni);
if (!$opzioni) $opzioni=array();
$valore=$this->get_value();
if (!isset($opzioni[$valore]))$this->set_value('');
return $this;
}
function set_value($valore) {
MyField::set_value($valore);
if ($this->campi)
foreach ($this->campi as $label=>$campo)
if (trim($this->get_value())===trim($valore)) $this->campi[$label]->set_checked();
else $this->campi[$label]->set_unchecked();
return $this;
}
function isMultiple(){
return false;
}
/** @ignore*/
function &get_value_DB() {
RETURN $this->Get_value();
}
function get_errore_diviso() {
$valore=$this->get_value();
if ($this->notnull && strlen(trim($valore))==0) return 'non può essere nullo';
if($this->restrizioni_check && $this->get_value())
{
$opz=array_flip($this->get_opzioni());
if(!isset($opz[$this->get_value()])) return 'non è accettabile';
}
}
function &get_value() {
return MyField::get_value();
}
/** L'elenco si trasforma in un elenco di link
*
* @param string $url indica l'url di destinazione alla quale verrà automativamente accodato il valore cliccato
*
**/
function Set_Links($url,$add_random=false) {
$this->showlinks=array($url,$add_random);
return $this;
}
/**
* Imposta attributi delle singole opzioni es style, class
*
* @param array $opzioni Titoli (non i valori) delle opzioni da personalizzare
* @param string $attributo nome dell'attributo da settare
* @param string $valore valore dell'attributo
*/
function set_attributo_opzioni($opzioni,$attributo,$valore) {
foreach ($opzioni as $v)
{
if (!$this->attributi_opzioni[$v]) $this->attributi_opzioni[$v]=new myTag();
$this->attributi_opzioni[$v]->set_attributo($attributo,$valore);
if ($this->campi[$v]) $this->campi[$v]->set_attributo($attributo,$valore);
}
return $this;
}
function get_js_chk(){
// if ($this->notnull) return "if(strlen(myGetValueCampo('{$this->get_id()}','radio',null))==0) return \"{$this->trasl('non può essere nullo')}\";";
//else
//il notnull andrebbe controllato su tutte le opzioni
return "return null;";
}
function get_xml_value(){
return $this->get_value();
}
function &get_xml(){
return MyField::get_xml();
}
}
Class MySelect extends MyField {
/**#@+ @ignore */
protected $opzioni=array(),$default='',$reloaJSGET='',$pulsante,$attributi_opzioni,$ajaxloader=array(),$restrizioni_check=true;
protected static $all_ajaxloader=array();
/**#@-*/
/**
* Costruttore di classe
* @access public
*
* @param string $nome E' il nome del campo
* @param int/string $valore da assegnare come default
* @param array $opzioni E' un array associativo con le opzioni Titolo=>valore
* @param string $classe è la classe css da utilizzare
*/
function MySelect ($nome,$valori=array(),$opzioni=array(),$classe=''){
if ($valori && !is_array($valori)) $valori=array($valori);
parent::MyField($nome,$valori);
/*
function MySelect ($nome,$valore='',$opzioni=array(),$classe=''){
if ($valore && !is_array($valore)) $valore=array($valore);
parent::MyField($nome,$valore);
*/
if ($classe) $this->set_attributo('class',$classe);
if (is_array($nome) && $nome['opzioni']) $opzioni=$nome['opzioni'];
if (count($opzioni)) $this->set_Opzioni($opzioni);
//if (!$valori) $this->set_Domanda(' ');
$this->set_MyType('MySelect');
}
/**
* Permette di rendere il check_errore più o meno restrittivo
*/
function set_restrizioni_check($stato){
$this->restrizioni_check=$stato;
return $this;
}
/**
* Enter description here...
*
* @param unknown_type $script
* @param unknown_type $forza_reload
* @param unknown_type $icona_caricamento
* @return unknown
*/
function set_ajaxloader($script,$forza_reload=false,$icona_caricamento=''){
$this->ajaxloader=array('src'=>$script,'campi'=>array(),'forza'=>$forza_reload,'icona'=>$icona_caricamento);
return $this;
}
function set_ajaxloader_input($nome,&$campo){
if(!isset($this->ajaxloader['src'])) die ("Usare set_ajaxloader() prima di set_campo_input()");
$this->ajaxloader['campi'][$nome]=$campo;
self::$all_ajaxloader[$campo->get_id_istanza()][]=$this;
return $this;
}
/** Setta le opzioni
* @param array $opzioni E' un array associativo con le opzioni Titolo=>valore
*/
function set_Opzioni($opzioni=array()) {
$this->opzioni=$opzioni;
return $this;
}
/** elimina dal/i valore/i impostati quelli non presenti nelle opzioni
* attenziene a non usarla prima di aver settato tutte le opzioni valide
* altrimenti si annulla il valore
*/
function clean_value() {
$opzioni=@array_flip((array) $this->get_opzioni());
$valore=$this->get_value();
if ($opzioni && !isset($opzioni[$valore])) $this->set_value('');
return $this;
}
/** setta in automatico il primo valore valido se non ce ne sono settati
*/
function autovalue() {
$this->clean_value();
if (!strlen($this->get_value()))
{//echo "
";
$opz=$this->get_Opzioni();
//print_r($opz);
$opz=each($opz);
if (count($opz)) $this->set_value($opz[1]);
}
return $this;
}
/** Aggiunge una singola opzione
* @param string $titolo è il titolo da visualizzare
* @param string $valore è il valore da associare al titolo
* @param boolean $inizio se falso o omesso l'opzione si aggiunge in coda se true si aggiunge all'inizio
*/
function add_Opzione($titolo,$valore,$inizio=false) {
$this->opzioni=$this->get_Opzioni();
// echo "
$inizio";print_r($this->opzioni);
if (!$inizio) $this->opzioni[$titolo]=$valore;
else {$opzioni[$titolo]=$valore;
if (is_array($this->opzioni)) foreach ($this->opzioni as $id=>$val) $opzioni[$id]=$val;
$this->opzioni=$opzioni;
}
return $this;
}
function &get_value() {
$valori=parent::get_value();
if (!is_array($valori)) return $valori;
elseif (count($valori)>1) return $valori;
else {list($valore) = $valori;
return $valore;
}
}
/** Restituisce il titolo associato al valore
* @param string $valore se omesso si usa il valore predefinito del selettore
* @return string $titolo è il titolo visualizzato
*/
function get_Titolo($valore='') {
$opzioni=array_flip($this->get_opzioni());
return $opzioni[($valore?$valore:$this->get_value())];
}
/** Restituisce l'array associativo con le opzioni
* @return array
*/
function get_Opzioni() {
if (! $this->opzioni) return array();
$array=array();
foreach ($this->opzioni as $i=>&$v) $array[$this->trasl($i)]=$v;
return $array;
}
/** Imposta il valore di default del menù che verrà associato ad un valore nullo
* (se è un carattere verrà ripetutto per tutta la lunghezza del menù)
* @param string $domanda
*/
function set_Domanda($domanda) {
$this->default=$domanda;
return $this;
}
/** @ignore*/
function get_html_Accessibilita($evento) {
if ($evento)
{ // $out.=" ";
$pulsante=new MyPulsante('',($this->pulsante?$this->pulsante:$this->trasl('Aggiorna pagina')));
$pulsante->set_Tooltip($this->pulsante?$this->pulsante:$this->trasl("Premere qui per aggiornare la pagina"));
$this->myFields['NSelettori']++;
$pulsante->set_attributo('id',"puls_".$this->myFields['NSelettori']);
if (stripos($evento,'submit')===0)
{
$out.="
".$pulsante->get_Html()."
";
$this->myFields['static']['common']=false;
}
elseif($this->reloaJSGET)
{$links=$this->build_reload_urls($this->reloaJSGET[0],
$this->get_name(),
$this->reloaJSGET[1],
'',
'',
$this->reloaJSGET[2]);
foreach ($this->get_opzioni() as $titolo=>$valore)
{ $link = new MyLink(htmlentities($links[$valore],ENT_COMPAT|ENT_NOQUOTES|ENT_XHTML),$this->trasl('Scegliere l\'opzione'));
$link->set_attributo('id',"{$this->get_id()}_{$valore}");
if ($valore==$this->get_value()) {
$link->set_attributo('style','font-weight:bold');
$out.="
';
}
return "".($links?
"
":'');
}
}
function set_autotab() {
$this->autotab=true;
return $this;
}
/**
* Imposta attributi delle singole opzioni es style, class
*
* @param array $opzioni Titoli (non i valori) delle opzioni da personalizzare
* @param string $attributo nome dell'attributo da settare
* @param string $valore valore dell'attributo
*/
function set_attributo_opzioni($opzioni,$attributo,$valore) {
foreach ($opzioni as $v)
{
if (!$this->attributi_opzioni[$v]) $this->attributi_opzioni[$v]=new myTag();
$this->attributi_opzioni[$v]->set_attributo($attributo,$valore);
}
return $this;
}
/** @ignore */
protected function _get_html_show($pars){
if ($pars['campo'] && !$this->get_attributo['disabled']) $out=$this->_get_html_hidden($pars);
$attr=$this->stringa_attributi(array('class','style'),false)." id=\"myshow_only_{$this->get_attributo('id')}\"";
return "".$this->get_titolo()."".$out;
}
function get_Html () {
$attributi=$this->attributi;
if ($get_html=$this->Metodo_ridefinito['get_Html']['metodo']) return $this->$get_html($this->Metodo_ridefinito['get_Html']['parametri']);
$this->opzioni=$this->get_Opzioni();
// if (count($this->opzioni)==0) return;
// echo'', $this->get_name(),$this->ajaxloader['src'],$this->con_js,' ';
if($this->con_js && $this->ajaxloader['src'] && !$this->is_hidden() && !$this->get_attributo('disabled'))
{
$loadJs="myAjaxLoader_{$this->get_id()}_{$this->get_id_istanza()}";
if ($this->ajaxloader['src']) $forza="tt='+Math.random()+'&";
if(strpos($this->ajaxloader['src'],'?')!==false) $sep="&$forza";
else $sep="?$forza";
$monitor_eventi="myAjaxLoader_Monitor_{$this->get_id_istanza()}";
$indicatore_attesa="ajaxloader['icona']?$this->ajaxloader['icona']:"/{$this->get_MyFormsPath()}icone/load.gif")."\" style='display:none' />";
$jsAjaxLoader="
";
}
$onChange=$this->get_attributo('onchange');
if($this->con_js && !$onChange && count($this->opzioni)>10)
{
if (!$this->myFields['static']['js_src'][get_class($this)])
{
$js="";
$this->myFields['static']['js_src'][get_class($this)]=1;
}
$this->SetJS("KeyPressCombo(this)",'onkeyup',false);
$this->SetJS("StopKeypressedCombo()",'onblur',false);
$this->SetJS("StartKeypressedCombo()",'onfocus',false);
$this->set_attributo("title",$this->trasl("Digitare direttamente nel menù (quando è chiuso) la parte iniziale del valore che si intende scegliere, premere ESC per annullare la digitazione e ricominciare"));
}
//echo "
";print_r( $_SESSION['myFields']);
if($this->con_js && !$onChange && !$this->get_attributo('onkeyup') && $this->autotab)
{
parent::set_autotab();
$this->SetJS("MyTabulazione(this)",'onchange',false);
}
$valori=$this->get_value();
if (is_array($valori)) $valori=@array_flip($valori);
else if ($valori) $valori=array($valori=>1);
if (is_array($this->opzioni))
foreach ($this->get_opzioni() as $nome=>$val)
if (isset($valori[$val])) {$valorizzato=true;break;}
//echo $this->get_name()." > ".$this->default.">".$this->notnull . " >$valorizzato > ". $this->get_value() ."] ";
if (!$this->default && $this->notnull && (trim($this->get_value())==='' || !$valorizzato))
{
list($val)=array_values($this->opzioni);
$this->set_value($val);
$this->default=$val;
$valori=array($val=>1);
}
$default=$this->default;
if (is_array($this->opzioni))
{
foreach ($this->get_opzioni() as $nome=>$val)
{
if ($this->attributi_opzioni[$nome]) $attributi_opzione=$this->attributi_opzioni[$nome]->stringa_attributi(array('value'),true,true);
else $attributi_opzione='';
IF (isset($valori[$val]) || !$this->get_attributo('readonly')) $opz.="";
if (isset($valori[$val]) && $this->notnull) $default='';
$maxlen=max($maxlen,strlen($nome));
if (isset($valori[$val])) $valorizzato=true;
}
if ($default && count($this->opzioni)>=1)
{if (strlen($default)==1) $default=str_pad('', $maxlen , $default);
$opz="$opz";
}
}
$opz=$this->send_html("");
if (!$onChange || stripos($onChange,'location.href')!==0 || $this->get_attributo('readonly'))
$out="$jsAjaxLoader$opz$indicatore_attesa".$this->get_html_Accessibilita($onChange);
else {$sost=array('<'=>'<','>'=>'>','"'=>'\\"');
if($this->con_js) $out=''.
$this->get_html_Accessibilita($onChange);
}
$this->attributi=$attributi;
return ($this->con_js?$this->jsAutotab().$js:'').$out;
}
/**
* Passa in minuscolo (ma con la prima lettera di ogni parola maiuscola)
* facendo ovewriting di questo metodo si possono personalizzare le regole di "aggiustamento" delle opzioni
* @param string $cosa
* @param int $lungMax opzionale indica lunghezza massima della stringa (si tronca sulla parola)
*/
function Minuscolo ($cosa,$lungMax='') {
$v=explode(' ',str_replace('_',' ',trim($cosa)));
for ($i=0; $i4 && $x!='') $v[$i]=ucfirst(trim($v[$i]));
if ($x!='') $x.=' ';
$x.=$v[$i];
}
$cosa=trim($x);
if ($lungMax) $cosa=$this->Abbrevia($cosa,$lungMax);
return $cosa;
}
/**
* Abbrevia una stringa
* facendo ovewriting di questo metodo si possono personalizzare le regole di "aggiustamento" delle opzioni
* @param string $cosa
* @param int $lungMax indica lunghezza massima della stringa (si tronca sulla parola)
*/
function Abbrevia ($cosa,$lungMax) {
if (strlen($cosa)>$lungMax){$i=$lungMax-3;
while ($i>0 && !preg_match('# |,|.|-#',$cosa[$i])) {$i--;}
if ($i<=0) $i=$lungMax-3;
$cosa=substr($cosa,0,$i)."...";
}
return $cosa;
}
/**
* Abbrevia tutte le opzioni
* @param int $lungMax opzionale indica lunghezza massima della stringa (si tronca sulla parola)
*/
function set_Abbrevia_Opzioni($lungMax='') {
if (is_array($this->opzioni)) foreach ($this->opzioni as $id=>$val) $new[$this->Abbrevia($id,$lungMax)]=$val;
unset($this->opzioni);
$this->opzioni=$new;
return $this;
}
/**
* Passa in minuscolo tutte le opzioni
* @param int $lungMax opzionale indica lunghezza massima della stringa (si tronca sulla parola)
*/
function set_Miniscolo_Opzioni($lungMax='') {
if (is_array($this->opzioni)) foreach ($this->opzioni as $id=>$val) $new[$this->Minuscolo($id,$lungMax)]=$val;
unset($this->opzioni);
$this->opzioni=$new;
return $this;
}
/** Passa in minuscolo (ma con la prima lettera di ogni parola maiuscola) tutte le opzioni usando il metodo "Minuscolo($cosa)"
*/
function UcWordsOpzioni() {
if (is_array($this->opzioni))
{
foreach ($this->opzioni as $nome=>$val) $v[$this->Minuscolo($nome)]=$val;
$this->opzioni=$v;
}
}
/** se settato aggiunge il reload della pagina sull'evento passato, di default è onChange
* @param parametro|completo|azzera|submit $Tipo Il default è 'parametro'
* @param string $evento Il nome dell'evento su cui attivare il reload
* @param string $fragment eventuale frafment da aggiungere alla url (solo per reload in get)
* Supponiamo che questo selettore si chiami 'Tipo' e la url della pagina sia
* http://www.fdsf.it?abc=32432&Tipo=424&altro=12345
* con l'opzione 'parametro' si ricaricherà http://www.fdsf.it?abc=32432&Tipo=nuovo_valore
* con l'opzione 'completo' si ricaricherà http://www.fdsf.it?abc=32432&Tipo=nuovo_valore&altro=12345
* con l'opzione 'azzera' si ricaricherà http://www.fdsf.it?Tipo=nuovo_valore
* con l'opzione 'submit' effettua l'invio in POST del form così com'è
*
**/
function SetReloadJS($Tipo='parametro',$evento='onchange',$fragment='',$usa_random=true,$sostituisci=false) {
if (!$Tipo) $Tipo='parametro';
$evento=strtolower($evento);
if ($Tipo=='submit') $this->set_js("submit()",$evento,false);
else {$this->set_js("location.href=myLinks_{$this->get_id_istanza()}[this.options[this.selectedIndex].value];",$evento,$sostituisci);
$this->reloaJSGET=array($Tipo,$usa_random,$fragment);
}
return $this;
}
/**
*
* Calcola le url usate nel mySelect::setReloadJS() nelle modalità GET,
* utile per eventuali overriding
*
* @param parametro|completo|azzera|submit $Tipo Il default è 'parametro'
* @param string $nome_campo nome del campo usato come riferimento per la costr. nuova url
* @param boolean $usa_random se true aggiunge tt randomico
* @param string $url eventuale url da usare, se string avuota o omesso si usa $_SERVER['PHP_SELF']
* @param string $query_string eventuale string di parametri se FALSE non si usa omesso o stringa vuota usa $_SERVER["QUERY_STRING"]
* @param string $fragment eventuale fragment
*
* @return string
*/
function build_reload_urls($Tipo,$nome_campo,$usa_random,$url='',$query_string='',$fragment=''){
$nuova=array();
if($query_string==='') $query_string=$_SERVER["QUERY_STRING"];
if($query_string) @parse_str($query_string,$parametri);
if(!$url) $url=$_SERVER['PHP_SELF'];
$parametri=(array) $parametri;
static $build;
if($build[serialize(func_get_args())]) return $build[serialize(func_get_args())];
$secure=new mySecurizer();
if($parametri)
foreach ($parametri as $par=>$val)
{
if ($Tipo=='parametro' && $par==$nome_campo) break;
if ($par!=$nome_campo && (is_array($val) || trim($val)!==''))
$nuova[$par]=(mySecurizer::seemsSecurized($val) &&
($val=$secure->decode($par, $val,false))!==false
?$secure->encode($par, $val):$val);
}
if ($Tipo=='azzera') $nuova=array();
if($usa_random) $nuova['tt']=self::unid();
if($fragment) $fragment="#$fragment";
foreach ($this->get_Opzioni() as $titolo=>$val)
{$nuova[$nome_campo]=$val;
$valori[$val]=$url.'?'.http_build_query($nuova).$fragment;
}
return $build[serialize(func_get_args())]=$valori;
}
/**
* alias di
* @see mySelect::setreloadjs()
**/
function set_reloadjs($Tipo='parametro',$evento='onchange',$fragment='',$usa_random=true,$sostituisci=false){
return $this->SetReloadJS($Tipo,$evento,$fragment,$usa_random,$sostituisci);
}
/**
* Setta le opzioni del selettore
*
* @param ADODBConnection $db è la connessione a DB da utilizzare
* @param string $qry la query da usare per reperire i dati in cui il primo campo è Titolo ed il secondo è il valore del selettore
* @param boolean $registra se true i valori vengono memorizzati in una variabile di sessione e la qry non si riesegue più
*/
function set_OpzioniQRY(&$db,$qry='',$registra=true) {
$this->qry=$qry;
IF ($_SESSION['myFields']['MyOpzioniRegistrate'][md5($this->qry)] && $registra)
{$this->opzioni=$_SESSION['myFields']['MyOpzioniRegistrate'][md5($this->qry)];
$opzioni=$this->opzioni;
}
else { $v=&$db->getarray($qry);
$n=count($v);
for ($i=0;$i<$n;++$i)
if (is_array($v[$i])) $opzioni[array_shift($v[$i])]=array_shift($v[$i]);
}
$this->set_Opzioni($opzioni);
if ($registra) $this->registra_opzioni();
return $this;
}
/**
* Registra le opzioni in sessione
**/
function registra_opzioni() {
$_SESSION['myFields']['MyOpzioniRegistrate'][md5($this->qry)]=$this->opzioni;
}
/**
* Elimina le opzioni dalla sessione
**/
function deregistra_opzioni() {
unset($_SESSION['myFields']['MyOpzioniRegistrate'][md5($this->qry)]);
}
/** Restituisce un messaggio se l'attributo value non soddisfa condizioni di notnull,maxlength,minlength
* @return string
*/
function get_errore_diviso() {
if ($this->notnull && count($this->get_value())==0) return 'non può essere nullo';
if($this->restrizioni_check && $this->get_value())
{
$opz=array_flip($this->get_opzioni());
if(!isset($opz[$this->get_value()])) return 'non è accettabile';
}
return parent::get_errore_diviso();
}
function get_js_chk(){
if($this->get_showonly()===2 || !$this->notnull) return "return null;";
if($this->get_showonly()===0) $js="valore=trim(''+document.getElementById('{$this->get_id()}').options[document.getElementById('{$this->get_id()}').selectedIndex].value);";
else $js="valore=trim(''+document.getElementById('{$this->get_id()}').value);";
$js.="if(strlen(valore)==0) return \"{$this->trasl('non può essere nullo')}\";\n";
return $js;
}
}
/**
* @package myFields
*/
Class MyPulsante extends MyField {
/**#@+ @ignore */
protected $set_lockform_onsend=false;
/**#@-*/
/**
* Costruttore di classe
* @access public
*
* @param string $nome E' il nome del campo
* @param string $valore Valore da assegnare come default
* @param string $classe è la classe css da utilizzare
*/
function MyPulsante ($nome,$valore="",$classe=''){
parent::MyField($nome,$valore);
if ($classe) $this->set_attributo('class',$classe);
$this->set_attributo('type','submit');
$this->set_MyType('MyPulsante');
if ($this->get_value()) $this->set_Tooltip($this->get_value());
}
/**
* Associa al pulsante uno javascript che chiede la conferma della pressione
*
* @param string $domanda Testo della domanda che lo javascript rivolge
*/
function set_Domanda($domanda) {
$this->set_attributo('onclick','if (confirm(\''.addslashes($domanda).'\')) return true; else {if(window.event) window.event.returnValue=false;return false;}');
$this->set_attributo('onkeypress','if (confirm(\''.addslashes($domanda).'\')) return true; else {if(window.event) window.event.returnValue=false;return false;}');
return $this;
}
function set_lockform_onsend(){
$this->set_lockform_onsend=true;
return $this;
}
function get_html() {
if ($this->set_lockform_onsend && !$this->myFields['static']['js_src'][get_class($this)])
{$this->myFields['static']['js_src'][get_class($this)]=$js="";
}
if(!$this->myFields['static']['common']) {$jsCommon=$this->get_js_common();$this->myFields['static']['common']=true;}
return (!$this->con_js?'':$jsCommon).$this->send_html(parent::get_html()).($this->con_js && $this->set_lockform_onsend?"$js":'');
}
function get_xml_value(){
return '';
}
}
/**
* @package myFields
*/
Class MyBottone extends MyPulsante {
/**
* Costruttore di classe
* @access public
*
* @param string $nome E' il nome del campo
* @param string $valore Valore da assegnare come default
* @param string $classe è la classe css da utilizzare
*/
function MyBottone ($nome,$valore="",$classe=''){
parent::MyPulsante($nome,$valore,$classe);
$this->set_attributo('type','button');
$this->set_MyType('MyBottone');
}
}
/**
* @package myFields
*/
Class MyImage extends MyPulsante {
/**
* Costruttore di classe
* @access public
*
* @param string $nome E' il nome del campo
* @param string $src E' il percorso dell'immagine da usare
* @param string $tooltip E' l'eventuale tooltip
*/
function MyImage ($nome,$src,$tooltip=""){
parent::MyField($nome);
$this->set_attributo('type','image');
$this->set_attributo('src',$src);
if ($tooltip) $this->set_Tooltip($tooltip);
$this->set_style('border','0em');
$this->set_MyType('MyImage');
}
/** Setta la larghezza e l'altezza in % o pt
* @param integer $width
* @param integer $height
*/
function set_size($width,$height) {
$this->set_attributo('width',$width);
$this->set_attributo('height',$height);
return $this;
}
/** Setta il Tooltip del campo
* @param string $testo è il testo
*/
function set_Tooltip ($testo) {
$this->set_attributo("alt",$testo);
return $this;
}
/** @ignore*/
function stringa_attributi ($v=array()) {
$nogood=array('border','height','width');
foreach ($nogood as $nome) if (($attributo=$this->get_attributo($nome))!==null) $this->set_style($nome,$attributo);
$stringa=parent::stringa_attributi(array_merge($nogood,$v),true,true);
// if ($style) $stringa.=" style='$style' ";
return $stringa;
}
}
/**
* @package myFields
*/
Class MyLink extends myTag {
/**#@+ @ignore */
protected $html;
/**#@-*/
/**
* Costruttore di classe
* @access public
*
* @param string $link E' l'url da usare se è un link
* @param string $tooltip E' l'eventuale tooltip
* @param string $html E' l'html a cui applicare il link
* @param _blank|_parent|_self $target Opzionale
* @param string
* @param string $classe E' l'eventuale classe css da utilizzare per il link
*/
function MyLink ($link,$tooltip="",$html='',$target='',$classe=''){
$this->set_attributo('href',$link);
if ($classe) $this->set_attributo('class',$classe);
if ($tooltip) $this->set_attributo('title',htmlentities(html_entity_decode($tooltip)));
if ($target) $this->set_attributo('target',$target);
if ($html) $this->html=$html;
$this->set_MyType('MyLink');
}
/** Restituisce il nome del tipo del campo
*
* @return string
*/
function get_MyType() {
return $this->MyType;
}
/**
* setta l'html a cui applicare il link.
*
* @param string $html
*/
function set_html($html) {
$this->html=$html;
return $this;
}
/** Restituisce l'url
*
* @return string
*/
function get_Url() {
return $this->get_attributo('href');
}
/** @ignore*/
function set_MyType($nome) {
$this->MyType=$nome;
return $this;
}
/*** Restituisce il campo in html pronto per la visualizzazione
*
* @param string $html è l'html a cui applicare il link se omesso si usa quello memorizzato nel costruttore
* @return string
*/
function get_html($html='') {
if (!$html) $html=$this->html;
$html="stringa_attributi().">$html";
return (!$this->con_js?$html:$this->jsAutotab().$this->send_html($html));
}
/** @ignore*/
function stringa_attributi ($v=array()) {
return parent::stringa_attributi($v,true,true);
}
}
/**
* @package myFields
*/
Class MyIcon extends MyImage {
/**#@+ @ignore */
protected $Link;
/**#@-*/
/**
* Costruttore di classe
*
* @access public
* @param string $src E' il percorso dell'immagine da usare
* @param string $tooltip E' l'eventuale tooltip
*/
function MyIcon ($src,$tooltip=""){
if ($tooltip) $this->set_attributo('alt',$tooltip);
$this->set_attributo('src',$src);
$this->set_style('border','0em');
$this->set_MyType('MyIcon');
}
/*** setta un link per l'icona
*
* @param MyLink $Link E' il link da applicare all'icona
*/
function set_link($Link) {
$this->Link=$Link->clonami();
return $this;
}
/*** restituisce il link applicato all'icona
*
* @return MyLink
*/
function get_link() {
return $this->Link;
}
function get_Html () {
if ($get_html=$this->Metodo_ridefinito['get_Html']['metodo']) return $this->$get_html($this->Metodo_ridefinito['get_Html']['parametri']);
$stringa=$this->stringa_attributi();
if ($this->Link)
{$Alt=$this->get_attributo('alt');
$this->set_attributo('alt',$this->Link->get_attributo('title'));
$x=$this->Link->get_html("");
$this->set_attributo('alt',$Alt);
}
else $x="";
return $this->jsAutotab().$this->send_html($x);
}
}
/**
* @package myFields
*/
Class MyUploadText extends MyField {
/**#@+ @ignore */
protected $file,$ext_ammesse, $descrizione, $extra,$show_info=array(true,true,true),$ext;
/**#@-*/
/**
* @property array $file attributo in sola lettura con le info sul file corrente o appena uploadato ( dopo check_errore())
*/
/**
* Costruttore di classe
*
* @access public
* @param string $nome E' il nome del campo
* @param string $nomeFile E' il nome del file attualmente in uso COMPLETO DI PERCORSO ASSOLUTO
* @param string $classe è la classe css da utilizzare
*/
function MyUploadText ($nome='',$valore="",$classe=''){
parent::MyField($nome,$valore);
if (!isset($this->myFields['FILES']) && $_FILES) $this->myFields['FILES']=$_FILES;
if ($classe) $this->set_attributo('class',$classe);
$this->set_attributo('type','file');
$this->set_MyType('MyUploadText');
$this->set_max(min(self::ricalcolasize(ini_get('upload_max_filesize'),false),
self::ricalcolasize(ini_get('post_max_size'),false)));
}
/**
* Imposta l'estensione di default per il file
* @param string $ext
*/
function set_ext($ext){
$this->ext=$ext;
return $this;
}
/** Non attiva in questa classe
*/
function set_readonly($stato=true){
$this->show_info[1]=!$stato;
return $this;
}
/** Setta la caratteristica di disabled
*/
function set_disabled(){
$this->set_attributo("",'disabled');
return $this;
}
/** Setta la dimensione max file Uploadato
* @param integer $max è la dimensione in byte
*/
function set_max($maxlength) {
$this->maxlength=$this->ricalcolasize($maxlength,false);
return $this;
}
/** Restituisce la dimensione max file Uploadato
* @return integer
*/
function get_max() {
return $this->maxlength;
}
/** Setta la dimensione min file Uploadato
* @param integer $min è la dimensione in byte
*/
function set_min($min) {
$this->minlength=$min;
return $this;
}
/**
* @ignore
*/
function __get($attributo){
return $x=$this->file;
}
/** Restituisce la dimensione max file Uploadato
* @return integer
*/
function get_min() {
return $this->minlength;
}
/** Restituisce un messaggio se l'attributo value non soddisfa condizioni di notnull,maxlength,minlength
* @return string
*/
function get_errore_diviso() {
if($_POST[$this->get_name().'_remove_'])
{
$this->set_value($x='');
if($this->notnull) return ' non può essere nullo';
return;
}
if ($this->myFields['FILES'][$this->get_name().'_file']['name'])
$this->file=$this->myFields['FILES'][$this->get_name().'_file'];
if (!$this->file && $this->get_value()) return;
if ($this->file['error']>=1 &&
$this->file['error']<=2) return array(' non può essere più grande di %1%Bytes',$this->ricalcolasize($this->maxlength));
elseif ($this->file['error']>2) return ' non inviato correttamente';
elseif (!$this->file['size']) {
if ($this->notnull) return ' deve essere allegato';
}
else{
$v=explode('.',$this->file['name']);
$ext=strtolower($v[count($v)-1]);
if ($this->ext_ammesse && !isset($this->ext_ammesse[$ext])) return array(' non è accettabile, estensioni ammesse: %1%',implode(',',array_flip($this->ext_ammesse)));
if ($this->maxlength && $this->get_size()>$this->maxlength) return array(' non può essere più grande di %1%Bytes',$this->ricalcolasize($this->maxlength));
if ($this->minlength && $this->get_size()<$this->minlength) return array(' non può essere più piccolo di %1%Bytes',$this->ricalcolasize($this->minlength));
$this->set_ext($ext);
$this->set_value($v=file_get_contents($this->myFields['FILES'][$this->get_name().'_file']['tmp_name']));
}
}
function set_value(&$valore) {
//if($_POST[$this->get_name().'_remove_']){$this->attributi['value']=''; return $this;}
$this->attributi['value']=$valore;
if(strlen($valore) >0 && $valore=base64_decode($valore,true)) $this->attributi['value']=$valore;
return $this;
}
/**
* Restituisce informazioni di sitema sul file appena uploadato,
* funziona solo se il file è stato correttamente appena uploadato e se prima è stato fatto myforms::check_errore() o myUpload::errore()
* @return myArrayObject @see myArrayObject
*/
function get_info_uploaded(){
return new myArrayObject($this->file);
}
/** setta le estensioni ammesse
* @param array $estensioni E' un array con l'elenco delle estensioni ammesse (senza punto davanti)
*/
function set_ext_ammesse($estensioni) {
$this->ext_ammesse=array_flip(explode(',',strtolower(implode(',',$estensioni))));
return $this;
}
/** Restituisce le estensioni ammesse
* @return array
*/
function get_ext_ammesse() {
return array_flip($this->ext_ammesse);
}
/** Restituisce la dimensione del file Uploadato
* @return integer
*/
function get_size() {
return $this->file['size'];
}
/** setta un titolo d far comparire sul link al file
* @param string $testo
*/
function set_Descrizione($testo) {
$this->descrizione=$testo;
return $this;
}
function set_show_info($anteprima=true,$max=true){
$this->show_info=func_get_args();
return $this;
}
/** Imposta dell'HTML da visualizzare dopo l'icona del file
* @param string $html
*/
function set_extra_html($html){
$this->extra=$html;
return $this;
}
static function ricalcolasize($a,$consuffisso=true) {
$unim = array("","K","M","G","T","P");
if ($consuffisso) {
$c = 0;
while ($a>=1024) {
$c++;
$a = $a/1024;
}
return number_format($a,(strpos($c,".")===false ? 0 : 1),".",",")." ".$unim[$c];
}
else {
unset($unim[0]);
$a=strtoupper($a);
$unim=array_flip($unim);
$p=1024;
foreach ($unim as $suff=>&$peso)
{$peso="*$p";
$p=$p*1024;
}
$a=strtr($a,$unim);
eval("\$out=$a;");
return $out;
}
}
/** Restituisce il campo in html pronto per la visualizzazione
* @return string
*/
function get_Html () {
if ($get_html=$this->Metodo_ridefinito['get_Html']['metodo']) return $this->$get_html($this->Metodo_ridefinito['get_Html']['parametri']);
$v=&$this->attributi['value'];
if ($v) { $s=new mySessions('myFieldsUploaded');
$icona=$this->ext;
$id=MyUUID::v4();
$upl=array('desc'=>trim($this->descrizione),
'content'=>&$v,
'ext'=>trim($this->ext));
$s->set('file_'.$this->get_id(),$upl);
$s->set('id',array($id,$this->get_id()));
if (!$this->descrizione) $this->descrizione="Download";
$this->descrizione.=' '.strlen($v)." Bytes";
$root= dirname(__FILE__).'/MyUploadIcones/';
if (!is_file("$root$icona.gif")) $icona='folder';
$root= "/".$this->get_MyFormsPath()."MyUploadIcones/$icona.gif";
if ($this->show_info[0]) $icona="get_MyFormsPath()}util/uploaded.php?id=$id\" title=\"".htmlentities($this->descrizione)."\">{$this->trasl("File attuale")}:descrizione)."\" style='border:0' /> ";
else $icona='';
if ($this->extra || $icona) $icona.="$this->extra ";
}
if($this->get_notnull()==false) {
$c=new MyCheck($this->get_name().'_remove ',1);
if(!$v) $c->set_checked();
$c->set_js($jsNofile="if(document.getElementById('{$this->get_id()}').disabled=document.getElementById('{$c->get_id()}').checked) {document.getElementById('upl_div_{$this->get_id()}').style.display='none'} else {document.getElementById('upl_div_{$this->get_id()}').style.display='block'}",'onclick');
$nofile="$c";
}
return $this->jsAutotab().$this->send_html("$nofile
")."";
}
/** @ignore*/
function _get_html_show($pars){
$v=&$this->attributi['value'];
if ($v) { $s=new mySessions('myFieldsUploaded');
$icona=$this->ext;
$id=MyUUID::v4();
$upl=array('desc'=>trim($this->descrizione),
'content'=>&$v,
'ext'=>trim($this->ext));
$s->set('file_'.$this->get_id(),$upl);
$s->set('id',array($id,$this->get_id()));
if (!$this->descrizione) $this->descrizione="Download";
$this->descrizione.=' '.strlen($v)." Bytes";
$root= dirname(__FILE__).'/MyUploadIcones/';
if (!is_file("$root$icona.gif")) $icona='folder';
$root= "/".$this->get_MyFormsPath()."MyUploadIcones/$icona.gif";
if ($this->show_info[0]) $icona="get_MyFormsPath()}util/uploaded.php?id=$id\" title=\"".htmlentities($this->descrizione)."\">{$this->trasl("File attuale")}:descrizione)."\" style='border:0' /> ";
else $icona='';
if ($this->extra || $icona) $icona.="$this->extra ";
}
return $this->jsAutotab()."$icona
get_max()}\" />
get_name()}\" value=\"".base64_encode($v)."\" />
get_name()}_file\" ".$this->stringa_attributi(array('value','name'),1)." />".($this->show_info[1]?"(max ".self::ricalcolasize($this->get_max())."Bytes)":'')."
";
}
/** @ignore */
protected function _get_html_hidden($pars){
return;
}
}
/**
* @package myFields
*/
Class MyUpload extends MyUploadText {
/**#@+ @ignore */
protected $path,$file,$ext_ammesse,$nomeAttuale, $descrizione, $originale, $extra,$show_info=array(true,true,true);
/**#@-*/
/**
* @property array $file attributo in sola lettura con le info sul file corrente o appena uploadato ( dopo check_errore())
*/
/**
* Costruttore di classe
*
* @access public
* @param string $nome E' il nome del campo
* @param string $nomeFile E' il nome del file attualmente in uso COMPLETO DI PERCORSO ASSOLUTO
* @param string $classe è la classe css da utilizzare
*/
function MyUpload ($nome='',$nomeFile="",$classe=''){
parent::MyField($nome);
if (!isset($this->myFields['FILES']) && $_FILES) $this->myFields['FILES']=$_FILES;
if ($classe) $this->set_attributo('class',$classe);
$this->set_attributo('type','file');
$this->set_MyType('MyUpload');
$this->path=$this->get_PathSito();
$this->set_value($nomeFile);
$this->set_max(min(self::ricalcolasize(ini_get('upload_max_filesize'),false),
self::ricalcolasize(ini_get('post_max_size'),false)));
}
/**
* Azzera le informazioni sul file corrente
*/
function reset_originale(){
$this->originale='';
}
/**
* @ignore
*/
function set_nome_attuale($nome) {
$this->nomeAttuale=$nome;
return $this;
}
/** Restituisce l'estensione del file Uploadato
* @return string
*/
function get_ext() {
$v=explode('.',$this->get_value());
return strtolower($v[count($v)-1]);
}
/**
* @param string $nomeFile E' il nome del file attualmente in uso con percorso relativo a dir di lavoro (vedi set_dir) se non trova il file fallisce
* @param boolean $forzaValore Se true forza il valore inserito MA NON FA ALCUNA VERIFICA CHE SIA VERITIERO
*/
function set_value($nomeFile='',$forzaValore=false) {
if (!$nomeFile) return;
if (is_file($this->path.$nomeFile))
{
$this->file['size']=@filesize($this->path.$nomeFile);
$this->nomeAttuale=$nomeFile;
//$this->myFields['FILES'][$this->get_name()]['name']=$nomeFile;
return parent::set_value($nomeFile);
}
if ($forzaValore) {
$this->file['size']=@filesize($nomeFile);
$this->nomeAttuale=$nomeFile;
return parent::set_value($nomeFile);
}
}
/** Restituisce un messaggio se l'attributo value non soddisfa condizioni di notnull,maxlength,minlength
* @return string
*/
function get_errore_diviso() {
// print_r($this->myFields['FILES']);exit;
if ($this->myFields['FILES'][$this->get_name()]['name'])
{$this->file=$this->myFields['FILES'][$this->get_name()];
parent::set_value($this->myFields['FILES'][$this->get_name()]['name']);
}
if ($this->notnull && !$this->file['size']) return ' deve essere allegato';
elseif ($this->file['size'])
{ if ($this->file['error']) return ' non inviato correttamente';
if ($this->ext_ammesse && !isset($this->ext_ammesse[$this->get_ext()])) return array(' non è accettabile, estensioni ammesse: %1%',implode(',',array_flip($this->ext_ammesse)));
if ($this->maxlength && $this->get_size()>$this->maxlength) return array(' non può essere più grande di %1%Bytes',$this->ricalcolasize($this->maxlength));
if ($this->minlength && $this->get_size()<$this->minlength) return array(' non può essere più piccolo di %1%Bytes',$this->ricalcolasize($this->minlength));
}
}
/** setta un titolo d far comparire sul link al file, se omesso si usa il nome del file
* @param string $testo
*/
function set_Descrizione($testo) {
$this->descrizione=$testo;
return $this;
}
function set_show_info($anteprima=true,$max=true){
$this->show_info=func_get_args();
return $this;
}
/**Elimina il file corrente
*/
function Elimina () {
$oldabs=realpath( $this->path."/".$this->nomeAttuale);
if (!is_file($oldabs)) $oldabs=realpath($this->nomeAttuale);
@unlink($oldabs);
if (is_file($oldabs)) return "Errore nell'eliminazione del file";
parent::set_value($x='');
$this->file=null;
}
/**Salva il file su file system USARE SOLO DOPO CHECK_ERRORE
* @param string $nome è il nome con cui completo di un percorso ASSOLUTO
* @param boolean $ForzaDir Forza la creazione delle directory che formano il percorso inserito in $nome
* @return string se tutto OK niente altrimenti un messaggio d'errore
*/
function Salva ($nome,$ForzaDir=true,$ForzaPath=false,$Path='') {
if(!$Path) $docroot= $this->path;
else $docroot=$Path;
$nome=str_replace('\\','/',$nome);
if ($nome{0}=='/') $newabs=$docroot.$nome;
else $newabs=$docroot.dirname($_SERVER['PHP_SELF']).'/'.$nome;
if (strpos($newabs,'//')===0) $newabs='/'.str_replace('//','/',$newabs);
else $newabs=str_replace('//','/',$newabs);
$oldabs=realpath($docroot.$this->nomeAttuale);
// $newabs=str_replace(array('\\','//'),array('/','/'),$newabs);
// $newabs=str_replace(array('//','//'),array('/','/'),$newabs);
if ($ForzaPath) $newabs=$nome;
if ($ForzaDir) {
$percorsi=explode('/',$newabs);
unset($percorsi[count($percorsi)-1]);
foreach ($percorsi as $dir) @mkdir($d.="$dir/", 0777);
}
// echo "{$this->file['tmp_name']},$newabs";
if ($this->file['tmp_name'] && (!@copy($this->file['tmp_name'],$newabs) || !@is_file($newabs))) return $this->trasl("Impossibile salvare il file %1% in %2%",array('%1%'=>$this->file['tmp_name'],'%2%'=>$newabs)) ;
$this->set_value($nome,$ForzaDir,$ForzaPath);
}
/**Salva il file su file system conservando etensione del file uploadato USARE SOLO DOPO CHECK_ERRORE
* @param string $nome è il nome con cui completo di un percorso ASSOLUTO senza estensione
* @param boolean $ForzaDir Forza la creazione delle directory che formano il percorso inserito in $nome
* @return string se tutto OK niente altrimenti un messaggio d'errore
*/
function Salva_con_ext ($nome,$ForzaDir=true,$ForzaPath=false,$Path='') {
if ($this->get_ext()) return $this->Salva($nome.".".$this->get_ext(),$ForzaDir,$ForzaPath,$Path);
}
function set_path($path){
$this->path=$path;
return $this;
}
function ricalcola_percorso($percorso) {
return $percorso;
}
/** Restituisce il campo in html pronto per la visualizzazione
* @return string
*/
function get_Html () {
if ($get_html=$this->Metodo_ridefinito['get_Html']['metodo']) return $this->$get_html($this->Metodo_ridefinito['get_Html']['parametri']);
if (is_file($percorso=$this->nomeAttuale) ||
is_file($percorso=$this->path.$this->nomeAttuale)
)
{
if (!$this->descrizione) $this->descrizione=basename($this->nomeAttuale)."\n".filesize($percorso)." Bytes";
$v=explode('.',$this->nomeAttuale);
$icona=strtolower($v[count($v)-1]);
$root= dirname(__FILE__).'/MyUploadIcones/';
if (!is_file("$root$icona.gif")) $icona='folder';
$root= "/".$this->get_MyFormsPath()."MyUploadIcones/$icona.gif";
if ($this->show_info[0]) $icona="ricalcola_percorso($this->nomeAttuale))."\" target='_blank' title=\"".htmlentities($this->descrizione)."\">{$this->trasl("File attuale")}:descrizione)."\" style='border:0' /> ";
else $icona='';
if ($this->extra || $icona) $icona.="$this->extra ";
}
return $this->jsAutotab()."$icona
get_max()}\" />".
$this->send_html("stringa_attributi(array('value'),1)." />").($this->show_info[1]?"(max ".self::ricalcolasize($this->get_max())."Bytes)":'')."";
}
/** @ignore*/
function _get_html_show($pars){
if (is_file($this->get_PathSito().'/'.$this->nomeAttuale))
{
if (!$this->descrizione) $this->descrizione="$this->nomeAttuale\n".filesize($this->get_PathSito().'/'.$this->nomeAttuale)." Bytes";
$v=explode('.',$this->nomeAttuale);
$icona=strtolower($v[count($v)-1]);
$root= $this->get_PathSito().$this->get_MyFormsPath().'MyUploadIcones/';
if (!is_file("$root$icona.gif")) $icona='folder';
$root= "/".$this->get_MyFormsPath()."MyUploadIcones/$icona.gif";
return $icona="nomeAttuale)."\" target='_blank' title=\"".htmlentities($this->descrizione)."\">{$this->trasl("File attuale")}:descrizione)."\" style='border:0em' /> ";
}
}
/** @ignore */
protected function _get_html_hidden($pars){
return;
}
}
/**
* @package myFields
*/
class MyEditor extends MyText {
/**#@+ @ignore */
protected $tinymcepar=array(),$EstendoMyText=true, $width,$height,$css,$stili,$ajaxFileManager,$toolbar,
$vietati=',link,submit,button,input,textarea,select,object,param,body,script,applet,frame,iframe,html,head,title,meta,form,!doctype,!--,link,var', //DEVE INIZIARE CON VIRGOLA
$disabilitati,$modalita,$cleanup=array('cleanup'=>'true','cleanup_on_startup'=>'false','verify_html'=>'true');
/**#@-*/
/**
* Costruttore di classe
* E' prevista una toolbar con questi elementi:
*
* bold, italic,underline,strikethrough,justifyleft,justifycenter,justifyright,justifyfull,
* bullist,numlist,outdent,indent,cut,copy,paste,undo,redo,link,unlink,image,
* cleanup,hr,removeformat,sub,sup,forecolor,backcolor,charmap,visualaid,pastetext,
* pasteword,search,replace,anchor,insertdate,inserttime,forecolor,fontselect,fontsizeselect,fullscreen,print,tablecontrols
*
*
* @access public
* @param string $nome E' il nome del campo
* @param string $valore Valore da assegnare come default
*/
function MyEditor ($nome,$valore='') {
parent::MyField($nome,$valore);
$this->set_MyType('MyEditor');
$this->set_attributo('id',$this->get_attributo('id').'_editor');
$this->toolbar[0]="bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,styleselect,formatselect,fontselect,fontsizeselect";
$this->toolbar[1]="selectall,cut,copy,pastetext,pasteword,paste,separator,search,replace,separator,bullist,numlist,separator,outdent,indent,separator,undo,redo,separator,link,unlink,anchor,image,cleanup,separator,forecolor,separator,fullscreen"; //code;
$this->toolbar[2]="tablecontrols,hr,removeformat,visualaid,separator,sub,sup,separator,charmap,separator,insertdate,inserttime";
$this->disabilitati=array();
$this->modalita='advanced';
}
/**
* @ignore
*/
protected function clean_accessibilita($valore){
$valore=preg_replace('@(<.+ style[\s]*=[\s]*".*)font-size[\s]*:[\s]*[0-9]+[\s]*(pt|px)(.*\">)@sUi','\1\3',$valore);
$valore=preg_replace('@(<.+ style[\s]*=[\s]*".*font.*:[\s]*)([0-9]+[\s]*(pt|px))(.*\">)@sUi','\1\4',$valore);
$valore=preg_replace('@(<.+ style[\s]*=[\s]*".*)background.*:[ ^;^"]+(.*\">)@sUi','\1\4',$valore);
$valore=preg_replace('@(<.+ )style[\s]*=[\s]*\"[ ;]*\"(>)@sU','\1\2',$valore);
return $valore;
}
/** Setta la larghezza e l'altezza in % o pt
* @param string $width
* @param string $height
*/
function set_size($width,$height) {
$this->width=$width;
$this->height=$height;
return $this;
}
/**
* setta le eventuali toolbar max su 3 righe
* riceve un array di elementi
*
* Es. per avere una toolbar di 2 righe
*
* $toolbar[0]="bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,styleselect,formatselect,fontselect,fontsizeselect";
* $toolbar[1]="selectall,cut,copy,pastetext,pasteword,separator,search,replace,myiespell,separator,bullist,numlist,separator,outdent,indent,separator,undo,redo,separator,link,unlink,anchor,image,cleanup,separator,insertdate,inserttime,separator,forecolor,separator,fullscreen"; //code;
*
* $oggetto=new myEditor('campo');
* $oggetto->set_toolbar($toolbar);
*
*
* @param array $toolbar
*/
function set_toolbar($toolbar) {
$this->toolbar=$toolbar;
$this->toolbar[]='';$this->toolbar[]='';$this->toolbar[]='';
return $this;
}
/** Rende invisibile un elemento della toolbar
* @param string $nomeElemento es 'paste'
*/
function unset_toolbar_element($nomeElemento) {
$this->disabilitati[]=$nomeElemento;
}
/** Setta il percorso della cartella Immagini
* @param string $percorso E' il percorso assoluto seguito da / es: /utenti/img/
*/
function set_cartella_img($percorso) {
$this->ajaxFileManager=new myAjaxFileManagerPlugin($percorso);
return $this;
}
/**
* Deve essere usato dopo @myEditor::set_cartella_img() e imposta parametri specifici del file manager @see http://www.phpletter.com/
* @param array $pars array associativo con i valori delle costanti di configurazione NON PEECEDURE DAL PREFISSO "CONFIG_"
*/
function set_filemanager_pars(array $pars) {
if($this->ajaxFileManager)
foreach ($pars as $k=>$v)
$this->ajaxFileManager->$k=$v;
return $this;
}
/**
* Imposta parametri specifici del file manager @see http://www.tinymce.com/wiki.php/Configuration
* @param array $pars array associativo con i valori selle costanti di configurazione NON PEECEDURE DAL PREFISSO "CONFIG_"
*/
function set_tinymce_pars($pars) {
$this->tinymcepar=$pars;
return $this;
}
/** Restituisce il nome del tipo del campo
*
* @return string
*/
function get_MyType() {return $this->MyType; }
/** @ignore*/
function set_MyType($nome) {$this->MyType=$nome; return $this;}
/** Non attiva in questa classe */
function set_readonly(){return $this;}
/** Non attiva in questa classe */
function set_autotab () {return $this;}
/** Non attiva in questa classe */
function set_disabled(){return $this;}
/** Setta gli stili CSS consentiti
* @param string $fileCSS E' il percorso assoluto al file css le classi ammesse
* @param array $stili E' un array con l'elenco delle classi ammesse
*/
function set_stili($fileCSS,$stili) {
$this->css=$fileCSS;
if (is_array($stili)) $this->stili=$stili;
return $this;
}
/** Setta la modalità della toolbar
* @param myadvanced|advanced|simple $modalita
*/
function set_modalita($quale='advanced') {
if (preg_match('/advanced|simple/',$quale)) $this->modalita=strtolower($quale);
return $this;
}
/**
* Setta i tag non ammessi e/o eventuali loro parametri
*
* @param string $stringa
*
* es. 'iframe,table[bgcolor|background]' esclude il tag iframe ed i parametri bgcolor e background del tag table
* In ogni caso vengono eliminati 'submit,button,input,textarea,select,object,param,body,script,applet,frame,iframe,html,head
*/
function set_TagVietati($stringa){ $this->vietati.=','.$stringa; return $this;}
//L'eliminazione dei tag avviene tramite js
function striptags($testo){
$txtArea=new MyTextArea('');
return $txtArea->striptags($testo,$this->vietati);
}
/**
* @deprecated
*/
function set_puliziahtml($Abilitata,$AncheInCaricamento=true) {
if ($Abilitata) {$this->cleanup=array('verify_html'=>'true','cleanup'=>'true');
$AncheInCaricamento=false;
}
else $this->cleanup=array('verify_html'=>'false','cleanup'=>'false');
$this->cleanup['cleanup_on_startup']=($AncheInCaricamento?'true':'false');
return $this;
// $this->cleanup['add_form_submit_trigger']=($SuInvio?'true':'false');
}
function js() {
$v=$this->disabilitati;
if ($this->modalita=='simple') $v=array_merge($v,array('bullist','numlist'));
elseif ($this->modalita=='advanced')
foreach ($this->toolbar as $i=>$scelta)
{$v=array_merge($v,explode(',',$scelta));
$i++;
$toolbars.=" theme_advanced_buttons$i : \"$scelta\",\n";
}
$v=array_flip($v);
if (!isset($v['tablecontrols'])) $this->vietati=',table,thead,td,tfoot,th,tr'.$this->vietati;
if (!isset($v['numlist'])) $this->vietati=',ol,li'.$this->vietati;
if (!isset($v['bullist'])) $this->vietati=',ul,li'.$this->vietati;
if (!isset($v['link'])) $this->vietati=',a'.$this->vietati;
if (!isset($v['formatselect'])) $this->vietati=',h1,h2,h3,h4,h5,h6'.$this->vietati;
if (!isset($v['fontselect'])) $this->vietati=',font[face]'.$this->vietati;
if (!isset($v['fontsizeselect'])) $this->vietati=',font[size]'.$this->vietati;
if ($this->ajaxFileManager)
{ /*
$imgScript=' dir_image: "'.$this->imgDir.'",
root_image: "'.str_replace('//','/',$this->imgDir).'",
external_image_list_url : "/'.$this->get_MyFormsPath().'js/tiny_mce/plugins/myadvimage/listaImg.php?dir='.$this->imgDir.'&realdir='.$this->imgRealDir.'&tt='.self::unid().'",';
*/
$ajaxFileMan='function ajaxfilemanager_'.$this->get_id().'(field_name, url, type, win) {
var ajaxfilemanagerurl = "'.$this->ajaxFileManager->get_url().'";
var view = "detail";
switch (type) {
case "image":
view = "thumbnail";
break;
case "media":
break;
case "flash":
break;
case "file":
break;
default:
return false;
}
tinyMCE.activeEditor.windowManager.open
(
{
url: "'.$this->ajaxFileManager->get_url().'&view=" + view,
width: 782,
height: 440,
inline : "yes",
close_previous : "yes"
},
{
window : win,
input : field_name
}
);
}';
}
else {$this->disabilitati[]='image';
$this->vietati=',img'.$this->vietati;
}
if ($this->width) $dimensioni='width : "'.$this->width.'",';
if ($this->height) $dimensioni.='height : "'.$this->height.'",';
if ($this->css) $stili='content_css : "'.$this->css.'",';
if ($this->stili) {$styles=array();
foreach ($this->stili as $s) $styles[]="$s=$s";
$stili.='theme_advanced_styles : "'.implode(';',$styles).'", // Theme specific setting CSS classes';
}
$standard='
docs_language : "it",
language: "it",
debug : false,
mode : "exact",
elements : "'.$this->get_attributo('id').'",
event_elements : "",
myformpath: "'.$this->get_MyFormsPath().'",
accessibility_warnings : true,
object_resizing : false,
auto_resize : false,
gecko_spellcheck : true,
add_unload_trigger : false,
// fix_table_elements : '.$this->cleanup['verify_html'].',
fix_list_elements : true,
font_size_style_values : "0.5em, 0.7em, 1em, 1.2em, 1.6em, 2em, 2.6em",
fix_content_duplication : false,
trim_span_elements : false,
theme_advanced_resizing : true,
element_format : "xhtml",
inline_styles : true,
table_inline_editing : false,
keep_styles : false,
verify_html: true,
force_hex_style_colors : true,
plugin_insertdate_dateFormat : "%d/%m/%Y",
plugin_insertdate_timeFormat : "%H:%M",
convert_fonts_to_spans : true,
convert_newlines_to_brs : false,
paste_auto_cleanup_on_paste : true,
paste_convert_headers_to_strong : true,
paste_strip_class_attributes: "mso",
//paste_strip_class_attributes : "all",
paste_retain_style_properties: "font-size,color",
paste_remove_styles_if_webkit: true,
force_p_newlines : true,
force_br_newlines : false,
forced_root_block : "div",
relative_urls : false,
doctype : String.fromCharCode(60)+\'!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"\'+String.fromCharCode(62),
';
if ($this->modalita=='simple')
$defaults='
var mce_defaults={
invalid_elements : "submit,button,input,textarea,select,object,param,body,script,applet,frame,iframe,table,tr,td,th,thead,tfoot,a'.$this->vietati.'",
'."$standard\n$imgScript\n$dimensioni\n".'
theme : "simple"
}';
else $defaults='
var mce_defaults={
theme : "myadvanced",
plugins : "table,advhr,myadvimage,myadvlink,mytable,paste,insertdatetime,searchreplace,print,directionality,fullscreen",
theme_advanced_disable : "'.implode(',',$this->disabilitati).'",
theme_advanced_blockformats : "p,h1,h2,h3,h4,h5,h6",
'.$toolbars.'
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
force_hex_style_colors : true,
invalid_elements : "body,script,applet,frame,iframe,table[bgcolor|background],tr[bgcolor|background],td[bgcolor|background],th[bgcolor|background]'.$this->vietati.'",
theme_advanced_statusbar_location : "bottom",
// extended_valid_elements : "hr[class|width|size|noshade],span[class|align|style]",
'."$standard\n$stili\n$imgScript\n$dimensioni\n".'
file_browser_callback : "ajaxfilemanager_'.$this->get_id().'",
theme_advanced_resize_horizontal : false,
theme_advanced_resizing : false
}';
foreach ($this->tinymcepar as $k=>$v) $defaults.="\n;mce_defaults[\"{$k}\"]=".myJQuery::quote($v).";";
return $defaults.';'.$ajaxFileMan;
}
/** Restituisce il campo in html pronto per la visualizzazione
* @return string
*/
function get_Html () {
if ($get_html=$this->Metodo_ridefinito['get_Html']['metodo']) return $this->$get_html($this->Metodo_ridefinito['get_Html']['parametri']);
if ($this->width) $dimensioni=" width:".$this->width."px;";
if ($this->height) $dimensioni.=" height:".$this->height."px;";
$this->unset_attributo('size');
if (!$this->myFields['static']['js_src'][get_class($this)]) {
$js='';
// $js='
// ';
$js.='';
$this->myFields['static']['js_src'][get_class($this)]=1;
}
return $this->jsAutotab().$js.'
';
}
}
/**
* @package myFields
* @deprecated
*/
/**
* @package myFields
*/
class MyPopUp extends MyHidden {
/**#@+ @ignore */
protected $valori, $extraJSpopup;
/**#@-*/
/**
* Costruttore di classe
* Questo oggetto permette di creare dei campi nascosti "ma visibili"
* Si può usare in alternativa ad un MySelect quando le opzioni sono veramente tante
* e si deve associare una Descrizione ad un codice
* Compare un myLink cliccando il quale si apre una popup in essa si sceglie il
* valore e automaticamente si chiude settando sia il codice che la descrizione
* nella finestra chiamante
*
* Supponiamo di voler inserire un campo in cui compaiano un cognome ed un nome
* ma che internamente associ una matricola.
*
* Nello script occorrerà scrivere
*
* $valore_default=array('12345'=>'Gianluca Gimigliano'); //setto un valore di default
* $oggetto= new MyPopUp("matricola",$valore_default); //istanzio campo con impostanto come default i miei dati
* $linkpopup=new MyLink('/cercapersone.php','Click qui per cercare persona'); //creo il link da usare per aprire la popup
* $oggetto->set_popup($linkpopup); //aggancio il link da usare all'oggetto
* echo $oggetto->get_html();
*
*
*
* Nello script chiamato (nell'esempio è cercapersone.php) gerrà passato in GET un parametro chiamato
* id_MyPopUp. Supponendo che il risultato della ricerca nella popup porti un elenco di nomi,
* questi dovranno essere della forma
*
* echo "
Matricola: 13213 Nome:Mario Rossi
";
* echo "
Matricola: 32145 Nome:Mario Bianchi
";
* //il comando Javascript MyFieldPopUPsetVal risiede nel chiamante, per questo si invoca
* //attraverso opener.MyFieldPopUPsetVal() e riceve tre parametri:
* // l'id del campo da settare (che è passato in GET con il nome di id_MyPopUp)
* // la chiave (in questo caso la matricola)
* // la descrizione da far comparire (in questo caso cognome e nome)
*
*
*
* @access public
* @param string $nome E' il nome del campo
* @param array() $valore Codice=>Descrizione da assegnare come default
* @param string $classe è la classe css da utilizzare
*/
function MyPopUp ($nome,$valore='',$classe='') {
parent::MyHidden($nome,$valore,$classe);
$this->set_MyType('MyPopUp');
$this->Prevede_label=true;
}
/**
* @param array() $valore Codice=>Descrizione da assegnare come default
*/
function set_value($valore) {
if (is_array($valore))
{$this->valori=$valore;
$bar = each($valore);
return parent::set_value($bar['key']);
}
else return parent::set_value($valore);
}
/**
* return string descrizione attuale
**/
function get_Descrizione() {
$bar = @each($valore=$this->valori);
return $bar['value'];
}
/** alias di get_Descrizione
* return string descrizione attuale
**/
function get_titolo() {
return $this->get_Descrizione();
}
function set_readonly() {
$this->set_showonly();
}
function set_disabled() {
$this->set_showonly();
}
function is_hidden() {
return $this->Metodo_ridefinito['get_Html']['metodo']=='_get_html_hidden';
}
/** @ignore */
protected function _get_html_show($pars){
if ($pars['campo'] && !$this->get_attributo('disabled')) $out=$this->_get_html_hidden($pars);
$attr=$this->stringa_attributi(array('class','style'),false)." id=\"myshow_only_{$this->get_attributo('id')}\"";
return "".$this->get_titolo()."".$out;
}
/**
* setta la popup sulla base del myLink che linka lo script da lanciare nella popup
* @param MyLink $myLink E' il link
* @param int larg larghezza della popup
* @param int alt altezza della popup
* @param string extraJS comandi extra che debbono essere eseguiti nello javascript MyFieldPopUPsetVal
*
* es. vogliamo che la popup si chiuda automaticamente e ci sia un alert 'ciao' appena si fa una scelta
*
* $x->set_popup($miolink,'','','MyPopUp.close();alert("ciao"); '); //MyPopUp è la variabile globale javascript che individua la popup, così come k è il valore e v la descrizione del mypopup scelti
*
**/
function set_popup($myLink,$larg=200,$alt=300,$extraJS='') {
$myLink->set_attributo('Href',$url);
$myLink->set_attributo('id',$this->get_id());
$this->extraJSpopup=$extraJS;
$this->popup=array('link'=>$myLink,'larg'=>$larg,'alt'=>$alt);
return $this;
}
/**
* elimina l'impostazione popup
**/
function unset_popup() {
unset($this->popup);
}
static function js_always_top($forza_get=false) {
$f=new MyField();
if (!$f->myFields['static']['js_src']['js_always_top'])
{$f->myFields['static']['js_src']['js_always_top']=true;
return "";
}
}
/**
* @return ignore
*/
function js(){
if (!$this->myFields['static']['js_src'][get_class($this)])
{$this->myFields['static']['js_src'][get_class($this)]=true;
return "
";
}
}
function get_html() {
if ($get_html=$this->Metodo_ridefinito['get_Html']['metodo']) return $this->$get_html($this->Metodo_ridefinito['get_Html']['parametri']);
if($this->popup ) {
$myLink=&$this->popup['link'];
$url=$myLink->get_Url();
if (strpos($url,'=')) $url.="&id_MyPopUp=".$this->get_id();
else $url.="?id_MyPopUp=".$this->get_id();
$myLink->set_attributo('Href',$url);
$myLink->set_attributo("onmouseup","MyFieldPopUP(this,{$this->popup['larg']},{$this->popup['alt']},'{$this->get_id()}');return false;");
$myLink->set_attributo("onkeyup","MyFieldPopUP(this,{$this->popup['larg']},{$this->popup['alt']},'{$this->get_id()}');return false;");
}
$js.=$this->js();
$js.="";
if ( $this->popup) $js.=self::js_always_top();
$this->set_attributo('id',"hidden_".$this->get_id());
if(!$this->myFields['static']['common']) {$jsCommon=$this->get_js_common();$this->myFields['static']['common']=true;}
return (!$this->con_js?'':$this->jsAutotab().$js.$jsCommon).
($this->popup['link']?$this->popup['link']->get_html($this->get_Descrizione()):$this->get_Descrizione()).
$this->send_html(parent::get_html());
}
/** Restituisce un messaggio se l'attributo value non soddisfa condizioni di notnull,maxlength,minlength
* @return string
*/
function get_errore_diviso() {
return MyField::get_errore_diviso();
}
}
/**
* @package myFields
*/
class MyMultiTree extends MyMultiCheck {
public /** @ignore */ $albero,$chiavi,$pulsante,$JS,
$nodes=array(),$folders=array(),$figli=array(), $aperto,
$opzioni,$campi,
$opzionitree=array(),$Id, $statoNodi=array(),$accessibile=true;
/**
* Questo oggetto permette di creare dei campi nascosti "ma visibili"
* Si può usare in alternativa ad un MyMulticheck quando le opzioni sono tante
* e soprattutto hanno un'organizzazione gerarchica
*
*
*
* $albero=array('lazio'=>array('','Lazio'),
* 'rm'=>array('lazio','Roma'),
* 'fr'=>array('lazio','Frosinone'),
* 'ri'=>array('lazio','Rieti'),
* 'lt'=>array('lazio','Latina'),
* 'H501'=>array('rm','Roma',1),
* 'H244'=>array('rm','Mentana',1),
* 'H324'=>array('rm','Monterotondo',1),
* 'H421'=>array('fr','Arpino',1),
* 'H445'=>array('fr','Isola Liri',1),
* 'friuli'=>array('','Friuli Venezia Giulia'),
* 'ud'=>array('friuli','Udine'),
* 'pn'=>array('friuli','Pordenone'),
* 'C444'=>array('pn','Pordenone',1),
* 'CR34'=>array('pn','Altro comune in prov. Pordenone',1)
* );
*
* $miotree=new MyMultiTree('mio',array('H501','CR34'),$albero); //istanzio l'oggetto inizializzando con il valore ricevuto in get
* echo $miotree->get_html();
*
*
* @access public
* @param string $nome E' il nome del campo
* @param array $valori da assegnare come default
* @param array $albero E' un array associativo come nell'esempio
* @param string $classe è la classe css da utilizzare
*/
function MyMultiTree ($nome,$valore='',$albero='',$classe='') {
parent::MyMultiCheck($nome,$valore,array(),$classe);
$this->set_MyType('MyMultiTree');
$this->Id=$this->myFields['static']['MyTree']['istanze']++;
$this->Id=(int) $this->Id;
$this->folders['aperta']="/".$this->get_MyFormsPath()."js/imgTree/folderopen.gif";
$this->folders['chiusa']="/".$this->get_MyFormsPath()."js/imgTree/folder.gif";
if (is_array($albero)) $this->set_Opzioni($albero);
if ($valore) $this->set_value($valore);
}
/**
* Permette di personalizzare le icone di cartella aperta e cartella chiusa
* sarebbe meglio che fossero immagini di dimensione 23x20
*
* @param string $foglia Url dell'immagine da usare, nei casi non sia stata specificata nel set_opzioni
* @param string $aperta Url dell'immagine da usare (se '*' non viene visualizzata)
* @param string $chiusa Url dell'immagine da usare (se '*' non viene visualizzata)
*/
function set_icons($foglia,$aperta='',$chiusa='') {
if ($aperta=='*') $aperta="/".$this->get_MyFormsPath()."js/imgTree/piatta.gif";
if ($chiusa=='*') $chiusa="/".$this->get_MyFormsPath()."js/imgTree/piatta.gif";
if ($foglia) $this->folders['foglia']=$foglia;
if ($aperta) $this->folders['aperta']=$aperta;
if ($aperta) $this->folders['chiusa']=$chiusa;
return $this;
}
function get_html() {
if ($get_html=$this->Metodo_ridefinito['get_Html']['metodo']) return $this->$get_html($this->Metodo_ridefinito['get_Html']['parametri']);
$this->set_attributo('style','border:0px;padding:0');
$MyTree=$this->Id;
if (!$this->myFields['static']['js_src'][get_class($this)])
{$js.="";
$this->myFields['static']['js_src'][get_class($this)]=1;
}
if ($this->albero) foreach ($this->albero as $i=>$v) $riga.="nodes[$MyTree][$i] =new Array(\"".htmlentities($v[0]).'","'.htmlentities($v[1]).'","'.htmlentities($v[2]).'","'.htmlentities($v[3])."\");\n";
$js.="
";
if(!$this->myFields['static']['common']) {$jsCommon=$this->get_js_common();$this->myFields['static']['common']=true;}
$MyTree++;
return (!$this->con_js?'':$jsCommon.$this->jsAutotab().$js).$this->get_html_Accessibilita($this->get_attributo('onclick'));;
}
/**
* Imposta l'albero su cui costruire il tutto
* Es.
*
* $albero=array('lazio'=>array('','Lazio'),
* 'rm'=>array('lazio','Roma',0,'/icons/provincia.gif'),
* 'fr'=>array('lazio','Frosinone'),
* 'ri'=>array('lazio','Rieti'),
* 'lt'=>array('lazio','Latina'),
* 'H501'=>array('rm','Roma' ,1,'/icons/comune.gif'),
* 'H244'=>array('rm','Mentana',1),
* 'H324'=>array('rm','Monterotondo',1),
* 'H421'=>array('fr','Arpino',1),
* 'H445'=>array('fr','Isola Liri',1,'/icons/comune.gif'),
* 'friuli'=>array('','Friuli Venezia Giulia'),
* 'ud'=>array('friuli','Udine'),
* 'pn'=>array('friuli','Pordenone',0,'/icons/provincia.gif'),
* 'C444'=>array('pn','Pordenone',1,'/icons/comune.gif'),
* 'CR34'=>array('pn','Altro comune in prov. Pordenone',1,'/icons/comune.gif')
* );
* $miotree->set_opzioni($albero);
* echo $miotree->get_html();
*
*
* Si tratta ovviamente di un array di array, ogni sottoarray rappresenta un nodo in cui:
* 'lazio'=>array('','Lazio'),
* In questo caso 'lazio' è il valore associato al nodo in cui 'Lazio' sarà la descrizione che comparirà.
* Non essendo valorizzato il primo valore questo nodo sarà una "radice" in particolare non selezionabile
* 'rm'=>array('lazio','Roma',0,'/icons/provincia.gif'),
* In quest'altro caso 'rm' è il valore associato al nodo in cui 'Roma' sarà la descrizione che comparirà.
* Inoltre la presenza dello 0 indica che non è selezionabile e che Qualora fosse una foglia l'icona da usare è '/icons/provincia.gif' altrimenti non c'è icona
* Questo sarà un "figlio" del nodo 'Lazio' ma non sarà ancora selezionabile
* 'H324'=>array('rm','Monterotondo',1),
* In quest'altro caso 'H324' è il valore associato al nodo in cui 'Monterotondo' sarà la descrizione che comparirà.
* Questo sarà un "figlio" del nodo 'Roma' ed è selezionabile (terzo valore =1 o =true), questo fa si che si possa scegliere di rendere selezionabili sia le foglie che i rami che le radici
*
* @param array $albero
*
*/
function set_Opzioni($albero) {
parent::set_Opzioni($this->set_Opzioni_tree($albero));
return $this;
}
/** @ignore*/
function &set_Opzioni_tree($albero) {
if (!$albero) return;
$this->albero=array();
$this->chiavi=array();
$this->opzioni=array();
$this->figli=array();
$this->opzionitree=&$albero;
$i=1;
foreach ($albero as $k=>$v) {$this->chiavi[htmlentities($k)]=$i;$i++;}
$ordine=array_keys($albero);
$i=1;
foreach ($ordine as $k) {
if (!$albero[$k]) $albero[$k]=array();
$v=array_values($albero[$k]);
//echo "
";print_r($this->albero);
return $opzioni;
// foreach ($opzioni as $i=>$v) $opzioni[]
}
/** Aggiunge una singola opzione
*
* $albero=array('lazio'=>array('','Lazio'),
* 'rm'=>array('lazio','Roma',0,'/icons/provincia.gif'),
* 'fr'=>array('lazio','Frosinone'),
* 'ri'=>array('lazio','Rieti'),
* 'lt'=>array('lazio','Latina'),
* 'H501'=>array('rm','Roma' ,1,'/icons/comune.gif'),
* 'H244'=>array('rm','Mentana',1),
* 'H324'=>array('rm','Monterotondo',1),
* 'H421'=>array('fr','Arpino',1),
* 'H445'=>array('fr','Isola Liri',1,'/icons/comune.gif'),
* 'friuli'=>array('','Friuli Venezia Giulia'),
* 'ud'=>array('friuli','Udine'),
* 'pn'=>array('friuli','Pordenone',0,'/icons/provincia.gif'),
* 'C444'=>array('pn','Pordenone',1,'/icons/comune.gif'),
* 'CR34'=>array('pn','Altro comune in prov. Pordenone',1,'/icons/comune.gif')
* );
* $miotree->set_opzioni($albero);
*
* $altra=array('H502','lazio','Latina',1,'/icons/provincia.gif');
* $miotree->add_opzione($albero,true);
*
* echo $miotree->get_html();
*
*
* @param array opzione è un array NON ASSOCIATIVO con (chiave,chiave_padre,selezionabile,descrizione,icona)
* @param boolean $fine se falso o omesso l'opzione si aggiunge in coda se true si aggiunge all'inizio del ramo
*/
function add_Opzione($opzione,$fine=false) {
$V=array();
foreach ($opzione as $k=>$v) if (!isset($K)) $K=$v;
else $V[$k]=$v;
if ($fine) {$this->opzionitree[$K]=$V;
$this->set_Opzioni($this->opzionitree);
}
else {$x=array($K=>$V);
foreach ($this->opzionitree as $k=>$v) $x[$k]=$v;
$this->set_Opzioni($x);
}
return $this;
//echo "
"; print_r($this->opzionitree);
}
/**
* Effettua la potatura delle opzioni eliminando i rami secchi, cioe tutti quei rami che portano a foglie non selezionabili
* da usare ovviamento dopo set_opzioni
*
* @param boolean $potaRadicise vero anche radici non selezionabili vengono eliminate
*/
function &pota_Opzioni($potaRadici=false) {
//$selezionabili sono tutti i nodi con flag di selezionabilità a 1
$selezionabili=array();
foreach ($this->opzionitree as $k=>$v)
{
$arra=array_values($v);
if ($arra[2]) $selezionabili[]=$k;
}
$buoni=array();
//per ogni selezionabile
if($selezionabili) foreach ($selezionabili as $buono)
do {
$buoni[$buono]=true; //inserisce buono nei buoni
$arra=array_values($this->opzionitree[$buono]);
$buono=$arra[0]; //prox_buono è padre del buono attuale
}
while ( isset($this->opzionitree[$buono]) && !$buoni[$buono]); //Smette di iterare se arrivato su un percorso già battuto o se è radice
if ($this->opzionitree) foreach ($this->opzionitree as $k=>$v) if ($buoni[$k]) $albero[$k]=$v;
if ($potaRadici) do {//foreach ($albero as $k=>$v) $livelli[$k]=count($this->get_percorso($k));
$eliminate=false;
if ( count($albero))
foreach ($albero as $k=>$v)
{
$v=array_values($v);
if (!isset($albero[$v[0]]) && !$v[2]) //se è radice e non è selezionabile
{//Radice candidata all'eliminazione ha fratelli?
$hafratello=false;
foreach ($albero as $kk=>$vv)
{ $vv=array_values($vv);
if ($vv[0]==$v[0] && $kk!=$k)
{//se $vv ha lo stesso padre di $v e non è lui e non è selezionabile
$hafratello=true;
break;
}
}
if (!$hafratello && isset($albero[$k])){
$eliminate=true;
unset($albero[$k]);
}
}
}
} while ($eliminate==true && count($albero));
$this->set_Opzioni($albero);
return $this;
}
function get_opzioni() {
return $this->opzionitree;
}
function get_errore_diviso() {
$valore=$this->get_value();
if ($this->notnull && !$valore) return 'non può essere nullo';
if($this->restrizioni_check && $valore)
{ if(!$valore) $valore=array();
if(array_diff($valore,array_keys((array) $this->get_opzioni()))) return 'non è accettabile';
}
}
/** elimina dal/i valore/i impostati quelli non presenti nelle opzioni
* attenziene a non usarla prima di aver settato tutte le opzioni valide
* altrimenti si annulla il valore
*/
function clean_value() {
$opzioni=(array) $this->get_opzioni();
foreach ($opzioni as $v=>&$foglia) if($foglia[2]) $selezionabili[$v]=true;
$valori=$this->get_value();
if (!is_array($valori)) $valori=array($valori);
$new_val=array();
foreach ($valori as &$v)
if ($selezionabili[$v]) $new_val[]=$v;
$this->set_value($new_val);
return $this;
}
/** setta in automatico il primo valore valido se non ce ne sono settati
*/
function autovalue() {
$this->clean_value();
if (!strlen($this->get_value()))
foreach ($this->get_Opzioni() as $k=>$v) if ($v[2]) {$this->set_value($k);
return;
}
}
/**
* Setta le opzioni del selettore
*
* @param ADODBConnection $db è la connessione a DB da utilizzare
* @param string $qry la query da usare per reperire i dati in cui il primo campo è la chiave del nodo, il secondo e la chiave del padre il terzo è il Titolo del nodo e il quarto è 1 o 0 a seconda che sia un nodo selezionabile
* @param boolean $registra se true i valori vengono memorizzati in una variabile di sessione e la qry non si riesegue più
*/
function set_OpzioniQRY(&$db,$qry='',$registra=true) {
$this->qry=$qry;
IF ($_SESSION['myFields']['MyOpzioniRegistrate'][md5($this->qry)] && $registra)
{$this->opzioni=$_SESSION['myFields']['MyOpzioniRegistrate'][md5($this->qry)];
$opzioni=$this->opzioni;
}
else {$db->debug=0;
$opzioni=$this->opzioni=&$db->getassoc($qry);
// if ($registra) $_SESSION['myFields']['MyOpzioniRegistrate'][md5($this->qry)]=$opzioni;
if ($registra) $this->registra_opzioni();
}
return $this->set_Opzioni($opzioni);
}
/** Restituisce array con i nodi dalla radice fino al nodo $nodo
* @param int|string $nodo
* @return array
*/
function get_percorso($nodo) {
$buoni=array();
while (is_array($this->opzionitree) &&
@isset($this->opzionitree[$nodo])) {
$buoni[]=$nodo;
$arra=array_values($this->opzionitree[$nodo]);
$nodo=$arra[0];
}
return array_reverse($buoni);
}
/** Restituisce il codice relativo alla radice del nodo
* @param int|string $nodo
* @return array
*/
function get_radice($nodo) {
$buoni=$this->get_percorso($nodo);
return $buoni[0];
}
/** Se usato, l'albero si presenta già completamente aperto
*
**/
function set_aperto() {
$this->aperto=true;
return $this;
}
/** I nodi dell'albero diventano tutti foglie non selezionabili
* utile se si vuole usare per costruire menu in cui le descizione di nodi sono già dei link
*
**/
function set_soloalbero() {
$this->showlinks='';
return $this;
}
/** Riduce il livello di accessibilità escludendo la possibilità di usare
* l'albero con javascript non attivo e css attivo ma ne rende più performante
* la visualizzazione nel caso di innumerevoli rami
*
**/
function unset_accessibilita() {
$this->accessibile=false;
return $this;
}
/** @ignore*/
function &Tree($Id,$arrName, $startNode='') {
$this->nodes[$Id] =$arrName;
if (count($this->nodes[$Id])> 0)
{
$startNode = 0;
//if ($openNode != 0) $this->setOpenNodes($Id,$openNode);
$recursedNodes[$Id]=array();
$aperti=$this->NodiAperti($Id);
//echo "
";print_r($nodeValues);echo "$ls - $hcn";
// Write out line & empty icons
for ($g=0; $gget_MyFormsPath()."js/imgTree/line.gif\" alt='' />";
else $out.="";
// put in array line & empty icons
if ($ls) array_push($recursedNodes[$Id],0);
else array_push($recursedNodes[$Id],1);
// Write out join icons
if (!$hcn)
{
if ($ls) $out.="get_MyFormsPath()."js/imgTree/join.gif\" alt='' />";
else $out.="get_MyFormsPath()."js/imgTree/joinbottom.gif\" alt='' />";
if ($nodeValues[4] || $this->folders['foglia'])
{
if ($nodeValues[4]) $icona= $nodeValues[4];
else $icona= $this->folders['foglia'];
// else $icona=$this->folders['aperta'];
$out.="";
}
}
else {
if ($ls){
if ($ino) $icona='minusbottom.gif';
else $icona='plusbottom.gif';
$out.="
";
}
else {
if ($ino) $icona='minus.gif';
else $icona='plus.gif';
$out.="
";
}
if ($ino) $icona=$this->folders['aperta'];
else $icona=$this->folders['chiusa'];
$out.="
";
}
if ($nodeValues[3]!='') $out.="
".$this->get_html_singolo($nodeValues[2])."
";
else $out.="
$nodeValues[2]
";
$out.="";
if (!$ino) $this->statoNodi[$nodeValues[0]]=0;
else $this->statoNodi[$nodeValues[0]]=1;
// If node has children write out divs and go deeper
if ($hcn && count($this->nodes[$Id])>0)
{
if (!$ino && $this->accessibile) $this->JS.="document.getElementById(\"div$Id"."_$nodeValues[0]\").style.display = 'none';\n";
if ($ino || $this->accessibile) $out.="
\n";
}
// remove last line or empty icon
array_pop($recursedNodes[$Id]);
}
}
return $out;
}
/** Alias di myMultiTree::setReloadJS()
**/
function Set_ReloadJS($Tipo='parametro',$evento='onclick',$opzioni='',$fragment='',$usa_random=true,$sostituisci=false) {
return $this->SetReloadJS($Tipo,$evento,$opzioni,$fragment,$usa_random,$sostituisci);
}
/** se settato aggiunge il reload della pagina sull'evento passato, di default è onclick
* DA USARE SOLO DOPO AVER IMPOSTATO LE OPZIONI
* @param parametro|completo|azzera|submit $Tipo Il default è 'parametro'
* @param string $evento Il nome dell'evento su cui attivare il reload
* @param array $opzioni A cui applicare
* @param string $fragment Eventuale fragment da aggiungere alla url
* @param boolean $usaRandom se false non si aggiunge parametro random "tt"
* @param boolean $sostituisci se true eventuali eventu preimpostati si sovrascrivono
*
* Supponiamo che questo selettore si chiami 'Tipo' e la url della pagina sia
* http://www.fdsf.it?abc=32432&Tipo=424&altro=12345
* con l'opzione 'parametro' si ricaricherà http://www.fdsf.it?abc=32432&Tipo=nuovo_valore
* con l'opzione 'completo' si ricaricherà http://www.fdsf.it?abc=32432&Tipo=nuovo_valore&altro=12345
* con l'opzione 'azzera' si ricaricherà http://www.fdsf.it?Tipo=nuovo_valore
* con l'opzione 'submit' effettua l'invio in POST del form così com'è
*
**/
function SetReloadJS($Tipo='parametro',$evento='onclick',$opzioni='',$fragment='',$usa_random=true,$sostituisci=false) {
if (!$Tipo) $Tipo='parametro';
if ($Tipo=='submit'||$Tipo=='submit()')
$this->setjs($opzioni,"submit()",$evento,$sostituisci);
else foreach ($this->campi as $id=>&$campo) {
$val=$campo->get_value();
if(!$opzioni || in_array($val, $opzioni))
//$this->setjs(array($val),"location.href='?$extra&".$this->get_name()."=".rawurlencode($val)."$fragment'",$evento,$sostituisci);
{
$this->reloadJSGET[$val]=array($Tipo,$usa_random,$fragment);
$this->setjs(array($val),"location.href=myLinks_{$campo->get_id_istanza()}[this.value];",$evento,$sostituisci);
}
}
// echo "
";print_r($this->campi);
}
/**
*
* Calcola le url usate nel mySelect::setReloadJS() nelle modalità GET,
* utile per eventuali overriding
*
* @param parametro|completo|azzera|submit $Tipo Il default è 'parametro'
* @param string $nome_campo nome del campo usato come riferimento per la costr. nuova url
* @param boolean $usa_random se true aggiunge tt randomico
* @param string $url eventuale url da usare, se string avuota o omesso si usa $_SERVER['PHP_SELF']
* @param string $query_string eventuale string di parametri se FALSE non si usa omesso o stringa vuota usa $_SERVER["QUERY_STRING"]
* @param string $fragment eventuale fragment
*
* @return string
*/
function build_reload_urls($Tipo,$nome_campo,$usa_random,$url='',$query_string='',$fragment=''){
$nuova=array();
if($query_string==='') $query_string=$_SERVER["QUERY_STRING"];
if($query_string) @parse_str($query_string,$parametri);
if(!$url) $url=$_SERVER['PHP_SELF'];
$parametri=(array) $parametri;
static $build;
if($build[serialize(func_get_args())]) return $build[serialize(func_get_args())];
$secure=new mySecurizer();
if($parametri)
foreach ($parametri as $par=>$val)
{
if ($Tipo=='parametro' && $par==$nome_campo) break;
if ($par!=$nome_campo && (is_array($val) || trim($val)!==''))
$nuova[$par]=(mySecurizer::seemsSecurized($val) &&
($val=$secure->decode($par, $val,false))!==false
?$secure->encode($par, $val):$val);
}
if ($Tipo=='azzera') $nuova=array();
if($usa_random) $nuova['tt']=self::unid();
if($fragment) $fragment="#$fragment";
foreach ($this->get_Opzioni() as $val=>$ramo)
{$nuova[$nome_campo]=$val;
$valori[$val]=$url.'?'.http_build_query($nuova).$fragment;
}
return $build[serialize(func_get_args())]=$valori;
}
/** se assegna un JS ad un evento delle $opzioni di default è onclick
* DA USARE SOLO DOPO AVER IMPOSTATO LE OPZIONI
* @param array $opzioni E' un array con l'elenco delle CHIAVI su cui attivare l'evento, se vuoto si applica a tutte
* @param string $JS E' lo JavaScript da lanciare
* @param string $evento Il nome dell'evento su cui attivare lo JS
* @param boolean $sostituisci sostituisce eventuali precedenti eventi
*/
function Set_JS($opzioni='',$JS,$evento='onclick',$sostituisci=false) {
$this->setjs($opzioni,$JS,$evento,$sostituisci);
}
/** se assegna un JS ad un evento delle $opzioni di default è onclick
* DA USARE SOLO DOPO AVER IMPOSTATO LE OPZIONI
* @param array $opzioni E' un array con l'elenco delle CHIAVI su cui attivare l'evento, se vuoto si applica a tutte
* @param string $JS E' lo JavaScript da lanciare
* @param string $evento Il nome dell'evento su cui attivare lo JS
* @param boolean $sostituisci sostituisce eventuali precedenti eventi
*/
function SetJS($opzioni='',$JS,$evento='onclick',$sostituisci=false) {
if (!$opzioni || count($opzioni)==0)
$this->set_attributo($evento,str_replace('"','\\"',$JS),$sostituisci);
else foreach ($this->campi as $id=>$v)
if (in_array($v->get_value(), $opzioni))
$this->campi[$id]->set_attributo($evento,str_replace('"','\\"',$JS),$sostituisci);
}
}
/**
* @package myFields
*
* Questo oggetto permette di creare dei campi nascosti "ma visibili"
* Si può usare in alternativa ad un MyMulticheck quando le opzioni sono tante
* e soprattutto hanno un'organizzazione gerarchica
*
*
*
* $albero=array('lazio'=>array('','Lazio'),
* 'rm'=>array('lazio','Roma'),
* 'fr'=>array('lazio','Frosinone'),
* 'ri'=>array('lazio','Rieti'),
* 'lt'=>array('lazio','Latina'),
* 'H501'=>array('rm','Roma',1),
* 'H244'=>array('rm','Mentana',1),
* 'H324'=>array('rm','Monterotondo',1),
* 'H421'=>array('fr','Arpino',1),
* 'H445'=>array('fr','Isola Liri',1),
* 'friuli'=>array('','Friuli Venezia Giulia'),
* 'ud'=>array('friuli','Udine'),
* 'pn'=>array('friuli','Pordenone'),
* 'C444'=>array('pn','Pordenone',1),
* 'CR34'=>array('pn','Altro comune in prov. Pordenone',1)
* );
*
* $miotree=new MyTree('mio','H501',$albero); //istanzio l'oggetto inizializzando con il valore ricevuto in get
* echo $miotree->get_html();
*
*/
class MyTree extends MyMultiTree {
function MyTree($nome,$valore='',$albero='',$classe=''){
parent::MyMultiTree($nome,$valore,$albero,$classe);
}
/**
* Imposta l'albero su cui costruire il tutto
* Es.
*
* $albero=array('lazio'=>array('','Lazio'),
* 'rm'=>array('lazio','Roma',0,'/icons/provincia.gif'),
* 'fr'=>array('lazio','Frosinone'),
* 'ri'=>array('lazio','Rieti'),
* 'lt'=>array('lazio','Latina'),
* 'H501'=>array('rm','Roma' ,1,'/icons/comune.gif'),
* 'H244'=>array('rm','Mentana',1),
* 'H324'=>array('rm','Monterotondo',1),
* 'H421'=>array('fr','Arpino',1),
* 'H445'=>array('fr','Isola Liri',1,'/icons/comune.gif'),
* 'friuli'=>array('','Friuli Venezia Giulia'),
* 'ud'=>array('friuli','Udine'),
* 'pn'=>array('friuli','Pordenone',0,'/icons/provincia.gif'),
* 'C444'=>array('pn','Pordenone',1,'/icons/comune.gif'),
* 'CR34'=>array('pn','Altro comune in prov. Pordenone',1,'/icons/comune.gif')
* );
* $miotree->set_opzioni($albero);
* echo $miotree->get_html();
*
*
* Si tratta ovviamente di un array di array, ogni sottoarray rappresenta un nodo in cui:
* 'lazio'=>array('','Lazio'),
* In questo caso 'lazio' è il valore associato al nodo in cui 'Lazio' sarà la descrizione che comparir�.
* Non essendo valorizzato il primo valore questo nodo sarà una "radice" in particolare non selezionabile
* 'rm'=>array('lazio','Roma',0,'/icons/provincia.gif'),
* In quest'altro caso 'rm' è il valore associato al nodo in cui 'Roma' sarà la descrizione che comparir�.
* Inoltre la presenza dello 0 indica che non è selezionabile e che Qualora fosse una foglia l'icona da usare è '/icons/provincia.gif' altrimenti non c'� icona
* Questo sarà un "figlio" del nodo 'Lazio' ma non sarà ancora selezionabile
* 'H324'=>array('rm','Monterotondo',1),
* In quest'altro caso 'H324' è il valore associato al nodo in cui 'Monterotondo' sarà la descrizione che comparir�.
* Questo sarà un "figlio" del nodo 'Roma' ed è selezionabile (terzo valore =1 o =true), questo fa si che si possa scegliere di rendere selezionabili sia le foglie che i rami che le radici
*
* @param array $albero
*
*/
function set_Opzioni($albero) {
MyRadio::set_Opzioni($this->set_Opzioni_tree($albero));
return $this;
}
function isMultiple(){
return false;
}
/** @ignore*/
function &get_value_DB() {
return myField::get_value_DB();
}
function get_value(){
return myField::get_value();
}
/** L'elenco si trasforma in un elenco di link
*
* @param string $url indica l'url di destinazione alla quale verrà automativamente accodato il valore cliccato
*
**/
function Set_Links($url,$add_random=false) {
$this->showlinks=array($url,$add_random);
return $this;
}
/** elimina dal/i valore/i impostati quelli non presenti nelle opzioni
* attenzione a non usarla prima di aver settato tutte le opzioni valide
* altrimenti si annulla il valore
*/
function clean_value() {
$opzioni=(array)$this->get_opzioni();
foreach ($opzioni as $v=>&$foglia) if($foglia[2]) $selezionabili[$v]=true;
if (!$selezionabili[$this->get_value()]) $this->set_value('');
}
/** setta in automatico il primo valore valido
*/
function autovalue() {
MyMultiTree::autovalue();
}
}
/**
* @package myFields
* @see http://en.wikipedia.org/wiki/International_Bank_Account_Number#Validating_the_IBAN
* @see http://www.swift.com/dsp/resources/documents/IBAN_Registry.pdf
*
* Supporta i 63 Stati indicati su wikipedia http://en.wikipedia.org/wiki/International_Bank_Account_Number#Validating_the_IBAN
*/
class MyIBAN extends myText{
/**#@+ @ignore */
protected $restrizioni_check=true;
protected $stato_def=array();
protected static $internationals=array (
'AL' =>
array (
0 => 'Albania',
1 => '28',
2 => '8n, 16c',
3 => 'ALkk bbbs sssx cccc cccc cccc cccc',
4 => 'b = National bank code s = Branch code x = National check digit c = Account number',
),
'AD' =>
array (
0 => 'Andorra',
1 => '24',
2 => '8n,12c',
3 => 'ADkk bbbb ssss cccc cccc cccc',
4 => 'b = National bank code s = Branch code c = Account number',
),-
'AT' =>
array (
0 => 'Austria',
1 => '20',
2 => '16n',
3 => 'ATkk bbbb bccc cccc cccc',
4 => 'b = National bank code c = Account number',
),
'AZ' =>
array (
0 => 'Azerbaijan',
1 => '28',
2 => '4c,20n',
3 => 'AZkk bbbb cccc cccc cccc cccc cccc',
4 => 'b = National bank code c = Account number',
),
'BE' =>
array (
0 => 'Belgium',
1 => '16',
2 => '12n',
3 => 'BEkk bbbc cccc ccxx',
4 => 'b = National bank code c = Account number x = National check digits',
),
'BH' =>
array (
0 => 'Bahrain',
1 => '22',
2 => '4a,14c',
3 => 'BHkk bbbb cccc cccc cccc cc',
4 => 'b = National bank code c = Account number',
),
'BA' =>
array (
0 => 'Bosnia and Herzegovina',
1 => '20',
2 => '16n',
3 => 'BAkk bbbs sscc cccc ccxx',
4 => 'k = IBAN check digits (always 39) b = National bank code s = Branch code c = Account number x = National check digits',
),
'BG' =>
array (
0 => 'Bulgaria',
1 => '22',
2 => '4a,6n,8c',
3 => 'BGkk bbbb ssss ddcc cccc cc',
4 => 'b = BIC bank code s = Branch (BAE) number d = Account type c = Account number',
),
'CR' =>
array (
0 => 'Costa Rica',
1 => '21',
2 => '17n',
3 => 'CRkk bbbc cccc cccc cccc c',
4 => 'b = bank code c = Account number',
),
'HR' =>
array (
0 => 'Croatia',
1 => '21',
2 => '17n',
3 => 'HRkk bbbb bbbc cccc cccc c',
4 => 'b = Bank code c = Account number',
),
'CY' =>
array (
0 => 'Cyprus',
1 => '28',
2 => '8n,16c',
3 => 'CYkk bbbs ssss cccc cccc cccc cccc',
4 => 'b = National bank code s = Branch code c = Account number',
),
'CZ' =>
array (
0 => 'Czech Republic',
1 => '24',
2 => '20n',
3 => 'CZkk bbbb ssss sscc cccc cccc',
4 => 'b = National bank code s = Branch code c = Account number',
),
'DK' =>
array (
0 => 'Denmark',
1 => '18',
2 => '14n',
3 => 'DKkk bbbb cccc cccc cc',
4 => 'b = National bank code c = Account number',
),
'DO' =>
array (
0 => 'Dominican Republic',
1 => '28',
2 => '4a,20n',
3 => 'DOkk bbbb cccc cccc cccc cccc cccc',
4 => 'b = Bank identifier c = Account number',
),
'EE' =>
array (
0 => 'Estonia',
1 => '20',
2 => '16n',
3 => 'EEkk bbss cccc cccc cccx',
4 => 'b = National bank code s = Branch code c = Account number x = National check digit',
),
'FO' =>
array (
0 => 'Faroe Islands[Note 4]',
1 => '18',
2 => '14n',
3 => 'FOkk bbbb cccc cccc cx',
4 => 'b = National bank code c = Account number x = National check digit',
),
'FI' =>
array (
0 => 'Finland',
1 => '18',
2 => '14n',
3 => 'FIkk bbbb bbcc cccc cx',
4 => 'b = Bank and branch code c = Account number x = National check digit',
),
'FR' =>
array (
0 => 'France[Note 5]',
1 => '27',
2 => '10n,11c,2n',
3 => 'FRkk bbbb bggg ggcc cccc cccc cxx',
4 => 'b = National bank code g = Branch code (fr:code guichet) c = Account number x = National check digits',
),
'GE' =>
array (
0 => 'Georgia',
1 => '22',
2 => '2c,16n',
3 => 'GEkk bbcc cccc cccc cccc cc',
4 => 'b = National bank code c = Account number',
),
'DE' =>
array (
0 => 'Germany',
1 => '22',
2 => '18n',
3 => 'DEkk bbbb bbbb cccc cccc cc',
4 => 'b = Bank and branch identifier (de:Bankleitzahl or BLZ) c = Account number',
),
'GI' =>
array (
0 => 'Gibraltar',
1 => '23',
2 => '4a,15c',
3 => 'GIkk bbbb cccc cccc cccc ccc',
4 => 'b = BIC bank code c = Account number',
),
'GR' =>
array (
0 => 'Greece',
1 => '27',
2 => '7n,16c',
3 => 'GRkk bbbs sssc cccc cccc cccc ccc',
4 => 'b = National bank code s = Branch code c = Account number',
),
'GL' =>
array (
0 => 'Greenland[Note 4]',
1 => '18',
2 => '14n',
3 => 'GLkk bbbb cccc cccc cc',
4 => 'b = National bank code c = Account number',
),
'GT' =>
array (
0 => 'Guatemala',
1 => '28',
2 => '4c,20c',
3 => 'GTkk bbbb cccc cccc cccc cccc cccc',
4 => 'b = National bank code c = Account number Effective 1 July 2014',
),
'HU' =>
array (
0 => 'Hungary',
1 => '28',
2 => '24n',
3 => 'HUkk bbbs sssk cccc cccc cccc cccx',
4 => 'b = National bank code s = Branch code c = Account number x = National check digit',
),
'IS' =>
array (
0 => 'Iceland',
1 => '26',
2 => '22n',
3 => 'ISkk bbbb sscc cccc iiii iiii ii',
4 => 'b = National bank code s = Branch code c = Account number i = holder\'s kennitala (national identification number).',
),
'IE' =>
array (
0 => 'Ireland',
1 => '22',
2 => '4c,14n',
3 => 'IEkk aaaa bbbb bbcc cccc cc',
4 => 'a = BIC bank code b = Bank/branch code (sort code) c = Account number',
),
'IL' =>
array (
0 => 'Israel',
1 => '23',
2 => '19n',
3 => 'ILkk bbbn nncc cccc cccc ccc',
4 => 'b = National bank code n = Branch number c = Account number 13 digits (padded with zeros).',
),
'IT' =>
array (
0 => 'Italy',
1 => '27',
2 => '1a,10n,12c',
3 => 'ITkkx aaaaa bbbbb ccccc ccccccc',
4 => 'x = Check char (CIN) a = National bank code (it:Associazione bancaria italiana or Codice ABI ) b = Branch code (it:Coordinate bancarie or CAB - Codice d\'Avviamento Bancario) c = Account number',
),
'KZ' =>
array (
0 => 'Kazakhstan',
1 => '20',
2 => '3n,13c',
3 => 'KZkk bbbc cccc cccc cccc',
4 => 'b = National bank code c = Account number',
),
'KW' =>
array (
0 => 'Kuwait',
1 => '30',
2 => '4a, 22c',
3 => 'KWkk bbbb aaaa aaaa aaaa aaaa aaaa aa',
4 => 'b = National bank code a = Account number.',
),
'LV' =>
array (
0 => 'Latvia',
1 => '21',
2 => '4a,13c',
3 => 'LVkk bbbb cccc cccc cccc c',
4 => 'b = BIC Bank code c = Account number',
),
'LB' =>
array (
0 => 'Lebanon',
1 => '28',
2 => '4n,20c',
3 => 'LBkk bbbb aaaa aaaa aaaa aaaa aaaa',
4 => 'b = National bank code a = Account number',
),
'LI' =>
array (
0 => 'Liechtenstein',
1 => '21',
2 => '5n,12c',
3 => 'LIkk bbbb bccc cccc cccc c',
4 => 'b = National bank code c = Account number',
),
'LT' =>
array (
0 => 'Lithuania',
1 => '20',
2 => '16n',
3 => 'LTkk bbbb bccc cccc cccc',
4 => 'b = National bank code c = Account number',
),
'LU' =>
array (
0 => 'Luxembourg',
1 => '20',
2 => '3n,13c',
3 => 'LUkk bbbc cccc cccc cccc',
4 => 'b = National bank code c = Account number',
),
'MK' =>
array (
0 => 'Macedonia',
1 => '19',
2 => '3n,10c,2n',
3 => 'MKkk bbbc cccc cccc cxx',
4 => 'k = IBAN check digits (always = "07") b = National bank code c = Account number x = National check digits',
),
'MT' =>
array (
0 => 'Malta',
1 => '31',
2 => '4a,5n,18c',
3 => 'MTkk bbbb ssss sccc cccc cccc cccc ccc',
4 => 'b = BIC bank code s = Branch code c = Account number',
),
'MR' =>
array (
0 => 'Mauritania',
1 => '27',
2 => '23n',
3 => 'MRkk bbbb bsss sscc cccc cccc cxx',
4 => 'b = National bank code s = Branch code (fr:code guichet) c = Account number x = National check digits Planned effective date 1 January 2012.',
),
'MU' =>
array (
0 => 'Mauritius',
1 => '30',
2 => '4a,19n,3a',
3 => 'MUkk bbbb bbss cccc cccc cccc cccc cc',
4 => 'b = National bank code s = Branch identifier c = Account number',
),
'MC' =>
array (
0 => 'Monaco',
1 => '27',
2 => '10n,11c,2n',
3 => 'MCkk bbbb bsss sscc cccc cccc cxx',
4 => 'b = National bank code s = Branch code (fr:code guichet) c = Account number x = National check digits',
),
'MD' =>
array (
0 => 'Moldova',
1 => '24',
2 => '2c,18n',
3 => 'MDkk bbcc cccc cccc cccc cccc',
4 => 'b = National bank code c = Account number',
),
'ME' =>
array (
0 => 'Montenegro',
1 => '22',
2 => '18n',
3 => 'MEkk bbbc cccc cccc cccc xx',
4 => 'k = IBAN check digits (always = "25") b = Bank code c = Account number x = National check digits',
),
'NL' =>
array (
0 => 'Netherlands[Note 6]',
1 => '18',
2 => '4a,10n',
3 => 'NLkk bbbb cccc cccc cc',
4 => 'b = BIC Bank code c = Account number',
),
'NO' =>
array (
0 => 'Norway',
1 => '15',
2 => '11n',
3 => 'NOkk bbbb cccc ccx',
4 => 'b = National bank code c = Account number x = Modulo-11 national check digit',
),
'PK' =>
array (
0 => 'Pakistan',
1 => '24',
2 => '4c,16n',
3 => 'PKkk bbbb cccc cccc cccc cccc',
4 => 'b = National bank code c = Account number Effective 31 December 2012',
),
'PS' =>
array (
0 => 'Palestinian Territory, Occupied',
1 => '29',
2 => '4c,21n',
3 => 'PSkk bbbb xxxx xxxx xccc cccc cccc c',
4 => 'b = National bank code c = Account number x = Not specified',
),
'PL' =>
array (
0 => 'Poland',
1 => '28',
2 => '24n',
3 => 'PLkk bbbs sssx cccc cccc cccc cccc',
4 => 'b = National bank code s = Branch code x = National check digit c = Account number,',
),
'PT' =>
array (
0 => 'Portugal',
1 => '25',
2 => '21n',
3 => 'PTkk bbbb ssss cccc cccc cccx x',
4 => 'k = IBAN check digits (always = "50") b = National bank code s = Branch code C = Account number x = National check digit',
),
'RO' =>
array (
0 => 'Romania',
1 => '24',
2 => '4a,16c',
3 => 'ROkk bbbb cccc cccc cccc cccc',
4 => 'b = BIC Bank code c = Branch code and account number (bank-specific format)',
),
'SM' =>
array (
0 => 'San Marino',
1 => '27',
2 => '1a,10n,12c',
3 => 'SMkk xaaa aabb bbbc cccc cccc ccc',
4 => 'x = Check char (it:CIN) a = National bank code (it:Associazione bancaria italiana or Codice ABI) b = Branch code (it:Coordinate bancarie or CAB - Codice d\'Avviamento Bancario) c = Account number',
),
'SA' =>
array (
0 => 'Saudi Arabia',
1 => '24',
2 => '2n,18c',
3 => 'SAkk bbcc cccc cccc cccc cccc',
4 => 'b = National bank code c = Account number preceded by zeros, if required',
),
'RS' =>
array (
0 => 'Serbia',
1 => '22',
2 => '18n',
3 => 'RSkk bbbc cccc cccc cccc xx',
4 => 'b = National bank code c = Account number x = Account check digits',
),
'SK' =>
array (
0 => 'Slovakia',
1 => '24',
2 => '20n',
3 => 'SKkk bbbb ssss sscc cccc cccc',
4 => 'b = National bank code s = Branch code c = Account number',
),
'SI' =>
array (
0 => 'Slovenia',
1 => '19',
2 => '15n',
3 => 'SIkk bbss sccc cccc cxx',
4 => 'k = IBAN check digits (always = "56") b = National bank code s = Branch code c = Account number x = National check digits',
),
'ES' =>
array (
0 => 'Spain',
1 => '24',
2 => '20n',
3 => 'ESkk bbbb gggg xxcc cccc cccc',
4 => 'b = National bank code g = Branch code x = Check digits c = Account number',
),
'SE' =>
array (
0 => 'Sweden',
1 => '24',
2 => '20n',
3 => 'SEkk bbbc cccc cccc cccc cccx',
4 => 'b = National bank code c = Account number x = Check digit',
),
'CH' =>
array (
0 => 'Switzerland',
1 => '21',
2 => '5n,12c',
3 => 'CHkk bbbb bccc cccc cccc c',
4 => 'b = National bank code c = Account number',
),
'TN' =>
array (
0 => 'Tunisia',
1 => '24',
2 => '20n',
3 => 'TNkk bbss sccc cccc cccc cccc',
4 => 'b = National bank code s = Branch code c = Account number',
),
'TR' =>
array (
0 => 'Turkey',
1 => '26',
2 => '5n,17c',
3 => 'TRkk bbbb bxcc cccc cccc cccc cc',
4 => 'b = National bank code x = Reserved for future use (currently "0") c = Account number',
),
'AE' =>
array (
0 => 'United Arab Emirates',
1 => '23',
2 => '3n,16n',
3 => 'AEkk bbbc cccc cccc cccc ccc',
4 => 'b = National bank code c = Account number',
),
'GB' =>
array (
0 => 'United Kingdom[Note 7]',
1 => '22',
2 => '4a,14n',
3 => 'GBkk bbbb ssss sscc cccc cc',
4 => 'b = BIC bank code s = Bank and branch code (sort code) c = Account number',
),
'VG' =>
array (
0 => 'Virgin Islands, British',
1 => '24',
2 => '4c,16n',
3 => 'VGkk bbbb cccc cccc cccc cccc',
4 => 'b = National bank code c = Account number',
)
);
/**#@-*/
function __construct($campo,$valore='',$classe='') {
parent::myText($campo,$valore,$classe);
if(!$this->stato_def) $this->set_stato('IT');
}
function set_value($v){
$this->set_stato($v);
if(!$this->stato_def) $this->set_stato('IT');
return parent::set_value(str_replace(' ','',strtoupper($v)));
}
function get_html(){
if(!$this->stato_def) $this->set_stato('IT');
$this->add_myJQuery(new myJQMask("#{$this->get_id()}"))->set_mask($this->stato_def[7]);
foreach (self::$internationals as $k=>$v) $masks["'$k'"]=$v[7];
$jq=new myJQuery("#{$this->get_id()}");
$jq->add_common_code('myIBAN_FIELDS={};myIBAN_MASKS='.myJQuery::encode_array($masks,'{}'),'myIBAN');
$jq->add_code("{$jq->JQid()}.keyup(function(event)
{var stato=this.value.substr(0,2).toUpperCase();
if(myIBAN_MASKS[stato]!==undefined &&
myIBAN_FIELDS['{$this->get_id()}']!=stato
){myIBAN_FIELDS['{$this->get_id()}']=stato;
var mask=myIBAN_MASKS[stato];
var value=this.value.toUpperCase().replace(/[ _]+/g,'');
this.value='';
this.size=mask.length+1;
this.maxlength=mask.length;
{$jq->JQid()}.unmask();
{$jq->JQid()}.mask(mask);
for (var j=0;jJQid()}.trigger(press);
}
}
}
)");
$jq->add_code("myIBAN_FIELDS['{$this->get_id()}']='{$this->stato_def[5]}'");
return parent::get_html().$jq;
}
/**
* Restituisce l'ABI contenuto nel IBAN (ha senso solo per iBAN italiano)
* @return string
*/
function get_ABI(){
return substr($this->get_value(),5,5);
}
/**
* Restituisce il CAB contenuto nel IBAN (ha senso solo per iBAN italiano)
* @return string
*/
function get_CAB(){
return substr($this->get_value(),10,5);
}
/**
* Restituisce il CIN contenuto nel IBAN
* @return string
*/
function get_CIN(){
return substr($this->get_value(),4,1);
}
/**
* Restituisce il CC contenuto nel IBAN
* @return string
*/
function get_CC(){
return substr($this->get_value(),15,12);
}
/**
* Restituisce sigla Nazione contenuto nel IBAN
* @return string
*/
function get_nazione(){
return substr($this->get_value(),0,2);
}
/**
* Permette di rendere il check_errore più o meno restrittivo
*
* @param boolean $verifica //verifica calcolo cin
*/
function set_restrizioni_check($verifica=true){
$this->restrizioni_check=$verifica;
return $this;
}
function get_errore_diviso() {
if ($errore=parent::get_errore_diviso()) return $errore;
$valore=strtoupper($this->get_value());
if ($valore && $this->restrizioni_check && !$this->check_validita()) return "formalmente errato";
}
/**
* Imposta lo stato di default per l'Iban
* se ammissibile resituisce true altrimenti false
* @param string $stato codice di due caratteri
* @param boolean $forza lo stato non può essere cambiato dall'utente
* @return boolean
*/
function set_stato($stato,$forza=false){
/* 'IT' =>
array (
0 => 'Italy',
1 => '27',
2 => '1a,10n,12c',
3 => 'ITkk xaaa aabb bbbc cccc cccc ccc',
4 => 'x = Check char (CIN) a = National bank code (it:Associazione bancaria italiana or Codice ABI ) b = Branch code (it:Coordinate bancarie or CAB - Codice d\'Avviamento Bancario) c = Account number',
5 => 'IT',
6 => regExp
7 => JQmask
)
*/
self::rebuild_internationals();
$stato=substr(strtoupper($stato),0,2);
if(!self::$internationals[$stato]) return false;
$this->stato_def=self::$internationals[$stato];
if($forza) {
$this->stato_def[6]=preg_replace('/^\[A-Z\]\{2\}/',$stato,$this->stato_def[6]);
$this->stato_def[7]=preg_replace('/^aa/',$stato,$this->stato_def[7]);
}
$this->set_minlength($this->stato_def[1])
->set_maxlength($this->stato_def[1],strlen($this->stato_def[7])+1)
->set_regexp("^{$this->stato_def[6]}\$")
->set_maimin('Maiuscolo')
->set_xml_facoltativo();
return true;
}
/**
* @ignore
*/
private static function rebuild_internationals() {
/* 'IT' =>
array (
0 => 'Italy',
1 => '27',
2 => '1a,10n,12c',
3 => 'ITkk xaaa aabb bbbc cccc cccc ccc',
4 => 'x = Check char (CIN) a = National bank code (it:Associazione bancaria italiana or Codice ABI ) b = Branch code (it:Coordinate bancarie or CAB - Codice d\'Avviamento Bancario) c = Account number',
)
*/
if(self::$internationals['IT'][5]=='IT') return;
foreach (self::$internationals as $stato=>&$componente) {
$parti=explode(',',trim($componente[2]));
$preg="[A-Z]{2}[0-9]{2}";
$mask="aa99";
foreach ($parti as $parte)
{$lung_parte=(int) $parte;
switch ($parte{strlen($parte)-1}) {
case 'a':
$preg.="[A-Za-z]{{$lung_parte}}";
$mask.=str_repeat('a', $lung_parte);
break;
case 'c':
$preg.="[0-9A-Za-z]{{$lung_parte}}";
$mask.=str_repeat('*', $lung_parte);
break;
case 'n':
$preg.="[0-9]{{$lung_parte}}";
$mask.=str_repeat('9', $lung_parte);
break;
}
}
$componente[5]=$stato;
$componente[6]=$preg;
$j=0;
for ($i=0;$istato_def) $this->set_stato('IT');
if(!isset(self::$internationals[$this->get_nazione()])) return false;
// echo $this->get_CIN(),' != ',self::contrcin($this->get_ABI().$this->get_CAB().$this->get_cc());
if ($this->get_nazione()=='IT' && $this->get_CIN() != self::contrcin($this->get_ABI().$this->get_CAB().$this->get_cc())) return false;
$cc1 = substr($this->get_value(),4).$this->get_nazione()."00";
$iban2="";
$tabella63="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for($iban1=0;$iban1get_value(),2,2);
if ($iban2 != substr($this->get_value(),2,2)) return false;
return true;
}
/**
* @ignore
*/
private static function contrcin($cc)
{
$aa="A0B1C2D3E4F5G6H7I8J9K#L#M#N#O#P#Q#R#S#T#U#V#W#X#Y#Z#-#.# #";
$bb="B1A0K#P#L#C2Q#D3R#E4V#O#S#F5T#G6U#H7M#I8N#J9W#Z#Y#X# #-#.#";
$dd=0;
for($ii=1;$ii<22;$ii+=2)$dd=$dd+floor(strpos($aa,$cc{$ii})/2);
for($ii=0;$ii<22;$ii+=2)$dd=$dd+floor(strpos($bb,$cc{$ii})/2);
$dd=$dd-(floor($dd/26)*26);
return $aa{$dd*2};
}
}
/**#@+
* @ignore
* serve a fermare l'indicizzazione del myAutoloader cha altrimenti caricherebbe le due include_once
* in fondo alla myTree
**/
class myClasseInutileMaiIstanziata {}
include_once(dirname(__FILE__).'/myDeprecated/myFields.php');
include_once(dirname(__FILE__).'/myExtras/myFieldsItaly.php');
/**#@-*/
?>