null,'case'=>'','header'=>''); function __destruct() { IF(self::$dipendenza_campi['daClonare'] && self::$dipendenza_campi['daClonare']->get_id_istanza()==$this->id_istance) { unset(self::$dipendenza_campi['js_dipendenze_campo']['allFunc'][$this->id_istance]); unset(self::$dipendenza_campi['relazioni'][$this->id_istance]); unset(self::$dipendenza_campi['info'][$this->id_istance]); } self::$dipendenza_campi['daClonare']=false; } function onClose(){} function onStart(){} function onAddedField(){ } function set_no_html(){ $this->__destruct(); } public function offsetSet($offset, $value) { $this->add_campo($value,$offset); } public function offsetExists($offset) { return is_object($this->get_campo($offset)); } public function offsetUnset($offset) { $this->unset_campo($offset); } public function offsetGet($offset) { return $this->get_campo($offset); } public function set_myMultiform($myMultiForm) { if (!$myMultiForm) $this->myMultiForm=null; else $this->myMultiForm=$myMultiForm; } function onUserError($error) { foreach ($this->eventManager as &$mng) $mng->onUserError($error,$this); } function onInternalError($error) { foreach ($this->eventManager as &$mng) $mng->onInternalError($error,$this); } /**#@-*/ /** * * Imposta un eventManager EventManager * @throws Exception se $mng non ha metodi pubblici onUserError e onInternalError * @param EventManager $mng */ function add_myEventManager(myEventManager $mng,$propaga=true){ if(!method_exists($mng, 'onUserError') && !method_exists($mng, 'onInternalError') ) throw new Exception("set_EventManager deve passare un'istanza di EventManager o sottoclasse che abbia i metodi pubblici onUserError e onInternalError"); $this->eventManager[]=$mng; } function set_gruppo_campi($testo, $dal_campo, $al_campo=''){ foreach ($this->get_campi() as $campo) { if($campo===$dal_campo) $attivo=true; if($attivo) { self::$Gruppi[spl_object_hash($campo)]=array('titolo'=>$testo,'tipo'=>($campo===$dal_campo?'I':($campo===$al_campo?'F':'X'))); } if($campo===$al_campo) break; } return $this; } /** * Costruttore di classe */ function myForm() { if(!$this->id_istance) { parent::__construct(); $f=new myField(''); $this->myForms=&$f->myFields['myForms']; $this->id_istance=$f->get_id_istanza(); if (!isset($this->myForms['usafile'])) $this->myForms['usafile']=true; $this->mostra_label=true; } } function get_id_istanza(){ return $this->id_istance; } /** @ignore */ function __toString(){ return $this->get_html(); } /** @ignore */ function __call($metodo,$pars){ foreach ($this->campi as &$campo) if (method_exists($campo,$metodo)) call_user_func_array(array($campo, $metodo),$pars); } /** @ignore */ function AbsPath(){ MyField::AbsPath(); } /** 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='') { MyField::setAbsPath($PathSito,$myFormsPath); } /** * Aggiunge un porefisso al nome dei CAMPI (IN PRATICA INFLUISCE SULL'ATTRIBUTO NAME DELL'HTML) * @param string $prefisso * @param boolean $applica se true si applica altrimenti si rimmuove */ function set_prefisso_nomi_campi($prefisso,$applica=true){ if($applica) { $this->prefisso=$prefisso.$this->prefisso; foreach ($this->get_campi() as $id=>$campo) $campo->set_name($prefisso.$campo->get_name(),false); } else { $this->prefisso=preg_replace("/^$prefisso/S",'',$this->prefisso); foreach ($this->get_campi() as $id=>$campo) { $nome=$campo->get_name(); $campo->set_name(preg_replace("/^$prefisso/S",'',$nome),false); } } return $this; } /** * Porta a minuscolo cosa e le prime lettere maiuscole * @param string $cosa */ function Minuscolo ($cosa) { $v=explode("_",trim($cosa)); $x=''; for ($i=0; $iget_myFormContainer()) || in_array(spl_object_hash($next),$fatti)) return $cur; $cur=$next; } while (true); } /** * Restituisce il puntatore all'eventuale multiform nel quale è contenuta la myForm * * @return myMultiform_DB */ public function get_myFormContainer() { return $this->myMultiForm; } /** * @ignore */ public function get_id_in_myFormContainer() { foreach ($this->myMultiForm->get_forms() as $id=>$form) if ($form==$this) return $id; ; } /** * Setta le classi css da usare nel form * @param string $classe_label Classe da usare per la Label del campo * @param string $classe_valori Classe da usare nella casella in cui va il campo * @param string $classe_campi Classe da usare per i campi */ function set_classi ($classe_label='',$classe_valori='',$classe_campi='') { if ($classe_campi) if ($this->campi) foreach ($this->campi AS $id=>$val) $this->campi[$id]->set_attributo('class',$classe_campi);; if ($classe_label) $this->classe_label=$classe_label; if ($classe_valori) $this->classe_valori=$classe_valori; return $this; } /** * Inserisce eventuale html aggiuntivo per la colonna delle labels e dei valori es: align='right' * si tratta di soli parametri * * @param string $extra_html_label Attributi da usare la colonna delle Label * @param string $extra_html_valori Attributi da usare per la colonna del campo * */ function set_extra_html_colonne ($extra_html_label='',$extra_html_valori='') { $this->extra_html_label=$extra_html_label; $this->extra_html_valori=$extra_html_valori; return $this; } /** * Restituisce IL RIFERIMENTO ad un campo del form va quindi usato preceduto da & * @param string|int $quale_campo Restituisce l'oggetto corrispondente ad un campo (Maiuscolo) se è un numero da il campo corrispettivo al numero d'ordine, * 1=>il primo 2=>il secondo ... 0=>l'ultimo * @return MyObject */ function &get_campo($quale_campo) { if(is_int($quale_campo)) { $k=$this->ordine; if($quale_campo===0) $quale_campo=$k[count($k)-1]; else $quale_campo=$k[$quale_campo-1]; } return $this->campo($quale_campo); } /** * Alias di get_campo Restituisce IL RIFERIMENTO ad un campo del form va quindi usato preceduto da & * @param string $nome_campo Restituisce l'oggetto corrispondente ad un campo (Maiuscolo) * @return MyObject */ function &campo($nome_campo) { if (isset($this->campi[$nome_campo]) && is_object($this->campi[$nome_campo])) return $this->campi[$nome_campo]; elseif (isset($this->campi[$nome_campo=strtoupper($nome_campo)]) && is_object($this->campi[$nome_campo])) return $this->campi[strtoupper($nome_campo)]; elseif($this->debug) echo "
Errore myForms: in metodo campo('$nome_campo')/get_campo('$nome_campo') non è un campo della form
"; } /** * Restituisce IL RIFERIMENTO all'array con tutti i campi del form istanziati va quindi usato preceduto da & * @deprecated * @param boolean $caseOriginale case delle chiavi se false tutto maiuscolo altrimenti risponde a quello usato nell'add_campo/analizza_tabella * @return array */ function &get_campi($caseOriginale=false) { if(!$caseOriginale) return $this->campi; $new=array(); foreach ($this->campi as $k=>&$v) $new[$this->colonneOriginali[$k]]=&$this->campi[$k]; return $new; } /** Aggiunge un campo al form * @param MyObject $campo Campo da aggiungere * @param string $label Label da associare al campo * @param boolean $indirizzo Se true il passaggio della variabile $campo avviene per indirizzo ed il campo aggiunto rimane collegato a quello esterno * @param string $dopo Nome del campo dopo il quale campo posizionare il campo aggiunto se omesso si aggiunge in coda se null si mette in testa */ function &add_campo(&$campo,$label='',$indirizzo=false,$dopo='') { self::MyForm(); if (!$this->campi) $this->campi=array(); if ($this->debug && (!is_object($campo) )) { echo "
Errore myForms: è stato usato un add_campo('$campo','$label') ma il campo aggiunto non è un myfield"; } if (!$indirizzo) { $old_campo=&$campo; if(method_exists($campo,'clonami')) $campo=$campo->clonami(); else $campo=clone $campo; foreach ($old_campo->get_myJQueries() as $k=>$mJQ) $campo->add_myJQuery($mJQ); } $nome_campo=$campo->get_name(); $this->colonneOriginali[strtoupper($nome_campo)]=$nome_campo; $nome_campo=strtoupper($nome_campo); if ($dopo==='' || !$this->campi) {$this->campi[$nome_campo]=$campo; $this->ordine[]=$nome_campo; } elseif ($dopo===null) {$this->campi=array_merge(array($nome_campo=>&$campo),(array) $this->campi); $this->ordine=array_keys($this->campi); } else { $nuovo=array(); $nuovo_ordine=array(); if (!$this->ordine) $this->ordine=array_keys($this->campi); foreach ($this->ordine as $id) { $nuovo[$id]=&$this->campi[$id]; if (strtoupper($id)==strtoupper($dopo)) $nuovo[$nome_campo]=$campo; } $this->campi=& $nuovo; $this->ordine=array_keys($this->campi); } if ($label) $this->labels[strtoupper($nome_campo)]=$label; else $this->labels[strtoupper($nome_campo)]=$this->Minuscolo($nome_campo); //if($nome_campo=='OSPITE') print_r($this->campi[$nome_campo]); if(method_exists($this->campi[$nome_campo],'onAddedField')) $this->campi[$nome_campo]->onAddedField(); if($this->secure && method_exists($this->campi[$nome_campo],'set_secure')) $this->campi[$nome_campo]->set_secure($this->secure); return $this->campi[$nome_campo]; } /** Elimina un campo al form * @param string $nome_campo nome del campo (Maiuscolo) */ function unset_campo($nome_campo) { unset($this->campi[strtoupper($nome_campo)]); unset($this->labels[strtoupper($nome_campo)]); $this->ordine=array_keys($this->campi); return $this; } /** Associa label a campo/i * @param string|array $nome_campo nome del campo (Maiuscolo), se è un array deve essere un array associativo campi=>Labels * @param string $label Label da associare al campo */ function set_label($nome_campo,$label='') { if (is_array($nome_campo)) foreach ($nome_campo as $id=>$val) $this->labels[strtoupper($id)]=$val; else $this->labels[strtoupper($nome_campo)]=$label; return $this; } /** Imposta l'autotab nei campi ove possibile */ function set_autotab() { $this->autotab=true; return $this; } /** Restituisce la/e label/s del/i campo/i * @param string|array $nome_campo nome del campo, se è un array è l'elenco delle labels * @return string|array $label Label associate al/ai campo/i */ function get_label($nome_campo) { $labels=array_change_key_case($this->labels,CASE_UPPER); if (is_array($nome_campo)) {foreach ($nome_campo as $id) $lbl[strtoupper($id)]=$this->trasl($labels[strtoupper($id)]); return $lbl; } else return $this->trasl($labels[strtoupper($nome_campo)]); } /** Restituisce l'ordine di visualizzazione dei campi * @return array */ function get_ordine() { if (!$this->ordine) $this->ordine=array_keys($this->campi); return $this->ordine; } /** Setta l'ordine di visualizzazione dei campi * @param array $ordine Rappresenta l'ordine di visualizzazione dei campi, $ordine non è associativo e se mancano dei campi, non vengono visualizzati ma restano nel form e se ne tiene conto altrove */ function set_ordine($ordine) { $this->ordine=$this->array_maiuscolo($ordine); return $this; } /** Setta i valori ai campi * @param array $valori Array associativo es $_POST o $_GET * @package boolean $intersezione se true setta solo i campi della form aventi chiave in $valori * altrimenti ricopre tutti i campi con i valori della form con il relativo valore di $valori, se assente lo setta a nulll */ function set_values($valori,$intersezione=false) { if (!$this->campi) return $this; if (!$intersezione) {foreach ($this->campi AS $id=>$val) if (is_object($this->campi[$id])) { //setta il valore e basta //ECHO $this->campi[$id]->get_name(),'=>',$valori[$this->campi[$id]->get_name()],'
'; /*if($this->prefisso && isset($valori[preg_replace("/^{$this->prefisso}/",'',$this->campi[$id]->get_name())])) $this->campi[$id]->set_value($valori[preg_replace("/^{$this->prefisso}/",'',$this->campi[$id]->get_name())]); else */ $this->campi[$id]->set_value($valori[$this->campi[$id]->get_name()]); } } else {foreach ($valori as $id=>&$v) { if (is_object($this->get_campo($id))) //setta solo i valori passati in valori $this->get_campo($id)->set_value($v); } } return $this; } /** * Imposta una dipendenza tra campi * * @param string $campo nome del campo * @param string $relazione espressione di confronto per la verifica della dipendenza * @param mixed $js se false verificva solo in check_errore la dipendenza, se true genera uno js * @param disabled|hidden $modo indica se i campi incongruenti sono da disabilitare o nascondere */ function set_dipendenza_campo($campo,$relazione,$js=true,$modo='disabled') { self::myForm(); $relazione=str_replace(array("\r","\n","\t"),array('',' ',''),$relazione); do {$relazione=str_replace(array("-> "," ->"),array("->","->"),$relazione,$sost);} while ($sost); //$relazioni=preg_replace('/([a-z_0-9]+(->[a-z_0-9]+)?)/i',' $1 ',trim($relazioni)); //do {$relazioni=str_replace(" "," ",$relazioni,$sost);} while ($sost); $relazione=trim($relazione); foreach (explode('§',$relazione) as $i=>$token) { $token=trim($token); if(!$token) continue; if(($i==0 && $relazione{0}!='§') ||!preg_match('/^([a-z_0-9]+(->[a-z_0-9]+)?)/iSs',$token,$m)) $relazioni[]=$token; else{$resto=substr($token,strlen($m[1])); $token=$m[1]; $tok=explode('->',$token); if (count($tok)>=2 && is_object($this->get_myFormRootContainer())) { $form="\$this->get_myFormRootContainer()"; for($i=0;$imyMultiForm)) {$form="\$this->myMultiForm->get_form('$tok[0]')"; $tok[0]=$tok[1]; }*/ else{ $form="\$this"; if($tok[1]) $tok[0]=$tok[1]; } $cls=new stdClass(); $cls->token=$token; $cls->form=$form; $cls->campo=$tok[0]; $relazioni[]=$cls; $relazioni[]=$resto; } } static $id; ++$id; self::$dipendenza_campi['relazioni'][$this->id_istance][strtoupper($campo)][$id]=$relazioni; self::$dipendenza_campi['info'][$this->id_istance][strtoupper($campo)][$id]=array('js'=>$js,'modo'=>$modo); return $this; } /** * @ignore */ protected function check_dipendenze_campo($campo) { if (!self::$dipendenza_campi['relazioni'] || !self::$dipendenza_campi['relazioni'][$this->id_istance] ) return; foreach (self::$dipendenza_campi['relazioni'][$this->get_id_istanza()] as $dip) if($dip[strtoupper($campo)]) foreach ($dip[strtoupper($campo)] as $relazione) {$labels=array(); if(!$this->campo($campo)->get_notnull() && !$this->campo($campo)->get_value()) continue; //echo $campo,'=>',$this->campo($campo)->get_value(); $scheletroExpr=''; foreach ($relazione as $cond) if(!is_object($cond)) $scheletroExpr.=trim($cond); foreach ($relazione as $j=>&$cond) if(is_object($cond)) {eval($f="\$form={$cond->form};"); echo $f,'
'; if (is_object($form)) eval($f="\$obj=\$form->campo('{$cond->campo}');"); echo $f,'
'; if(!is_object($obj)) $cond=$cond->token; else { eval("\$labels['strtoupper({$cond->campo})']=trim(\"'\".{$cond->form}->get_label('{$cond->campo}').\"'\");"); eval("\$cond_{$j}=\$this->campo_valorizzato(\$obj,\$scheletroExpr);"); $cond="\$cond_{$j}"; //echo $cond,'=>',$$cond,'
'; } } $cerr=error_reporting(0); // echo $cond_0,'
'; eval($expr="\$espressione=(".implode("",$relazione).");"); // echo $expr,'
'; error_reporting($cerr); if(!$espressione) return $this->trasl(" è incongruente rispetto a: ".str_replace(',,',',',implode(',',$labels))); } } /** * @ignore * @param int $id_ist id_istanza del campo dipendente * @return multitype */ protected function &get_dipendenze_campi($id_ist) { $dipendenza=array(); $istanze=array_keys((array) self::$dipendenza_campi['relazioni']); foreach ($istanze as $id_istanza) if($id_ist==$id_istanza) foreach (self::$dipendenza_campi['relazioni'][$id_istanza] as $campo=>&$relazioni) foreach ($relazioni as $idr=>$relazione) { $newrel=array(); foreach ($relazione as $cond) if(!is_object($cond)) $newrel[]=$cond; else{eval("\$form={$cond->form};"); if (is_object($form)) eval("\$obj=\$form->campo('{$cond->campo}');"); if(!is_object($obj)) $newrel[]=$cond->token; else $newrel[]=$obj; } $dipendenze[strtoupper($campo)][$idr]=$newrel; } return $dipendenze; /* $dipendenza=array(); if(self::$dipendenza_campi) foreach (self::$dipendenza_campi as $id_istanza=>$Relazioni) foreach ($relazioni['relazioni'] as $campo=>$relazioni) { foreach ($relazioni as $relazione) { $newrel=array(); foreach ($relazione as $cond) if(!is_object($cond)) $newrel[]=$cond; else{eval("\$form={$cond->form};"); if (is_object($form)) eval("\$obj=\$form->campo('{$cond->campo}');"); if(!is_object($obj)) $newrel[]=$cond->token; else $newrel[]=$obj; } } $dipendenze[strtoupper($campo)][]=$newrel; } return $dipendenze; */ } /** * @ignore */ function campo_valorizzato($campo,$expr) { $expr=trim($expr); if (!$campo) return false; if(!$expr) { if (method_exists($campo,'get_checked')) return ($campo->get_checked()?true:false); $val=$campo->get_value(); if(is_array($val) && count($val)>0) $val=true; return ($val || !$campo->get_notnull()?true:false); } else{ if (method_exists($campo,'get_checked')) return ($campo->get_checked()?true:false); if ($campo->is_numeric()) return floatval($campo->get_value()); if ($campo instanceof MyDate) return $campo->get_formatted(); return $campo->get_value(); } } /** Setta il valore di un campo * @param string $campo * @param mixed $valore */ function set_value($campo,$valore) { if (isset($this->campi[$campo]) ) $this->campi[$campo]->set_value($valore); return $this; } /** Restituisce un array associativo con i valori dei campi * @param array $campi array con i nomi dei campi da estrapolare, se omesso si estraggono tutti * @param $label se true la chiave dell'array non è il nome ma la label associata * @param $name se true la chiave dell'array non è il nome ma l'attributo name (se anche $label non è presa in considerazione) * @return array $valori */ function get_values($campi='',$label=false,$name=false) { if (!$campi) $campi=array_keys($this->campi); if (!$campi) return; $campi=array_flip($campi); if (is_array($this->campi)) foreach ($this->campi as $id=>$obj) if(isset($campi[$id]) && is_object($obj)) { if($label) $valori[$this->get_label($id)]=$obj->get_value(); elseif ($name) $valori[str_replace('[]','',$obj->get_name())]=$obj->get_value(); else $valori[$id]=$obj->get_value(); } return $valori; } /** Restituisce il valore del $nome_campo * @param string $nome_campo * @return mixed $valori */ function get_value($nome_campo='') { //if(!$nome_campo) return $this->get_values(); if ($this->campi[$nome_campo]) return $this->campi[$nome_campo]->get_value(); } /** Restituisce il valore del $nome_campo NEL FORMATO DB * @param string $nome_campo * @return mixed $valori */ function get_value_db($nome_campo) { return $this->campi[$nome_campo]->get_value_db(); } /** Imposta i tag che devono precedere e seguire ogni campo * @param String $tag è la sequenza di tag da usare; di default è . * Mettendo la stringa vuota tutti i campi del get_html saranno su un unica riga */ function set_pref_html_field($tag='tr') { $this->pref_html=$tag; return $this; } /** @ignore */ function array_maiuscolo($array){ if (!$array) return array(); else foreach ($array as $val) $nuovo[]=strtoupper($val); return $nuovo; } /** @ignore */ function creaTd($valore='',$classe='',$extra='',$td='td') { return "<$td $extra ".($classe?" class=\"$classe\">":'>')."$valore"; } /** @ignore */ function creaTable($valore='',$classe='',$extra='') { if(stripos(trim($valore), '":'>')."$valore"; } /** @ignore */ function _qualicampi($qualicampi='',$Esclusi=true) { if ($qualicampi) $qualicampi=array_flip($this->array_maiuscolo($qualicampi)); if (!$this->ordine) $this->ordine=array_keys($this->campi); $nomicampi=array(); foreach ($this->ordine as $campo) { if (!$qualicampi) $nomicampi[]=$campo; elseif(!$Esclusi) {if (isset($qualicampi[$campo])) $nomicampi[]=$campo;} elseif($Esclusi) {if (!isset($qualicampi[$campo])) $nomicampi[]=$campo;} } return $nomicampi; } /** Imposta lo showonly per tutti i campi ove possibile * @param string|array $qualicampi campi a cui applicare/non applicare (se omesso si applica a tutti indipendentemente da $Esclusi) * @param boolean $Esclusi se true o omesso $qualicampi sono esclusi dalla funzione se false si applica esclusivamente quelli */ function set_showonly($qualicampi='',$Esclusi=true) { if(!is_array($qualicampi)) $qualicampi=array($qualicampi); foreach ($this->_qualicampi($qualicampi,$Esclusi) as $campo) if (is_object($this->campi[$campo]) && method_exists($this->campi[$campo],"set_showonly")) $this->campi[$campo]->set_showonly(); return $this; } /** * Il campo viene trasformato in myHidden anche dopo l'istanziazione * es. * * $f=new myForm(); * $f->add_campo(new myText('testo1','testo 1')); * $f->add_campo(new myText('testo2','testo 2')); * * echo $f->get_html_completo(); * echo '
'; * $f->set_hidden('testo1'); * echo $f->get_html_completo(); *
* * @param string|array $qualicampi campi a cui applicare/non applicare (se omesso si applica a tutti indipendentemente da $Esclusi) * @param boolean $Esclusi se true o omesso $qualicampi sono esclusi dalla funzione se false si applica esclusivamente quelli * @param array $campi_esclusi campi da non controllare */ function set_hidden($qualicampi='',$Esclusi=true) { if(!is_array($qualicampi)) $qualicampi=array($qualicampi); foreach ($this->_qualicampi($qualicampi,$Esclusi) as $campo) if (is_object($this->campi[$campo])){ $v=array_flip(get_class_methods(get_class($this->campi[$campo]))); if (isset($v["set_hidden"])) $this->campi[$campo]->set_hidden(); } return $this; } /** Disattiva lo showonly per tutti i campi ove possibile * @param array $qualicampi campi a cui applicare/non applicare (se omesso si applica a tutti indipendentemente da $Esclusi) * @param boolean $Esclusi se true o omesso $qualicampi sono esclusi dalla funzione se false si applica esclusivamente quelli */ function unset_showonly($qualicampi='',$Esclusi=true) { if(!is_array($qualicampi)) $qualicampi=array($qualicampi); foreach ($this->_qualicampi($qualicampi,$Esclusi) as $campo) if (is_object($this->campi[$campo]) && method_exists($this->campi[$campo],"set_showonly")) $this->campi[$campo]->unset_showonly(); return $this; } /** Effettua analisi di validità dei campi * @param array $qualicampi campi da controllare/non controllare (se omesso si applica a tutti indipendentemente da $Esclusi) * @param boolean $Esclusi se true o omesso $qualicampi sono esclusi dalla verifica se false si verificano esclusivamente quelli * @return string Messaggio di errore */ function Check_Errore($qualicampi='',$Esclusi=true,$testoLinkCampoErrato='') { $errore=$this->Check_Errore_Diviso($qualicampi,$Esclusi); if ($errore) { if (is_array($errore['label'])) $lbl=implode(',',$errore['label']); elseif($errore['campo']) { $js=""; if(!$this->JQDialog) $lbl=$errore['label'].$js; else $lbl=$errore['label']; } $out=strtr($errore['errore'],array('%label%'=>$lbl,'%errore%'=>$errore['errore_puro'])); if($testoLinkCampoErrato && $lbl && !$this->JQDialog) $out.=" get_attributo('id')."' title=\"{$this->trasl('Vai al campo')}\">$testoLinkCampoErrato"; $this->onUserError($out); if($this->JQDialog) { $this->JQDialog->set_html($out); return $this->JQDialog.$js; } return $out; } } /** * Imposta una lingua da usare (carica dizionario predefinito dalle myForms) * * @param string(2) $lingua codice lingua */ function set_lingua($lingua='en',$logErrori=false) { if (!$lingua) return ; $this->dizionario[0]=new myDizionario($lingua); $this->dizionario[0]->log_errori($logErrori); return $this; } /** * Aggiunge un dizionario alternativo (da usare solo dopo myForm::set_lingua) * @throws Exception se non usato dopo @see myForm::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 throw new Exception("add_dizionario solo dopo set_lingua"); return $this; } /** * * 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=null; foreach ($this->dizionario as &$dizionario) { $tradotto=$dizionario->trasl($messaggio,$parole,$esito); if ($esito && $tradotto) return $tradotto; } return $messaggio; } /** @ignore */ function &MyCacheDati($secondi,$nomeVariabile,$dati='') { static $cache; $autostore=myAutoSessions::get_Istanza('myForms'); if($secondi==-1) {if($cache[$nomeVariabile]) return $cache[$nomeVariabile]; return $cache[$nomeVariabile]=$autostore->get($nomeVariabile); } $cache[$nomeVariabile]=$dati; if($secondi) $autostore->set($nomeVariabile,$dati,true,$secondi); return $this; } /** * Applica la cifratura a tutti i campi nascosti (beta) * @param mySecurizer $secure * @return myForm */ function set_secure(mySecurizer $secure){ $this->secure=$secure; foreach ($this->campi as $campo) if(method_exists($campo,'set_secure')) $campo->set_secure($this->secure); return $this; } /** * Forza il check_errore a produrre l'errore indicato a prescindere dai parametri * @param string $errore Messaggio di errore non tradotto * @param user|internal $tipo tipo di errore * @param string $campo nome del campo (il nome che si userebbe in una get_campo) */ static function Forza_Errore($errore,$tipo='internal',$campo=''){ self::$erroreForzato=array('errore_puro'=>$errore, 'errore_tipo'=>$tipo, 'campo'=>$campo); } /** Effettua analisi di validità dei campi * @param array $qualicampi campi da controllare/non controllare (se omesso si applica a tutti indipendentemente da $Esclusi) * @param boolean $Esclusi se true o omesso $qualicampi sono esclusi dalla verifica se falo si verificano esclusivamente quelli * @return array Array associativo con label=>'Label del campo errato' errore=>'messaggio di errore' campo=>'nome del campo errato' */ function Check_Errore_Diviso($qualicampi='',$Esclusi=true) { if(self::$erroreForzato) {$campo=self::$erroreForzato['campo']; $errore=array('errore_forzato'=>1, 'errore_puro'=>self::$erroreForzato['errore_puro'], 'errore_tipo'=>self::$erroreForzato['errore_tipo'], 'errore'=>self::$erroreForzato['errore_puro'] ); if($this->campi[$campo]) {if(self::$Gruppi[spl_object_hash($this->campi[$campo])]) $prefisso=$this->trasl("Nella sezione '%1%'",array('%1%'=>self::$Gruppi[spl_object_hash($this->campi[$campo])]['titolo'])).' '; $errore=array('label'=>$this->get_label($campo), 'campo'=>$this->get_campo($campo), 'errore'=>ucfirst($prefisso.$this->trasl("il campo '%label%' %errore%")) ); if($prefisso) $errore['sezione']=self::$Gruppi[spl_object_hash($this->campi[$campo])]; } $this->ultimoErrore=$errore; $this->onInternalError($errore); return $errore; } foreach ($this->_qualicampi($qualicampi,$Esclusi) as $campo) IF (is_object($this->campi[$campo])) {if ($this->dizionario[0]) $this->campi[$campo]->set_lingua($this->dizionario[0]->get_al()); for ($d=1;$ddizionario);$d++) $this->campi[$campo]->add_dizionario($this->dizionario[$d],$d); $errore=$this->campi[$campo]->Errore(); if (!$errore) $errore=$this->check_dipendenze_campo($campo); IF ($errore) { if(self::$Gruppi[spl_object_hash($this->campi[$campo])]) $prefisso=$this->trasl("Nella sezione '%1%'",array('%1%'=>self::$Gruppi[spl_object_hash($this->campi[$campo])]['titolo'])).' '; $errore=array('label'=>$this->get_label($campo), 'errore'=>ucfirst($prefisso.$this->trasl("il campo '%label%' %errore%")), 'errore_puro'=>$errore, 'errore_forzato'=>0, 'errore_tipo'=>'user', 'campo'=>$this->get_campo($campo)); if($prefisso) $errore['sezione']=self::$Gruppi[spl_object_hash($this->campi[$campo])]; $this->ultimoErrore=$errore; $this->onUserError($errore); return $errore; } } } /** Imposta se visualizzare le labels * @param boolean $mostra_label */ function set_mostra_labels($mostra_label=true) { $this->mostra_label=$mostra_label; return $this; } /** * Definisce il tipo di classe nel metodo @see store * * @throws Eccezione generica se non ha entrambi i parametri validi * @param mySessions $container E' un'istanza di mySessions( o estensione) * @param string $chiave Chiave da usare per i dati durante la memorizzazione */ function set_store_params($container,$chiave){ if(!is_object($container) || !$chiave || !method_exists($container,'set') || !method_exists($container,'get') || !method_exists($container,'del')) throw new Exception("Parametri non validi in set_store_params()"); $this->stored=$container; $this->stored_key=$chiave; return $this; } /** * Memorizza i dati in una sessione * @see myForm::set_store_param() * */ function store_values() { if(!$this->stored) throw new Exception("prima di usare lo storing usare set_store_params"); $this->stored->set($this->stored_key,$this->get_values(),true); return $this; } /** * Annulla il contenuto memorizzato in sessione * @see myForm::stored_values() * */ function clean_stored_values(){ if(!$this->stored) throw new Exception("prima di usare lo storing usare set_store_params"); $this->stored->del($this->stored_key); return $this; } /** * Restituisce il contenuto memorizzato con @see stored_values * */ function get_stored_values(){ if(!$this->stored) throw new Exception("prima di usare lo storing usare set_store_params"); return $this->stored->get($this->stored_key); } /** * Ripristina nella form il contenuto memorizzato con @see stored_values * */ function restore_values() { if(!$this->stored) throw new Exception("prima di usare lo storing usare set_store_params"); $stored=$this->stored->get($this->stored_key); if($stored)$this->set_values($stored); return $this; } /** * Imposta l'oggetto myJQMyFormTabs da usare per la visualizzazione a tabs di JQuery * @param myJQMyFormTabs $JQ */ function set_myJQTab(myJQMyFormSezioni $JQ) { $this->JQTab=$JQ; return $this->JQTab; } /** * Imposta l'oggetto myJQMyFormDialof da usare per la visualizzazione a tabs di JQuery * @param myJQMyFormTabs $JQ */ function set_myJQDialogErrore(myJQMyFormDialog $JQ) { $this->JQDialog=$JQ; $JQ->set_form($this); return $this->JQDialog; } /** Restituisce l'html di una form completa di tage ed eventuali pulsanti * Es. * * $form=new MyForm(); //istanzio form * $form->add_campo(..); //aggiungo campi * ....... * $form->add_campo(..); * * * $pulsanti[0] = new MyPulsante('Salva',$_POST['Salva']); //creo un array con un pulsante per salvare * $pulsanti[1] = new MyPulsante('Elimina',$_POST['Elimina']); //aggiungo all'array un pulsante per eliminare * * echo $form->Get_html_Completo('','','method="post"','border="1"',$pulsanti); * * * @param array $campo_inizio Nome del campo da cui iniziare nella costruzione, se omesso si comincia dall'inizio * @param string $campo_fine Nome del campo da cui finire nella costruzione, se omesso si usa solo campo inizio, SE OMESSI ENTRAMBI SI USANO TUTTI I CAMPI * @param string $AttributiForm sono eventuali attributi del tag
(se omesso o false il tag non verrà inserito ne chiuso) * @param bool|string $AttributiTable sono eventuali attributi del tag table che contiene i campi (se omesso si inserisce ugualmente se flse non si mette il tag table) * @param array $Pulsanti array di MyPulsante * @return string */ function &Get_html_Completo($campo_inizio='',$campo_fine='',$AttributiForm='',$AttributiTable='',$Pulsanti=array()) { if (is_array($Pulsanti)) {foreach ($Pulsanti as $i=>$p) if (is_object($p)) $pulsanti[]=$p; } else $pulsanti=array(); if ($AttributiForm) { $AttributiForm=new myTag($AttributiForm); if (!$AttributiForm->get_attributo('method')) {$AttributiForm->set_attributo('method','get'); foreach ($this->get_campi() as $campo) { if ($campo->Estende('myUploadText',true)) {$AttributiForm->set_attributo('method','post'); $AttributiForm->set_attributo('enctype','multipart/form-data'); } } } if (!$AttributiForm->get_attributo('action')) $AttributiForm->set_attributo('action',$_SERVER['PHP_SELF'].($_SERVER['QUERY_STRING']?'?'.htmlentities($_SERVER['QUERY_STRING']):'')); else {$action=$AttributiForm->get_attributo('action'); if (stripos($action,'&')!==false && stripos($action,'&')===false) $AttributiForm->set_attributo('action',str_replace('&','&',$action)); } $AttributiForm=$AttributiForm->get_html(); } if ($this->muovi_lables<2) { $x=$this->Get_html($campo_inizio,$campo_fine); if(stripos($x,'pref_html=='tr'?" extra_html_label}>extra_html_valori}> ":'').$x; } else{ $ordine=$this->ordine; if(!$ordine) $ordine=$this->colonne; foreach ($this->campi as $nome_campo=>$campo) if($campo->get_MyType()!='MyHidden' && in_array(strtoupper($nome_campo),$ordine)) { $si_label=$this->get_label($nome_campo); if ($si_label) {$x.=$this->creaTd($si_label,($this->classe_label?array('class'=>$this->classe_label):''),$this->extra_html_label.' scope="col" id="th_'.$nome_campo.'" ','th'); $colgroup.=""; } } if($this->pref_html=='tr' && $AttributiTable!==false) $x="$colgroup$x"; $x=(new MyTag($this->pref_html,($this->classe_label?array('class'=>$this->classe_label):''),$x)).$this->Get_html($campo_inizio,$campo_fine); } if($AttributiTable!==false) $x=$this->creaTable($x,'',$AttributiTable); if($this->JQTab) $x=$this->get_elaborazione_myJQ($x); if ($pulsanti) { foreach ($pulsanti as $pls) $pulsantiera.=$this->creatd($pls->get_html(),""," style='width:".(100/count($pulsanti))."%;text-align:center'"); $x.=(new MyTag($this->pref_html,'', $this->creaTd( $this->creaTable(new MyTag($this->pref_html,'',$pulsantiera),'',' style="width:100%;border:0px"'), '','colspan="2"') ) ); } if ($AttributiForm) $x="$x"; if(!$this->get_myFormContainer() && $this->myForms['DipendenzeCalls']) $x.=""; return $x; } /** * Se si sono aggiunti elementi myJQuery attraverso il metodo @see set_myJQtabs() * e non si usa get_html_completo, passare l'html costruito usando @see get_html() * a questo metodo prima di visualizzarlo; se non si è usato almento get_html() non si avranno effetti JQ automatici * @param string $html */ function get_elaborazione_myJQ($html) { if($this->JQTab) { $J=0; foreach (self::$Gruppi as $i=>$sez) if($sez['titolo']) $titoli[$sez['titolo']]=1; $titoli=array_flip(array_keys($titoli)); $this->JQTab->add_items($titoli); $this->JQTab->set_content($html); if($this->ultimoErrore['sezione']) $this->JQTab->set_selected($titoli[$this->ultimoErrore['sezione']['titolo']]); $html=$this->JQTab; } return $html; } /** * 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=false){ $this->facoltativoXML=$facoltativo; return $this; } /** * Salva l'xml della form * * @param string $nomeFile percorso del file in cui salvare * @param string $tag è il tag che deve racchiudere la form se omesso viene messo il nome della classe * @param char $case se omesso si rispetta il case originale dei campi (o del DB) , U= maiuscolo L=minuscolo * @param string $header header dell'XML, se false non si mette se nullo si inserisce xml version="1.0" encoding="UTF-8" * @param array|string $campo_inizio Nome del campo da cui iniziare nella costruzione, se omesso si comincia dall'inizio oppure è l'array con i nomi dei campi da usare (in questo caso il secondo parametro non viene usato) * @param string $campo_fine Nome del campo da cui finire nella costruzione, se omesso si usa solo campo inizio, SE OMESSI ENTRAMBI SI USANO TUTTI I CAMPI * @return string */ function salva_xml($nomeFile,$tag='',$case='',$header='',$campo_inizio='',$campo_fine='') { if(!$tag) $tag=get_class($this); $xml=$this->Get_xml($tag,$case,$header,$campo_inizio,$campo_fine); $scritto=@file_put_contents($nomeFile,$xml,LOCK_EX); if ($scritto!=strlen($xml)) @unlink($nomeFile); return $scritto==strlen($xml); } /** * Carica dati da xml, se si passa un nome di file lo carica da li , se si passa l'xml usa quello i due parametri si escludono, se valorizzati entrambi si usa solo il nomefile * * @param string $nomeFile nome del file contenente xml * @param string $xml xml passato * @return void */ function load_xml($nomeFile='',$xml='') { if ($nomeFile) $xml=@simplexml_load_file(realpath($nomeFile),NULL, LIBXML_NOBLANKS|LIBXML_NOCDATA); else $xml=@simplexml_load_string($xml,NULL, LIBXML_NOBLANKS|LIBXML_NOCDATA); if(!$xml) return false; foreach ($xml as $elemento=>$v) {if(!is_object($this->campo($elemento))) continue; $valori=array(); foreach ($v as $valore) $valori[]=utf8_decode((string)$valore); if(!count($valori)) $valori[]=utf8_decode((string) $v); if ($this->campo($elemento)->estende('mymulticheck',true)) $this->campo($elemento)->set_value($valori); else $this->campo($elemento)->set_value($valori[0]); } return true; } /** * Imposta i valori di default per i parametrii @see get_xml * * @param string $tag è il tag che deve racchiudere la form se omesso non ci sarà * @param char $case se omesso si rispetta il case originale dei campi (o del DB) , U= maiuscolo L=minuscolo * @param string $header header dell'XML, se false non si mette se nullo si inserisce xml version="1.0" encoding="UTF-8" */ function set_parametri_xml($tag=null,$case='',$header=''){ if ($tag!==null) $this->xml['tag']=$tag; $this->xml['case']=$case; if ($header!=='') $this->xml['header']=$header; return $this; } /** * Restituisce l'xml della form * * @param string $tag è il tag che deve racchiudere la form se omesso non ci sarà * @param char $case se omesso si rispetta il case originale dei campi (o del DB) , U= maiuscolo L=minuscolo * @param string $header header dell'XML, se false non si mette se nullo si inserisce xml version="1.0" encoding="UTF-8" * @param array|string $campo_inizio Nome del campo da cui iniziare nella costruzione, se omesso si comincia dall'inizio oppure è l'array con i nomi dei campi da usare (in questo caso il secondo parametro non viene usato) * @param string $campo_fine Nome del campo da cui finire nella costruzione, se omesso si usa solo campo inizio, SE OMESSI ENTRAMBI SI USANO TUTTI I CAMPI * @return string */ function &Get_xml($tag=null,$case='',$header='',$campo_inizio='',$campo_fine='') { if ($tag===null) {$tag=$this->xml['tag']; if ($tag===null) $tag=get_class($this); } if (!$case) $case=$this->xml['case']; if ($header==='' && !isset($this->xml['header'])) $header=$this->xml['header']; if (!$this->ordine) $ordine=array_keys($this->campi); else $ordine=$this->ordine; if (is_array($campo_inizio)) {$ordine=$campo_inizio; $campo_inizio=$campo_fine=''; } $campo_inizio=strtoupper($campo_inizio); $campo_fine=strtoupper($campo_fine); $non_saltare=@func_get_arg(5); if ($campo_inizio && !$campo_fine) { if(is_object($obj=$this->get_campo($campo_inizio)) && ($non_saltare || !in_array(spl_object_hash($obj),self::$salta_get_xml))) { if(!$case) { $tag_obj=$obj->get_xml_tag(true); if(!$tag_obj['ridefinito']) $obj->set_parametri_xml($this->colonneOriginali[$campo_inizio]); } if($case=='U') $obj->set_parametri_xml($campo_inizio); if($case=='L') $obj->set_parametri_xml($campo_inizio); $xml=$obj->set_xml_facoltativo($this->facoltativoXML)->get_xml(); } } else {$Nascosti=''; $iniziato=false; $ordine=array_flip(array_change_key_case(array_flip($ordine),CASE_UPPER)); foreach ($ordine as $campo) if ($campo==$campo_inizio || $iniziato || !$campo_inizio) { $iniziato=true; if(!is_object($this->campo($campo)) || (!$non_saltare && in_array(spl_object_hash($obj),self::$salta_get_xml))) continue; if ($campo==$campo_fine) break; } $iniziato=false; foreach ($ordine as $campo) if ($campo==$campo_inizio || $iniziato || !$campo_inizio) {$obj=$this->get_campo($campo); if(!is_object($obj) || (!$non_saltare && in_array(spl_object_hash($obj),self::$salta_get_xml))) continue; if(!$case) { $tag_obj=$obj->get_xml_tag(true); if(!$tag_obj['ridefinito']) $obj->set_parametri_xml($this->colonneOriginali[$campo]); } if($case=='U') $obj->set_parametri_xml(strtoupper($campo)); if($case=='L') $obj->set_parametri_xml(strtolower($campo)); if($this->facoltativoXML && (method_exists($obj,'set_xml_facoltativo'))) $obj->set_xml_facoltativo($this->facoltativoXML); $xml.=$obj->get_xml(); $iniziato=true; if ($campo==$campo_fine) break; } } $xml=trim($xml); if($tag) { if($xml) $xml="<$tag>$xml"; elseif($this->facoltativoXML) return ''; else $xml="<$tag />"; } if($header===false) return $xml; if($header) return $header.$xml; return ''.$xml; } /** @ignore */ function htmlLabelCampo($campo,$Label=true,$prepost=false) { if (!$this->campo($campo)) return; if($prepost) $txtlabel=$this->pre_post_label[strtolower($campo)]['pre'].$this->get_label($campo).$this->pre_post_label[strtolower($campo)]['post']; else $txtlabel=$this->get_label($campo); if ($Label) return ''; else return ''.$txtlabel.''; } /** * I campi passati come parametri non verranno usati in @see get_html e @see get_html_completo * * @param string $campo .... * es * * $f->salta_get_html('nascondi1','nascondi2' ... ); * * */ function salta_get_html() { foreach (func_get_args() as $campo) if (is_object($this->campo($campo)) ) self::$salta_get_html[]=spl_object_hash($this->campo($campo)); } /** * I campi passati come parametri non verranno usati in @see get_xml * * @param string $campo .... * es * * $f->salta_get_xml('nascondi1','nascondi2' ... ); * * */ function salta_get_xml() { foreach (func_get_args() as $campo) if (is_object($this->campo($campo))) self::$salta_get_xml[]=spl_object_hash($this->campo($campo)); } /** * Imposta un un gruppo di campi @see myGroupFields * * @param myGroupFields $myGroupFields * @param string|boolean $dopo funzione in modo analogo ad @see add_campo */ function set_myGroupFields(myGroupFields $myGroupFields,$dopo='') { $myGroupFields->in_form($this); $this->add_campo($myGroupFields,$myGroupFields->get_label(),false,$dopo); return $myGroupFields; } /** Restituisce l'html dei campi sotto forma di senza tag di inizio e fine * * @param array|string $campo_inizio Nome del campo da cui iniziare nella costruzione, se omesso si comincia dall'inizio oppure è l'array con i nomi dei campi da usare (in questo caso il secondo parametro non viene usato) * @param string $campo_fine Nome del campo da cui finire nella costruzione, se omesso si usa solo campo inizio, SE OMESSI ENTRAMBI SI USANO TUTTI I CAMPI * @return string */ protected static function get_id_sezione($titolo){ return "mt_".str_replace('=','_',base64_encode($titolo)); } function &Get_html($campo_inizio='',$campo_fine='') { if (!$this->ordine) $ordine=$this->colonne; else $ordine=$this->ordine; if(!$ordine) $ordine=array_keys($this->campi); if (is_array($campo_inizio)) {$ordine=$campo_inizio; $campo_inizio=$campo_fine=''; } $campo_inizio=strtoupper($campo_inizio); $campo_fine=strtoupper($campo_fine); //html di un solo campo if ($campo_inizio && !$campo_fine) { if (in_array(spl_object_hash($this->campi[$campo_inizio]),self::$salta_get_html)) continue; if ($this->campi[$campo_inizio]->is_hidden()) return $this->Get_html_campo($campo_inizio); else { $X=''; $si_label=$this->Get_html_label($campo_inizio); if ($si_label && !$this->muovi_lables) { $X.=$this->creaTd($si_label,$this->classe_label,$this->extra_html_label); } $X.=$this->creaTd($Nascosti.$this->Get_html_campo($campo_inizio),$this->classe_valori,$this->extra_html_valori.(!$si_label?' colspan="2" ':'')); $Nascosti=''; if (!$this->orizzontale) $X=new MyTag($this->pref_html,array('id'=>"tr_{$this->campi[$campo_inizio]->get_id()}"),$X)."\n"; return (string) $X; } } else {$ordine=array_flip(array_change_key_case(array_flip($ordine),CASE_UPPER)); //crea parti di html dei campi nascosti $iniziato=false; $Nascosti=''; foreach ($ordine as $campo) if ($campo==$campo_inizio || $iniziato || !$campo_inizio) { if(!is_object($this->campi[$campo]) || in_array(spl_object_hash($this->campi[$campo]),self::$salta_get_html)) continue; if ($this->campi[$campo]->is_hidden()) $Nascosti.=$this->Get_html_campo($campo); else{$X=''; $si_label=$this->Get_html_label($campo); if ($si_label && !$this->muovi_lables && $this->mostra_label) { $X.=$this->creaTd($si_label,$this->classe_label,$this->extra_html_label); } $X.=$this->creaTd($this->Get_html_campo($campo),$this->classe_valori,$this->extra_html_valori.(!$si_label?' colspan="2" ':'')); if (!$this->orizzontale) $X=new MyTag($this->pref_html,array('id'=>"tr_{$this->campi[$campo]->get_id()}"),$X)."\n"; switch (self::$Gruppi[spl_object_hash($this->campi[$campo])]['tipo']) { case 'I': self::$Gruppi['content'][self::$Gruppi[spl_object_hash($this->campi[$campo])]['titolo']]= (!$this->JQTab?"
".self::$Gruppi[spl_object_hash($this->campi[$campo])]['titolo']."": " ") .($this->pref_html!='tr'? "<{$this->pref_html}>": "
extra_html_label}>extra_html_valori}>").$X; $X=''; break; case 'X': self::$Gruppi['content'][self::$Gruppi[spl_object_hash($this->campi[$campo])]['titolo']].=$X; $X=''; break; case 'F': $X=self::$Gruppi['content'][self::$Gruppi[spl_object_hash($this->campi[$campo])]['titolo']].$X. "pref_html=='tr'?'table':$this->pref_html).">" .(!$this->JQTab?"":''); if($this->JQTab) $X=$this->JQTab->get_panel(self::$Gruppi[spl_object_hash($this->campi[$campo])]['titolo'], $X); break; } $x.=$X; } $iniziato=true; if ($campo==$campo_fine) break; } if($Nascosti) { if (!$this->orizzontale) $x.="<{$this->pref_html} style=\"display:none;height:0px;margin:0px;border:0px;padding:0px\">\n"; $x.=$this->creaTd($Nascosti.'','',(!$this->orizzontale?' colspan="2" style="display:none;height:0px;margin:0px;border:0px;padding:0px" ':' style="display:none;height:0px;margin:0px;border:0px;padding:0px" ')); if (!$this->orizzontale) $x.="pref_html}>\n"; } if ($x && $this->orizzontale) $x=new MyTag($this->pref_html,array('class'=>$this->classe_valori),$x); return $x; } } /** * Imposta modalità di visualizzazione campi, vedere anche @see set_showLables * * @param boolean $orizzontale se true è orizzontale se false è verticale */ function set_orientamento($orizzontale=true) { $this->orizzontale=$orizzontale; return $this; } /** * Cambia l'impostazione di visualizzazioen delle labels vedere anche @see set_orientamento * * @param 0|1|2 $modalita 0=standard (davanti al campo), 1=nessuna,2= con get_html_completo diventa intestazione */ function set_showLables($modalita=0) { $this->muovi_lables=$modalita; return $this; } /** * @ignore */ static function getcast_js($cond) { if($cond instanceof myDate) $cast='date'; elseif($cond instanceof myTime || $cond instanceof myOra) $cast='hour'; elseif($cond->Estende('myFloat',true)) $cast="float,'$cond->get_separatore()'"; elseif($cond->Estende('myInt',true)) $cast='int'; elseif($cond->Estende('myRadio',true)) $cast='radio'; elseif($cond->Estende('myMulticheck',true)) $cast='multicheck'; elseif($cond->Estende('myCheck',true)) $cast='check'; else $cast=''; return $cast; } /** * @ignore */ protected function calcola_dipendenze() { if(!self::$dipendenza_campi['js_dipendenze_campo']['allFunc']) self::$dipendenza_campi['js_dipendenze_campo']=array('allFunc'=>array(),'funzioni'=>array(),'dipendenza'=>array()); $allFunc=&self::$dipendenza_campi['js_dipendenze_campo']['allFunc']; $funzioni=&self::$dipendenza_campi['js_dipendenze_campo']['funzioni']; $dipendenza=&self::$dipendenza_campi['js_dipendenze_campo']['dipendenza']; $field=new MyField(); //echo '
',$this->get_id_in_myFormContainer(),'=0>'; //estrae le dipendenze di questo $dipendenze=(array) $this->get_dipendenze_campi($this->id_istance); foreach ($dipendenze as $campo_dipendente=>$relazioni) if($this->campo($campo_dipendente) && !$this->campo($campo_dipendente)->get_hidden()) { $static=$field->myFields; $field->myFields['CONTESTO']='myForm::calcolo_dipendenze'; // if($static['static']['myJqueryJS']['sent']) die('a'); $x=$this->campo($campo_dipendente)->get_html(); if ($x) {$pre=$post=''; if($this->pre_post_campo[strtolower($campo_dipendente)]['pre']) $pre="campo($campo_dipendente)->get_id()}\">{$this->pre_post_campo[strtolower($campo_dipendente)]['pre']}"; if($this->pre_post_campo[strtolower($campo_dipendente)]['post']) $post="campo($campo_dipendente)->get_id()}\">{$this->pre_post_campo[strtolower($campo_dipendente)]['post']}"; $x=$pre.$x.$post; } preg_match_all('@<.+\s+id=("[^"]+").*>@sSU',$x,$tag_implicati); // if($static['static']['myJqueryJS']['sent']) die('b'); unset( $field->myFields['CONTESTO']); $field->myFields=$static; foreach ($relazioni as $idr=>$relazione) { //if (self::$dipendenza_campi['info'][$this->id_istance][strtoupper($campo_dipendente)][$idr]['js']===false) continue; $exp=''; $tags=$tag_implicati[1]; $modo=self::$dipendenza_campi['info'][$this->id_istance][strtoupper($campo_dipendente)][$idr]['modo']; if ($modo=='hidden') { preg_match_all('@<.+\s+id=("[^"]+").*>@sSU',$this->Get_html_label($campo_dipendente),$tag_labels); if($tag_labels[1]) $tags=array_merge($tags,$tag_labels[1]); } $trovata=false; foreach ($relazione as $cond) { if(!is_object($cond)) {$exp.=$cond; $trovata=true; } else{ if($cond->get_hidden()) continue; $cast=self::getcast_js($cond); $exp.=" myGetValueCampo(\"{$cond->get_id()}\",'$cast',function(){ {$cond->get_js_chk()} } ) "; if(strpos($cond->get_id(), 'ID_STRUTTURA')!=false && strpos($cond->get_id(), '__')==false) throw new Exception(); //meglio non fare niente in alcuni casi il campo potrebbe risultare obbligatorio durante costr JS ma poi non esserlo più e poi rimane il vincolo // $exp.=" myGetValueCampo(\"{$cond->get_id()}\",'$cast',null ) "; $dipendenza[$cond->get_id()][$campo_dipendente]=$this->campo($campo_dipendente)->get_id(); // echo '
',$this->campo($campo_dipendente)->get_id(),' dipende da ',$cond->get_id(); $trovata=true; } } //if (is_string(self::$dipendenza_campi[$this->id_istance]['info'][strtoupper($campo_dipendente)][$idr]['js'])) $exp=self::$dipendenza_campi[$this->id_istance]['info'][strtoupper($campo_dipendente)][$idr]['js']; if (!$trovata || $funzioni[$this->campo($campo_dipendente)->get_id()]['chiamata'][$idr]) continue; $exp=preg_replace('/\barray\(/Usi',' new Array(',$exp); $allFunc[$this->id_istance][]=$funzioni[$this->campo($campo_dipendente)->get_id()]['chiamata'][$idr]="my_dipendenza_campo_{$this->campo($campo_dipendente)->get_id()}_$idr();"; $funzioni[$this->campo($campo_dipendente)->get_id()]['testo'][$idr]= "function my_dipendenza_campo_{$this->campo($campo_dipendente)->get_id()}_$idr(){ var campi=new Array(".implode(',',$tags)."); try { if($exp) myFieldStatoCampi(campi,false,'$modo','{$this->campo($campo_dipendente)->get_id()}'); else myFieldStatoCampi(campi,true,'$modo','{$this->campo($campo_dipendente)->get_id()}'); } catch (Exception) { myFieldStatoCampi(campi,true,'$modo','{$this->campo($campo_dipendente)->get_id()}'); } $extra; }"; } } //self::$dipendenza_campi['daClonare']='';print_r(self::$dipendenza_campi); } /** * @ignore * @param string $campo * @return string restituisce lo js per la costruzione della dipendenza di un campo */ protected function get_js_dipendenze_campo($campo) { $allFunc=self::$dipendenza_campi['js_dipendenze_campo']['allFunc']; if(!$campo) {foreach ($allFunc as $id_ist=>$jsarray) foreach (array_unique((array) $jsarray) as $js) $funz.="try{ $js }catch (err) {};"; self::$dipendenza_campi['js_dipendenze_campo']['allFunc']=array(); return $funz; } $funzioni=self::$dipendenza_campi['js_dipendenze_campo']['funzioni']; $dipendenza=self::$dipendenza_campi['js_dipendenze_campo']['dipendenza']; $id_campo_dipendente=$this->campo($campo)->get_id(); if($dipendenza[$id_campo_dipendente] && !$this->campo($campo)->get_hidden()) {IF($this->campo($campo)->estende('mySelect',true)) $tipo='select'; elseif($this->campo($campo)->estende('myMulticheck',true)) $tipo='multicheck'; elseif($this->campo($campo)->estende('myCheck',true)) $tipo='check'; elseif($this->campo($campo)->estende('myDate',true)) $tipo='data'; //echo $campo,'=>',$this->campo($campo)->get_mytype(),'=>',$tipo,"
\n"; switch ($tipo) { case 'select': $eventi['onchange']=explode(';',$this->campo($campo)->get_attributo('onchange')); $eventi['onkeyup']=explode(';',$this->campo($campo)->get_attributo('onkeyup'));; break; case 'multicheck': case 'check': $eventi['onclick']=explode(';',$this->campo($campo)->get_attributo('onclick')); $eventi['onkeyup']=explode(';',$this->campo($campo)->get_attributo('onkeyup')); $eventi['onmouseup']=explode(';',$this->campo($campo)->get_attributo('onmouseup')); break; default: $eventi['onfocus']=explode(';',$this->campo($campo)->get_attributo('onfocus')); $eventi['onkeyup']=explode(';',$this->campo($campo)->get_attributo('onkeyup')); $eventi['onmouseup']=explode(';',$this->campo($campo)->get_attributo('onmouseup')); break; } /*echo '
';echo $id_campo_dipendente; print_r($dipendenza[$id_campo_dipendente]); print_r($funzioni);*/ do { if($dipendenza[$id_campo_dipendente]) foreach ($dipendenza[$id_campo_dipendente] as $campo_dipendente=>$dipende_da) { $fatti[$id_campo_dipendente]=$id_campo_dipendente; if(!$fatti[$dipende_da]) $ids[]=$dipende_da; foreach ($funzioni[$dipende_da]['testo'] as $testo) {$js.=$testo; $testo=''; } foreach ($funzioni[$dipende_da]['chiamata'] as $chiamata) foreach ($eventi as $evento=>&$chiamate) { $chiamata=preg_replace(array('/^;/','/;$/'),array('',''), trim($chiamata)); if(!in_array($chiamata,$chiamate)) $chiamate[]=$chiamata; } foreach ($eventi as $evento=>&$chiamate) switch ($tipo) { case 'multicheck': $opzioni=$this->campo($campo)->get_opzioni(); $this->campo($campo)->setjs(array_values($opzioni),implode(';',array_unique($chiamate)),$evento); break; default: $this->campo($campo)->set_attributo($evento,implode(';',array_unique($chiamate)),false); break; } } $ids=array_diff($ids,array_values($fatti)); $id_campo_dipendente=array_pop($ids); } while ($id_campo_dipendente!=''); if ($js) $js=""; return $js; } } /** */ function flush_dipendenze_campo() { $this->calcola_dipendenze(); //if($this->myMultiForm) $this->myMultiForm->flush_dipendenze_campo(); } /**Restituisce l'html della label di un certo campo senza formattazione tabellare * * @param string $campo Nome del campo da estrapolare * @return string */ function Get_html_campo($campo) { $this->calcola_dipendenze(); if ($campObj=$this->campo($campo)) { if ($this->dizionario[0]) { //echo "$campo applico dizionario {$this->dizionario[0]->get_al()}
"; $campObj->set_lingua($this->dizionario[0]->get_al()); } for ($d=1;$ddizionario);$d++) { $campObj->add_dizionario($this->dizionario[$d],$d); } if ($this->get_label($campo) && !$campObj->get_tooltip() && !$campObj->get_attributo('title') && !$campObj->get_attributo('alt')) { //if($campObj->get_tooltip()!==null) $campObj->set_tooltip(strip_tags($this->get_label($campo))); } if ($this->autotab) $campObj->set_autotab(); if($this->secure && method_exists($campObj,'set_secure')) $campObj->set_secure($this->secure); if($campObj->get_MyType()!='MyHidden') { $js_dipendenze=$this->get_js_dipendenze_campo($campo); if($js_dipendenze) { $f=new MyField(''); if(!$f->myFields['static']['common']) { $jsCommon=$f->get_js_common(); $f->myFields['static']['common']=1; } $funzioni_dipendenze=$this->get_js_dipendenze_campo(''); if($funzioni_dipendenze) {$this->myForms['DipendenzeCalls'].=$funzioni_dipendenze.';'; $jsCommon.=" "; } } } $x= ($campObj->get_MyType()!='MyHidden'?"":'').$campObj->get_html().$js_dipendenze; $campo=strtolower($campo); if ($x) { if($this->pre_post_campo[$campo]['pre']) $pre="get_id()}\">{$this->pre_post_campo[$campo]['pre']}"; if($this->pre_post_campo[$campo]['post']) $post="get_id()}\">{$this->pre_post_campo[$campo]['post']}"; $x=$pre.$x.$post; } return $jsCommon.$x; } } /** * Setta dell'html da inserire prima e/o dopo un campo * * @param string $campo nome del campo * @param string $html_pre htlm da mettere prima * @param string $html_post html da mettere dopo */ function set_pre_post_campo($campo,$html_pre='',$html_post=''){ $campo=strtolower($campo); $this->pre_post_campo[$campo]['pre'].=$html_pre; $this->pre_post_campo[$campo]['post'].=$html_post; return $this; } /** * Uguale a set_pre_post_campo() ma cumulativa passando degli array * * //vogliamo inserire un asterisco dopo il campo PIPPO ed un meno prima del campo PLUTO * $form->set_pre_post_campi( array('PLUTO'=>'-') , array('PIPPO'=>'*') ); * * @param array $html_pre array associativo con l'html da inserire prima del campo associato * @param array $html_post array associativo con l'html da inserire dopo il campo associato */ function set_pre_post_campi($html_pre=array(),$html_post=array()){ if ($html_pre) foreach ($html_pre as $campo=>$html) $this->set_pre_post_campo($campo,$html,''); if ($html_post) foreach ($html_post as $campo=>$html) $this->set_pre_post_campo($campo,'',$html); return $this; } /** * Setta dell'html da inserire prima e/o dopo una label * * @param string $campo nome del campo * @param string $html_pre htlm da mettere prima la label associata * @param string $html_post html da mettere dopo dopo la label associata */ function set_pre_post_label($campo,$html_pre='',$html_post=''){ $campo=strtolower($campo); $this->pre_post_label[$campo]['pre'].=$html_pre; $this->pre_post_label[$campo]['post'].=$html_post; return $this; } /** * Uguale a set_pre_post_label() ma cumulativa passando degli array * * //vogliamo inserire un asterisco dopo il campo PIPPO ed un meno prima del campo PLUTO * $form->set_pre_post_campi( array('PLUTO'=>'-') , array('PIPPO'=>'*') ); * * @param array $html_pre array associativo con l'html da inserire prima della label associata * @param array $html_post array associativo con l'html da inserire dopo la label associata */ function set_pre_post_labels($html_pre=array(),$html_post=array()){ if ($html_pre) foreach ($html_pre as $campo=>$html) $this->set_pre_post_label($campo,$html,''); if ($html_post) foreach ($html_post as $campo=>$html) $this->set_pre_post_label($campo,'',$html); return $this; } /** Restituisce l'html del singolo campo senza formattazione tabellare * * @param string $campo Nome del campo da estrapolare * @return string */ function &Get_html_label($campo) { if ($this->get_label($campo) && $this->get_campo($campo)->Prevede_label) { $x=$this->htmlLabelCampo($campo,$this->get_campo($campo)->Richiede_tag_label); if ($x) $x=$this->pre_post_label[strtolower($campo)]['pre'].$x.$this->pre_post_label[strtolower($campo)]['post']; } return $x; } /** * Aggiunge un segno dopo le label impostati non nulli * * @param string $segno da mettere * @param int spazi tra label e segno * @param boolean prima o dopo la label */ function set_segno_notnull($segno='*',$spazi=1,$dopo=true){ for ($i=0;$i<$spazi;$i++) $blank.=' '; foreach ($this->get_campi() as $nome=>$campo) if ($campo->get_notnull()) { if ($dopo) $this->set_pre_post_label($nome,'',$blank.$segno); else $this->set_pre_post_label($nome,$segno.$blank,''); } return $this; } /** * Aggiunge un segno € dopo tutti i capmi MyEuro * * @param string $segno da mettere * @param int spazi tra campo e segno * @param boolean prima o dopo il campo */ function set_segno_euro($segno='€',$spazi=1,$dopo=true){ for ($i=0;$i<$spazi;$i++) $blank.=' '; foreach ($this->get_campi() as $nome=>$campo) if (strtolower(get_class($campo))=='myeuro') { if ($dopo) $this->set_pre_post_campo($nome,'',$blank.$segno); else $this->set_pre_post_campo($nome,$segno.$blank,''); } return $this; } /** * Metodo statico che estrae dei sottoarray a partire da una sequenza di array, * il sottoarray viene estratto solo se un degli $array per le chiavi di $nomi_campi possiede TUTTI i valori!='' * * $array1=array('A'=>5,'b'=>'7','c'=>4); * $array2=array('a'=>5,'b'=>'6','c'=>'','d'=>9); * * //questo non restituisce nulla perchè il primo non ha 'd' il secondo non ha 'c' * $out= myForm::recupera_valori(array('c'=>'primo','d'=>'secondo',array($array1,$array2)); * * //questo restituisce array('primo'=>5,'secondo'=>7) perchè trovati nel primo si ferma * $out= myForm::recupera_valori(array('a'=>'primo','b'=>'secondo',array($array1,$array2)); * * //questo restituisce array('primo'=>5,'secondo'=>6) perchè introdotto vincolo CASE * $out= myForm::recupera_valori(array('a'=>'primo','b'=>'secondo',array($array1,$array2),true); * * * * * @param array $nomi_campi array associativo in cui le chiavi vengono cercate ed i valori sono le chiavi usate nell'array restituito * @param array $arrays array di array associativi in cui cercare * @param boolean $casesensitive confronto tra i nomi delle chiavi sensitive o meno * @param boolean $tutti se true restituisce un array se strova tuutte le chiavi se falso restituisce solo le chiavi trovate * @return array */ static function recupera_valori($nomi_campi, $arrays,$casesensitive=false,$tutti=true) { if (!$casesensitive) $nomi_campi=array_change_key_case($nomi_campi); $n=count(array_flip($nomi_campi)); foreach ($arrays as &$array) if($array) { $trovati=array(); if (!$casesensitive) $valori=array_change_key_case($array); else $valori=&$array; foreach ($nomi_campi as $chiave=>$nome) { if (!$trovati[$nome] && (is_array($valori[$chiave]) || trim($valori[$chiave])!=='')) $trovati[$nome]=$valori[$chiave]; if ($tutti && count($trovati)==$n) return $trovati; } if (count($trovati) && !$tutti) return $trovati; } return array(); } /** @ignore */ function clonami() { self::$dipendenza_campi['daClonare']=$this; if (PHP_VERSION >= 5) return clone($this); else return $this; } } /** * Questa classe permette la costruzione e gestione facilitata di Form basate su una tabella di DB generico * Supponiamo di voler costruire una form da una tabella Prodotti costituita id(Pk),Nome,Prezzo * e che, se la variabile $_GET['id'] è valorizzata deve presentare i campi valorizzati con quelli riferiti a $_GET['id'] * altrimenti si predispone all'inserimento * * .... precedemente mi connetto al DB ed includo myForms * if (!$_GET['id']) $_GET['id']=$_POST['id']; //se non $_GET['id'] lo valorizza con un eventuale precedente valore postato * $f=new MyForm_DB($AdoConn,'','Prodotti',array('id'=>$_GET['id'])); * $f->Analizza_Tabella(); //prima di ogni cosa * $f->CambiaTipoCampo('PREZZO','MyEuro'); //il tipo di default assegnato da MyForm non mi piace e lo cambio * $f->IstanziaCampi(); //Ora non si possono più cambiare i tipi; * if ($_POST['id']) {//se E' stato premuto un pulsante * $f->set_values($_POST); //cambio i valori dei campi con quelli postati * $mess=$f->Check_Errore(); //verifico la presenza di errori * if (!$mess) { * if ($_POST['Salva']) $f->Salva(); //se premuto Salva * if ($_POST['Elimina']) {$f->Elimina(); //se premuto Elimina * $f->set_defaults();//reimposta i valori di default del form * } * $mess='Operazione completata'; * } * * * if ($mess) echo $mess."
"; // visualizzo messaggio di risposta; * echo "
"; //un po' di html serve sempre, ma poco * echo $f->Get_html(); //visualizzo Form * echo "
"; * * $s=new MyPulsante('Salva','Salva'); //creo pulsante Salva * echo $s->get_Html(); // lo visualizzo * * $e=new MyPulsante('Elimina','Elimina'); //creo pulsante Elimina * $e->set_Domanda('Sicuro di voler cancellare'); //setta domanda di conferma per il pulsante * echo $e->get_Html(); // lo visualizzo * echo ""; * * @access public * @package myForms **/ Class myForm_DB extends myForm { /**#@+ @ignore */ protected $con, $tabella, $schema, $condizioni, $colonne, $lastqry, $ParametriAutomatici='',$metaDatiTabella='', $chiavi=array(), $indici=array(), $AutoIncrementante='',$recordset_attivo='', $istanziati=false, $separatore_decimali='.', $ripetizione=false, $id,$FK,$SalvaInfo=0; /**#@-*/ /** * Costruttore di classe * @access public * * @param ADODBConnection $con Connessione al db da usare * @param array $colonne elenco delle colonne della tabella da utilizzare, se omesso si usano tutte * @param string $tabella Nome della tabella da utilizzare * @param array $condizioni Array associativo Colonna=>Valore per la condizione di recupero valori dalla tabella */ function myForm_DB(&$con,$colonne=array(),$tabella,$condizioni='') {parent::myForm(); $this->con=&$con; $this->schema=$con->database; $this->id=sha1($_SERVER['PHP_SELF']."=> {$this->schema}.{$tabella}.{$this->id_istance}.=>".var_export($condizioni,1).var_export($colonne,1)); if (!$colonne) $colonne=array(); $this->colonne=$colonne; $this->colonne=array_unique($this->colonne); $this->tabella=$tabella; if (is_array($condizioni)) foreach ($condizioni as $i=>&$v) $this->condizioni[strtoupper($i)]=stripslashes("$v"); $this->ripetizione=self::is_f5(); if ($this->ripetizione && ($recovered=$this->recover_chiavi())) $this->condizioni=$recovered; } /** * @ignore */ protected function recover_chiavi($chiavi=''){ $s=new mySessions('myFormsStatus'); $last_chiavi=$s->get($this->id); //estraggo elenco chiavi if($chiavi) {$s->set('last_status',mySecurizer::checksum_user_sent(),true); $last_chiavi=array('key'=>$chiavi, 'chk'=>mySecurizer::checksum_user_sent()); $s->set($this->id,$chiavi,true,60*5); } if($last_chiavi[$this->id]['chk']==mySecurizer::checksum_user_sent()) return $last_chiavi[$this->id]['key']; else $s->del($this->id); } /** * @ignore */ protected static function is_f5(){ static $is_f5; if($is_f5===null) { $s=new mySessions('myFormsStatus'); $is_f5=($s->get('last_status')==mySecurizer::checksum_user_sent()); if(!$is_f5) $s->dels(); } // print_r($_SESSION['mySessions>myFormsStatus']); return $is_f5; } /**Restituisce l'html della label di un certo campo senza formattazione tabellare * * @param string $campo Nome del campo da estrapolare * @return string */ function Get_html_campo($campo) { $campo=strtoupper($campo); if ($field=$this->get_campo($campo)) { $html=parent::Get_html_campo($campo); if ($this->prefisso_nascoste && in_array($campo,$this->chiavi)) { $valori=$this->get_valori_recorddiLavoro(false,'U'); $hidden=new myHidden($this->prefisso_nascoste.$field->get_name(),$valori[$campo]); $html.=$hidden->get_html(); } return $html; } } /** * Imposta il timeout per il salvataggio delle metainformazioni delle tabelle * @param int $timeout secondi di cache, se 0 ogni volta ricarica da DB metadati */ function set_cache_metadata($timeout){ $this->SalvaInfo=$timeout; return $this; } /** * Aggiunge campi nascosti con i valori delle chiavi ricavabili tramite get_valori_recorddiLavoro() * precedute da un certo prefisso. Utile quando la chiave primaria è editabile dall'utente e lui può modificarla * Es. supponiamo che una tabella abbia come chiave primaria il codice fiscale, * possiamo avere diversi casi * 1) il codice fiscale è passato in GET per preparare la modifica, in questo caso si deve usare quello nel costruttore * 2) il codice fiscale è regolarmente "postato", in quel caso potrebbe essere stato modificato dall'operatore quindi server ricavare quello originale * quindi conviene * * //cerca in $_POST prima @numeropolizza e poi numeropolizza * //se non trova nulla le cerca in $_GET * $condizioni=myForm::recupera_valori(array('@numeropolizza'=>'numeropolizza', * 'numeropolizza'=>'numeropolizza', * ), * array($_POST,$_GET) * ); * //alla fine $condizioni o è null o è della forma ('numeropolizza'=>valore) * $form=new myForm_mysql($conn,'','persone',$condizioni); * $form->add_chiavi_nascoste(); * * * @param string $prefisso //prefisso che verrà posto davanti ai nomi delle chiavi */ function add_chiavi_nascoste($prefisso='@') { if (!$this->chiavi) die('add_chiavi_nascoste() va usato dopo set_chiavi()'); //foreach ($this->chiavi as $chiave) $this->add_campo(new MyHidden("$prefisso$chiave")); $this->prefisso_nascoste=$prefisso; return $this; } function add_campo(&$campo,$label='',$indirizzo=false,$dopo='') { $obj=parent::add_campo($campo,$label,$indirizzo,$dopo); $this->colonne=array_keys($this->get_campi()); return $obj; } function unset_campo($nome) { parent::unset_campo($nome); $this->colonne=array_keys($this->get_campi()); return $this; } /** * Restituisce un array associativo che rappresenta tutte le foreign keys della tabella a cui è associata la form * * @return array */ function MetaForeignKeys() { if ($this->FK) return $this->FK; return $this->con->MetaForeignKeys($this->tabella,false,true,false); } /** * Restituisce un array associativo con le metacolumns della tabella a cui è associata la form * * @return unknown */ function MetaColumns() { return $this->con->MetaColumns($this->tabella,true); } /** @ignore */ function MetaIndexes ($table, $primary = FALSE, $owner=false) { return $this->con->MetaIndexes ($table, $primary, $owner); } /** @ignore */ protected function get_meta_type($fld){ $classe=$this->con->rsPrefix.$this->con->databaseType; if (class_exists($classe)) eval("\$type=$classe::MetaType(\$fld->type,\$len,\$fld);"); else $type=ADORecordSet::MetaType($fld->type,$len,$fld); return $type; } /** * Imposta uni indice univoco tra i campi della form, * la verifica viene effettuata solo quando tutte le colonne dlla form sono valorizzate * * @param string $nome nome dell'indice * @param colonna $colonne nomi delle colonne */ function set_univocita($nome,$colonne=array()){ $this->indici[strtoupper($nome)]['unique']=1; $this->indici[strtoupper($nome)]['columns']=$colonne; return $this; } /** * Restituisce il nome della tabella di lavoro * * @return string */ function get_tabella(){ return $this->tabella; } /** * @ignore */ protected function quota_colonne($array,$tutte=false) { $where=array(); if ($array) foreach ($array as $col=>&$val) { $val=trim($val); $col=strtoupper($col); if ($tutte && $val==='') return null; if (($val=trim($val))!=='' && ($this->metaDatiTabella[$col]->primary_key || ($this->chiavi && array_search($col,$this->chiavi)!==false))) {$type=$this->get_meta_type($this->metaDatiTabella[$col]); if (in_array($type,array('D','T'))) { $val=explode(' ',$val,2); $d=new mydate('',$val[0]); $val[0]=$d->get_formatted(); $where[]="$col=".$this->con->quote(implode(' ',$val)); } elseif (in_array($type,array('N','I','R')) && @preg_match('|^[0-9]*[\.]{0,1}[0-9]*$|',$val)) $where[]="$col=$val"; else $where[]="$col=".$this->con->quote($val); } } return $where; } /** * Effettua l'analisi della tabella ma ancora non istanzia i campi per * permettere l'uso di CambiaTipoCampo */ function Analizza_Tabella() { self::MyForm(); if ($this->ParametriAutomatici) RETURN $this; global $ADODB_COUNTRECS;$tempcount=$ADODB_COUNTRECS; $ADODB_COUNTRECS = true; $precFetch =$this->con->setfetchmode(ADODB_FETCH_ASSOC); $INFO=$this->MyCacheDati(-1,'myForms:'.$this->schema.".".$this->tabella); IF (!$INFO['InfTable']) {$salvaInformazioni=true; $INFO['InfTable']=$this->MetaColumns(); $INFO['FK']=$this->MetaForeignKeys(); $INFO['Indici']=$this->MetaIndexes($this->tabella,true); } $InfTable= &$INFO['InfTable']; $_FK= &$INFO['FK']; $this->indici=&$INFO['Indici']; $FK=array(); $this->metaDatiTabella=@array_change_key_case($InfTable,CASE_UPPER); //echo "
";print_r($InfTable);

    	if (is_array($_FK)) {
    						foreach ($_FK as $tab=>$campi)
		 						if (is_array($campi))
		 								foreach ($campi as $cols) {
		 										$cols=explode('=',$cols);
		 									  	$FK[strtoupper($cols[0])][]=array(strtoupper($tab)=>strtoupper($cols[1]));
		 									  	$REALTAB_NAMES[strtoupper($tab)]=$tab;
		 										}
		 					$this->FK=$FK;
		 					}




     	foreach ($this->colonne as $i=>$colonna){
     								  	 	     $v=explode(' ',trim($colonna));
     								  	 	     $this->colonne[$i]=strtoupper($v[count($v)-1]);
     								  	 	    }
    	IF ($this->condizioni)
    				{
    				$where=$this->quota_colonne($this->condizioni);
    				if (count($where)==count($this->condizioni)) $where=" where ".implode(' and ',$where);
    														else $where=" where 1=0 ";
    				if(count($this->colonne)>0) $colonne=implode(',',array_unique(array_merge($this->colonne,array_keys(array_change_key_case($this->condizioni,CASE_UPPER)))));
    									   else $colonne='*';
    				$this->recordset_attivo=$Table=$this->con->selectlimit("select $colonne from {$this->tabella} $where ",1,0);
		  	     	for ($i=0;$i<$Table->_numOfFields;$i++)
												 {$fld=$Table->FetchField($i);
												  $extraInfo[strtoupper($fld->name)]['unsigned']=$fld->unsigned;
		 							  			  $extraInfo[strtoupper($fld->name)]['maxValue']=$fld->max_length;
		 							  			  if ($where && $Table->RowCount()==1) $extraInfo[strtoupper($fld->name)]['Value']=$Table->fields[$fld->name];
		                						 }

					}
		//echo "
";	print_r($this->colonne );	print_r($extraInfo);

/*
    	echo "
";print_r($FK);print_r($InfTable);

			 MAXSIZE = Dimensione massima del campo
				 NONNULLO = Campo con IMpossibilità di essere a NULL
				 POSITIVO= Campo con segno positivo
				 INCREMENTALE = Campo incrementale
				 VALORE = Valore del campo nel recordset recuperato
				 VALOREDEFAULT = Valore di defalut in definizione tabella
				 MYTYPE =  Nostro tipo
				 TIPO = Tipo dichiaratio dal db
				 ADODB = Nome usato dalla classe Adodb per identificare il campo
				 FK = (tabella=>campo)

*/



		$chiavi_valorizzato=count($this->chiavi);
		if ($InfTable)
			foreach ($InfTable as $key=>$fld)
			  // if (count($this->colonne)==0 || isset($this->colonne[$key]))
			        {
			        $this->colonneOriginali[$key]=$fld->name;
			        if ($fld->not_null) $this->ParametriAutomatici[$key]['NONNULLO']=$fld->not_null;
					if ($extraInfo[$key]['unsigned']>0) $this->ParametriAutomatici[$key]['POSITIVO']=$extraInfo[$key]['unsigned'];
					if ($fld->auto_increment) {$this->ParametriAutomatici[$key]['INCREMENTALE']=$fld->auto_increment;
											   $this->AutoIncrementante=$key;
											   $fld->primary_key=true;
											  }

					$this->ParametriAutomatici[$key]['VALOREDEFAULT']=$fld->default_value;
					if ($where && $Table->_numOfRows==1) $this->ParametriAutomatici[$key]['VALORE']=$extraInfo[$key]['Value'];
 		 										    else $this->ParametriAutomatici[$key]['VALORE']=$fld->default_value;

 		 			if ($fld->primary_key && !$chiavi_valorizzato) $this->chiavi[]=strtoupper($key);

					$this->ParametriAutomatici[$key]['TIPO']=$fld->type;
					//echo "
"; 	print_r($fld);
					if ($fld->enums) $this->ParametriAutomatici[$key]['TIPO'].="(".implode(',',$fld->enums).")";

					$len=$fld->max_length;
					if ($len>0) $this->ParametriAutomatici[$key]['MAXSIZE']=$len;
					  	    elseif ($this->ParametriAutomatici[$key]['MAXVALUE']) $len=$extraInfo[$key]['maxValue'];;

					$type=$this->get_meta_type($fld);
					$this->ParametriAutomatici[$key]['ADODB']=$type;

					if ($this->ParametriAutomatici[$key]['INCREMENTALE']) $this->AutoIncrementante=$key;
					//echo "
";print_r($FK);
					if (count($FK[$key])==1) {
											  //echo "*$tab=>$cols[$key]
"; list($campo, $tab) = each($FK[$key][0]); $this->ParametriAutomatici[$key]['FK']=array($tab=>$campo); $this->ParametriAutomatici[$key]['REALTAB_NAMES']=&$REALTAB_NAMES; } //echo "/$key=>$type"; switch ($type) { case 'C': { if ($len>90) $tipo="MyTextArea"; elseif ($len==1) $tipo="MyBoolean"; else $tipo="MyText"; } break; case 'X': if ($len>90) $tipo="MyTextArea"; elseif ($len==1) $tipo="MyBoolean"; else $tipo="MyText"; break; case 'B': if ($len>90) $tipo="MyTextArea"; elseif ($len==1) $tipo="MyBoolean"; else $tipo="MyText"; break; case 'D': $tipo="MyDate"; break; case 'T':{ if ($len==8) $tipo="MyTime"; else $tipo="MyDateTime"; } break; case 'L': $tipo="MyBoolean"; break; case 'I':{ IF (!$this->ParametriAutomatici[$key]['INCREMENTALE']) $tipo="MyInt"; else $tipo="MyHidden"; } break; case 'N': { if ($fld->scale>0) {$tipo="MyFloat"; $this->ParametriAutomatici[$key]['DECIMALI']=$fld->scale; $this->ParametriAutomatici[$key]['MAXSIZE']=max(6,$len); } else {$tipo="MyInt"; $this->ParametriAutomatici[$key]['MAXSIZE']=max(4,$len); } } break; case 'R': $tipo="MyHidden"; break; } if ($this->ParametriAutomatici[$key]['POSITIVO'] && 'MyInt'==$tipo) $tipo='MyIntPos'; if ( ('MyDate'==$tipo || 'MyDateTime'==$tipo) && ''==str_replace(array(':','-','0',' '),'',$this->ParametriAutomatici[$key]['VALORE']) ) $this->ParametriAutomatici[$key]['VALORE']=''; $this->ParametriAutomatici[$key]['MYTYPE']=$tipo; } $this->SpecificheTecnologiche(); // if ($this->chiavi) $this->chiavi=array_flip(array_flip($this->chiavi)); if (!count($this->chiavi)) $this->chiavi=($INFO['PK']?$INFO['PK']:$INFO['PK']=$this->con->MetaPrimaryKeys($this->tabella)); $this->set_chiavi($this->chiavi); //echo "
"; print_r($this->ParametriAutomatici);


		//	}
	   	if (!$this->chiavi) {echo "Impossibile individuare chiave primaria, usare Set_chiavi() prima di Analizza_tabella({$this->tabella})";
							 exit;
							}
		$k=array_flip($this->chiavi);
		if ($this->ParametriAutomatici) foreach ($this->ParametriAutomatici as $key=>$vals)   if (!isset($k[$key]) && $vals['FK']) $this->ParametriAutomatici[$key]['MYTYPE']='MySelect';

		//echo '
';print_r($this->ParametriAutomatici);
		//forzo il salvataggio dei dati
		if ($salvaInformazioni )  $this->MyCacheDati( $this->SalvaInfo,'myForms:'.$this->schema.".".$this->tabella,$INFO);
		
		$ADODB_COUNTRECS= $tempcount;
		$this->con->setfetchmode($precFetch);
		if($this->colonne) $this->set_ordine($this->colonne);

		return $this;
	    }


 	/** @ignore */
    function SpecificheTecnologiche() {}

 	/** @ignore */
  	function _get_key_conn(){
  		return $this->con->dsnType.$this->con->database.$this->con->host.$this->con->user.print_r($this->con->_connectionID,1);
    }


    /** @ignore */
  	function _get_conn(){
  		return $this->con;
    }



	/**
     * Cambia il tipo di un campo - Si può usare prima di aver effettuato IstanziaCampi()
     * @param    string $nome_campo Nome del campo
     * @param    string $myTipo Nome della classe di MyFields da usare
    */
	function CambiaTipoCampo($nome_campo,$myTipo) {
		 $nome_campo=strtoupper($nome_campo);
	  	 if ($this->istanziati) {echo "Impossibile cambiare tipo di $nome_campo in $myTipo perchè i campi sono già stati istanziati o tabella DB non è stata caricata";exit;}
	     $this->ParametriAutomatici[$nome_campo]['MYTYPE']=$myTipo;
	     if (!preg_match('/enum|set/i',$this->ParametriAutomatici[$nome_campo]['TIPO'])) unset($this->ParametriAutomatici[$nome_campo]['TIPO']);
	     if (preg_match('/multi|radio|select|check|date/i',$this->ParametriAutomatici[$nome_campo]['MYTYPE']))
			   		 {unset($this->ParametriAutomatici[$nome_campo]['MAXSIZE']);
	        	 	  unset($this->ParametriAutomatici[$nome_campo]['DECIMALI']);
	        	 	  //unset($this->ParametriAutomatici[$nome_campo]['TIPO']);
	        	 	  unset($this->ParametriAutomatici[$nome_campo]['SIZE']);
			  		 }
		return $this;
		}


	/** Restituisce il valore in formato ANSI
     * @param    string $nome_campo
     * @return   mixed $valori
     */
	function &get_value_db($obj) {
		if (is_string($obj)) $obj=$this->campo($obj);
		if (!is_object($obj) || strlen((string) $obj->get_value())==0) return '';
		if ($obj instanceof MyDate) return $obj->get_formatted('amg','-');
		if ($obj instanceof MyAnno) return $obj->get_value();
		if ($obj->estende('myFloat',true))
										{$obj->is_numeric(true);
										  return str_replace($obj->get_separatore(),$this->separatore_decimali,$obj->get_value());
										}
		if ($obj instanceof MyTime ||
			$obj instanceof MyOra) {
		 							 $v=explode(':',$obj->get_value());
	 								 if (count($v)==2) $v[]='00';
	 								 if (method_exists($obj,'get_secs_mode') && !$obj->get_secs_mode()) unset($v[2]);
	 								 return implode(':',$v);
  									}
		if ($obj instanceof MyOrario) return $obj->get_minuti();
		if ($obj instanceof MyMultiCheck)  {$obj->is_numeric(false);
			  							    if (is_array($obj->get_value())) return implode(',',$obj->get_value());
											 						    else return $obj->get_value();
	 									   }

		return $obj->get_value();
	}


	 /** @ignore */
	function Quota_Campo ($obj) {
		if (is_string($obj)) $obj=$this->campo($obj);
		if (!is_object($obj))  return '';

 		$x=trim($this->get_value_db($obj));

 		if ($obj->is_numeric()!==true && !$obj->get_formula())
 						 {  if (strlen($x)==0) $x='null';
 						    $x=$this->con->Quote($x);
						    if(strtolower($x)=="'null'") $x='null';
 						 }
 	 	  	  elseif ($obj->get_formula()) $x=$obj->get_formula();
 	 	  	     elseif ($obj->is_numeric()===true)
 	 	  	      	  	 {
 	 	  	      	  	 	if (strlen($x)==0) $x='null';
 						 }
 				    elseif ($obj->get_value()==0) $x='null';

 		return $x;
 	}



	



    /**
     * Setta le chiavi primarie della tabella se non avviene automaticamente
     * @param    array $elenco_chiavi Elenco delle chiavi
     * @param    boolean $autoincrementante se elenco ha un solo elemento questo parametro può indicare il fatto che sia autoincrementante
     */
 	function set_chiavi($elenco_chiavi,$autoincrementante=false) {
 	 if (!is_array($elenco_chiavi)) echo "Il parametro di set_chiavi deve essere un array";
 	   else  {$this->chiavi=$this->array_maiuscolo($elenco_chiavi)	;
 	          if (count($this->chiavi)==1 && $autoincrementante) $this->AutoIncrementante=$this->chiavi[0];
 	   		 //ormai inutile foreach($this->chiavi as $k) $this->chiavi_valore[$k]=$this->campi[$k]->get_value();
 	   		 }
 	   return $this;
 	}


 	/**
     * Ritorna un array associativo con le chiavi ed i relativi valori
     * @return    array
     */
 	function get_chiavi() {
 	  $nuovo=array();
 	  if (is_array($this->chiavi)) foreach ($this->chiavi as $k) $nuovo[$k]=$this->get_value($k);
 	  return $nuovo;
 	}



	function  get_last_query() {
		return $this->lastqry;
	}


	 /**
     * Imposta il valore come formula
     * @param    string $campo
	 * @param    string $formula Utile se si vuole che il valore venga interpretato come una formula in fase di salvataggio su db
	 *
	 * Es.
	 * 
	 *   .....
	 *   // Se $F è un myForm_DB o estensione ..
	 *  $F->set_formula('DATA_INSERIMENTO','sysdate()');  //in questo modo il campo prenderà il valore della funzione del DB sysdate()
	 * 
	 */
    function set_formula($campo,$formula) {
       	  if($this->campo($campo)) $this->campo($campo)->set_formula($formula);
       	  return $this;
    }


    /**
     * Ritorna un array associativo con i campi ed i relativi valori del record attivo
     * attenzione, non corrispone necessariamente ai valori dei campi della form, che potrebbero
     * essere stati modificati a seguito di post di dati che non hanno avuto effetto sul DB
     * questi sono proprio i valori che sono attualmente (si fa per dire) sul DB
     *
     * @param     boolean $ricarica se true forza il ricaricamento dei dati dal DB
     * @param 	  U|L|N   $caseChiavi dell'array Upper,Lower,Normal (di default Uppercase... come escono da DB)
     * @return    array
     */
	function get_valori_recorddiLavoro($ricarica=false,$caseChiavi='U') {
	   if ($ricarica) {
	   		  	   $where=array();
    			   foreach ($this->chiavi as $col) {
    		 			$val=trim($this->condizioni[strtoupper($col)]);
    		 			if ($val==='') {$where=array();
    		 							break;
    		 						   }
    				     $where[$col]=$val;
    			  }
    			 if ($where) $this->recordset_attivo=&$this->con->selectlimit("select * from {$this->tabella}  where ".implode(' and ',$this->quota_colonne($where)),1,0);
    				   else $this->recordset_attivo=null;
    			}

		if ($this->recordset_attivo &&
			$this->recordset_attivo->fields)
			 switch ($caseChiavi) {
			 	case 'U': return array_change_key_case($this->recordset_attivo->fields,CASE_UPPER);
			 	case 'N': return $this->recordset_attivo->fields;
			 	case 'L': return array_change_key_case($this->recordset_attivo->fields,CASE_LOWER);
			 }
		return null;
	}


	 function set_valori_recorddiLavoro($values) {
		if (!$this->recordset_attivo) $this->recordset_attivo=new stdClass();
		$this->recordset_attivo->fields=$values;
		return $this;
	}


	/** @ignore */
    protected function GeneraWhere($valori,$where=" where ") {
    	$valori=@array_change_key_case($valori,CASE_UPPER);
    	$conds=array();
    	if($valori)
    		foreach ($valori as $nome=>&$valore)
    		  if (is_object($this->campo($nome)))
    	   	    	{
    	   	    	$campo=clone $this->campo($nome);
    			    $campo->set_value($valore);
    			    $campo->set_formula('');
    			    $conds[]="$nome=".$this->Quota_Campo($campo);
    				}
    	if ($conds) return $where.implode(' and ',$conds);
    		   else return $where.' 1=0 ';
     }



    /** @ignore */
    protected function GeneraWhereActiveRecord($valori,$where=" where ") {
    	//print_r($this->get_chiavi());
    	$valori=@array_change_key_case($valori,CASE_UPPER);
    	$chiavi=@array_change_key_case($this->get_chiavi(),CASE_UPPER);
    	$condizione=(array)  @array_intersect_key((array) $valori,(array) $chiavi);
    	return $this->GeneraWhere($condizione,$where);
    }

    /** @ignore */
    protected function GeneraInsert($valori){
    	 return "insert into {$this->tabella} (".implode(',',@array_keys($valori)).") values (".implode(',',array_values($valori)).")";
    }


    /** @ignore */
    protected function generaDelete() {
    	return "delete from {$this->tabella} ".$this->GeneraWhereActiveRecord($this->get_valori_recorddiLavoro());
    }

    /** @ignore */
    protected function GeneraUpdate($valori){
    	$where=$this->GeneraWhereActiveRecord($this->get_valori_recorddiLavoro());
    	$partenza=@array_change_key_case($this->get_valori_recorddiLavoro(),CASE_UPPER);

        foreach ($partenza as $nome=>&$valore)
    	    if (is_object($this->campo($nome)) && isset($this->metaDatiTabella[$nome]))
    	   	 {
    		  $campo=clone $this->campo($nome);
    		  $campo->set_value($valore,1); //1 per i myupload
    		  if($this->campo($nome)->get_formula() ||
    		  	   	 strcmp($this->Quota_Campo($campo),$valori[$nome])!==0 ||
    		       						//in caso di datetime nullo su DB $this->Quota_Campo($campo) darebbe ora corrente
    		       						//$valori[$nome]=ora corrente e non salva quindi faccio anche la
    		         strlen(trim($valore))==0 && strlen(trim($valori[$nome]))!=0 ||
    		         strlen(trim($valore))!=0 && strlen(trim($valori[$nome]))==0
    		        )
    		       	$updates[]="$nome=".$this->Quota_Campo($nome);
    	     }

    	if (!$updates) return '';
    	return "update {$this->tabella} set ".implode(',',$updates).' '.$where;
    }


    /**
     * Elimina dal DB la tupla relativa ai dati nel Form,se ok ritorna null
     */
    function Elimina() {
    	//echo $this->tabella.$this->con->_connectionID." ".$this->con->_commit."
"; //echo $this->tabella.$this->con->_connectionID." ".$this->con->_commit."
"; if ($this->ripetizione) return ; $this->lastqry=''; if ($this->AutoIncrementante) $this->campo($this->AutoIncrementante)->is_numeric(true); if ($this->get_valori_recorddiLavoro()) { $qry=$this->generaDelete(); $esito=$this->con->execute($qry); if ($esito===false) {$errore=$this->con->ErrorMsg(); $this->onInternalError($errore); return $errore; } else $this->lastqry=$qry; } } function disabilita_verifica_ripetizione() { $this->ripetizione=false; return $this; } /** * Salva i dati presenti nel Form su DB,se ok ritorna null * @param bool $auto_ricarica_dati se true dopo l'inserimento di una riga con formule o autoincrementandi i dati vengono ricaricati per refreshare i campi con quanto prodotto dal DB, se falso non si fa ricaricamento */ function Salva($auto_ricarica_dati=true) { if ($this->ripetizione) return ; $this->lastqry=''; if ($this->AutoIncrementante && is_object($this->campo($this->AutoIncrementante)) ) $this->campo($this->AutoIncrementante)->is_numeric(true); if ($this->get_chiavi() && !$this->get_valori_recorddiLavoro()) $this->get_valori_recorddiLavoro(true); foreach ($this->campi as $id=>$obj) $out[$id]=$this->Quota_Campo($obj); $out=array_change_key_case($out,CASE_UPPER); if($this->AutoIncrementante && !$this->campo($this->AutoIncrementante)->get_value()) { $this->campo($this->AutoIncrementante)->set_value(''); unset($out[strtoupper($this->AutoIncrementante)]); $inserimento=true; } foreach ($out as $nome=>&$valore) { if(!isset($this->metaDatiTabella[$nome])) unset($out[$nome]); elseif ($this->campo($nome)->get_formula()) $Presente_formula=true; } //$this->con->debug=1; if (!$inserimento && $this->get_valori_recorddiLavoro()) { //echo "
";print_r($_POST);print_r($out);
				 $qry=$this->GeneraUpdate($out);
				 if (!$qry || $this->con->execute($qry)===false)
				 						{$errore=$this->con->ErrorMsg();
				 						 $this->onInternalError($errore);
				 						 return $errore;
				 						}
				}

    	  else {$qry=$this->GeneraInsert($out);
    	  		if (!$qry || $this->con->execute($qry)===false)
    	  							    {$errore=$this->con->ErrorMsg();
				 						 $this->onInternalError($errore);
				 						 return $errore;
				 						}
    			if ($this->AutoIncrementante && $last_id=$this->con->Insert_ID($this->tabella,$this->AutoIncrementante))
    					{
    					 $this->campo($this->AutoIncrementante)->set_value($last_id); //avendo una id può ricaricare i valori dalla tabella
    					 if(isset($this->condizioni[strtoupper($this->AutoIncrementante)])) $this->condizioni[strtoupper($this->AutoIncrementante)]=$last_id;
    					}
    			 $inserimento=true;
    			 }
    	$this->lastqry=$qry;

    	if(!$Presente_formula || !$auto_ricarica_dati) $this->set_valori_recorddiLavoro(array_change_key_case($this->get_values(),CASE_UPPER));
    					 elseif($this->condizioni )
    					 		{ foreach ($this->condizioni as $i=>&$v)
    					 				    $v=&$this->campo($i)->get_value();
    					 		$this->set_values(array_merge($this->get_values(),(array) $this->get_valori_recorddiLavoro(true)));
    						   }
		$this->recover_chiavi($this->get_chiavi());
		return false;
    }


	/** Effettua analisi di validità dei campi
     * @param    array $qualicampi campi da controllare/non controllare (se omesso si applica a tutti indipendentemente da $Esclusi)
     * @param 	 boolean $Esclusi  se true o omesso $qualicampi sono esclusi dalla verifica se falo si verificano esclusivamente quelli
     * @return   array Array associativo con label=>'Label del campo errato' errore=>'messaggio di errore' campo=>'nome del campo errato'
     */
	function Check_Errore_Diviso($qualicampi='',$Esclusi=true) {
//echo "
";print_r($this->campi);
	 $errore=parent::Check_Errore_Diviso($qualicampi,$Esclusi);
	 if ($errore) return  $errore;

	 if (is_array($this->indici) && count($this->indici)>0 && !$this->ripetizione) {
	 	$chiavi=$this->condizioni;
	 //	print_r($this->get_values());

		//$this->con->debug=1;
	 	if ($this->recordset_attivo->fields)
    			{
    			 $qry=$this->GeneraWhereActiveRecord($this->get_valori_recorddiLavoro(),'');
    			 if ($qry) $noChiave=" and not ($qry)";
    			}

	  	foreach ($this->indici as $indice)
	 	  	if ($indice['unique'] && !$gia_fatto[serialize($indice['columns'])] )
	 	  				{
	 	  				$gia_fatto[serialize($indice['columns'])]=1;
						$colonne=array_flip(array_change_key_case(array_flip((array) $indice['columns']),CASE_UPPER));



						$campi=array();
						$condizioni='';
						foreach ($colonne as $colonna)
								if ($this->campo($colonna) &&
							       strlen($valoredb=$this->get_value_db($this->campo($colonna))))
											{
											$campi[$colonna]=$valoredb;
											//echo "$colonna =>".$this->campo($colonna)->get_value()."
"; } if ($campi && count($campi)==count($indice['columns'])) { if ($campi==$chiavi) continue; $condizioni=$this->GeneraWhere($campi); } if ($condizioni) { $rs=&$this->con->selectlimit("select 1 from $this->tabella $condizioni $noChiave",1,0); if ($rs && $rs->fields) {$labels=array(); foreach ($colonne as $vals) if ($this->get_label($vals) && !$this->campo($vals)->is_hidden()) {$labels[]=$this->get_label($vals); $fields[]=$this->campo($vals); } return array('label'=>$labels, 'errore_forzato'=>1, 'errore_tipo'=>'internal', 'errore'=>(count($labels)==1 ?$this->trasl("Il campo: '%label%' è già stato usato in un altro record") :$this->trasl("I campi: '%label%' sono già stati usati in un altro record") ), 'campo'=>$fields); } } } } } /** * Istanzia i Campi, a questo punto si può usare &get_campo() ma non è più possibile l'uso di CambiaTipoCampo() * * @param boolean $carica_FK se vero crea automaticamente dei menu a tendina da tabelle per le quali ci sono Foreign keys * * N.B. Il caricamento automatico avviene SOLO se la tabella referenziata sia composta da DUE sole colonne di cui una e la chiave esterna */ function IstanziaCampi($carica_FK=false) { if (!$this->chiavi) {echo "Impossibile individuare la chiave primaria automaticamente utilizzare set_chiavi"; exit;} if ($this->istanziati) {echo "Campi già istanziati per ".$this->tabella." o tabella DB non caricata";exit;} $colonne=array_flip($this->colonne); if (is_array($this->ParametriAutomatici)) foreach ($this->ParametriAutomatici as $id=>$val) if (!$colonne || isset($colonne[strtoupper($id)])) { // echo "
".memory_get_usage(); // echo "
new $val[MYTYPE]($id,$val[VALORE])
"; // print_r($val); //$campo=$this->istanzia($val['MYTYPE'],$id,$val['VALORE']); //print_r($campo); //if ($J++==5) exit; if(!$val['MYTYPE']) continue; $campo=new $val['MYTYPE']($id,null); $this->add_campo($campo,'',true); //print_r($this->campi); if (isset($val['NONNULLO']) && $val['NONNULLO'] && (!isset($val['INCREMENTALE']) || !$val['INCREMENTALE'])) $this->campi[$id]->set_notnull(); if (is_object($this->campi[$id]) && $this->campi[$id]->estende('myText',true) ) { if ($val['MAXSIZE'] && $val['MYTYPE']!='MyDate') { if( $this->campi[$id]->estende('myFloat',true)) {$MinMax=str_repeat('9', $val['MAXSIZE']-$val['DECIMALI']-$val['DECIMALI']-1).'.'.str_repeat('9',$val['DECIMALI']); // if($this->campi[$id]->get_maxlength()===null) $this->campi[$id]->set_maxlength($val['MAXSIZE']-$val['DECIMALI']); if($this->campi[$id]->get_min()===null) $this->campi[$id]->set_min(-$MinMax); if($this->campi[$id]->get_max()===null) $this->campi[$id]->set_max($MinMax); } elseif( $this->campi[$id]->estende('myInt',true)) {$MinMax=str_repeat('9', $val['MAXSIZE']); if($this->campi[$id]->get_maxlength()===null) $this->campi[$id]->set_maxlength(($val['POSITIVO']?$val['MAXSIZE']:$val['MAXSIZE']+1)); if($this->campi[$id]->get_max()===null) $this->campi[$id]->set_max($MinMax); if($this->campi[$id]->get_min()===null) $this->campi[$id]->set_min(($val['POSITIVO']?0:-$MinMax)); } else $this->campi[$id]->set_maxlength($val['MAXSIZE']); } } if ($val['MYTYPE']=='MyTextArea') {$this->campi[$id]->set_rows(4); $this->campi[$id]->set_cols(70); } if ($val['MYTYPE']=='MyOrario') $this->campi[$id]->set_minuti($val['VALORE']); if ($val['MYTYPE']=='MySelect' && $carica_FK && is_array($val['FK'])) { $tempmode=$this->con->SetFetchMode(ADODB_FETCH_ASSOC); //echo "
",$tab,print_r($val);
    											 foreach ($val['FK'] as $col=>$tab) {;}

    											 $tab=$val['REALTAB_NAMES'][$tab];
    											// $this->con->debug=0;
    											 $rs=&$this->con->cacheselectlimit(7*24*3600,"select * from $tab",1,0);


	  	      									 if(count($rs->fields)==2) {$k=array_keys($rs->fields);
	  	      									 							if (strtoupper($k[0])==$col) $altra=$k[1];
	  	      									 													else $altra=$k[0];
    											  							$this->campi[$id]->set_opzioniQRY($this->con,"select $altra,$col from $tab order by $altra");
    											  							if (!$this->campi[$id]->get_notnull()) $this->campi[$id]->set_domanda(' ');
	  	      									 						   }
    											 $this->con->SetFetchMode($tempmode);
	  	      									 }

			   }
	  $values=array();
      if (is_array($this->ParametriAutomatici))
         foreach ($this->ParametriAutomatici as $id=>$val)
	  		if ((!$colonne || isset($colonne[$id])) && $this->campi[$id])
	  			{
	  	      	if ($val['MYTYPE']=='MyMultiCheck') $values[$id]=(trim($val['VALORE'])!==''?explode(',',$val['VALORE']):array());
	  										   ELSE $values[$id]=$val['VALORE'];
	  		  	}
	 $this->set_defaults($values);
	 $this->istanziati=true;
	 return $this;
	}



	/**
	 * Imposta il separatore dei decimali da usare nelle queri del DB
	 * @param  .|, $separatore
	 */
	function set_separatore_decimali($separatore)
	{if ($separatore=='.' || $separatore==',') 	$this->separatore_decimali=$separatore;
 	 return $this;
	}


	/**
	 * Imposta il form con i valori prelevati dal DB per il record attivo se assente usa i defaults dichiarati nel DB
	 * Viene invocato nella myForm_DB::istanziacampi()
	 *
	 * @param array $valori valori prelevati dal DB per il record attivo
	 */
   function set_defaults($valori='') {
   	if($valori) foreach ($valori as $id=>&$val)
   							if($this->campo($id))
   									$this->campo($id)->set_value($val);
      elseIF (is_array($this->ParametriAutomatici))
    		foreach ($this->ParametriAutomatici as $id=>$val)
    						if($this->campo($id))  $this->campo($id)->set_value($val['VALOREDEFAULT']);
    return $this;
   }



   function get_defaults() {
    IF (is_array($this->ParametriAutomatici))  foreach ($this->ParametriAutomatici as $id=>$val) if($val['VALOREDEFAULT']) $campi[$id]=$val['VALOREDEFAULT'];
    return $campi;
   }

   /**
    * Imposta i tooltip prelevandoli dai commenti della tabella
    *
    */
   function set_tooltip_da_commenti() {return $this;}

}




/**
 *  Versione di myForm_DB ottimizzata per Mysql
  *  @package myForms
**/

Class myForm_MySql extends myForm_DB  {
/**#@+ @ignore */
protected  $SalvaInfo=30;
/**#@-*/

	/**
     * Costruttore di classe
  	 * @access  public
     *
	 * @param    ADODBConnection $con Connessione al db da usare
     * @param    array $colonne elenco delle colonne della tabella da utilizzare, se omesso si usano tutte
     * @param    string $tabella Nome della tabella da utilizzare
     * @param    array $condizioni Array associativo Colonna=>Valore per la condizione di recupero valori dalla tabella
     */
    function myForm_MySQL(&$con,$colonne=array(),$table,$condizioni=array())
	   {//$con->debug=1;
	   	parent::MyForm_DB($con,$colonne,$table,$condizioni);
	  	$this->SalvaInfo=30;
	   }



/** @ignore */
     protected function get_meta_type($fld){
     	if (strtoupper($fld->type)=='YEAR') return 'I';
     	return parent::get_meta_type($fld);
	 }


	function MetaForeignKeys()
	 {  $prec=$this->con->SetFetchMode(ADODB_FETCH_NUM);
		 	$rs=$this->con->cacheexecute(60,"SHOW CREATE TABLE {$this->tabella}");
	 	$this->con->SetFetchMode($prec);

	 	$create=explode('FOREIGN KEY',$rs->fields[1]);
	 	unset($create[0]);
		$f_k=array();

		if (is_array($create))
			foreach ($create as $str)
				{
				 $campi=preg_split('~\\)|\\(~s',str_replace('`',"'",str_replace('REFERENCES ','',$str)));

				 if (count($campi)>=5) {
				 						eval("\$k_locali=array($campi[1]);");
				 						eval("\$tab=$campi[2];");
				 						eval("\$k_ext=array($campi[3]);");
				 						$valori=array();
				 						foreach ($k_locali as $i=>$val) $f_k[$tab][]="$val=$k_ext[$i]";
				 						//echo $tab."-".$campi[1]."
"; } } return $f_k; } /** @ignore */ function SpecificheTecnologiche() { IF ($this->ParametriAutomatici) foreach ($this->ParametriAutomatici as $id=>$val) { if (strpos($val['TIPO'],'enum')!==false) { //print_r($val); if (count(explode("','",$val['TIPO']))>4) $this->ParametriAutomatici[$id]['MYTYPE']='MySelect'; else $this->ParametriAutomatici[$id]['MYTYPE']='MyRadio'; } if (strpos($val['TIPO'],'set')!==false) { $this->ParametriAutomatici[$id]['MYTYPE']='MyMultiCheck'; } if (preg_match('/blob$|text$/i',$val['TIPO'])) {$this->ParametriAutomatici[$id]['MYTYPE']='MyTextArea'; if (stripos($val['TIPO'],'tiny')!==false) $this->ParametriAutomatici[$id]['MAXSIZE']=255; elseif (stripos($val['TIPO'],'long')!==false) $this->ParametriAutomatici[$id]['MAXSIZE']=4294967295; elseif (stripos($val['TIPO'],'medium')!==false) $this->ParametriAutomatici[$id]['MAXSIZE']=16777215; else $this->ParametriAutomatici[$id]['MAXSIZE']=65535; } if ($val['TIPO']=='time') {$this->ParametriAutomatici[$id]['MYTYPE']='MyTime'; unset($this->ParametriAutomatici[$id]['MAXSIZE']); unset($this->ParametriAutomatici[$id]['DECIMALI']); } if ($val['TIPO']=='year') {$this->ParametriAutomatici[$id]['MYTYPE']='MyIntPos'; $this->ParametriAutomatici[$id]['ADODB']='I'; unset($this->ParametriAutomatici[$id]['MAXSIZE']); unset($this->ParametriAutomatici[$id]['DECIMALI']); } if (preg_match('/multi|radio|select|check/i',$this->ParametriAutomatici[$id]['MYTYPE'])) { unset($this->ParametriAutomatici[$id]['MAXSIZE']); unset($this->ParametriAutomatici[$id]['DECIMALI']); } } } function IstanziaCampi($carica_FK=false) { parent::IstanziaCampi($carica_FK); $colonne=array_flip($this->colonne); if($this->ParametriAutomatici) foreach ($this->ParametriAutomatici as $id=>$val) { if(is_object($this->campi[$id])) $val['MYTYPE']=$this->campi[$id]->get_MyType(); if (!$colonne || isset($colonne[$id])) { if ($val['MYTYPE']=='MyIntPos'){ if ($val['TIPO']=='tinyint') $this->campi[$id]->set_max(255); elseif ($val['TIPO']=='smallint') $this->campi[$id]->set_max(65535); elseif ($val['TIPO']=='mediumint') $this->campi[$id]->set_max(16777215); elseif ($val['TIPO']=='int') $this->campi[$id]->set_max(4294967295); if ($val['MAXSIZE']) $this->campi[$id]->set_maxlength($val['MAXSIZE']); } if ($val['MYTYPE']=='MyInt'){ if ($val['TIPO']=='tinyint') {$this->campi[$id]->set_max(127); $this->campi[$id]->set_min(-128); } elseif ($val['TIPO']=='smallint') {$this->campi[$id]->set_max(32767); $this->campi[$id]->set_min(-32768); } elseif ($val['TIPO']=='mediumint') {$this->campi[$id]->set_max(8388607); $this->campi[$id]->set_min(-8388608); } elseif ($val['TIPO']=='int') { $this->campi[$id]->set_max(2147483647); $this->campi[$id]->set_min(-2147483648); } if ($val['MAXSIZE']) $this->campi[$id]->set_maxlength($val['MAXSIZE']); } if ($val['MYTYPE']=='MyOrario' || $val['MYTYPE']=='MyOra') { $val=explode(':',$this->campi[$id]->get_value()); unset($val[2]); $this->campi[$id]->set_value(implode(':',$val)); } if ($this->campi[$id] && ($val['MYTYPE']=='MySelect' || $val['MYTYPE']=='MyRadio' || $val['MYTYPE']=='MyMultiCheck') && preg_match('/enum|set/',$val['TIPO'])) { $opzioni=array(); if(!$this->campi[$id]->get_notnull() && $val['MYTYPE']=='MyRadio') $opzioni=array(); if ($v=preg_split("~\\('|','|'\\)~",str_replace("''","'",$val['TIPO']))) { unset($v[count($v)-1]); unset($v[0]); $opzioni=array_merge($opzioni,array_values($v)); } $opz=array(); foreach ($opzioni as $o) $opz[($o)]=$o; $this->campi[$id]->set_Opzioni($opz); if(!$this->campi[$id]->get_notnull() && !isset($opz['']) && $val['MYTYPE']=='MySelect') { $this->campi[$id]->set_domanda(' '); } } if ($val['MYTYPE']=='MyTextArea' && preg_match('/medium|long/',$val['TIPO'])) $this->campi[$id]->set_rows('30'); if ($val['TIPO']=='year') {$this->campi[$id]->set_max(2100,4); $this->campi[$id]->set_min(1890,4); } } } return $this; } function set_tooltip_da_commenti() { $info=&$this->con->cachegetassoc(3,"show full COLUMNS from ".$this->tabella) ; foreach ($info as $campo=>$infos) if ($infos['Comment']) $this->campo($campo)->set_tooltip($infos['Comment']); return $this; } } /** * Versione di myForm_DB ottimizzata per Oracle * @package myForms **/ Class myForm_Oracle extends myForm_DB { /**#@+ @ignore */ private $sessione_corrente; protected $separatore_decimali='.'; protected $SalvaInfo=43000; /**#@-*/ /** * Costruttore di classe * @access public * * @param ADODBConnection $con Connessione al db da usare * @param array $colonne elenco delle colonne della tabella da utilizzare, se omesso si usano tutte * @param string $tabella Nome della tabella da utilizzare * @param array $condizioni Array associativo Colonna=>Valore per la condizione di recupero valori dalla tabella */ function myForm_Oracle(&$con,$colonne=array(),$tabella,$condizioni='') {if ($colonne) foreach ($colonne as $i=>$v) $colonne[$i]=strtoupper($v); parent::myForm_DB($con,$colonne,strtoupper($tabella),$condizioni); $this->schema=$con->user; $this->SalvaInfo=43000; } /** @ignore */ private function presente_tipo($classe){ foreach ($this->get_campi() as $campo) if (strtolower(get_class($campo))==strtolower($classe)) return true; return false; } function analizza_tabella(){ $this->set_ambiente(true); parent::Analizza_Tabella(); foreach ($this->ParametriAutomatici as $nome=>&$campo) if (preg_match('|^SYS_.+\$$|',$nome)) unset($this->ParametriAutomatici[$nome]); // echo '
';print_r($this->ParametriAutomatici);echo '
'; return $this; } function IstanziaCampi($fk=false){ parent::IstanziaCampi($fk); $this->reset_ambiente(); return $this; } /** Restituisce il valore in formato OCI * @param string $nome_campo * @return mixed $valori */ function get_value_db($obj) { if (is_string($obj)) $obj=$this->campo($obj); if (!is_object($obj) || strlen($obj->get_value())==0) return ''; return parent::get_value_db($obj); } /** * Setta l'ambiente migliore per il salvataggio dei datetime, viene invocato automaticamente * utile invocarlo manualmente se si usano tanti salva su myForm_Oracle non inseriti in una myMultiform * */ function set_ambiente($forza=false){ if ($forza || (!$this->sessione_corrente && $this->presente_tipo('mydatetime'))) { if(!$this->con->enterprisedb) $sessione_corrente=$this->con->getone("SELECT value FROM V\$NLS_PARAMETERS where parameter='NLS_DATE_FORMAT'"); else $sessione_corrente=$this->con->getone("show DATESTYLE"); if (strtolower($sessione_corrente)=='yyyy-mm-dd hh24:mi:ss') $this->sessione_corrente=null; else {$this->sessione_corrente=$sessione_corrente; $this->con->execute("alter session set nls_date_format = 'yyyy-mm-dd hh24:mi:ss'"); } } return $this; } /** * reimposta l'ambiente allo stato normale * */ function reset_ambiente(){ if ($this->sessione_corrente) $this->con->execute("alter session set nls_date_format = '{$this->sessione_corrente}'"); $this->sessione_corrente=null; return $this; } /** * Setta una sequence per la tabella * @param string $nome_sequence * @param string $nome_campo */ function set_sequence($nome_campo,$nome_sequence) { $this->seq_oracle=array($nome_campo=>$nome_sequence); return $this; } function Salva() { if ($this->ripetizione) return ; // se la colonna è not null non dovrebbe bloccare elaborazione*/ if (is_array($this->seq_oracle)) foreach ($this->seq_oracle as $nome_campo=>$nome_sequence) { if (!$this->chiavi) {echo "Impossibile individuare automaticamente le chiavi primarie, impostarle con set_chiavi"; exit;} if ($nome_campo=='' xor $nome_sequence=='') {echo "Specificare sia la sequence che il nome della colonna in cui deve andare il valore"; exit;} elseif ($nome_campo && !isset($this->campi[$nome_campo])) {echo "Sequence associata a colonna '$nome_campo' non presente nella tabella"; exit;} elseif ($nome_campo) {$this->campo($nome_campo)->is_numeric(true); if (!$this->get_value($nome_campo)) {$seq[$nome_campo]=$this->con->getone("SELECT $nome_sequence.nextval as SEQ FROM DUAL"); $this->campo($nome_campo)->set_value($seq[$nome_campo]); if(isset($this->condizioni[strtoupper($nome_campo)])) $this->condizioni[strtoupper($nome_campo)]=$seq[$nome_campo]; } } } $this->set_ambiente(); $esito=parent::salva(); $this->reset_ambiente(); if ($esito!=null && $seq!=null) foreach ($this->seq_oracle as $nome_campo=>&$nome_sequence) {//rollaback manuale della sequenzce $this->campo($nome_campo)->set_value(''); if(isset($this->condizioni[strtoupper($nome_campo)])) $this->condizioni[strtoupper($nome_campo)]=null; } return $esito; } function SpecificheTecnologiche() { // echo "***************************"; if ($this->ParametriAutomatici) foreach ($this->ParametriAutomatici as $id=>$val) { if ($val['TIPO']=='DATE') $this->ParametriAutomatici[$id]['MYTYPE']='MyDate'; } } function Elimina() { if ($this->ripetizione) return ; $this->set_ambiente(); $esito=parent::Elimina(); $this->reset_ambiente(); return $esito; } function Check_Errore_Diviso($qualicampi='',$Esclusi=true){ $this->set_ambiente(); $esito=parent::Check_Errore_Diviso($qualicampi,$Esclusi); $this->reset_ambiente(); return $esito; } function &MetaColumns() { $table=$this->tabella; $normalize=true; $this->database=$this->con->getone("select sys_context('USERENV','CURRENT_SCHEMA') from dual"); /* $info=parent::MetaColumns($table,$normalize); if (is_array($info) && count($info)>0) {return $info;} */ if(!$this->con->enterprisedb) $schemacol=' owner '; else $schemacol=' schemaname '; $rs = $this->con->Execute("select column_name, data_type, data_length, data_scale,data_precision,nullable, data_default from all_tab_columns where $schemacol=:db and table_name=:tabella order by column_id",array('db'=>$this->database,'tabella'=>$table)); if ($rs === false || $rs->EOF) $rs = $this->con->Execute("select column_name, data_type, data_length, data_scale,data_precision,nullable,data_default from all_tab_columns where table_name=:tabella order by column_id",array('tabella'=>$table)); if ($rs === false || $rs->EOF) {return false;} $retarr = array(); while (!$rs->EOF) { $fld = new ADOFieldObject(); $fields=array_values($rs->fields); $fld->name = $fields[0]; $fld->type = $fields[1]; $fld->not_null=$fields[5]=='N'; $fld->default_value=$fields[6]; if ($fields[3]) { if ($fields[4]>0) $fld->max_length = $fields[4]; $fld->scale = $fields[3]; if ($fld->scale>0) $fld->max_length += 1; } else $fld->max_length = $fields[2]; $retarr[strtoupper($fld->name)] = $fld; $rs->MoveNext(); } $rs->Close(); return $retarr; } // Mark Newnham function &MetaIndexes ($table, $primary = FALSE, $owner=false) { // save old fetch mode global $ADODB_FETCH_MODE; $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; if ($this->con->fetchMode !== FALSE) $savem = $this->con->SetFetchMode(FALSE); // get index details $table = strtoupper($table); // get Primary index $primary_key = ''; $false = false; $rs = $this->con->Execute("SELECT * FROM ALL_CONSTRAINTS WHERE UPPER(TABLE_NAME)=:tabella AND CONSTRAINT_TYPE='P'",array('tabella'=>$table)); if ($row = $rs->FetchRow()) $primary_key = $row[1]; //constraint_name if ($primary==TRUE && $primary_key=='') { if (isset($savem)) $this->con->SetFetchMode($savem); $ADODB_FETCH_MODE = $save; return $false; //There is no primary key } $rs= $this->con->Execute("SELECT INDEX_NAME, UNIQUENESS FROM ALL_INDEXES WHERE UPPER(TABLE_NAME)=:tabella",array('tabella'=>$table)); if (!is_object($rs)) { if (isset($savem)) $this->con->SetFetchMode($savem); $ADODB_FETCH_MODE = $save; return $false; } $indexes = array (); // parse index data into array while ($row = $rs->FetchRow()) { // if ($primary && $row[0] != $primary_key) continue; $indexes[$row[0]] = array( 'unique' => ($row[1] == 'UNIQUE'), 'columns' =>array_values((array) $this->con->getassoc("SELECT COLUMN_POSITION,COLUMN_NAME FROM ALL_IND_COLUMNS WHERE INDEX_NAME=:indice",array('indice'=>$row[0]))) ); } // sort columns by order in the index foreach ( array_keys ($indexes) as $index ) ksort ($indexes[$index]['columns']); if (isset($savem)) { $this->con->SetFetchMode($savem); $ADODB_FETCH_MODE = $save; } return $indexes; } } /** * Container di MyForm * @package myForms **/ Class myMultiForm_DB extends myEventManager implements ArrayAccess { /**#@+ @ignore */ protected $myForms,$id_istance,$security,$myMultiform=null,$xml=array('tag'=>null,'case'=>'','header'=>''),$cloni=array(),$eventManager=array(); public function set_myMultiform($myMultiForm) { if (!$myMultiForm) $this->myMultiForm=null; else $this->myMultiForm=$myMultiForm; } /** * Invocato quando questa form viene aggiunta ad una myMultiForm_DB * eventualmente da ridefinire */ function onAddedForm(){ } function onStart(){} function onClose(){} function init(){} public function offsetSet($offset, $value) { return $this->add_Form($offset,$value); } public function offsetExists($offset) { return is_object($this->get_form($offset)); } public function offsetUnset($offset) { $this->unset_Form($offset); } public function offsetGet($offset) { return $this->get_form($offset); } /** @ignore */ function __toString(){ return $this->get_html(); } protected $Forms=array(), $Dipendenze=array(),$lastqry, $separati=true, $AbilitaTransazioni=array(true,true); function __call($metodo,$pars){ if($this->Forms) foreach ($this->Forms as $form) if (method_exists($form,$metodo)) call_user_func_array(array($form, $metodo),$pars); } function __destruct(){ foreach (array_keys($this->Forms) as $idForm) $this->unset_Form($idForm); } function onUserError($error) { foreach ($this->eventManager as &$mng) $mng->onUserError($error,$this); } function onInternalError($error) { foreach ($this->eventManager as &$mng) $mng->onInternalError($error,$this); } /**#@-*/ /** * Distrugge l'istanza e tutte le form in essa contenute indip. dal fatto che siano aggiunte per indirizzo * */ function destruct(){ foreach ($this->Forms as $id=>&$form) { if(method_exists($form,'destruct')) $form->destruct(); if(method_exists($form,'__destruct')) $form->__destruct(); $this->unset_Form($idForm); } } /** * se è un istanza di servizio (non si visualizza il suo html) potrebbe creare problemi * con lo javascript di altre form, questo metodo */ function set_no_html(){ foreach ($this->Forms as $id=>&$form) { if(method_exists($form,'set_no_html')) $form->set_no_html(); } } /** * REstituisce la radice di tutte le myForm e multiform nidificate */ public function get_myFormRootContainer(){ $fatti=array(); $cur=$this; do { $fatti[]=spl_object_hash($cur); if(!is_object($next=$this->get_myFormContainer()) || in_array(spl_object_hash($next),$fatti)) return $cur; $cur=$next; } while (true); } /** * Restituisce il puntatore all'eventuale multiform nel quale è contenuta la myForm * * @return myMultiform_DB */ public function get_myFormContainer() { return $this->myMultiForm; } /** * Costruttore di classe * @access public * @param boolean $separati se false l'html viene costuito in modo che campi di form diversi ma con stessa "name" vengano fusi dopo il POST, il default e TRUE * */ function myMultiForm_DB($separati=true) { parent::__construct(); $this->separati=$separati; if(!$this->id_istance) { $f=new myField(''); $this->myForms=&$f->myFields['myForms']; $this->id_istance=$f->get_id_istanza(); if (!isset($this->myForms['usafile'])) $this->myForms['usafile']=true; $this->mostra_label=true; } } /** @ignore */ function ordineIns() { if(!$this->Forms) return array(); $idForms=array_combine(array_keys($this->Forms),array_keys(array_change_key_case($this->Forms))); if ($this->Dipendenze) $dips=array_change_key_case($this->Dipendenze); while (count($idForms)>0) foreach ($idForms as $id_orig=>$id) { $dipende=false; if (is_array($dips)) foreach ($dips as $padre=>$figli) { $figli=array_change_key_case($figli); if (isset($figli[$id])) { $figli=array_change_key_case($figli[$id]); $dipende=true;break; } } if (!$dipende || count($dips)==0) {$Ordine[]=$id_orig; unset($idForms[$id_orig]); unset($dips[$id]); } } return $Ordine; } /** * * Imposta un eventManager EventManager * @throws Exception se $mng non ha metodi pubblici onUserError e onInternalError * @param EventManager $mng * @param boolean $propaga se true $mng si applica alle form aggiunte con addForm */ function add_EventManager(EventManager $mng,$propaga=true){ if(!method_exists($mng, 'onUserError') && !method_exists($mng, 'onInternalError') ) throw new Exception("set_EventManager deve passare un'istanza di EventManager o sottoclasse che abbia i metodi pubblici onUserError e onInternalError"); $this->eventManager[]=array($mng,$propaga); } function set_secure(mySecurizer $secure) { $this->security=$secure; foreach ($this->Forms as &$form) $form->set_security($this->security); return $this; } /** * Aggiunge Form al multiForm * @param string|int $idForm identificativo univoco della Form aggiunta vedi Salva_form(); * @param MyForm $Form Form da aggiungere * @param boolean $indirizzo se false (default) viene aggiunto un clone del form, altrimenti si inserisce il riferimento all'oggetto passato */ function add_Form($idForm,&$Form,$indirizzo=false) { if ($indirizzo) { if (PHP_VERSION>=5) $this->Forms[$idForm]=$Form; else $this->Forms[$idForm]=&$Form; } else { //$this->Forms[$idForm]=unserialize(serialize($Form)); //$this->Forms[$idForm]->con=$Form->con; //$this->Forms[$idForm]->recordset_attivo=$Form->recordset_attivo; $this->cloni[$idForm]=$idForm; if (PHP_VERSION>=5) $this->Forms[$idForm]=clone ($Form); else $this->Forms[$idForm]=$Form; } if(!$this->Forms[$idForm]->get_id_istanza()) $this->Forms[$idForm]->myForm();//se estensione senza estensione del costruttore forza il costruttore originale $this->Forms[$idForm]->set_myMultiform($this); $this->Forms[$idForm]->onAddedForm(); foreach ($this->eventManager as &$mng) if($mng[1]) $this->Forms[$idForm]->add_EventManager($mng[0]); if($this->security) $this->Forms[$idForm]->set_secure($this->security); $my=new MyUpload(); if ($this->separati && $_FILES) foreach ($_FILES as $i=>$file) {$i=explode('__',$i,2); if ($i[0]==$idForm) $my->MyFields['FILES'][$i[1]]=$file; } //foreach ($Form->get_campi() as $i=>$v) if ($_FILES[$i]) $_FILES[$idForm.'___'.$i]=$_FILES[$i]; //echo "
$idForm";    					print_r(	$this->Forms[$idForm]);
    	$idForms=array_keys((array) $this->Forms);
    	foreach ($idForms as $i=>$id) {
    		//echo "
$idForm";   print_r($this->Forms[$id]->MetaForeignKeys());
    		if (method_exists($this->Forms[$id],'MetaForeignKeys') &&
    		    is_array($_FK=$this->Forms[$id]->MetaForeignKeys())) {
    			$FK=array();
    			foreach ($_FK as $tab=>$campi)
		 					if (is_array($campi))
		 								foreach ($campi as $cols) {
		 										$cols=explode('=',$cols);
		 									  	$FK[strtoupper($cols[0])][]=array(strtoupper($tab)=>strtoupper($cols[1]));
		 										}


    			foreach ($FK as $campoFiglio=>$padri)
    		     	foreach ($padri as $fk)
    			     		foreach ($fk as $tabella=>$campoPadre)
    			     				foreach ($this->Forms as $idf=>$form)
    					     				  if (strtoupper($form->get_tabella())==strtoupper($tabella) &&  $idf!=$id)
    								     				  		 $this->Set_dipendenze($id,$campoFiglio,$idf,$campoPadre);
    		}
    	}

    	return $this->Forms[$idForm];
      }


     function unset_Form($idForm) {
     	if($this->Forms[$idForm] && method_exists($this->Forms[$idForm],'set_myMultiform')) $this->Forms[$idForm]->set_myMultiform(null);
    	unset($this->Forms[$idForm]);
    	unset($this->Dipendenze[$idForm]);
    	foreach ($this->Dipendenze as &$dipendenza) unset($dipendenza[$idForm]);

    	return $this;
    }




     /**
     * Elimina dai DB la tuple relative ai Forms aggiunti,se ok ritorna null
     * @param    array $idForms Array con gli id dei form da eliminare (fa fede ordine), se omesso si eliminano tutti in ordine di inserimento
     */
    function Elimina($idForms='') {
    	$this->lastqry='';
    	if (!$idForms) $idForms=array_keys($this->Forms);
    	if ($this->AbilitaTransazioni[0])
    		foreach ($idForms as $i=>$id) {
    			$keyconn=$this->Forms[$id]->_get_key_conn();
    			if (!$fatta[$keyconn])
    					{$fatta[$keyconn]=1;
    					 $this->Forms[$id]->_get_conn()->begintrans();
    					}
    		}

    	$idForms=array_flip($idForms);
    	$ordine=array_reverse($this->ordineIns());

        foreach ($ordine as $id)
    	  if (isset($idForms[$id]))
    	   {
    	   	if (($errore=$this->Forms[$id]->Elimina())) break;
    		$this->lastqry.=$this->Forms[$id]->get_last_query();
    	    if ($errore) break;
    	   }

    	$fatta=array();
    	if ($this->AbilitaTransazioni[1])
    		foreach ($idForms as $id=>$i) {
    			$keyconn=$this->Forms[$id]->_get_key_conn();
    			if (!$fatta[$keyconn])
    					{
    					 if (!$errore) $this->Forms[$id]->_get_conn()->committrans();
    						 	  else $this->Forms[$id]->_get_conn()->rollbacktrans();
    					 $fatta[$keyconn]=1;
    					}
    		}
    	$this->onInternalError($errore);
    	return $errore;
     }



   /**
     * Salva la tuple relative ai Forms aggiunti sui DB, se ok ritorna null
     * @param    array $idForms Array con gli id dei form da salvare (fa fede ordine), se omesso si salvano tutti in ordine di inserimento
     */

    function Salva($idForms='') {
    	//$FILES=$_FILES;
		$fatta=array();
    	$this->lastqry='';
    	if (!$idForms) $idForms=array_keys($this->Forms);
    	if ($this->AbilitaTransazioni[0])
    		foreach ($idForms as $i=>$id) {
    			$keyconn=$this->Forms[$id]->_get_key_conn();
    			if (!$fatta[$keyconn])
    					{$fatta[$keyconn]=1;
    					 if( $this->Forms[$id]->_get_conn()) $this->Forms[$id]->_get_conn()->BeginTrans();
    					}
    		}

    	$idForms=array_flip($idForms);
    	$ordine=$this->ordineIns();
    	$dips=$this->Dipendenze;
		foreach ($ordine as $id)
    	  if (isset($idForms[$id]))
    	   {
			 /*$_FILES=$FILES;
    	     if ($this->separati && $_FILES)
    	    			{
   	  	 				foreach ($_FILES as $i=>&$file)
   	  	 					{$i=explode('__',$i,2);
   	  	 	 				 if ($i[0]==$id) $_FILES[$i[1]]=$file;
   	  	 				  	}
   	  					}*/
    	   	if (($errore=$this->Forms[$id]->Salva())) break;

    		$this->lastqry.=$this->Forms[$id]->get_last_query();
    	    if (isset($dips[$id]))
    	     				   {
    	     					 foreach ($dips[$id] as $FormFiglio=>$campi)
    	     					 		foreach ($campi as $campoPadre=>$campoFiglio)
    	     					 			if (is_object($this->Form($FormFiglio)) &&
    	     					 				is_object($this->Form($FormFiglio)->campo($campoFiglio)) &&
    	     					 				is_object($this->Form($id)) &&
    	     					 				is_object($this->Form($id)->campo($campoPadre))
    	     					 				)
    	     					 			{
    	     					 		//	echo "
=======================>$id=>$FormFiglio $campoPadre {$this->Forms[$id]->get_value($campoPadre)}=>$campoFiglio=".$this->Forms[$id]->get_value($campoPadre)."
"; //print_r(array_merge($this->Forms[$FormFiglio]->get_values(),array($campoFiglio=>$this->Forms[$id]->get_value($campoPadre)))); $this->Form($FormFiglio)->campo($campoFiglio)->set_value($this->Form($id)->campo($campoPadre)->get_value()); } // else echo "
NON ASSEGNATO=======================>$id=>$FormFiglio $campoPadre {$this->Forms[$id]->get_value($campoPadre)}=>$campoFiglio=".$this->Forms[$id]->get_value($campoPadre)."
"; unset($dips[$id]); } // echo "
"; if ($errore) break; } $fatta=array(); if ($this->AbilitaTransazioni[1]) foreach ($idForms as $id=>$i){ $keyconn=$this->Forms[$id]->_get_key_conn(); if ($keyconn && !$fatta[$keyconn]) { if (!$errore) $this->Forms[$id]->_get_conn()->committrans(); else $this->Forms[$id]->_get_conn()->rollbacktrans(); $fatta[$keyconn]=1; } } //$_FILES=$FILES; $this->onInternalError($errore); return $errore; } /** * Setta dipendenza relazionale (di Foreign Key) tra i campi delle form che compongono la MultiForm * @param string|int $idFormFiglio E' l'idForm assegnato con il metodo addForm * @param string $nomeCampoFiglio E' il campo che deve assumere il valore * @param string|int $idFormPadre E' l'idForm assegnato con il metodo addForm * @param string $nomeCampoPadre E' il campo che distribuisce il valore */ function Set_dipendenze($idFormFiglio,$nomeCampoFiglio,$idFormPadre,$nomeCampoPadre) { $this->Dipendenze[$idFormPadre][$idFormFiglio][strtoupper($nomeCampoPadre)]=strtoupper($nomeCampoFiglio); return $this; } /** * Annulla tutte le dipendenze relazionali (di Foreign Key) tra i campi delle form che compongono la MultiForm * @param string|int $idFormFiglio E' l'idForm assegnato con il metodo addForm * @param string|int $idFormPadre E' l'idForm assegnato con il metodo addForm */ function unSet_dipendenze($idFormFiglio,$idFormPadre) { unset($this->Dipendenze[$idFormPadre][$idFormFiglio]); return $this; } /** * Restituisce il parametro passato nel costruttore * * @return boolean */ function get_separati(){ return $this->separati; } private function __check_errore($idForms=array(),$Esclusi=array(),$testoLinkCampoErrato=array(),$function) { $IDForms=@array_keys((array) $this->Forms); if (!count($IDForms)) return; if(!$idForms) {$idForms=array(); foreach($IDForms as $idf){ $idForms[$idf]=array(); $Esclusi[$idf]=false; } } if(array_values($idForms)===$idForms) $idForms=array_flip((array)$idForms);//se non è associativo lo flippo foreach($IDForms as $idf) {if(isset($idForms[$idf])) $idForms[$idf]=(is_array($idForms[$idf])?$idForms[$idf]:array()); if(!isset($Esclusi[$idf])) $Esclusi[$idf]=false; } $FILES=$_FILES; $f=new MyUpload(''); foreach ($idForms as $idForm=>$esclusi) {$_FILES=$FILES; if (!is_array( $esclusi)) $esclusi=''; if ($this->separati && $_FILES) { foreach ($_FILES as $i=>&$file) {$i=explode('__',$i,2); if ($i[0]==$idForm) $_FILES[$i[1]]=$file; } } $f->myFields['FILES']=$_FILES; if ($errore=$this->Forms[$idForm]->$function($esclusi,$Esclusi[$idForm],$testoLinkCampoErrato[$idForm])) return array('errore'=>$errore,'id'=>$idForm); } $_FILES=$FILES; } /** * Analogo a MyForm * @param array $idForms Array associativo che associa ad ogni idForms i nomi dei campi da escludere/includere, se omesso si verificano tutti, se non è associativo si considerano tutti i campi * @param array $Esclusi Array associativo che associa ad ogni idForms un booleano se true o assente si escludono i campi elencati nel parametro precedente, se falso si applica solo a quelli nel parametro precedente */ function check_errore($idForms='',$Esclusi=array(),$testoLinkCampoErrato=array()) { $errore=$this->__check_errore($idForms,$Esclusi,$testoLinkCampoErrato,'check_errore'); if($errore['errore_tipo']=='user') $this->onUserError($errore); else $this->onInternalError($errore); return $errore['errore']; } /** * Analogo a MyForm * @param array $idForms Array associativo che associa ad ogni idForms i nomi dei campi da escludere/includere, se omesso si verificano tutti * @param array $Esclusi Array associativo che associa ad ogni idForms un boleano se true o assente si escludono i campi elencati nel parametro precedente, se falso si applica solo a quelli nel parametro precedente */ function check_errore_diviso($idForms='',$Esclusi=array(),$testoLinkCampoErrato=array()) { $errore= $this->__check_errore($idForms,$Esclusi,$testoLinkCampoErrato,'check_errore_diviso'); if($errore['errore_tipo']=='user') $this->onUserError($errore); else $this->onInternalError($errore); return $errore; } /** * Analogo a MyForm * @param string $idForm è si l'id del form in cui settare il valore * @param string $campo * @param mix $valore */ function set_value($idForm,$campo,$valore) { if ($this->Forms[$idForm]) { if ($this->separati && preg_match("/^{$idForm__}/i",$campo)) {$campo=explode('__',$campo,2); $campo=$campo[0]; } $this->Forms[$idForm]->set_value($campo,$valore); } return $this; } /** Setta i valori ai campi * @param array $valori Array associativo es $_POST o $_GET */ function set_values($valori) { foreach ($this->Forms as $id=>$obj) if (!$this->separati) $this->Forms[$id]->set_values($valori,$intersezione); else {$vals=array(); foreach ($valori as $i=>&$v) { $i=explode('__',$i,2); if ($i[0]==$id) $vals[$i[1]]=&$v; } $this->Forms[$id]->set_values($vals,$intersezione); } return $this; //echo "
"; print_r($_FILES);
	}


	 /**
     * Analogo a MyForm
     * @param     string $idForm è si l'id del form da cui estrarre il valore
     * @param    string|array $nome_campo nome del campo, se è un array è l'elenco delle labels
     * @return   string|array $label Label associate al/ai campo/i
     */

	function set_label($idForm,$nome_campo,$label) {
		 $this->Forms[$idForm]->set_label($nome_campo,$label);
		 return $this->Forms[$idForm];
  	}


  	function &get_forms() {
		return $this->Forms;
	}



	function &get_form($idForm) {
	  if($this->Forms)
	  	 foreach ($this->Forms as $id=>$form)
	    	if(strtolower($idForm)==strtolower($id) ) 		return $this->Forms[$id];
	}


	function &form($idForm) {
		return $this->get_form($idForm);
	}


	/**
	 * Definisce il tipo di classe nel metodo @see store
	 *
	 * @throws Eccezione generica se non ha entrambi i parametri validi
	 * @param mySessions $container E' un'istanza di mySessions( o estensione)
 	 * @param string $chiave 		Chiave da usare per i dati durante la memorizzazione
	 */
	function set_store_params($container,$chiave){
		if(!is_object($container) ||
		   !$chiave ||
		   !method_exists($container,'set') ||
		   !method_exists($container,'get') ||
		   !method_exists($container,'del')) throw new Exception("Parametri non validi in set_store_params()");
	   if($this->Forms)
	  		 foreach ($this->Forms as $id=>$form)
	  		 			{
	  		 			 $form->set_store_params($container,"{$id}_$chiave");
	  		 			}
		return $this;
	}


	function store_values() {
	  if($this->Forms)
	  	 foreach ($this->Forms as $id=>$form) $form->store_values();
	  	 return $this;
	}


	function get_stored_values(){
		if($this->Forms)
	  	 foreach ($this->Forms as $id=>$form) $out=array_merge((array) $out, $form->get_stored_values());
	  	return $out;
	}


	function restore_values() {
		if($this->Forms)
	  	 foreach ($this->Forms as $id=>$form)  $form->restore_values();
	  	return $this;
	}



     /**
     * Analogo a MyForm
     * @param     string $idForm è si l'id del form da cui estrarre il valore
     * @param     boolean $caseOriginale se false tutto maiuscolo se true quello originale
     * @return    mix
     */
	function &Get_campi($idForm='',$caseOriginale=false) {
		if(!$idForm) {foreach ($this->Forms as $form)  $v=array_merge((array)$v,$form->get_campi($caseOriginale));
					  return $v;
					 }
			elseif ($this->Forms[$idForm]) return $this->Forms[$idForm]->get_campi($caseOriginale);

  	}





  	 /**
     * Analogo a MyForm
     * @param     string $idForm è si l'id del form da cui estrarre il valore
     * @param     string $campo Nome del campo di cui si vuole conoscere il valore
     * @return    mix
     */
	function Get_value($idForm,$campo) {
		if ($this->Forms[$idForm]) return $this->Forms[$idForm]->get_value($campo);

  	}


  	 /**
     * Restituisce array associativo i valori del form
     * @param     string $idForm è si l'id del form da cui estrarre i valori, se omesso estrae i valori di tutti i form
     * @return    array
     */
	function &Get_values($idForm=array(),$label=false,$name=false) {
		//echo "
";print_r($this->Forms[$idForm]);
		if ($idForm) return $this->Forms[$idForm]->get_values('',$label,$name);
				elseif(is_array($idForm))
					 {foreach ($this->Forms as $i=>$f) $v[$i]=$f->get_values('',$label,$name);
    				  return $v;
					 }
					else {$v=array();
						  foreach ($this->Forms as $i=>$f) $v=array_merge($v,$f->get_values('',$label,$name));
    				  	  return $v;
					      }

  	}


  	 /**  Analogo a MyForm
  	 * @param  array $idForms array con le id dei form da visualizzare, se omesso si visualizzano tutti
	 * @param    string $AttributiForm tag della form
     * @param    array  $pulsanti array di MyPulsante
     * @param    string $AttributiTable tag della table
     * @return   string
     */
  	 function &Get_html_Completo($idForms='',$AttributiForm='',$Pulsanti=array(),$AttributiTable=" style='border:0' ") {
  	 	if (is_array($Pulsanti)) {foreach ($Pulsanti as $i=>$p) if (is_object($p)) $pulsanti[]=$p; 	}
  	 						else $pulsanti=array();
		$HTML=$this->Get_html($idForms);

   	 	if ($AttributiForm) {	$AttributiForm=new myTag($AttributiForm);
   	 							if (!$AttributiForm->get_attributo('method'))
   	 									{ $AttributiForm->set_attributo('method','get');
   	 									  if(strpos($HTML,'set_attributo('method','post');
   	 											 			 $AttributiForm->set_attributo('enctype','multipart/form-data');
   	 											 			}
   	 									}
  	 							if (!$AttributiForm->get_attributo('action')) $AttributiForm->set_attributo('action',$_SERVER['PHP_SELF'].($_SERVER['QUERY_STRING']?'?'.htmlentities($_SERVER['QUERY_STRING']):''));
  	 																	else {$action=$AttributiForm->get_attributo('action');
  	 																		 if (stripos($action,'&')!==false &&
  	 							    											 stripos($action,'&')===false) $AttributiForm->set_attributo('action',str_replace('&','&',$action));
  	 																	  	}
  	 							$AttributiForm=$AttributiForm->get_html();
  	 						}
		$table=new myTag($AttributiTable);
		if(trim($HTML)) {
				$x="".$HTML;
				if ($pulsanti) {
								foreach ($pulsanti as $pls) if(method_exists($pls,'get_html')) $pulsantiera.="";
								$x.='		';
							   }
				$x.="
".$pls->get_html()."
'.$pulsantiera.'
"; } if ($AttributiForm) $x="
$x
"; if($this->myForms['DipendenzeCalls']) $x.=""; return $x; } /** * Analogo a MyForm * @param array $idForms array con le id dei form da visualizzare, se omesso si visualizzano tutti * @param array $inizio array associativo con chiave id_form e valore il campo iniziale (eventuale) * @param array $FINE array associativo con chiave id_form e valore il campo FINALE (eventuale) * @return string */ function &get_html($idForms='',$inizio=array(),$fine=array()) { if (!$idForms) $idForms=array_keys($this->Forms); elseif (!is_array($idForms)) $idForms=array($idForms); foreach ($idForms as $idf) if($this->Forms[$idf]) $out.=$this->Get_html_Form($idf,$inizio[$idf],$fine[$idf]); return $out; } /** * Salva l'xml della form * * @param string $nomeFile percorso del file in cui salvare * @param array $idForms array assaociativo che associa alle id delle form da visualizzare il relativo tag, se il valore è null si usa l'id,se il valore è FALSE non si mette tag nella form, se l'array è null si visualizzano tutte le form con l'id come tag * @param array $inizio array associativo con chiave id_form e valore il campo iniziale (eventuale) * @param array $FINE array associativo con chiave id_form e valore il campo FINALE (eventuale) * @return string */ function Salva_xml($nomeFile,$tag='',$case='',$header='',$idForms='',$inizio=array(),$fine=array()) { if(!$tag) $tag=get_class($this); $xml=$this->get_xml($tag,$case,$header,$idForms,$inizio,$fine); $scritti=@file_put_contents($nomeFile,$xml); if(strlen($xml)==$scritti) return true; else {@unlink($nomeFile); $this->onInternalError($this->trasl('Impossibile salvare')); return false; } } /** * Analogo a MyForm * @param array $idForms array assaociativo che associa alle id delle form da visualizzare il relativo tag, se il valore è null si usa l'id,se il valore è FALSE non si mette tag nella form, se l'array è null si visualizzano tutte le form con l'id come tag * @param array $inizio array associativo con chiave id_form e valore il campo iniziale (eventuale) * @param array $FINE array associativo con chiave id_form e valore il campo FINALE (eventuale) * @return string */ function &Get_xml($tag=null,$case='',$header='',$idForms='',$inizio=array(),$fine=array()) { if ($tag===null) {$tag=$this->xml['tag']; if ($tag===null) $tag=get_class($this); } if (!$case) $case=$this->xml['case']; if ($header==='' && !isset($this->xml['header'])) $header=$this->xml['header']; if (!$idForms) $idForms=array_combine(array_keys($this->Forms),array_keys($this->Forms)); elseif (!is_array($idForms)) $idForms=array($idForms); foreach ($idForms as $idf=>$tagForm) { $out.=$this->Forms[$idf]->get_xml(null,$case,false, $inizio[$idf],$fine[$idf]); /*continue; if (!$this->separati) $out.=$this->Forms[$idf]->get_xml(($tagForm===false?'':($tagForm==''?$idf:$tagForm)),$case,false, $inizio[$idf],$fine[$idf]); else { $form=new myform(); foreach ($this->Forms[$idf]->get_campi() as $id=>$campo) {$campo=clone $campo; $campo->set_parametri_xml("{$idf}__{$id}"); $form->add_campo($campo); } $out.=$form->get_xml(($tagForm===false?'':($tagForm==''?$idf:$tagForm)),$case,false,$inizio[$idf],$fine[$idf]); }*/ } $xml=trim($out); if($tag) { if($xml) $xml="<$tag>$xml"; elseif($this->facoltativoXML) return ''; else $xml="<$tag />"; } if($header===false) return $xml; if($header) return $header.$xml; return ''.$xml; } /** * Carica dati da xml, se si passa un nome di file lo carica da li , se si passa l'xml usa quello i due parametri si escludono, se valorizzati entrambi si usa solo il nomefile * * @param string $nomeFile nome del file contenente xml * @param string $xml xml passato * @return void */ function load_xml($nomeFile='',$xml='') { if ($nomeFile) $xml=@simplexml_load_file(realpath($nomeFile),NULL, LIBXML_NOBLANKS|LIBXML_NOCDATA); else $xml=@simplexml_load_string($xml,NULL, LIBXML_NOBLANKS|LIBXML_NOCDATA); if(!$xml) return false; foreach ($xml as $elemento=>$v) { $form=$this->form((string) $elemento); if($form) {$dom = new DOMDocument('1.0', 'UTF-8'); $dom->appendChild($dom->importNode(dom_import_simplexml($v),true)); $form->load_xml(null,$dom->saveXML()); } } return true; } /** * Analogo a MyForm * @param string $idForm è si l'id del form da visualizzare * @param array $campo_inizio Nome del campo da cui iniziare nella costruzione, se omesso si comincia dall'inizio * @param string $campo_fine Nome del campo da cui finire nella costruzione, se omesso si usa solo campo inizio, SE OMESSI ENTRAMBI SI USANO TUTTI I CAMPI * @return string */ function &Get_html_Form($idForm,$campo_inizio='',$campo_fine='') { if(!$this->Forms[$idForm]) return; if (!$this->separati) return $this->Forms[$idForm]->get_html($campo_inizio,$campo_fine); ELSE { $this->Forms[$idForm]->set_prefisso_nomi_campi($idForm."__",true); $html=$this->Forms[$idForm]->get_html($campo_inizio,$campo_fine); $this->Forms[$idForm]->set_prefisso_nomi_campi($idForm."__",false); return $html; } } function abilitazione_transazioni($start,$chiusura) { $this->AbilitaTransazioni=array($start,$chiusura); return $this; } } /** * @author Gianluca GIMIGLIANO * @package myForms */ class myForm_XML extends myForm_MySql { protected $dom, $pointer, $nomefile, $risorsefile, $xml_originale, $transazione = false; protected static $files; function myForm_XML($nomefile, $colonne, $tabella, $condizioni = '') { parent::myForm (); if (self::$files [$nomefile]) throw new Exception ( "File $nomefile già in uso in un'altra istanza" ); self::$files [$nomefile] = $nomefile; $this->colonne = $colonne; $this->condizioni = $condizioni; if (! is_file ( $nomefile ))@file_put_contents ( $nomefile, LOCK_EX ); $this->nomefile = realpath ( $nomefile ); $this->schema = get_class ( $this ); $this->tabella = $tabella; $this->id=md5($this->schema.$tabella."=>".$this->id_istance.serialize($condizioni).serialize($colonne).$_SERVER['PHP_SELF']); $this->ripetizione=$this->is_f5(); if ($this->ripetizione && ($recovered=$this->recover_chiavi())) $this->condizioni=$recovered; } /** * #@+ @ignore */ protected function quota_colonne($array, $tutte = false) { echo 'quota colonne'; exit (); } function MetaForeignKeys() { } function _get_conn() { return $this; } function Begintrans() { $this->transazione = true; } function RollbackTrans() { $this->transazione = false; $this->scarica_xml (); } function CommitTrans() { $this->transazione = false; $this->scarica_xml ( $false = false ); } protected function carica_xml($flock = '') { $this->domIndex = array (); $lock = @flock ( $this->risorsefile = @fopen ( $this->nomefile, 'r+' ), ($flock ? $flock : LOCK_SH) ); if (is_object ( $this->dom = DOMDocument::LoadXML ( $this->xml_originale = @fread ( $this->risorsefile, filesize ( $this->nomefile ) ) ) )) $this->pointer = $this->dom->getElementsByTagName ( $this->schema )->item ( 0 ); else { $this->dom = new DOMDocument ( '1.0', 'UTF-8' ); $this->dom->appendChild ( $this->pointer = $this->dom->createElement ( $this->schema ) ); if ($this->risorsefile) { @ftruncate ( $this->risorsefile, 0 ); @rewind ( $this->risorsefile ); } } $this->dom->preserveWhiteSpace = false; if ($flock || ! $lock) @rewind ( $this->risorsefile ); else { @flock ( $this->risorsefile, LOCK_UN ); @fclose ( $this->risorsefile ); } return $lock; } /** * * @ignore * */ protected function scarica_xml(&$xml = '') { if ($xml !== false) { if ($xml) @fwrite ( $this->risorsefile, $x = $xml ); else @fwrite ( $this->risorsefile, $x = $this->xml_originale ); @ftruncate ( $this->risorsefile, strlen ( $x ) ); // $mancanti=filesize($this->nomefile)-strlen($x); // if($mancanti) @fwrite($this->risorsefile,str_repeat(' // ',$mancanti)); } @flock ( $this->risorsefile, LOCK_UN ); @fclose ( $this->risorsefile ); } /** * * @ignore * */ protected function &intersezione(&$a, &$b) { $nuovo = array (); for($i = 0; $i < count ( $a ); $i ++) for($j = 0; $j < count ( $b ); $j ++) if ($a [$i] === $b [$j]) $nuovo [] = &$a [$i]; return $nuovo; } /** * * @ignore * */ protected function &differenza(&$a, &$b) { $nuovo = array (); for($i = 0; $i < count ( $a ); $i ++) { $trovato = false; for($j = 0; $j < count ( $b ); $j ++) if ($a [$i] === $b [$j]) $trovato = TRUE; if (! $trovato) $nuovo [] = &$a [$i]; } return $nuovo; } /** * * @ignore * */ protected function &estrai_indice($campo) { if ($this->domIndex [strtoupper ( $campo )]) return $this->domIndex [strtoupper ( $campo )]; $valori = $this->dom->getelementsbytagname ( $this->colonneOriginali [strtoupper ( $campo )] ); if (! $valori) return array (); else foreach ( $valori as $elemento ) $this->domIndex [strtoupper ( $campo )] [strtolower ( utf8_decode ( $elemento->nodeValue ) )] [] = &$elemento->parentNode; return $this->domIndex [strtoupper ( $campo )]; } /** * * @ignore * */ protected function &get_id_tupla(&$where, $eccezioni_entita = array()) { if ($where) foreach ( $where as $campo => &$valore ) { $indici [strtoupper ( $campo )] = &$this->estrai_indice ( $campo ); $myWhere [] = &$indici [strtoupper ( $campo )] [strtolower ( $valore )]; } $intersezioneInclusi = $myWhere [0]; for($i = 1; $i < count ( $myWhere ); $i ++) { $confronto = $myWhere [$i]; $intersezioneInclusi = $this->intersezione ( $intersezioneInclusi, $confronto ); } if ($eccezioni_entita && $intersezioneInclusi) { $myWhere = array (); foreach ( $eccezioni_entita as $campo => &$valore ) { foreach ( $this->estrai_indice ( $campo ) as $valori ) { $indici [strtoupper ( $campo )] = &$this->estrai_indice ( $campo ); $myWhere [] = &$indici [strtoupper ( $campo )] [strtolower ( $valore )]; } } $intersezioneEsclusi = $myWhere [0]; for($i = 1; $i < count ( $myWhere ); $i ++) { $confronto = $myWhere [$i]; $intersezioneEsclusi = $this->intersezione ( $intersezioneEsclusi, $confronto ); } if ($intersezioneEsclusi) $intersezioneInclusi = $this->differenza ( $intersezioneInclusi, $intersezioneEsclusi ); } // echo $intersezioneInclusi[0]->tagName;exit; return $intersezioneInclusi [0]; } /* * protected function &get_id_tupla(&$where,$eccezioni_entita=array()) { * $xpath = new DOMXPath($this->dom); $xpath->registerPHPFunctions(); * $xpath->registerNamespace("php", "http://php.net/xpath"); * $percorso="/{$this->schema}/{$this->tabella}"; if($where) foreach ($where * as $campo=>$valore) if(strlen($valore)) { * $valore=(addslashes(strtolower($valore))); * $campo=$this->colonneOriginali[$campo]; * $qry[]="php:functionString(\"strtolower\",{$campo})='$valore'"; } if * ($qry) $qry='('.implode(' and ',$qry).')'; if($eccezioni_entita) foreach * ($eccezioni_entita as $campo=>$valore) if(strlen($valore)) { * $valore=addslashes($valore); $campo=$this->colonneOriginali[$campo]; * $ecz[]="php:functionString(\"strtolower\",{$campo})!='$valore'"; } * if($ecz) {$ecz='('.implode(' or ',$ecz).')'; if($qry) $ecz="and $ecz"; } * echo '
'; echo $query="{$percorso}[$qry $ecz]"; * $entries=$xpath->query($query); print_r($entries->length); foreach * ($entries as $entry) return $entry; return false; } */ /** * * @ignore * */ protected function estrai_record(&$where, &$id_tupla, &$tupla) { $id_tupla = $tupla = null; $id_tupla = $this->get_id_tupla ( $where ); if ($id_tupla) foreach ( $id_tupla->childNodes as $i => $oChildNode ) $tupla [strtoupper ( $oChildNode->tagName )] = utf8_decode ( $oChildNode->nodeValue ); return $tupla !== null; } function set_valori_recorddiLavoro($values, $id_tupla) { if (! $this->recordset_attivo) $this->recordset_attivo = new stdClass (); $this->recordset_attivo->fields = $values; $this->recordset_attivo->id_tupla = $id_tupla; return $this; } function get_valori_recorddiLavoro($ricarica = false, $caseChiavi = 'U') { if (! $this->chiavi) return; if ($ricarica) { $this->recordset_attivo = null; $where = array (); $condizioni = array_change_key_case ( $this->condizioni ); foreach ( $this->chiavi as $col ) { $val = trim ( $condizioni [strtolower ( $col )] ); if ($val === '') { $where = array (); break; } $where [$col] = $val; } if ($this->estrai_record ( $where, $id_tupla, $tupla )) { $this->recordset_attivo = new stdClass (); $this->recordset_attivo->id_tupla = $id_tupla; $valori = array_change_key_case ( $tupla ); foreach ( $this->colonne as $colonna ) if (isset ( $valori [strtolower ( $colonna )] )) $this->recordset_attivo->fields [$colonna] = &$valori [strtolower ( $colonna )]; } } if ($this->recordset_attivo && $this->recordset_attivo->fields) switch ($caseChiavi) { case 'U' : return array_change_key_case ( $this->recordset_attivo->fields, CASE_UPPER ); case 'N' : return $this->recordset_attivo->fields; case 'L' : return array_change_key_case ( $this->recordset_attivo->fields, CASE_LOWER ); } return null; } function analizza_tabella() { foreach ( $this->colonne as $colonna ) { $COLONNA = strtoupper ( $colonna ); $this->colonneOriginali [$COLONNA] = $colonna; $this->ParametriAutomatici [$COLONNA] ['MYTYPE'] = 'MyText'; } $this->carica_xml (); IF ($this->condizioni) { if (! $this->chiavi) $this->set_chiavi ( array_keys ( $this->condizioni ) ); $valori = $this->get_valori_recorddiLavoro ( true, 'U' ); foreach ( $this->colonne as $colonna ) { $COLONNA = strtoupper ( $colonna ); $this->ParametriAutomatici [$COLONNA] ['VALORE'] = $valori [$COLONNA]; } } return $this; } /** * * @ignore * */ protected function estrai_active_record($id_tupla) { $CHIAVI = array_change_key_case ( array_flip ( $this->chiavi ), CASE_UPPER ); foreach ( $id_tupla->childNodes as $i => $oChildNode ) if (isset ( $CHIAVI [strtoupper ( $oChildNode->tagName )] )) { $CHIAVI [strtoupper ( $oChildNode->tagName )] = ( string ) $oChildNode->nodeValue; $settati ++; } if ($settati == count ( $CHIAVI )) return $CHIAVI; } function Check_Errore_Diviso($qualicampi = '', $Esclusi = true) { $errore = myForm::Check_Errore_Diviso ( $qualicampi, $Esclusi ); if ($errore) return $errore; return $this->Check_Errore_Diviso_univocita (); } /** * * @ignore * */ protected function Check_Errore_Diviso_univocita($id_tupla = '') { if (is_array ( $this->indici ) && count ( $this->indici ) > 0 && ! $this->ripetizione) { $chiavi = $this->condizioni; if (! $id_tupla) $id_tupla = $this->recordset_attivo->id_tupla; if ($id_tupla) $noChiave = $this->estrai_active_record ( $id_tupla ); foreach ( $this->indici as $indice ) if ($indice ['unique'] && ! $gia_fatto [serialize ( $indice ['columns'] )]) { $gia_fatto [serialize ( $indice ['columns'] )] = 1; $colonne = array_flip ( array_change_key_case ( array_flip ( ( array ) $indice ['columns'] ), CASE_UPPER ) ); $campi = array (); $condizioni = ''; foreach ( $colonne as $colonna ) if ($this->campo ( $colonna ) && strlen ( $valoredb = $this->get_value_db ( $this->campo ( $colonna ) ) )) { $campi [$colonna] = $valoredb; // echo "$colonna // =>".$this->campo($colonna)->get_value()."
"; } if ($campi && count ( $campi ) == count ( $indice ['columns'] )) { if ($campi == $chiavi) continue; $condizioni = &$campi; } $idtupla = $this->get_id_tupla ( $condizioni, $noChiave ); if ($idtupla) { $labels = array (); foreach ( $colonne as $vals ) if ($this->get_label ( $vals )) { $labels [] = $this->get_label ( $vals ); $fields [] = $this->campo ( $vals ); } return array ( 'label' => $labels, 'errore' => $this->trasl ( "I campi: '%label%' sono già stati usati in un altro record" ), 'campo' => $fields ); } } } } function Elimina() { $lock = $this->carica_xml ( LOCK_EX ); if (! $lock) { $this->onInternalError ( $this->trasl ( 'Impossibile eliminare' ) ); return $this->trasl ( 'Impossibile eliminare' ); } if ($this->recordset_attivo->id_tupla) $this->dom->removechild ( $this->recordset_attivo->id_tupla ); $this->scarica_xml (); } function Salva() { // echo $this->tabella.$this->con->_connectionID." // ".$this->con->_commit."
"; // if ($this->ripetizione) return ; $this->lastqry = ''; $lock = $this->carica_xml ( LOCK_EX ); if (! $lock) { $this->onInternalError ( $this->trasl ( 'Impossibile salvare' ) ); return $this->trasl ( 'Impossibile salvare' ); } $this->get_valori_recorddiLavoro ( true, 'U' ); $errore = $this->Check_Errore_Diviso_univocita (); if ($errore) $errore = strtr ( $errore ['errore'], array ( '%label%' => implode ( ',', $errore ['label'] ), '%errore%' => $errore ['errore_puro'] ) ); // $this->con->debug=1; if (! $errore) try { if ($this->AutoIncrementante && ! $this->campo ( $this->AutoIncrementante )->get_value ()) $this->campo ( $this->AutoIncrementante )->set_value ( myUUID::v4 () ); if ($this->recordset_attivo->id_tupla) $this->pointer->removechild ( $this->recordset_attivo->id_tupla ); // $this->recordset_attivo->id_tupla=$this->pointer->replaceChild($this->dom->importNode(DOMDocument::loadxml($this->Get_xml($this->tabella))->getElementsByTagName($this->tabella)->item(0),true),$this->recordset_attivo->id_tupla); $this->recordset_attivo->id_tupla = $this->pointer->appendChild ( $this->dom->importNode ( DOMDocument::loadxml ( $this->Get_xml ( $this->tabella ) )->getElementsByTagName ( $this->tabella )->item ( 0 ), true ) ); if ($this->transazione) { fwrite ( $this->risorsefile, $x = $this->dom->saveXML () ); @ftruncate ( $this->risorsefile, strlen ( $x ) ); } else $this->scarica_xml ( $this->dom->saveXML () ); } catch ( Exception $e ) { $errore = $this->trasl ( 'Impossibile salvare' ); } if (! $errore) { $this->set_valori_recorddiLavoro ( $this->get_values (), $this->recordset_attivo->id_tupla ); $this->recover_chiavi ( $this->get_chiavi () ); } else $this->onInternalError ( $errore ); return $errore; } /** * #@- */ } ?>