Main Page   Compound List   File List   Compound Members   File Members  

pgdb.php

Go to the documentation of this file.
00001 <?php
00002 ############################################################################
00003 #    Copyright (C) 2004 by Paolo Armani & Stefano Menegon                  #
00004 #    paolo.armani@gmail.com   menegon@itc.it                               #
00005 #                                                                          #
00006 #    This program is free software; you can redistribute it and#or modify  #
00007 #    it under the terms of the GNU Library General Public License as       #
00008 #    published by the Free Software Foundation; either version 2 of the    #
00009 #    License, or (at your option) any later version.                       #
00010 #                                                                          #
00011 #    This program is distributed in the hope that it will be useful,       #
00012 #    but WITHOUT ANY WARRANTY; without even the implied warranty of        #
00013 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         #
00014 #    GNU General Public License for more details.                          #
00015 #                                                                          #
00016 #    You should have received a copy of the GNU Library General Public     #
00017 #    License along with this program; if not, write to the                 #
00018 #    Free Software Foundation, Inc.,                                       #
00019 #    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             #
00020 ############################################################################
00021 
00022 
00024 //                                                                            //
00026 /*! \brief this class is used to interface Pgtable class to postgresql, 
00027  */
00028 class Pgdb{
00029   var $SQL_DEBUG;
00030 
00031   var $dbConn;
00032   var $pgVersion;
00033   var $useSchema;
00034 
00035   var $attribs; 
00036   var $notNull; 
00037   var $isExpression; 
00038 
00039   var $errors;
00040   var $warnings;
00041 
00042   var $files;
00043   var $filesDir;
00044 
00045   var $STRINGS;
00046 
00048   //                                                                            //
00050   function Pgdb($dbConn){
00051     $this->SQL_DEBUG=1;
00052     $this->errors = new Pgmessages(); 
00053     $this->warnings = new Pgmessages(); 
00054     $this->dbConn=$dbConn;
00055 
00056     $res=pg_query($this->dbConn, 'SELECT version();');
00057     $this->check_pg_errors();
00058     
00059     list($ver)=pg_fetch_row($res, 0);
00060     $this->pgVersion=preg_replace('/([^0-9]*)([0-9\.]+)(.*)/','$2', $ver);
00061     $this->useSchema = ($this->pgVersion >= '7.3');
00062     
00063     $this->files=array("delete"=>array(), "create"=>array());
00064     $this->filesDir=array("local"=>"", "remote"=>"");
00065 
00066     global $STRINGS;
00067     $this->STRINGS=&$STRINGS;
00068   }
00069 
00071   //                                                                            //
00073   function check_pg_errors(){
00074    $this->warnings->add(pg_last_notice($this->dbConn));
00075    return $this->errors->add(pg_last_error($this->dbConn));
00076   }
00077 
00079   //                                                                            //
00081   function get_table_attributes($tbSchema='public', $tbName){
00082     $tmp=get_table_attributes($this->dbConn, $tbName, '', PGSQL_NUM, PGSQL_ASSOC, $this->useSchema?$tbSchema:false);
00083     foreach($tmp as $key=>$val){
00084       $this->attribs[$tbSchema][$tbName][$val["attname"]]=$tmp[$key];
00085     }
00086 
00087     $arr =& $this->attribs[$tbSchema][$tbName] ;
00088     static $i=0;
00089     foreach($arr as $key=>$val){
00090       //set postgres "t" and "f" in php "true" and "false"
00091 
00092       $arr[$key]["attnotnull"] = ( $arr[$key]["attnotnull"]=='t');
00093       $arr[$key]["atthasdef"] = ( $arr[$key]["atthasdef"]=='t');
00094       $arr[$key]["table"] = $tbName;
00095       $arr[$key]["schema"] = $tbSchema;
00096 
00097       $arr[$key]["display"]=array("new"=>true, "edit"=>true, "search"=>true,"view"=>true,"preSearch"=>true, "export"=>true);
00098       $arr[$key]["priority"]=$i--;
00099     }
00100     
00101     $this->notNull[$tbSchema][$tbName]=$this->not_null($tbSchema, $tbName);
00102     $this->isExpression[$tbSchema][$tbName]=$this->is_expression($tbSchema, $tbName);
00103     return $arr;
00104   }
00105 
00107   //                                                                            //
00109   function get_foreign_keys($tbSchema='public', $tbName){
00110     $ref=array();
00111     if($this->pgVersion < '7.3') return array();
00112       
00113     $child= get_foreign_keys($this->dbConn, true, $tbName, false, $this->useSchema?$tbSchema:false);
00114     $parent= get_foreign_keys($this->dbConn, false, $tbName, false, $this->useSchema?$tbSchema:false);
00115     if(is_array($child)){
00116       foreach($child as $key1=>$val1){
00117         $ref[$val1["cl_parent"]]["child"][]=array('table'=>$val1["tb_child"], 'field'=>$val1["cl_child"]);
00118       }
00119     }
00120     if(is_array($parent)){
00121       foreach($parent as $key1=>$val1){
00122           $ref[$val1["cl_child"]]["parent"]=array('table'=>$val1["tb_parent"], 'field'=>$val1["cl_parent"], "when"=>array('search', 'view', 'preSearch', 'new', 'edit'), "query"=>false, "type"=>"popup");
00123 
00124 #Only for debug !!! to remove and uncomment previous line!!!! (why this is here???)
00125 #         $ref[$val1["cl_child"]]["parent"]=array('table'=>$val1["tb_parent"], 'field'=>$val1["cl_parent"], "when"=>array('search', 'view', 'preSearch', 'insert', 'edit'), "query"=>false, "type"=>"select");
00126 
00127       }
00128     }
00129     return $ref;
00130   }
00131   
00132   
00134   //                                                                            //
00136   function get_inh_tables($tbSchema='public', $tbName){
00137     if($this->pgVersion < '7.3') return array();
00138     
00139     $inherited= get_inh_tables($this->dbConn, $tbSchema, $tbName);
00140     $inh=array();
00141     if(is_array($inherited) && count($inherited)>0){
00142       $inh[$tbSchema][$tbName]=true;
00143     }
00144     return $inh;
00145   }
00146 
00148   //                                                                            //
00150   function set_value_from_pkey($tbSchema='public', $table,  $pkeyVal='', $pkey='oid', $query=false){
00151     $schemaTable='"'.($this->useSchema?(pg_escape_string($tbSchema).'"."'):'').pg_escape_string($table).'"';
00152     $where=" WHERE $schemaTable.\"".pg_escape_string($pkey)."\"='".pg_escape_string($pkeyVal)."';"; 
00153 
00154     if(!$query){
00155       $pkey=($pkey!='')?$pkey:'oid';
00156       $query='SELECT * FROM '.$schemaTable.$where;
00157     }
00158     elseif($pkeyVal!=''){
00159       $query.=$where;
00160     }
00161 
00162     if($this->SQL_DEBUG) echo $query."<br>";
00163     $result=pg_query($this->dbConn, $query);
00164     $this->check_pg_errors();
00165 
00166     $arr =pg_fetch_array($result,0,PGSQL_ASSOC);;
00167     $this->check_pg_errors();
00168 
00169     return $arr ;
00170   }
00171   
00173   //                                                                            //
00175   function select($query) {
00176     if($this->SQL_DEBUG) echo $query."\n<br>\n";
00177     $result=pg_query($this->dbConn, $query);
00178     $this->check_pg_errors();
00179 
00180     $arr =pg_fetch_all($result);
00181     $this->check_pg_errors();
00182 
00183     return $arr ;
00184   } 
00185 
00187   //                                                                            //
00189   function whereClause($tbSchema, $tbName, $field, $val, $operator='='){
00190     $schema=$this->useSchema?(' "'.pg_escape_string($tbSchema).'".'):' ';
00191     $this->parse_geometry($tbSchema, $tbName,&$val, $field);
00192     if(!$this->isExpression[$tbSchema][$tbName][$field]) $val="'".pg_escape_string($val)."'";
00193     return ($schema.'"'.pg_escape_string($tbName).'"."'.pg_escape_string($field).'"'.$operator.$val);
00194   }
00195 
00197   //                                                                            //
00199   function orderClause($tbSchema, $tbName, $field, $order='ASC'){
00200     $schema=$this->useSchema?('"'.pg_escape_string($tbSchema).'".'):'';
00201     return (" ORDER BY ".$schema.'"'.pg_escape_string($tbName).'"."'.pg_escape_string($field).'" '.$order.' ');
00202   }
00203   
00205   //                                                                            //
00207   function limitClause($limit=10, $offset=0){
00208     if($offset<0) $offset=0;
00209     if(!$limit || $limit>100 || $limit<1) $limit=10;
00210     return (" LIMIT $limit OFFSET $offset ;");
00211   }
00212   
00214   //                                                                            //
00216   function selectClause($tbSchema, $tbName, $field="*", $inherits){
00217     $schema=$this->useSchema?('"'.pg_escape_string($tbSchema).'".'):'';
00218     $tbName='"'.pg_escape_string($tbName).'"';
00219     $only=(!isset($inherits) || $inherits)?'':'ONLY';
00220     $field=($field=='' || $field=="*")? "*" : ("$schema$tbName.\"".pg_escape_string($field).'"');
00221     return (" SELECT $field FROM $only $schema$tbName");
00222   }
00223 
00225   //                                                                            //
00227   function numRecords($tbSchema, $tbName, $inherits=true, $where=''){
00228     $schema=$this->useSchema?('"'.pg_escape_string($tbSchema).'".'):'';
00229     $table='"'.pg_escape_string($tbName).'"';
00230     $only=(!isset($inherits) || $inherits)?'':'ONLY';
00231     $sql="SELECT count(*) FROM $only $schema$table ".$where;;
00232 
00233     if($this->SQL_DEBUG) echo $sql."\n<br>\n";
00234     $result=pg_query($this->dbConn, $sql);
00235     $this->check_pg_errors();
00236 
00237     $arr =pg_fetch_all($result);
00238     $this->check_pg_errors();
00239 
00240     return $arr[0]["count"] ;
00241   }
00242 
00243 
00245   //                                                                            //
00247   //return true if succes, false otherwise
00248   function delete($tbSchema='public', $tbName, $pkey, $pkeyField='oid', $num=0){
00249     pg_query($this->dbConn, 'BEGIN;');
00250 
00251     if (!$this->filesUpload($tbSchema, $tbName, $num, $val, "delete", $pkeyField, $pkey)){
00252 
00253       $this->filesRollback(); //if files are stored in a directory and not in a database, delete created files 
00254       pg_query($this->dbConn, 'ROLLBACK;');
00255       return false;
00256     }
00257 
00258     if($pkeyField=='')$pkeyField='oid';
00259 
00260     $query='DELETE FROM "'.($this->useSchema?(pg_escape_string($tbSchema).'"."'):'').pg_escape_string($tbName).'" ';
00261     $query.=where_sql(array($pkeyField=>$pkey)); 
00262     
00263     $result=pg_query($this->dbConn,$query);
00264     if($this->SQL_DEBUG) echo $query."<br>\n";
00265 
00266     if($this->check_pg_errors()){
00267       $this->filesRollback(); //if files are stored in a directory and not in a database, delete created files 
00268       pg_query($this->dbConn, 'ROLLBACK;');
00269       return false;
00270     }
00271     else{
00272       $lines=pg_affected_rows($result);
00273       if($lines!=1){
00274         $this->errors->add($this->STRINGS["try_delete"]." $lines ".$this->STRINGS["records"].": ".$this->STRINGS["ROLLBACK"]." !!!"); 
00275         $this->filesRollback(); //if files are stored in a directory and not in a database, delete created files 
00276         pg_query($this->dbConn, 'ROLLBACK;');
00277         return false;
00278       }
00279       else{
00280         $this->filesEnd($lines); //if files are stored in a directory and not ina a database, complete now operations to make possible a rollback
00281         pg_query($this->dbConn, 'END;');
00282         return true;
00283       }
00284     }
00285   }
00286 
00287 
00288 
00290   //                                                                            //
00292   //return pkey if succes, false otherwise
00293   function update($tbSchema='public', $tbName, $val, $pkey, $pkeyField='oid', $num){
00294     pg_query($this->dbConn, 'BEGIN;');
00295 
00296     if (!$this->filesUpload($tbSchema, $tbName, $num, $val, "update", $pkeyField, $pkey)){
00297 
00298       $this->filesRollback(); //if files are stored in a directory and not in a database, delete created files 
00299       pg_query($this->dbConn, 'ROLLBACK;');
00300       return false;
00301     }
00302 
00303     if($pkeyField=='')$pkeyField='oid';
00304 
00305     $this->parse_geometry($tbSchema, $tbName, &$val);
00306 
00307     $query=update_sql($tbSchema, $tbName, $val,  $this->notNull[$tbSchema][$tbName], $this->isExpression[$tbSchema][$tbName]);
00308     $query.=where_sql(array($pkeyField=>$pkey)) ; 
00309     
00310     $result=pg_query($this->dbConn,$query);
00311     if($this->SQL_DEBUG) echo $query."<br>\n";
00312 
00313     if($this->check_pg_errors()){
00314       $this->filesRollback(); //if files are stored in a directory and not in a database, delete created files 
00315       pg_query($this->dbConn, 'ROLLBACK;');
00316       return false;
00317     }
00318     else{
00319       $lines=pg_affected_rows($result);
00320       if($lines!=1){
00321         $this->errors->add($this->STRINGS["try_modify"]." $lines ".$this->STRINGS["records"].": ".$this->STRINGS["ROLLBACK"]." !!!"); 
00322         $this->filesRollback(); //if files are stored in a directory and not in a database, delete created files 
00323         pg_query($this->dbConn, 'ROLLBACK;');
00324         return false;
00325       }
00326       else{
00327         if(array_key_exists($pkeyField, $val) && $val[$pkeyField]!=$pkey){
00328           $pkey=$val[$pkeyField];
00329         }
00330         $this->filesEnd($lines); //if files are stored in a directory and not ina a database, complete now operations to make possible a rollback
00331 
00332         pg_query($this->dbConn, 'END;');
00333         return $pkey;
00334       }
00335     }
00336   }
00337 
00338 
00340   //                                                                            //
00342   //return pkey if succes, false otherwise
00343   function insert($tbSchema='public', $tbName, &$val, $pkeyfield, $num=0){
00344     pg_query($this->dbConn, 'BEGIN;');
00345     
00346     if (!$this->filesUpload($tbSchema, $tbName, $num, $val, "insert")){
00347       
00348       $this->filesRollback(); //if files are stored in a directory and not in a database, delete created files 
00349       pg_query($this->dbConn, 'ROLLBACK;');
00350       return false;
00351     }
00352 
00353     /*
00354       the problem is to know how record was insert if pkey is not already defined: so 
00355       if pkey value is defined ->insert
00356       elseif default value of pkey is defined -> select default value->insert
00357       else -> select insert, select  oid to chose where line was inserted, then select pkey   
00358     */
00359     if($pkeyField=='')$pkeyField='oid';
00360 
00361     /* use this three lines or select pkey value then
00362     if($pkeyField!='oid' && $val[$pkeyField]=='' && $this->attribs[$tbSchema][$table][$pkeyField]['adsrc']!=''){
00363       $tmp=$this->select("SELECT ".$this->attribs[$tbSchema][$table][$pkeyField]['adsrc'].";");
00364       $arr["val"][$tbSchema][$tbName][$pkeyField]=current($tmp[0]);
00365     }
00366     */
00367 
00368     $this->parse_geometry($tbSchema, $tbName, &$val);
00369 
00370     $query=insert_sql($tbSchema, $tbName, $val, $this->notNull[$tbSchema][$tbName], $this->isExpression[$tbSchema][$tbName]);
00371     $result=pg_query($this->dbConn,$query);
00372     if($this->SQL_DEBUG) echo $query."<br>\n";
00373 
00374     if($this->check_pg_errors()){
00375       $this->filesRollback(); //if files are stored in a directory and not in a database, delete created files 
00376       pg_query($this->dbConn, 'ROLLBACK;');
00377       return false;
00378     }
00379     else{
00380       $lines=pg_affected_rows($result);
00381       if($lines!=1){ 
00382         $this->errors->add($this->STRINGS["try_modify"]." $lines ".$this->STRINGS["records"].": ".$this->STRINGS["ROLLBACK"]." !!!"); 
00383         $this->filesRollback(); //if files are stored in a directory and not in a database, delete created files 
00384         pg_query($this->dbConn, 'ROLLBACK;');
00385         return false;
00386       }
00387 
00388       if($pkeyField=='oid'){
00389         $pkey=pg_last_oid($result);
00390       }
00391       //use these tree lines or tree commented upper 
00392       elseif($val[$pkeyField]==''){
00393         $tmp=select('select "'.pg_escape_string($pkeyField).'" from "'.($this->useSchema?(pg_escape_string($tbSchema).'"."'):'').pg_escape_string($tbName).'";');
00394         $pkey=current($tmp[0]);
00395       }
00396       else{
00397         $pkey=$val[$pkeyField];
00398       }
00399  
00400       $this->filesEnd(); //if files are stored in a directory and not ina a database, complete now operations to make possible a rollback
00401       pg_query($this->dbConn, 'END;');
00402       return $pkey;
00403     }
00404   }
00405 
00407   //                                                                            //
00409   function not_null($tbSchema, $tbName){
00410     $arr=array();
00411     foreach($this->attribs[$tbSchema][$tbName] as $field=>$val){
00412       $arr[$field]=$val["attnotnull"];
00413     }
00414     return $arr;
00415   }
00416   
00418   //                                                                            //
00420   function is_expression($tbSchema, $tbName){
00421     $arr=array();
00422     foreach($this->attribs[$tbSchema][$tbName] as $field=>$val){
00423       $arr[$field]=($val["type"]=='geometry');
00424     }
00425     return $arr;
00426   }
00427 
00429   //                                                                            //
00431   function parse_geometry($tbSchema, $tbName,  &$val, $field=' '){
00432     if(!is_array($val)) $tmp[$field]=&$val;
00433     else $tmp=&$val;
00434     
00435     foreach($tmp as $field=>$value){
00436       if($this->attribs[$tbSchema][$tbName][$field]["type"]!='geometry') continue;
00437       if($value){
00438         if($this->attribs[$tbSchema][$tbName][$field]['geosrid']){
00439           $tmp[$field]= "transform('".pg_escape_string($value)."',".$this->attribs[$tbSchema][$tbName][$field]['geosrid'].")";
00440         }
00441         else{
00442           $tmp[$field]=("'".$value."'");
00443         }
00444       }
00445       else{
00446         $tmp[$field]='NULL';
00447       }
00448     }
00449   }
00450 
00453 //                                                                            //
00454 // files upload functions                                                     //
00455 //                                                                            //
00458 
00460   //                                                                            //
00462   function filesEnd(){
00463     foreach($this->files["delete"] as $key=>$file){
00464       if($this->SQL_DEBUG) echo "Removiing file ".$file."...\n<br>\n";
00465       unlink($file);
00466     }
00467     $this->files["delete"]=array();
00468   }
00469 
00471   //                                                                            //
00473   function filesRollback(){
00474     foreach($this->files["create"] as $key=>$file){
00475       if($this->SQL_DEBUG) echo "ROLLBACK: removiing uploaded files ".$file."...\n<br>\n";
00476       unlink($file);
00477     }
00478     $this->files["create"]=array();
00479     $this->files["delete"]=array();
00480   }
00481 
00483   //                                                                            //
00485   function newFileName($oldName=''){
00486     $name=round(getmicrotime()*1000);
00487     $tmp=split('\.',$oldName);
00488     $num=count($tmp);
00489     if(--$num) $name.=".".$tmp[$num];
00490     return $name;
00491   }
00492   
00494   //                                                                            //
00496   //retur 1 if there is a file, 0 if there isnt, -1 if errors occurs
00497   function checkUploadedFile($schema, $table, $num, $field){
00498     if(is_array($_FILES) && is_array($_FILES["val"]) && is_array($_FILES["val"]["error"][$schema]) && is_array($_FILES["val"]["error"][$schema][$table]) && is_array($_FILES["val"]["error"][$schema][$table][$num]) && is_array($_FILES["val"]["error"][$schema][$table][$num][$field]) && array_key_exists("file", $_FILES["val"]["error"][$schema][$table][$num][$field])){
00499       if($_FILES["val"]["error"][$schema][$table][$num][$field]["file"] ){
00500         if($_FILES["val"]["error"][$schema][$table][$num][$field]["file"]!=4){
00501           //"File upload error: probably file too big for php/apache server settings"
00502           $this->errors->add($this->STRINGS["file_upload_error"].": ".$this->STRINGS["file_php_much_big"]);
00503           return -1;
00504         }
00505         else{
00506           return 0;
00507         }
00508       }
00509       if(!is_uploaded_file($_FILES["val"]["tmp_name"][$schema][$table][$num][$field]["file"])){
00510         $this->errors->add($this->STRINGS["file_not_uploaded"]);
00511         return -1;
00512       }
00513     }
00514     else{   
00515       return 0;
00516     }
00517        
00518     $attrib=$this->attribs[$schema][$table][$field];
00519     if (!is_array($attrib)) return 0; 
00520     if ($attrib['file']["maxsize"] && $_FILES["val"]["size"][$schema][$table][$num][$field]["file"]>$attrib['file']["maxsize"]){
00521       //      "File upload error: file too big, max is ".$attrib['file']["maxsize"].' byte.');
00522       $this->errors->add($this->STRINGS["file_upload_error"].": ".$this->STRINGS["file_too_big"].", ".$this->STRINGS["file_max_size"]." ".$attrib['file']["maxsize"].' bytes.');
00523       return -1;
00524     }
00525     if ($attrib['file']["type"]){
00526       $allowsTypes=(is_array($attrib['file']["type"]))?$attrib['file']["type"]:array($attrib['file']["type"]); 
00527       foreach($allowsTypes as $key=>$type){
00528         //        if (preg_match("/".$type."/i",$_FILES[$arr]["type"][$schema][$table][$field]["file"])) return true;
00529         if (eregi($type,$_FILES["val"]["type"][$schema][$table][$num][$field]["file"])) return 1;
00530       }
00531       $this->errors->add($this->STRINGS["file_upload_error"].": ".$this->STRINGS["file_type_no_match"]);
00532       return -1;
00533     }
00534     else{
00535       return 1;
00536     }
00537   }
00538 
00539   
00541   //                                                                            //
00543   function fupload($tbSchema,$tbName, $num, $field, &$arr){
00544     $attrib=$this->attribs[$tbSchema][$tbName][$field];
00545     
00546     if($attrib["file"]["mime_type_col"]){
00547       $arr[ $attrib["file"]["mime_type_col"] ]=$_FILES["val"]["type"][$tbSchema][$tbName][$num][$field]["file"];
00548     }
00549     if($attrib["file"]["name_col"]){
00550       $arr[ $attrib["file"]["name_col"] ]=$_FILES["val"]["name"][$tbSchema][$tbName][$num][$field]["file"];
00551     }
00552     if($attrib["file"]["size_col"]){
00553       $arr[ $attrib["file"]["size_col"] ]=$_FILES["val"]["size"][$tbSchema][$tbName][$num][$field]["file"];
00554     }
00555 
00556     $thumbnail=$exif='';
00557     if (($_FILES["val"]["type"][$tbSchema][$tbName][$num][$field]["file"]=='image/tiff' || $_FILES["val"]["type"][$tbSchema][$tbName][$num][$field]["file"]=='image/jpeg')){
00558       if($attrib["file"]["exif_col"]){
00559         $arr[ $attrib["file"]["exif_col"] ]=$this->readExif($_FILES["val"]["tmp_name"][$tbSchema][$tbName][$num][$field]["file"]);
00560       }
00561     }
00562     if (eregi('^image', $_FILES["val"]["type"][$tbSchema][$tbName][$num][$field]["file"]) && $attrib["file"]["thumbnail_col"]){
00563       $thumbnail=$this->makeThumbnail($_FILES["val"]["tmp_name"][$tbSchema][$tbName][$num][$field]["file"], $attribs["file"]["thumbnail_size"]);
00564     }
00565 
00566     if($attrib["type"]=='lobject'){
00567       if($this->SQL_DEBUG) echo "Loading large object...\n<br>\n";
00568       $arr[$field]=pg_lo_import($this->dbConn, $_FILES["val"]["tmp_name"][$tbSchema][$tbName][$num][$field]["file"]);
00569 
00570       $this->check_pg_errors();
00571 
00572       if($thumbnail){
00573         if($this->SQL_DEBUG) echo "Loading large object...\n<br>\n";
00574         $arr[ $attrib["file"]["thumbnail_col"] ]=pg_lo_import($this->dbConn,$thumbnail);        
00575         $this->check_pg_errors();
00576 
00577         if($this->SQL_DEBUG) echo "Removiing temporary thumbnail file ".$thumbnail."...\n<br>\n";
00578         unlink($thumbnail);
00579         if(!$arr[ $attrib["file"]["thumbnail_col"] ]){
00580           //"Error importing thumbanail large object."
00581           $this->errors->add($this->STRINGS["pglo_thmb_error"]);
00582           return false; 
00583         }
00584       }
00585       if(!$arr[$field]){
00586         //"Error importing large object."
00587         $this->errors->add($this->STRINGS["pglo_error"]);
00588         return false; 
00589       }
00590     }
00591     elseif($attrib["type"]=='file'){
00592       $arr[$field]=$this->newFileName($_FILES["val"]["name"][$tbSchema][$tbName][$num][$field]["file"]);
00593 
00594       if($this->SQL_DEBUG) echo "Moving uploaded file ".$_FILES["val"]["tmp_name"][$tbSchema][$tbName][$num][$field]["file"]. " to ". $this->filesDir["local"].$arr[$field]."...\n<br>\n";
00595       $cond1=move_uploaded_file($_FILES["val"]["tmp_name"][$tbSchema][$tbName][$num][$field]["file"], $this->filesDir["local"].$arr[$field]);
00596       if($thumbnail){
00597         $tmb_name=$this->newFileName(".jpeg");
00598         $arr[ $attrib["file"]["thumbnail_col"] ]=$tmb_name;
00599 
00600         if($this->SQL_DEBUG) echo "Copying thumbnail file ".$thumbnail. " to ".$this->filesDir["local"].$arr[$field]."...\n<br>\n";
00601         $cond2=copy($thumbnail, $this->filesDir["local"].$tmb_name);
00602         if($this->SQL_DEBUG) echo "Removiing temporary thumbnail file ".$thumbnail."...\n<br>\n";
00603         unlink($thumbnail);
00604 
00605         if(!$cond2){
00606           //"Error copiing thumbanail."
00607           $this->errors->add($this->STRINGS["cp_thmb_err"]); 
00608           return false; 
00609         }
00610         $this->files["create"][]=$this->filesDir["local"].$tmb_name;
00611       }
00612       if(!$cond1){
00613         //"Error copiing file."
00614         $this->errors->add($this->STRINGS["cp_err"]); 
00615         return false; 
00616       }
00617       $this->files["create"][]=$this->filesDir["local"].$arr[$field];
00618       return true;
00619     }
00620     else{
00621       //      "Column type is not valid for a file object."
00622       $this->errors->add($this->STRINGS["no_pglo_column"]); 
00623 
00624       return false;
00625     }
00626     return true;
00627   }
00628   
00629 
00631   //                                                                            //
00633   function fdelete($tbSchema,$tbName,$pkeyField,$pkeyVal,$field,&$arr){
00634     $attrib=$this->attribs[$tbSchema][$tbName][$field];
00635 
00636     //set references information
00637     if($attrib["file"]["mime_type_col"]){
00638       $arr[ $attrib["file"]["mime_type_col"] ]='';
00639     }
00640     if($attrib["file"]["name_col"]){
00641       $arr[ $attrib["file"]["name_col"] ]='';
00642     }
00643     if($attrib["file"]["size_col"]){
00644       $arr[ $attrib["file"]["size_col"] ]='';
00645     }
00646     if($attrib["file"]["exif_col"]){
00647       $arr[ $attrib["file"]["exif_col"] ]='';
00648     }
00649     if($attrib["file"]["thumbnail_col"]){
00650       $arr[ $attrib["file"]["thumbnail_col"] ]='';
00651     }
00652     $arr[$field]='';
00653     
00654 
00655     $thumbnail= ($attrib["file"]["thumbnail_col"]) ?' , "'.pg_escape_string($attrib["file"]["thumbnail_col"]).'" ':'';
00656     $tmp=$this->select('SELECT "'.pg_escape_string($field)."\" $thumbnail FROM \"".($this->useSchema?(pg_escape_string($tbSchema).'"."'):'').pg_escape_string($tbName).'" WHERE "'.pg_escape_string($pkeyField).'"=\''.pg_escape_string($pkeyVal).'\';');
00657 
00658     $file=current($tmp[0]);
00659     $thumbnail=$thumbnail?next($tmp[0]):'';
00660 
00661     if($file=='') return true;
00662     else{
00663       if($attrib["type"]=='lobject'){
00664         if($this->SQL_DEBUG) echo "Removiing large object...\n<br>\n";
00665         $result=pg_lo_unlink($this->dbConn,$file);
00666         $this->check_pg_errors();
00667 
00668         if($thumbnail){
00669           if($this->SQL_DEBUG) echo "Removiing large object...\n<br>\n";
00670           $res1=pg_lo_unlink($this->dbConn,$thumbnail);
00671           $this->check_pg_errors();
00672           $result=( $result && $res1);
00673         }
00674         return $result;
00675       }
00676       elseif($attrib["type"]=='file'){
00677         $this->files["delete"][]= $this->filesDir["local"].$file;
00678         if($thumbnail) $this->files["delete"][]= $this->filesDir["local"].$thumbnail;
00679         return true;
00680       }
00681       else{
00682         //      "Column type is not valid for a file object."
00683         $this->errors->add($this->STRINGS["no_pglo_column"]); 
00684         return false;
00685       }
00686     }
00687   }
00688 
00690   //                                                                            //
00692   function filesUpload($tbSchema='public', $tbName, $num, &$arr, $when, $pkeyField='oid', $pkeyVal=''){
00693     foreach($this->attribs[$tbSchema][$tbName] as $field=>$attrib){
00694       if($attrib["type"]!="file" && $attrib["type"]!="lobject") continue;
00695 
00696       $isFile=$this->checkUploadedFile($tbSchema, $tbName, $num, $field);
00697 
00698       if($isFile==-1) return false; //error occurs
00699 
00700       if($when=="delete"){
00701         if(!$this->fdelete($tbSchema,$tbName, $pkeyField,$pkeyVal,$field, $arr)) return false; // $arr[$tbSchema][$tbName][$field]
00702       }
00703       elseif($isFile==1){
00704         if($when=="update"){
00705           if(!$this->fdelete($tbSchema,$tbName,$pkeyField,$pkeyVal,$field, $arr)) return false;
00706         }
00707         if(!$this->fupload($tbSchema,$tbName, $num, $field, $arr)) return false;
00708       }
00709       elseif($when=="update" && is_array($arr[$field]) && array_key_exists("del",$arr[$field]) && $arr[$field]["del"]==1){
00710         if(!$this->fdelete($tbSchema,$tbName,$pkeyField,$pkeyVal,$field,$arr)) return false; 
00711         secure_unset($arr[$field]);
00712       }
00713 
00714       else{
00715         secure_unset($arr[$field]);
00716       }
00717     }
00718     return true;
00719   }
00720 
00721   
00723   //                                                                            //
00725   function makeThumbnail($file, $size=120){
00726     $sizeTmb=$size?$size:120;
00727     //this is faster but works only with recent convert
00728     //      system("convert -size ".$sizeTmb.'x'.$sizeTmb." -resize ".$sizeTmb.'x'.$sizeTmb." +profile \"*\" $file $file.jpeg",$ret);
00729     system("convert -geometry ".$sizeTmb.'x'.$sizeTmb." +profile \"*\" $file $file.jpeg",$ret);
00730     if($ret!=0){
00731       $img_file = fopen ($file, "r");
00732       $img_str = fread ($img_file, filesize ($file));
00733       fclose ($img_file);
00734       
00735       $img =imagecreatefromstring($img_str);
00736       
00737       $size[0]=imagesx($img);
00738       $size[1]=imagesy($img);
00739       $width=$sizeTmb/$size[0];
00740       $height=$sizeTmb/$size[1];
00741       if ($width<$height){
00742         $height=$width;
00743       };
00744       
00745       $width=(int)$size[0]*$height;
00746       $height=(int)$size[1]*$height;
00747 
00748       //this works, but with 256 colors
00749       $thumbnail=imagecreate($width,$height);
00750       //this work with many colors, but with php 4.?? with gdal ???
00751       //$thumbnail=imagecreatetruecolor($width,$height);
00752       
00753       //this is better, but works with php 4.?? with gdal ???
00754       //imagecopyresampled( $thumbnail, $img, 0, 0, 0, 0, $width, $height,$size[0],$size[1]);
00755       imagecopyresized( $thumbnail, $img, 0, 0, 0, 0, $width, $height,$size[0],$size[1]);
00756       
00757       imagejpeg($thumbnail,"$file.jpeg");
00758     }
00759     return ("$file.jpeg");
00760   }
00761   
00763   //                                                                            //
00765   function readExif($file){
00766     if(!function_exists('exif_read_data')) return '';
00767     $exifarr=(exif_read_data($file,'ANY_TAG',1));
00768     if(is_array($exifarr)){
00769       ksort($exifarr);
00770     }
00771     $this->clean_exif($exifarr);
00772     $exif=array_to_html($exifarr);
00773     return $exif;
00774   }
00775   
00777   //                                                                            //
00779   function clean_exif(&$arr){
00780     if (!is_array($arr)){
00781       //$arr=preg_replace('/\x0/','',$arr);
00782       //the fallows line it is not necessary, but clean from bad visive character, if commented the previous one is necessary to prevent db errors
00783       $arr=preg_replace('/[^ -\~]+/','',$arr);
00784     }
00785     else{
00786       foreach($arr as $key=>$val){
00787         clean_exif($arr[$key]);
00788       }
00789     }
00790   }
00791 
00793   //                                                                            //
00795   function export($query){
00796     $tmpTable="exp".rand(0, 10000);
00797     $query="CREATE TEMP TABLE $tmpTable AS ".$query;
00798     $this->select($query);
00799     
00800     /*    
00801     $tmpDirPath = "/www/Faunabl/html/admin/dumpDB/".$tableName;
00802     $tmpDirUrl = "/admin/dumpDB/".$tableName;
00803     $tmpFile=md5(time()).".tar.gz";
00804     $dbDir = "exportDB".$tableName.date("d_m_Y");
00805 
00806     //    system('ogr2ogr  -f "ESRI Shapefile"   -lco SHPT=POINT '. $tmpDirPath.'/'.$dbDir .' "PG:dbname=newfaunabl user=postgres" '.$tempTableName);
00807     system("tar czCf $tmpDirPath ".$tmpDirPath."/".$tmpFile." $dbDir");
00808     system("rm -r $tmpDirPath/$dbDir");
00809  
00810     
00811     
00812     */
00813     $this->select("DROP TABLE $tmpTable;");
00814     
00815     //return file url.....
00816     return $tmpTable; 
00817   }
00818 }
00819 ?>

Generated on Mon Nov 29 01:21:58 2004 for phpPgWeb by doxygen1.2.18