source: sandbox/2.5.1-evolucao/phpgwapi/inc/class.db.inc.php @ 8234

Revision 8234, 35.7 KB checked in by angelo, 10 years ago (diff)

Ticket #3491 - Compatibilizar Expresso com novas versoes do PHP

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2        /**************************************************************************\
3        * phpGroupWare API - database support via ADOdb                            *
4        * ------------------------------------------------------------------------ *
5        * This program is free software; you can redistribute it and/or modify it  *
6        * under the terms of the GNU Lesser General Public License as published    *
7        * by the Free Software Foundation; either version 2.1 of the License, or   *
8        * any later version.                                                       *
9        \**************************************************************************/
10
11
12        /*
13         * Database abstraction library
14         *
15         * This allows eGroupWare to use multiple database backends via ADOdb 4.20
16         *
17         * @package phpgwapi
18         * @subpackage db
19         * @author RalfBecker@outdoor-training.de
20         * @license LGPL
21         */
22
23        if(empty($GLOBALS['phpgw_info']['server']['db_type']))
24        {
25                $GLOBALS['phpgw_info']['server']['db_type'] = 'mysql';
26        }
27        include_once(PHPGW_API_INC.'/adodb/adodb.inc.php');
28
29        class db
30        {
31                /**
32                * @var string $type database type
33                */
34                var $Type     = '';
35
36                /**
37                * @var string $Host database host to connect to
38                */
39                var $Host     = '';
40
41                /**
42                * @var string $Port port number of database to connect to
43                */
44                var $Port     = '';
45
46                /**
47                * @var string $Database name of database to use
48                */
49                var $Database = '';
50       
51                /**
52                * @var string $User name of database user
53                */
54                var $User     = '';
55       
56                /**
57                * @var string $Password password for database user
58                */
59                var $Password = '';
60
61                /**
62                * @var bool $auto_stripslashes automatically remove slashes when returning field values - default False
63                */
64                var $auto_stripslashes = False;
65       
66                /**
67                * @var int $Auto_Free automatically free results - 0 no, 1 yes
68                */
69                var $Auto_Free     = 0;
70       
71                /**
72                * @var int $Debug enable debuging - 0 no, 1 yes
73                */
74                var $Debug         = 0;
75       
76                /**
77                * @var string $Halt_On_Error "yes" (halt with message), "no" (ignore errors quietly), "report" (ignore errror, but spit a warning)
78                */
79                var $Halt_On_Error = 'no';//'yes';
80       
81                /**
82                * @var string $Seq_Table table for storing sequences ????
83                */
84                var $Seq_Table     = 'db_sequence';
85
86                /**
87                * @var array $Record current record
88                */
89                var $Record   = array();
90       
91                /**
92                * @var int row number for current record
93                */
94                var $Row;
95
96                /**
97                * @var int $Errno internal rdms error number for last error
98                */
99                var $Errno    = 0;
100       
101                /**
102                * @var string descriptive text from last error
103                */
104                var $Error    = '';
105
106                //i am not documenting private vars - skwashd :)
107        var $xmlrpc = False;
108                var $soap   = False;
109                var $Link_ID = 0;
110                var $privat_Link_ID = False;    // do we use a privat Link_ID or a reference to the global ADOdb object
111                var $Query_ID = 0;
112
113                /**
114                * @param string $query query to be executed (optional)
115                */
116
117                function db($query = '')
118                {
119                        $this->query($query);
120                }
121
122                function db_($query='') {}      // only for NOT useing ADOdb
123
124                /**
125                * @return int current connection id
126                */
127                function link_id()
128                {
129                        return $this->Link_ID;
130                }
131
132                /**
133                * @return int id of current query
134                */
135                function query_id()
136                {
137                        return $this->Query_ID;
138                }
139
140                /**
141                * Open a connection to a database
142                *
143                * @param string $Database name of database to use (optional)
144                * @param string $Host database host to connect to (optional)
145                * @param string $Port database port to connect to (optional)
146                * @param string $User name of database user (optional)
147                * @param string $Password password for database user (optional)
148                */
149                function connect($Database = NULL, $Host = NULL, $Port = NULL, $User = NULL, $Password = NULL,$Type = NULL)
150                {
151                        /* Handle defaults */
152                        if (!is_null($Database) && $Database)
153                        {
154                                $this->Database = $Database;
155                        }
156                        if (!is_null($Host) && $Host)
157                        {
158                                $this->Host     = $Host;
159                        }
160                        if (!is_null($Port) && $Port)
161                        {
162                                $this->Port     = $Port;
163                        }
164                        if (!is_null($User) && $User)
165                        {
166                                $this->User     = $User;
167                        }
168                        if (!is_null($Password) && $Password)
169                        {
170                                $this->Password = $Password;
171                        }
172                        if (!is_null($Type) && $Type)
173                        {
174                                $this->Type = $Type;
175                        }
176                        elseif (!$this->Type)
177                        {
178                                $this->Type = $GLOBALS['phpgw_info']['server']['db_type'];
179                        }
180
181                        if (!$this->Link_ID)
182                        {
183                                foreach(array('Host','Database','User','Password') as $name)
184                                {
185                                        $$name = $this->$name;
186                                }
187                                $type = $this->Type;
188
189                                switch($this->Type)     // convert to ADO db-type-names
190                                {
191                                        case 'pgsql':
192                                                $type = 'postgres';
193                                                // create our own pgsql connection-string, to allow unix domain soccets if !$Host
194                                                $Host = "dbname=$this->Database".($this->Host ? " host=$this->Host".($this->Port ? " port=$this->Port" : '') : '').
195                                                        " user=$this->User".($this->Password ? " password='".addslashes($this->Password)."'" : '');
196                                                $User = $Password = $Database = '';     // to indicate $Host is a connection-string
197                                                break;
198                                        case 'mssql':
199                                                if ($this->Port) $Host .= ','.$this->Port;
200                                                break;
201                                        default:
202                                                if ($this->Port) $Host .= ':'.$this->Port;
203                                                break;
204                                }
205
206                                if ( ! isset( $GLOBALS[ 'phpgw' ] ) )
207                                {
208                                        $GLOBALS[ 'phpgw' ] = new stdClass;
209                                        $GLOBALS[ 'phpgw' ]->ADOdb = NULL;
210                                }
211                                if (!is_object($GLOBALS['phpgw']->ADOdb) ||     // we have no connection so far
212                                        (isset($GLOBALS['phpgw']->db) && is_object($GLOBALS['phpgw']->db) &&    // we connect to a different db, then the global one
213                                                ($this->Type != $GLOBALS['phpgw']->db->Type ||
214                                                $this->Database != $GLOBALS['phpgw']->db->Database ||
215                                                $this->User != $GLOBALS['phpgw']->db->User ||
216                                                $this->Host != $GLOBALS['phpgw']->db->Host ||
217                                                $this->Port != $GLOBALS['phpgw']->db->Port)))
218                                {
219                                        if (!is_object($GLOBALS['phpgw']->ADOdb))       // use the global object to store the connection
220                                        {
221                                                $this->Link_ID = &$GLOBALS['phpgw']->ADOdb;
222                                        }
223                                        else
224                                        {
225                                                $this->privat_Link_ID = True;   // remember that we use a privat Link_ID for disconnect
226                                        }
227                                        $this->Link_ID = ADONewConnection($type);
228                                        if (!$this->Link_ID)
229                                        {
230                                                $this->halt("No ADOdb support for '$type' !!!");
231                                                return 0;       // in case error-reporting = 'no'
232                                        }
233                                        $connect = ( isset( $GLOBALS['phpgw_info']['server']['db_persistent'] ) && $GLOBALS['phpgw_info']['server']['db_persistent'] ) ? 'PConnect' : 'Connect';
234                                        if (!$this->Link_ID->$connect($Host, $User, $Password, $Database))
235                                        {
236                                                $this->halt("ADOdb::$connect($Host, $User, \$Password, $Database) failed.");
237                                                return 0;       // in case error-reporting = 'no'
238                                        }
239                                        //echo "new ADOdb connection<pre>".print_r($GLOBALS['phpgw']->ADOdb,True)."</pre>\n";
240
241                                        if ($this->Type == 'mssql')
242                                        {
243                                                // this is the format ADOdb expects
244                                                $this->Link_ID->Execute('SET DATEFORMAT ymd');
245                                                // sets the limit to the maximum
246                                                ini_set('mssql.textlimit',2147483647);
247                                                ini_set('mssql.sizelimit',2147483647);
248                                        }
249                                }
250                                else
251                                {
252                                        $this->Link_ID = &$GLOBALS['phpgw']->ADOdb;
253                                }
254                        }
255                        return $this->Link_ID;
256                }
257
258                /**
259                * Close a connection to a database
260                */
261                function disconnect()
262                {
263                        if (!$this->privat_Link_ID)
264                        {
265                                unset($GLOBALS['phpgw']->ADOdb);
266                        }
267                        unset($this->Link_ID);
268                        $this->Link_ID = 0;
269                }
270
271                /**
272                * Escape strings before sending them to the database
273                *
274                * @param string $str the string to be escaped
275                * @return string escaped sting
276                */
277                function db_addslashes($str)
278                {
279                        if (!isset($str) || $str == '')
280                        {
281                                return '';
282                        }
283                        if (!$this->Link_ID && !$this->connect())
284                        {
285                                return False;
286                        }
287                        return $this->Link_ID->addq($str);
288                }
289
290                /**
291                * Convert a unix timestamp to a rdms specific timestamp
292                *
293                * @param int unix timestamp
294                * @return string rdms specific timestamp
295                */
296                function to_timestamp($epoch)
297                {
298                        if (!$this->Link_ID && !$this->connect())
299                        {
300                                return False;
301                        }
302                        // the substring is needed as the string is already in quotes
303                        return substr($this->Link_ID->DBTimeStamp($epoch),1,-1);
304                }
305
306                /**
307                * Convert a rdms specific timestamp to a unix timestamp
308                *
309                * @param string rdms specific timestamp
310                * @return int unix timestamp
311                */
312                function from_timestamp($timestamp)
313                {
314                        if (!$this->Link_ID && !$this->connect())
315                        {
316                                return False;
317                        }
318                        return $this->Link_ID->UnixTimeStamp($timestamp);
319                }
320
321                /**
322                * @deprecated
323                * @see limit_query()
324                */
325                function limit($start)
326                {}
327
328                /**
329                * Discard the current query result
330                */
331                function free()
332                {
333                        unset($this->Query_ID); // else copying of the db-object does not work
334                        $this->Query_ID = 0;
335                }
336
337                /**
338                * Execute a query
339                *
340                * @param string $Query_String the query to be executed
341                * @param mixed $line the line method was called from - use __LINE__
342                * @param string $file the file method was called from - use __FILE__
343                * @param int $offset row to start from
344                * @param int $num_rows number of rows to return (optional), if unset will use $GLOBALS['phpgw_info']['user']['preferences']['common']['maxmatchs']
345                * @return int current query id if sucesful and null if fails
346                */
347                function query($Query_String, $line = '', $file = '', $offset=0, $num_rows=-1)
348                {
349                        if ($Query_String == '')
350                        {
351                                return 0;
352                        }
353                        if (!$this->Link_ID && !$this->connect())
354                        {
355                                return False;
356                        }
357
358                        # New query, discard previous result.
359                        if ($this->Query_ID)
360                        {
361                                $this->free();
362                        }
363                        if ($this->Link_ID->fetchMode != ADODB_FETCH_BOTH)
364                        {
365                                $this->Link_ID->SetFetchMode(ADODB_FETCH_BOTH);
366                        }
367                        if (! $num_rows)
368                        {
369                                $num_rows = $GLOBALS['phpgw_info']['user']['preferences']['common']['maxmatchs'];
370                        }
371                        if ($num_rows > 0)
372                        {
373                                $this->Query_ID = $this->Link_ID->SelectLimit($Query_String,$num_rows,(int)$offset);
374                        }
375                        else
376                        {
377                                $this->Query_ID = $this->Link_ID->Execute($Query_String);
378                        }
379                        $this->Row = 0;
380                        $this->Errno  = $this->Link_ID->ErrorNo();
381                        $this->Error  = $this->Link_ID->ErrorMsg();
382
383                        if (! $this->Query_ID)
384                        {
385                                $this->halt("Invalid SQL: ".$Query_String, $line, $file);
386                        }
387                        return $this->Query_ID;
388                }
389
390                /**
391                * Execute a query with limited result set
392                *
393                * @param string $Query_String the query to be executed
394                * @param int $offset row to start from
395                * @param mixed $line the line method was called from - use __LINE__
396                * @param string $file the file method was called from - use __FILE__
397                * @param int $num_rows number of rows to return (optional), if unset will use $GLOBALS['phpgw_info']['user']['preferences']['common']['maxmatchs']
398                * @return int current query id if sucesful and null if fails
399                */
400                function limit_query($Query_String, $offset, $line = '', $file = '', $num_rows = '')
401                {
402                        return $this->query($Query_String,$line,$file,$offset,$num_rows);
403                }
404
405                /**
406                * Move to the next row in the results set
407                *
408                * @return bool was another row found?
409                */
410                function next_record()
411                {
412                        if (!$this->Query_ID)
413                        {
414                                $this->halt('next_record called with no query pending.');
415                                return 0;
416                        }
417                        if ($this->Row) // first row is already fetched
418                        {
419                                $this->Query_ID->MoveNext();
420                        }
421                        ++$this->Row;
422
423                        $this->Record = $this->Query_ID->fields;
424
425                        if ($this->Query_ID->EOF || !$this->Query_ID->RecordCount() || !is_array($this->Record))
426                        {
427                                return False;
428                        }
429
430                        return True;
431                }
432
433                /**
434                * Move to position in result set
435                *
436                * @param int $pos required row (optional), default first row
437                * @return int 1 if sucessful or 0 if not found
438                */
439                function seek($pos = 0)
440                {
441                        if (!$this->Query_ID  || !$this->Query_ID->Move($this->Row = $pos))
442                        {
443                                $this->halt("seek($pos) failed: resultset has " . $this->num_rows() . " rows");
444                                $this->Query_ID->Move( $this->num_rows() );
445                                $this->Row = $this->num_rows();
446                                return False;
447                        }
448                        return True;
449                }
450
451                /**
452                * Begin Transaction
453                *
454                * @return int current transaction id
455                */
456                function transaction_begin()
457                {
458                        if (!$this->Link_ID && !$this->connect())
459                        {
460                                return False;
461                        }
462                        //return $this->Link_ID->BeginTrans();
463                        return $this->Link_ID->StartTrans();
464                }
465
466                /**
467                * Complete the transaction
468                *
469                * @return bool True if sucessful, False if fails
470                */
471                function transaction_commit()
472                {
473                        if (!$this->Link_ID && !$this->connect())
474                        {
475                                return False;
476                        }
477                        //return $this->Link_ID->CommitTrans();
478                        return $this->Link_ID->CompleteTrans();
479                }
480
481                /**
482                * Rollback the current transaction
483                *
484                * @return bool True if sucessful, False if fails
485                */
486                function transaction_abort()
487                {
488                        if (!$this->Link_ID && !$this->connect())
489                        {
490                                return False;
491                        }
492                        //return $this->Link_ID->RollbackTrans();
493                        return $this->Link_ID->FailTrans();
494                }
495
496                /**
497                * Find the primary key of the last insertion on the current db connection
498                *
499                * @param string $table name of table the insert was performed on
500                * @param string $field the autoincrement primary key of the table
501                * @return int the id, -1 if fails
502                */
503                function get_last_insert_id($table, $field)
504                {
505                        if (!$this->Link_ID && !$this->connect())
506                        {
507                                return False;
508                        }
509                        $id = $this->Link_ID->Insert_ID();
510
511                        if ($id === False)      // function not supported
512                        {
513                                echo "<p>db::get_last_insert_id(table='$table',field='$field') not yet implemented for db-type '$this->Type'</p>\n";
514                                return -1;
515                        }
516                        if ($this->Type != 'pgsql' || $id == -1)
517                        {
518                                return $id;
519                        }
520                        // pgsql code to transform the OID into the real id
521                        $id = $this->Link_ID->GetOne("SELECT $field FROM $table WHERE oid=$id");
522
523                        return $id !== False ? $id : -1;
524                }
525
526                /**
527                * Lock a table
528                *
529                * @param string $table name of table to lock
530                * @param string $mode type of lock required (optional), default write
531                * @return bool True if sucessful, False if fails
532                */
533                function lock($table, $mode='write')
534                {}
535
536                /**
537                * Unlock a table
538                *
539                * @return bool True if sucessful, False if fails
540                */
541                function unlock()
542                {}
543
544                /**
545                * Get the number of rows affected by last update
546                *
547                * @return int number of rows
548                */
549                function affected_rows()
550                {
551                        if (!$this->Link_ID && !$this->connect())
552                        {
553                                return False;
554                        }
555                        return $this->Link_ID->Affected_Rows();
556                }
557
558                /**
559                * Number of rows in current result set
560                *
561                * @return int number of rows
562                */
563                function num_rows()
564                {
565                        return $this->Query_ID ? $this->Query_ID->RecordCount() : False;
566                }
567
568                /**
569                * Number of fields in current row
570                *
571                * @return int number of fields
572                */
573                function num_fields()
574                {
575                        return $this->Query_ID ? $this->Query_ID->FieldCount() : False;
576                }
577
578                /**
579                * short hand for @see num_rows()
580                */
581                function nf()
582                {
583                        return $this->num_rows();
584                }
585
586                /**
587                * short hand for print @see num_rows
588                */
589                function np()
590                {
591                        print $this->num_rows();
592                }
593
594                /**
595                * Return the value of a column
596                *
597                * @param string/integer $Name name of field or positional index starting from 0
598                * @param bool $strip_slashes string escape chars from field(optional), default false
599                * @return string the field value
600                */
601                function f($Name, $strip_slashes = False)
602                {
603                        if ($strip_slashes || ($this->auto_stripslashes && ! $strip_slashes))
604                        {
605                                return stripslashes($this->Record[$Name]);
606                        }
607                        else
608                        {
609                                return $this->Record[$Name];
610                        }
611                }
612
613                /**
614                * Print the value of a field
615                *
616                * @param string $Name name of field to print
617                * @param bool $strip_slashes string escape chars from field(optional), default false
618                */
619                function p($Name, $strip_slashes = True)
620                {
621                        print $this->f($Name, $strip_slashes);
622                }
623
624                /**
625                * Returns a query-result-row as an associative array (no numerical keys !!!)
626                *
627                * @param bool $do_next_record should next_record() be called or not (default not)
628                * @return array/bool the associative array or False if no (more) result-row is availible
629                */
630                function row($do_next_record=False)
631                {
632                        if ($do_next_record && !$this->next_record() || !is_array($this->Record))
633                        {
634                                return False;
635                        }
636                        $result = array();
637                        foreach($this->Record as $column => $value)
638                        {
639                                if (!is_numeric($column))
640                                {
641                                        $result[$column] = $value;
642                                }
643                        }
644                        return $result;
645                }
646
647                /**
648                * Get the id for the next sequence - not implemented!
649                *
650                * This seems not to be used anywhere in eGroupWhere !!!
651                *
652                * @param string $seq_name name of the sequence
653                * @return int sequence id
654                */
655                function nextid($seq_name)
656                {
657                        echo "<p>db::nextid(sequence='$seq_name') not yet implemented</p>\n";
658                }
659
660                /**
661                * Error handler
662                *
663                * @param string $msg error message
664                * @param int $line line of calling method/function (optional)
665                * @param string $file file of calling method/function (optional)
666                */
667                function halt($msg, $line = '', $file = '')
668                {
669                        if ($this->Link_ID)             // only if we have a link, else infinite loop
670                        {
671                                $this->Error = $this->Link_ID->ErrorMsg();      // need to be BEFORE unlock,
672                                $this->Errno = $this->Link_ID->ErrorNo();       // else we get its error or none
673
674                                $this->unlock();        /* Just in case there is a table currently locked */
675                        }
676                        if ($this->Halt_On_Error == "no")
677                        {
678                                return;
679                        }
680                        $this->haltmsg($msg);
681
682                        if ($file)
683                        {
684                                printf("<br><b>File:</b> %s",$file);
685                        }
686                        if ($line)
687                        {
688                                printf("<br><b>Line:</b> %s",$line);
689                        }
690                        printf("<br><b>Function:</b> %s\n",function_backtrace(2));
691
692                        if ($this->Halt_On_Error != "report")
693                        {
694                                echo "<p><b>Session halted.</b>";
695                                if (is_object($GLOBALS['phpgw']->common))
696                                {
697                                        $GLOBALS['phpgw']->common->phpgw_exit(True);
698                                }
699                                else    // happens eg. in setup
700                                {
701                                        exit();
702                                }
703                        }
704                }
705
706                function haltmsg($msg)
707                {
708                        printf("<p><b>Database error:</b> %s<br>\n", $msg);
709                        if (($this->Errno || $this->Error) && $this->Error != "()")
710                        {
711                                printf("<b>$this->Type Error</b>: %s (%s)<br>\n",$this->Errno,$this->Error);
712                        }
713                }
714
715                /**
716                * Get description of a table
717                *
718                * Beside the column-name all other data depends on the db-type !!!
719                *
720                * @param string $table name of table to describe
721                * @param bool $full optional, default False summary information, True full information
722                * @return array table meta data
723                */
724                function metadata($table='',$full=false)
725                {
726                        if (!$this->Link_ID && !$this->connect())
727                        {
728                                return False;
729                        }
730                        $columns = $this->Link_ID->MetaColumns($table);
731                        //$columns = $this->Link_ID->MetaColumnsSQL($table);
732                        //echo "<b>metadata</b>('$table')=<pre>\n".print_r($columns,True)."</pre>\n";
733
734                        $metadata = array();
735                        $i = 0;
736                        foreach($columns as $column)
737                        {
738                                // for backwards compatibilty (depreciated)
739                                unset($flags);
740                                if($column->auto_increment) $flags .= "auto_increment ";
741                                if($column->primary_key) $flags .= "primary_key ";
742                                if($column->binary) $flags .= "binary ";
743
744//                              _debug_array($column);
745                                $metadata[$i] = array(
746                                        'table' => $table,
747                                        'name'  => $column->name,
748                                        'type'  => $column->type,
749                                        'len'   => $column->max_length,
750                                        'flags' => $flags, // for backwards compatibilty (depreciated) used by JiNN atm
751                                        'not_null' => $column->not_null,
752                                        'auto_increment' => $column->auto_increment,
753                                        'primary_key' => $column->primary_key,
754                                        'binary' => $column->binary,
755                                        'has_default' => $column->has_default,
756                                        'default'  => $column->default_value,
757                                );
758                                $metadata[$i]['table'] = $table;
759                                if ($full)
760                                {
761                                        $metadata['meta'][$column->name] = $i;
762                                }
763                                ++$i;
764                        }
765                        if ($full)
766                        {
767                                $metadata['num_fields'] = $i;
768                        }
769                        return $metadata;
770                }
771
772                /**
773                * Get a list of table names in the current database
774                *
775                * @return array list of the tables
776                */
777                function table_names()
778                {
779                        if (!$this->Link_ID && !$this->connect())
780                        {
781                                return False;
782                        }
783                        $result = array();
784                        $tables = $this->Link_ID->MetaTables('TABLES');
785                        if (is_array($tables))
786                        {
787                                foreach($tables as $table)
788                                {
789                                        $result[] = array(
790                                                'table_name'      => $table,
791                                                'tablespace_name' => $this->Database,
792                                                'database'        => $this->Database
793                                        );
794                                }
795                        }
796                        return $result;
797                }
798
799                /**
800                * Return a list of indexes in current database
801                *
802                * @return array list of indexes
803                */
804                function index_names()
805                {
806                        $indices = array();
807                        if ($this->Type != 'pgsql')
808                        {
809                                echo "<p>db::index_names() not yet implemented for db-type '$this->Type'</p>\n";
810                                return $indices;
811                        }
812                        $this->query("SELECT relname FROM pg_class WHERE NOT relname ~ 'pg_.*' AND relkind ='i' ORDER BY relname");
813                        while ($this->next_record())
814                        {
815                                $indices[] = array(
816                                        'index_name'      => $this->f(0),
817                                        'tablespace_name' => $this->Database,
818                                        'database'        => $this->Database,
819                                );
820                        }
821                        return $indices;
822                }
823
824                /**
825                * Returns an array containing column names that are the primary keys of $tablename.
826                *
827                * @return array of columns
828                */
829                function pkey_columns($tablename)
830                {
831                        if (!$this->Link_ID && !$this->connect())
832                        {
833                                return False;
834                        }
835                        return $this->Link_ID->MetaPrimaryKeys($tablename);
836                }
837
838                /**
839                * Create a new database
840                *
841                * @param string $adminname name of database administrator user (optional)
842                * @param string $adminpasswd password for the database administrator user (optional)
843                */
844                function create_database($adminname = '', $adminpasswd = '')
845                {
846                        $currentUser = $this->User;
847                        $currentPassword = $this->Password;
848                        $currentDatabase = $this->Database;
849
850                        $extra = array();
851                        switch ($this->Type)
852                        {
853                                case 'pgsql':
854                                        $meta_db = 'template1';
855                                        break;
856                                case 'mysql':
857                                        $meta_db = 'mysql';
858                                        $extra[] = "grant all on $currentDatabase.* to $currentUser@localhost identified by '$currentPassword'";
859                                        break;
860                                default:
861                                        echo "<p>db::create_database(user='$adminname',\$pw) not yet implemented for DB-type '$this->Type'</p>\n";
862                                        break;
863                        }
864                        if ($adminname != '')
865                        {
866                                $this->User = $adminname;
867                                $this->Password = $adminpasswd;
868                                $this->Database = $meta_db;
869                        }
870                        $this->disconnect();
871                        $this->query("CREATE DATABASE $currentDatabase");
872                        foreach($extra as $sql)
873                        {
874                                $this->query($sql);
875                        }
876                        $this->disconnect();
877
878                        $this->User = $currentUser;
879                        $this->Password = $currentPassword;
880                        $this->Database = $currentDatabase;
881                        $this->connect();
882                }
883
884                /**
885                 * concat a variable number of strings together, to be used in a query
886                 *
887                 * Example: $db->concat($db->quote('Hallo '),'username') would return
888                 *      for mysql "concat('Hallo ',username)" or "'Hallo ' || username" for postgres
889                 * @param $str1 string already quoted stringliteral or column-name, variable number of arguments
890                 * @return string to be used in a query
891                 */
892                function concat($str1)
893                {
894                        $args = func_get_args();
895
896                        if (!$this->Link_ID && !$this->connect())
897                        {
898                                return False;
899                        }
900                        return call_user_func_array(array(&$this->Link_ID,'concat'),$args);
901                }
902
903                /**
904                * Correctly Quote Identifiers like table- or colmnnames for use in SQL-statements
905                *
906                * This is mostly copy & paste from adodb's datadict class
907                * @param $name string
908                * @return string quoted string
909                */
910                function name_quote($name = NULL)
911                {
912                        if (!is_string($name)) {
913                                return FALSE;
914                        }
915
916                        $name = trim($name);
917
918                        if (!$this->Link_ID && !$this->connect())
919                        {
920                                return False;
921                        }
922
923                        $quote = $this->Link_ID->nameQuote;
924
925                        // if name is of the form `name`, quote it
926                        if ( preg_match('/^`(.+)`$/', $name, $matches) ) {
927                                return $quote . $matches[1] . $quote;
928                        }
929
930                        // if name contains special characters, quote it
931                        if ( preg_match('/\W/', $name) ) {
932                                return $quote . $name . $quote;
933                        }
934
935                        return $name;
936                }
937
938                /**
939                * Escape values before sending them to the database - prevents SQL injunction and SQL errors ;-)
940                *
941                * Please note that the quote function already returns necessary quotes: quote('Hello') === "'Hello'".
942                * Int and Auto types are casted to int: quote('1','int') === 1, quote('','int') === 0, quote('Hello','int') === 0
943                *
944                * @param $value mixed the value to be escaped
945                * @param $type string the type of the db-column, default False === varchar
946                * @return string escaped sting
947                */
948                function quote($value,$type=False)
949                {
950                        if ($this->Debug) echo "<p>db::quote('$value','$type')</p>\n";
951
952                        switch($type)
953                        {
954                                case 'int':
955                                case 'auto':
956                                        return (int) $value;
957                        }
958                        if (!$this->Link_ID && !$this->connect())
959                        {
960                                return False;
961                        }
962                        switch($type)
963                        {
964                                case 'blob':
965                                        switch ($this->Link_ID->blobEncodeType)
966                                        {
967                                                case 'C':       // eg. postgres
968                                                        return "'" . $this->Link_ID->BlobEncode($value) . "'";
969                                                case 'I':
970                                                        return $this->Link_ID->BlobEncode($value);
971                                        }
972                                        break;  // handled like strings                                 
973                                case 'date':
974                                        return $this->Link_ID->DBDate($value);
975                                case 'timestamp':
976                                        return $this->Link_ID->DBTimeStamp($value);
977                        }
978                        return $this->Link_ID->qstr($value);
979                }
980
981                /**
982                * Implodes an array of column-value pairs for the use in sql-querys.
983                * All data is run through quote (does either addslashes() or (int)) - prevents SQL injunction and SQL errors ;-).
984                *
985                * @author RalfBecker<at>outdoor-training.de
986                *
987                * @param $glue string in most cases this will be either ',' or ' AND ', depending you your query
988                * @param $array array column-name / value pairs, if the value is an array all its array-values will be quoted
989                *       according to the type of the column, and the whole array with be formatted like (val1,val2,...)
990                *       If $use_key == True, an ' IN ' instead a '=' is used. Good for category- or user-lists.
991                *       If the key is numerical (no key given in the array-definition) the value is used as is, eg.
992                *       array('visits=visits+1') gives just "visits=visits+1" (no quoting at all !!!)
993                * @param $use_key boolean/string If $use_key===True a "$key=" prefix each value (default), typically set to False
994                *       or 'VALUES' for insert querys, on 'VALUES' "(key1,key2,...) VALUES (val1,val2,...)" is returned
995                * @param $only array/boolean if set to an array only colums which are set (as data !!!) are written
996                *       typicaly used to form a WHERE-clause from the primary keys.
997                *       If set to True, only columns from the colum_definitons are written.
998                * @param $column_definitions array/boolean this can be set to the column-definitions-array
999                *       of your table ($tables_baseline[$table]['fd'] of the setup/tables_current.inc.php file).
1000                *       If its set, the column-type-data determinates if (int) or addslashes is used.
1001                */
1002                function column_data_implode($glue,$array,$use_key=True,$only=False,$column_definitions=False)
1003                {
1004                        if (!is_array($array))  // this allows to give an SQL-string for delete or update
1005                        {
1006                                return $array;
1007                        }
1008                        if (!$column_definitions)
1009                        {
1010                                $column_definitions = $this->column_definitions;
1011                        }
1012                        if ($this->Debug) echo "<p>db::column_data_implode('$glue',".print_r($array,True).",'$use_key',".print_r($only,True).",<pre>".print_r($column_definitions,True)."</pre>\n";
1013
1014                        $keys = $values = array();
1015                        foreach($array as $key => $data)
1016                        {
1017                                if (!$only || $only === True && isset($column_definitions[$key]) || is_array($only) && in_array($key,$only))
1018                                {
1019                                        $keys[] = $this->name_quote($key);
1020
1021                                        $column_type = is_array($column_definitions) ? @$column_definitions[$key]['type'] : False;
1022
1023                                        if (is_array($data))
1024                                        {
1025                                                foreach($data as $k => $v)
1026                                                {
1027                                                        $data[$k] = $this->quote($v,$column_type);
1028                                                }
1029                                                $values[] = ($use_key===True ? $key.' IN ' : '') . '('.implode(',',$data).')';
1030                                        }
1031                                        elseif (is_int($key) && $use_key===True)
1032                                        {
1033                                                $values[] = $data;
1034                                        }
1035                                        else
1036                                        {
1037                                                $values[] = ($use_key===True ? $this->name_quote($key) . '=' : '') . $this->quote($data,$column_type);
1038                                        }
1039                                }
1040                        }
1041                        return ($use_key==='VALUES' ? '('.implode(',',$keys).') VALUES (' : '').
1042                                implode($glue,$values) . ($use_key==='VALUES' ? ')' : '');
1043                }
1044
1045                /**
1046                * Sets the default column-definitions for use with column_data_implode()
1047                *
1048                * @author RalfBecker<at>outdoor-training.de
1049                *
1050                * @param $column_definitions array/boolean this can be set to the column-definitions-array
1051                *       of your table ($tables_baseline[$table]['fd'] of the setup/tables_current.inc.php file).
1052                *       If its set, the column-type-data determinates if (int) or addslashes is used.
1053                */
1054                function set_column_definitions($column_definitions=False)
1055                {
1056                        $this->column_definitions=$column_definitions;
1057                }
1058
1059                function set_app($app)
1060                {
1061                        $this->app = $app;
1062                }
1063
1064                /**
1065                * reads the table-definitions from the app's setup/tables_current.inc.php file
1066                *
1067                * The already read table-definitions are shared between all db-instances via $GLOBALS['phpgw_info']['apps'][$app]['table_defs']
1068                *
1069                * @author RalfBecker<at>outdoor-training.de
1070                *
1071                * @param $app bool/string name of the app or default False to use the app set by db::set_app or the current app
1072                * @param $table bool/string if set return only defintions of that table, else return all defintions
1073                * @return mixed array with table-defintions or False if file not found
1074                */
1075                function get_table_definitions($app=False,$table=False)
1076                {
1077                        if (!$app)
1078                        {
1079                                $app = $this->app ? $this->app : $GLOBALS['phpgw_info']['flags']['currentapp'];
1080                        }
1081                        if (isset($GLOBALS['phpgw_info']['apps']))      // dont set it, if it does not exist!!!
1082                        {
1083                                $this->app_data = &$GLOBALS['phpgw_info']['apps'][$app];
1084                        }
1085                        // this happens during the eGW startup or in setup
1086                        else
1087                        {
1088                                $this->app_data =& $this->all_app_data[$app];
1089                        }
1090                        if (!isset($this->app_data['table_defs']))
1091                        {
1092                                $tables_current = PHPGW_INCLUDE_ROOT . "/$app/setup/tables_current.inc.php";
1093                                if (!@file_exists($tables_current))
1094                                {
1095                                        return $this->app_data['table_defs'] = False;
1096                                }
1097                                include($tables_current);
1098                                $this->app_data['table_defs'] = $phpgw_baseline;
1099                        }
1100                        if ($table && (!$this->app_data['table_defs'] || !isset($this->app_data['table_defs'][$table])))
1101                        {
1102                                return False;
1103                        }
1104                        return $table ? $this->app_data['table_defs'][$table] : $this->app_data['table_defs'];
1105                }
1106
1107                /**
1108                * Insert a row of data into a table, all data is quoted according to it's type
1109                *
1110                * @author RalfBecker<at>outdoor-training.de
1111                *
1112                * @param $table string name of the table
1113                * @param $data array with column-name / value pairs
1114                * @param $where mixed array with column-name / values pairs to check if a row with that keys already exists,
1115                *       if the row exists db::update is called else a new row with $date merged with $where gets inserted (data has precedence)
1116                * @param $line int line-number to pass to query
1117                * @param $file string file-name to pass to query
1118                * @param $app mixed string with name of app or False to use the current-app
1119                * @return object/boolean Query_ID of the call to db::query, or True if we had to do an update
1120                */
1121                function insert($table,$data,$where,$line,$file,$app=False)
1122                {
1123                        if ($this->Debug) echo "<p>db::insert('$table',".print_r($data,True).",".print_r($where,True).",$line,$file,'$app')</p>\n";
1124
1125                        $table_def = $this->get_table_definitions($app,$table);
1126
1127                        if (is_array($where) && count($where))
1128                        {
1129                                $this->select($table,'count(*)',$where,$line,$file);
1130                                if ($this->next_record() && $this->f(0))
1131                                {
1132                                        return !!$this->update($table,$data,$where,$line,$file,$app);
1133                                }
1134                                $data = array_merge($where,$data);      // the checked values need to be inserted too, value in data has precedence
1135                        }
1136                        $sql = "INSERT INTO $table ".$this->column_data_implode(',',$data,'VALUES',False,$table_def['fd']);
1137
1138                        return $this->query($sql,$line,$file);
1139                }
1140
1141                function persist_shared_groups($location,$account_id)
1142                {
1143
1144                        $sql = "delete from phpgw_cc_contact_grps where oid in (
1145                                select A.oid from phpgw_cc_contact_grps A inner join phpgw_cc_groups B on A.id_group=B.id_group
1146                                inner join phpgw_cc_contact_conns C on A.id_connection=C.id_connection
1147                                inner join phpgw_cc_contact D on C.id_contact=D.id_contact
1148                                where B.owner=$location and D.id_owner=$account_id );";
1149
1150                        return $this->query($sql);
1151                }
1152
1153                /**
1154                * Updates the data of one or more rows in a table, all data is quoted according to it's type
1155                *
1156                * @author RalfBecker<at>outdoor-training.de
1157                *
1158                * @param $table string name of the table
1159                * @param $data array with column-name / value pairs
1160                * @param $where array column-name / values pairs and'ed together for the where clause
1161                * @param $line int line-number to pass to query
1162                * @param $file string file-name to pass to query
1163                * @param $app mixed string with name of app or False to use the current-app
1164                * @return the return-value of the call to db::query
1165                */
1166                function update($table,$data,$where,$line,$file,$app=False)
1167                {
1168                        $table_def = $this->get_table_definitions($app,$table);
1169                        $sql = "UPDATE $table SET ".
1170                                $this->column_data_implode(',',$data,True,False,$table_def['fd']).' WHERE '.
1171                                $this->column_data_implode(' AND ',$where,True,False,$table_def['fd']);
1172
1173                        return $this->query($sql,$line,$file);
1174                }
1175
1176                /**
1177                * Deletes one or more rows in table, all data is quoted according to it's type
1178                *
1179                * @author RalfBecker<at>outdoor-training.de
1180                *
1181                * @param $table string name of the table
1182                * @param $where array column-name / values pairs and'ed together for the where clause
1183                * @param $line int line-number to pass to query
1184                * @param $file string file-name to pass to query
1185                * @param $app mixed string with name of app or False to use the current-app
1186                * @return the return-value of the call to db::query
1187                */
1188                function delete($table,$where,$line,$file,$app=False)
1189                {
1190                        $table_def = $this->get_table_definitions($app,$table);
1191                        $sql = "DELETE FROM $table WHERE ".
1192                                $this->column_data_implode(' AND ',$where,True,False,$table_def['fd']);
1193
1194                        return $this->query($sql,$line,$file);
1195                }
1196
1197                /**
1198                 * Formats and quotes a sql expression to be used eg. as where-clause
1199                 *
1200                 * The function has a variable number of arguments, from which the expession gets constructed
1201                 * eg. db::expression('my_table','(',array('name'=>"test'ed",'lang'=>'en'),') OR ',array('owner'=>array('',4,10)))
1202                 * gives "(name='test\'ed' AND lang='en') OR 'owner' IN (0,4,5,6,10)" if name,lang are strings and owner is an integer
1203                 * @param $table string name of the table
1204                 * @param $args mixed variable number of arguments of the following types:
1205                 *      string: get's as is into the result
1206                 *      array:  column-name / value pairs: the value gets quoted according to the type of the column and prefixed
1207                 *              with column-name=, multiple pairs are AND'ed together, see db::column_data_implode
1208                 *      bool: If False or is_null($arg): the next 2 (!) arguments gets ignored
1209                 * @return string the expression generated from the arguments
1210                 */
1211                function expression($table,$args)
1212                {
1213                        $table_def = $this->get_table_definitions($app,$table);
1214                        $sql = '';
1215                        $ignore_next = 0;
1216                        foreach(func_get_args() as $n => $arg)
1217                        {
1218                                if ($n < 1) continue;   // table-name
1219
1220                                if ($ignore_next)
1221                                {
1222                                        --$ignore_next;
1223                                        continue;
1224                                }
1225                                if (is_null($arg)) $arg = False;
1226
1227                                switch(gettype($arg))
1228                                {
1229                                        case 'string':
1230                                                $sql .= $arg;
1231                                                break;
1232                                        case 'boolean':
1233                                                $ignore_next += !$arg ? 2 : 0;
1234                                                break;
1235                                        case 'array':
1236                                                $sql .= $this->column_data_implode(' AND ',$arg,True,False,$table_def['fd']);
1237                                                break;
1238                                }
1239                        }
1240                        if ($this->Debug) echo "<p>db::expression($table,<pre>".print_r(func_get_args(),True)."</pre>) ='$sql'</p>\n";
1241                        return $sql;
1242                }
1243
1244                /**
1245                * Selects one or more rows in table depending on where, all data is quoted according to it's type
1246                *
1247                * @author RalfBecker<at>outdoor-training.de
1248                *
1249                * @param $table string name of the table
1250                * @param $cols mixed string or array of column-names / select-expressions
1251                * @param $where array/string string or array with column-name / values pairs AND'ed together for the where clause
1252                * @param $line int line-number to pass to query
1253                * @param $file string file-name to pass to query
1254                * @param $offset int/bool offset for a limited query or False (default)
1255                * @param string $append string to append to the end of the query, eg. ORDER BY ...
1256                * @param $app mixed string with name of app or False to use the current-app
1257                * @return the return-value of the call to db::query
1258                */
1259                function select($table,$cols,$where,$line,$file,$offset=False,$append='',$app=False)
1260                {
1261                        if ($this->Debug) echo "<p>db::select('$table',".print_r($cols,True).",".print_r($where,True).",$line,$file,$offset,'$app')</p>\n";
1262
1263                        $table_def = $this->get_table_definitions($app,$table);
1264                        if (is_array($cols))
1265                        {
1266                                $cols = implode(',',$cols);
1267                        }
1268                        if (is_array($where))
1269                        {
1270                                $where = $this->column_data_implode(' AND ',$where,True,False,$table_def['fd']);
1271                        }
1272                        $sql = "SELECT $cols FROM $table WHERE ".($where ? $where : '1=1').
1273                                ($append ? ' '.$append : '');
1274
1275                        if ($this->Debug) echo "<p>sql='$sql'</p>";
1276
1277                        return $this->query($sql,$line,$file,$offset,$offset===False ? -1 : 0);
1278                }
1279        }
Note: See TracBrowser for help on using the repository browser.