source: trunk/phpgwapi/inc/adodb/adodb-xmlschema.inc.php @ 2

Revision 2, 53.4 KB checked in by niltonneto, 17 years ago (diff)

Removida todas as tags usadas pelo CVS ($Id, $Source).
Primeira versão no CVS externo.

  • Property svn:eol-style set to native
  • Property svn:executable set to *
RevLine 
[2]1<?php
2// Copyright (c) 2004 ars Cognita Inc., all rights reserved
3/* ******************************************************************************
4    Released under both BSD license and Lesser GPL library license.
5        Whenever there is any discrepancy between the two licenses,
6        the BSD license will take precedence.
7*******************************************************************************/
8/**
9 * xmlschema is a class that allows the user to quickly and easily
10 * build a database on any ADOdb-supported platform using a simple
11 * XML schema.
12 *
13 * @author Richard Tango-Lowy & Dan Cech
14 *
15 * @package axmls
16 * @tutorial getting_started.pkg
17 */
18
19/**
20* Debug on or off
21*/
22if( !defined( 'XMLS_DEBUG' ) ) {
23        define( 'XMLS_DEBUG', FALSE );
24}
25
26/**
27* Default prefix key
28*/
29if( !defined( 'XMLS_PREFIX' ) ) {
30        define( 'XMLS_PREFIX', '%%P' );
31}
32
33/**
34* Maximum length allowed for object prefix
35*/
36if( !defined( 'XMLS_PREFIX_MAXLEN' ) ) {
37        define( 'XMLS_PREFIX_MAXLEN', 10 );
38}
39
40/**
41* Execute SQL inline as it is generated
42*/
43if( !defined( 'XMLS_EXECUTE_INLINE' ) ) {
44        define( 'XMLS_EXECUTE_INLINE', FALSE );
45}
46
47/**
48* Continue SQL Execution if an error occurs?
49*/
50if( !defined( 'XMLS_CONTINUE_ON_ERROR' ) ) {
51        define( 'XMLS_CONTINUE_ON_ERROR', FALSE );
52}
53
54/**
55* Current Schema Version
56*/
57if( !defined( 'XMLS_SCHEMA_VERSION' ) ) {
58        define( 'XMLS_SCHEMA_VERSION', '0.2' );
59}
60
61/**
62* Default Schema Version.  Used for Schemas without an explicit version set.
63*/
64if( !defined( 'XMLS_DEFAULT_SCHEMA_VERSION' ) ) {
65        define( 'XMLS_DEFAULT_SCHEMA_VERSION', '0.1' );
66}
67
68/**
69* Default Schema Version.  Used for Schemas without an explicit version set.
70*/
71if( !defined( 'XMLS_DEFAULT_UPGRADE_METHOD' ) ) {
72        define( 'XMLS_DEFAULT_UPGRADE_METHOD', 'ALTER' );
73}
74
75/**
76* Include the main ADODB library
77*/
78if( !defined( '_ADODB_LAYER' ) ) {
79        require( 'adodb.inc.php' );
80        require( 'adodb-datadict.inc.php' );
81}
82
83/**
84* Abstract DB Object. This class provides basic methods for database objects, such
85* as tables and indexes.
86*
87* @package axmls
88* @access private
89*/
90class dbObject {
91       
92        /**
93        * var object Parent
94        */
95        var $parent;
96       
97        /**
98        * var string current element
99        */
100        var $currentElement;
101       
102        /**
103        * NOP
104        */
105        function dbObject( &$parent, $attributes = NULL ) {
106                $this->parent =& $parent;
107        }
108       
109        /**
110        * XML Callback to process start elements
111        *
112        * @access private
113        */
114        function _tag_open( &$parser, $tag, $attributes ) {
115               
116        }
117       
118        /**
119        * XML Callback to process CDATA elements
120        *
121        * @access private
122        */
123        function _tag_cdata( &$parser, $cdata ) {
124               
125        }
126       
127        /**
128        * XML Callback to process end elements
129        *
130        * @access private
131        */
132        function _tag_close( &$parser, $tag ) {
133               
134        }
135       
136        function create() {
137                return array();
138        }
139       
140        /**
141        * Destroys the object
142        */
143        function destroy() {
144                unset( $this );
145        }
146       
147        /**
148        * Checks whether the specified RDBMS is supported by the current
149        * database object or its ranking ancestor.
150        *
151        * @param string $platform RDBMS platform name (from ADODB platform list).
152        * @return boolean TRUE if RDBMS is supported; otherwise returns FALSE.
153        */
154        function supportedPlatform( $platform = NULL ) {
155                return is_object( $this->parent ) ? $this->parent->supportedPlatform( $platform ) : TRUE;
156        }
157       
158        /**
159        * Returns the prefix set by the ranking ancestor of the database object.
160        *
161        * @param string $name Prefix string.
162        * @return string Prefix.
163        */
164        function prefix( $name = '' ) {
165                return is_object( $this->parent ) ? $this->parent->prefix( $name ) : $name;
166        }
167       
168        /**
169        * Extracts a field ID from the specified field.
170        *
171        * @param string $field Field.
172        * @return string Field ID.
173        */
174        function FieldID( $field ) {
175                return strtoupper( preg_replace( '/^`(.+)`$/', '$1', $field ) );
176        }
177}
178
179/**
180* Creates a table object in ADOdb's datadict format
181*
182* This class stores information about a database table. As charactaristics
183* of the table are loaded from the external source, methods and properties
184* of this class are used to build up the table description in ADOdb's
185* datadict format.
186*
187* @package axmls
188* @access private
189*/
190class dbTable extends dbObject {
191       
192        /**
193        * @var string Table name
194        */
195        var $name;
196       
197        /**
198        * @var array Field specifier: Meta-information about each field
199        */
200        var $fields = array();
201       
202        /**
203        * @var array List of table indexes.
204        */
205        var $indexes = array();
206       
207        /**
208        * @var array Table options: Table-level options
209        */
210        var $opts = array();
211       
212        /**
213        * @var string Field index: Keeps track of which field is currently being processed
214        */
215        var $current_field;
216       
217        /**
218        * @var boolean Mark table for destruction
219        * @access private
220        */
221        var $drop_table;
222       
223        /**
224        * @var boolean Mark field for destruction (not yet implemented)
225        * @access private
226        */
227        var $drop_field = array();
228       
229        /**
230        * Iniitializes a new table object.
231        *
232        * @param string $prefix DB Object prefix
233        * @param array $attributes Array of table attributes.
234        */
235        function dbTable( &$parent, $attributes = NULL ) {
236                $this->parent =& $parent;
237                $this->name = $this->prefix($attributes['NAME']);
238        }
239       
240        /**
241        * XML Callback to process start elements. Elements currently
242        * processed are: INDEX, DROP, FIELD, KEY, NOTNULL, AUTOINCREMENT & DEFAULT.
243        *
244        * @access private
245        */
246        function _tag_open( &$parser, $tag, $attributes ) {
247                $this->currentElement = strtoupper( $tag );
248               
249                switch( $this->currentElement ) {
250                        case 'INDEX':
251                                if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
252                                        xml_set_object( $parser, $this->addIndex( $attributes ) );
253                                }
254                                break;
255                        case 'DATA':
256                                if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
257                                        xml_set_object( $parser, $this->addData( $attributes ) );
258                                }
259                                break;
260                        case 'DROP':
261                                $this->drop();
262                                break;
263                        case 'FIELD':
264                                // Add a field
265                                $fieldName = $attributes['NAME'];
266                                $fieldType = $attributes['TYPE'];
267                                $fieldSize = isset( $attributes['SIZE'] ) ? $attributes['SIZE'] : NULL;
268                                $fieldOpts = isset( $attributes['OPTS'] ) ? $attributes['OPTS'] : NULL;
269                               
270                                $this->addField( $fieldName, $fieldType, $fieldSize, $fieldOpts );
271                                break;
272                        case 'KEY':
273                        case 'NOTNULL':
274                        case 'AUTOINCREMENT':
275                                // Add a field option
276                                $this->addFieldOpt( $this->current_field, $this->currentElement );
277                                break;
278                        case 'DEFAULT':
279                                // Add a field option to the table object
280                               
281                                // Work around ADOdb datadict issue that misinterprets empty strings.
282                                if( $attributes['VALUE'] == '' ) {
283                                        $attributes['VALUE'] = " '' ";
284                                }
285                               
286                                $this->addFieldOpt( $this->current_field, $this->currentElement, $attributes['VALUE'] );
287                                break;
288                        case 'DEFDATE':
289                        case 'DEFTIMESTAMP':
290                                // Add a field option to the table object
291                                $this->addFieldOpt( $this->current_field, $this->currentElement );
292                                break;
293                        default:
294                                // print_r( array( $tag, $attributes ) );
295                }
296        }
297       
298        /**
299        * XML Callback to process CDATA elements
300        *
301        * @access private
302        */
303        function _tag_cdata( &$parser, $cdata ) {
304                switch( $this->currentElement ) {
305                        // Table constraint
306                        case 'CONSTRAINT':
307                                if( isset( $this->current_field ) ) {
308                                        $this->addFieldOpt( $this->current_field, $this->currentElement, $cdata );
309                                } else {
310                                        $this->addTableOpt( $cdata );
311                                }
312                                break;
313                        // Table option
314                        case 'OPT':
315                                $this->addTableOpt( $cdata );
316                                break;
317                        default:
318                               
319                }
320        }
321       
322        /**
323        * XML Callback to process end elements
324        *
325        * @access private
326        */
327        function _tag_close( &$parser, $tag ) {
328                $this->currentElement = '';
329               
330                switch( strtoupper( $tag ) ) {
331                        case 'TABLE':
332                                $this->parent->addSQL( $this->create( $this->parent ) );
333                                xml_set_object( $parser, $this->parent );
334                                $this->destroy();
335                                break;
336                        case 'FIELD':
337                                unset($this->current_field);
338                                break;
339
340                }
341        }
342       
343        /**
344        * Adds an index to a table object
345        *
346        * @param array $attributes Index attributes
347        * @return object dbIndex object
348        */
349        function &addIndex( $attributes ) {
350                $name = strtoupper( $attributes['NAME'] );
351                $this->indexes[$name] =& new dbIndex( $this, $attributes );
352                return $this->indexes[$name];
353        }
354       
355        /**
356        * Adds data to a table object
357        *
358        * @param array $attributes Data attributes
359        * @return object dbData object
360        */
361        function &addData( $attributes ) {
362                if( !isset( $this->data ) ) {
363                        $this->data =& new dbData( $this, $attributes );
364                }
365                return $this->data;
366        }
367       
368        /**
369        * Adds a field to a table object
370        *
371        * $name is the name of the table to which the field should be added.
372        * $type is an ADODB datadict field type. The following field types
373        * are supported as of ADODB 3.40:
374        *       - C:  varchar
375        *       - X:  CLOB (character large object) or largest varchar size
376        *          if CLOB is not supported
377        *       - C2: Multibyte varchar
378        *       - X2: Multibyte CLOB
379        *       - B:  BLOB (binary large object)
380        *       - D:  Date (some databases do not support this, and we return a datetime type)
381        *       - T:  Datetime or Timestamp
382        *       - L:  Integer field suitable for storing booleans (0 or 1)
383        *       - I:  Integer (mapped to I4)
384        *       - I1: 1-byte integer
385        *       - I2: 2-byte integer
386        *       - I4: 4-byte integer
387        *       - I8: 8-byte integer
388        *       - F:  Floating point number
389        *       - N:  Numeric or decimal number
390        *
391        * @param string $name Name of the table to which the field will be added.
392        * @param string $type   ADODB datadict field type.
393        * @param string $size   Field size
394        * @param array $opts    Field options array
395        * @return array Field specifier array
396        */
397        function addField( $name, $type, $size = NULL, $opts = NULL ) {
398                $field_id = $this->FieldID( $name );
399               
400                // Set the field index so we know where we are
401                $this->current_field = $field_id;
402               
403                // Set the field name (required)
404                $this->fields[$field_id]['NAME'] = $name;
405               
406                // Set the field type (required)
407                $this->fields[$field_id]['TYPE'] = $type;
408               
409                // Set the field size (optional)
410                if( isset( $size ) ) {
411                        $this->fields[$field_id]['SIZE'] = $size;
412                }
413               
414                // Set the field options
415                if( isset( $opts ) ) {
416                        $this->fields[$field_id]['OPTS'][] = $opts;
417                }
418        }
419       
420        /**
421        * Adds a field option to the current field specifier
422        *
423        * This method adds a field option allowed by the ADOdb datadict
424        * and appends it to the given field.
425        *
426        * @param string $field  Field name
427        * @param string $opt ADOdb field option
428        * @param mixed $value Field option value
429        * @return array Field specifier array
430        */
431        function addFieldOpt( $field, $opt, $value = NULL ) {
432                if( !isset( $value ) ) {
433                        $this->fields[$this->FieldID( $field )]['OPTS'][] = $opt;
434                // Add the option and value
435                } else {
436                        $this->fields[$this->FieldID( $field )]['OPTS'][] = array( $opt => $value );
437                }
438        }
439       
440        /**
441        * Adds an option to the table
442        *
443        * This method takes a comma-separated list of table-level options
444        * and appends them to the table object.
445        *
446        * @param string $opt Table option
447        * @return array Options
448        */
449        function addTableOpt( $opt ) {
450                $this->opts[] = $opt;
451               
452                return $this->opts;
453        }
454       
455        /**
456        * Generates the SQL that will create the table in the database
457        *
458        * @param object $xmls adoSchema object
459        * @return array Array containing table creation SQL
460        */
461        function create( &$xmls ) {
462                $sql = array();
463               
464                // drop any existing indexes
465                if( is_array( $legacy_indexes = $xmls->dict->MetaIndexes( $this->name ) ) ) {
466                        foreach( $legacy_indexes as $index => $index_details ) {
467                                $sql[] = $xmls->dict->DropIndexSQL( $index, $this->name );
468                        }
469                }
470               
471                // remove fields to be dropped from table object
472                foreach( $this->drop_field as $field ) {
473                        unset( $this->fields[$field] );
474                }
475               
476                // if table exists
477                if( is_array( $legacy_fields = $xmls->dict->MetaColumns( $this->name ) ) ) {
478                        // drop table
479                        if( $this->drop_table ) {
480                                $sql[] = $xmls->dict->DropTableSQL( $this->name );
481                               
482                                return $sql;
483                        }
484                       
485                        // drop any existing fields not in schema
486                        foreach( $legacy_fields as $field_id => $field ) {
487                                if( !isset( $this->fields[$field_id] ) ) {
488                                        $sql[] = $xmls->dict->DropColumnSQL( $this->name, '`'.$field->name.'`' );
489                                }
490                        }
491                // if table doesn't exist
492                } else {
493                        if( $this->drop_table ) {
494                                return $sql;
495                        }
496                       
497                        $legacy_fields = array();
498                }
499               
500                // Loop through the field specifier array, building the associative array for the field options
501                $fldarray = array();
502               
503                foreach( $this->fields as $field_id => $finfo ) {
504                        // Set an empty size if it isn't supplied
505                        if( !isset( $finfo['SIZE'] ) ) {
506                                $finfo['SIZE'] = '';
507                        }
508                       
509                        // Initialize the field array with the type and size
510                        $fldarray[$field_id] = array(
511                                'NAME' => $finfo['NAME'],
512                                'TYPE' => $finfo['TYPE'],
513                                'SIZE' => $finfo['SIZE']
514                        );
515                       
516                        // Loop through the options array and add the field options.
517                        if( isset( $finfo['OPTS'] ) ) {
518                                foreach( $finfo['OPTS'] as $opt ) {
519                                        // Option has an argument.
520                                        if( is_array( $opt ) ) {
521                                                $key = key( $opt );
522                                                $value = $opt[key( $opt )];
523                                                @$fldarray[$field_id][$key] .= $value;
524                                        // Option doesn't have arguments
525                                        } else {
526                                                $fldarray[$field_id][$opt] = $opt;
527                                        }
528                                }
529                        }
530                }
531               
532                if( empty( $legacy_fields ) ) {
533                        // Create the new table
534                        $sql[] = $xmls->dict->CreateTableSQL( $this->name, $fldarray, $this->opts );
535                        logMsg( end( $sql ), 'Generated CreateTableSQL' );
536                } else {
537                        // Upgrade an existing table
538                        logMsg( "Upgrading {$this->name} using '{$xmls->upgrade}'" );
539                        switch( $xmls->upgrade ) {
540                                // Use ChangeTableSQL
541                                case 'ALTER':
542                                        logMsg( 'Generated ChangeTableSQL (ALTERing table)' );
543                                        $sql[] = $xmls->dict->ChangeTableSQL( $this->name, $fldarray, $this->opts );
544                                        break;
545                                case 'REPLACE':
546                                        logMsg( 'Doing upgrade REPLACE (testing)' );
547                                        $sql[] = $xmls->dict->DropTableSQL( $this->name );
548                                        $sql[] = $xmls->dict->CreateTableSQL( $this->name, $fldarray, $this->opts );
549                                        break;
550                                // ignore table
551                                default:
552                                        return array();
553                        }
554                }
555               
556                foreach( $this->indexes as $index ) {
557                        $sql[] = $index->create( $xmls );
558                }
559               
560                if( isset( $this->data ) ) {
561                        $sql[] = $this->data->create( $xmls );
562                }
563               
564                return $sql;
565        }
566       
567        /**
568        * Marks a field or table for destruction
569        */
570        function drop() {
571                if( isset( $this->current_field ) ) {
572                        // Drop the current field
573                        logMsg( "Dropping field '{$this->current_field}' from table '{$this->name}'" );
574                        // $this->drop_field[$this->current_field] = $xmls->dict->DropColumnSQL( $this->name, $this->current_field );
575                        $this->drop_field[$this->current_field] = $this->current_field;
576                } else {
577                        // Drop the current table
578                        logMsg( "Dropping table '{$this->name}'" );
579                        // $this->drop_table = $xmls->dict->DropTableSQL( $this->name );
580                        $this->drop_table = TRUE;
581                }
582        }
583}
584
585/**
586* Creates an index object in ADOdb's datadict format
587*
588* This class stores information about a database index. As charactaristics
589* of the index are loaded from the external source, methods and properties
590* of this class are used to build up the index description in ADOdb's
591* datadict format.
592*
593* @package axmls
594* @access private
595*/
596class dbIndex extends dbObject {
597       
598        /**
599        * @var string   Index name
600        */
601        var $name;
602       
603        /**
604        * @var array    Index options: Index-level options
605        */
606        var $opts = array();
607       
608        /**
609        * @var array    Indexed fields: Table columns included in this index
610        */
611        var $columns = array();
612       
613        /**
614        * @var boolean Mark index for destruction
615        * @access private
616        */
617        var $drop = FALSE;
618       
619        /**
620        * Initializes the new dbIndex object.
621        *
622        * @param object $parent Parent object
623        * @param array $attributes Attributes
624        *
625        * @internal
626        */
627        function dbIndex( &$parent, $attributes = NULL ) {
628                $this->parent =& $parent;
629               
630                $this->name = $this->prefix ($attributes['NAME']);
631        }
632       
633        /**
634        * XML Callback to process start elements
635        *
636        * Processes XML opening tags.
637        * Elements currently processed are: DROP, CLUSTERED, BITMAP, UNIQUE, FULLTEXT & HASH.
638        *
639        * @access private
640        */
641        function _tag_open( &$parser, $tag, $attributes ) {
642                $this->currentElement = strtoupper( $tag );
643               
644                switch( $this->currentElement ) {
645                        case 'DROP':
646                                $this->drop();
647                                break;
648                        case 'CLUSTERED':
649                        case 'BITMAP':
650                        case 'UNIQUE':
651                        case 'FULLTEXT':
652                        case 'HASH':
653                                // Add index Option
654                                $this->addIndexOpt( $this->currentElement );
655                                break;
656                        default:
657                                // print_r( array( $tag, $attributes ) );
658                }
659        }
660       
661        /**
662        * XML Callback to process CDATA elements
663        *
664        * Processes XML cdata.
665        *
666        * @access private
667        */
668        function _tag_cdata( &$parser, $cdata ) {
669                switch( $this->currentElement ) {
670                        // Index field name
671                        case 'COL':
672                                $this->addField( $cdata );
673                                break;
674                        default:
675                               
676                }
677        }
678       
679        /**
680        * XML Callback to process end elements
681        *
682        * @access private
683        */
684        function _tag_close( &$parser, $tag ) {
685                $this->currentElement = '';
686               
687                switch( strtoupper( $tag ) ) {
688                        case 'INDEX':
689                                xml_set_object( $parser, $this->parent );
690                                break;
691                }
692        }
693       
694        /**
695        * Adds a field to the index
696        *
697        * @param string $name Field name
698        * @return string Field list
699        */
700        function addField( $name ) {
701                $this->columns[$this->FieldID( $name )] = $name;
702               
703                // Return the field list
704                return $this->columns;
705        }
706       
707        /**
708        * Adds options to the index
709        *
710        * @param string $opt Comma-separated list of index options.
711        * @return string Option list
712        */
713        function addIndexOpt( $opt ) {
714                $this->opts[] = $opt;
715               
716                // Return the options list
717                return $this->opts;
718        }
719       
720        /**
721        * Generates the SQL that will create the index in the database
722        *
723        * @param object $xmls adoSchema object
724        * @return array Array containing index creation SQL
725        */
726        function create( &$xmls ) {
727                if( $this->drop ) {
728                        return NULL;
729                }
730               
731                // eliminate any columns that aren't in the table
732                foreach( $this->columns as $id => $col ) {
733                        if( !isset( $this->parent->fields[$id] ) ) {
734                                unset( $this->columns[$id] );
735                        }
736                }
737               
738                return $xmls->dict->CreateIndexSQL( $this->name, $this->parent->name, $this->columns, $this->opts );
739        }
740       
741        /**
742        * Marks an index for destruction
743        */
744        function drop() {
745                $this->drop = TRUE;
746        }
747}
748
749/**
750* Creates a data object in ADOdb's datadict format
751*
752* This class stores information about table data.
753*
754* @package axmls
755* @access private
756*/
757class dbData extends dbObject {
758       
759        var $data = array();
760       
761        var $row;
762       
763        /**
764        * Initializes the new dbIndex object.
765        *
766        * @param object $parent Parent object
767        * @param array $attributes Attributes
768        *
769        * @internal
770        */
771        function dbData( &$parent, $attributes = NULL ) {
772                $this->parent =& $parent;
773        }
774       
775        /**
776        * XML Callback to process start elements
777        *
778        * Processes XML opening tags.
779        * Elements currently processed are: DROP, CLUSTERED, BITMAP, UNIQUE, FULLTEXT & HASH.
780        *
781        * @access private
782        */
783        function _tag_open( &$parser, $tag, $attributes ) {
784                $this->currentElement = strtoupper( $tag );
785               
786                switch( $this->currentElement ) {
787                        case 'ROW':
788                                $this->row = count( $this->data );
789                                $this->data[$this->row] = array();
790                                break;
791                        case 'F':
792                                $this->addField($attributes);
793                        default:
794                                // print_r( array( $tag, $attributes ) );
795                }
796        }
797       
798        /**
799        * XML Callback to process CDATA elements
800        *
801        * Processes XML cdata.
802        *
803        * @access private
804        */
805        function _tag_cdata( &$parser, $cdata ) {
806                switch( $this->currentElement ) {
807                        // Index field name
808                        case 'F':
809                                $this->addData( $cdata );
810                                break;
811                        default:
812                               
813                }
814        }
815       
816        /**
817        * XML Callback to process end elements
818        *
819        * @access private
820        */
821        function _tag_close( &$parser, $tag ) {
822                $this->currentElement = '';
823               
824                switch( strtoupper( $tag ) ) {
825                        case 'DATA':
826                                xml_set_object( $parser, $this->parent );
827                                break;
828                }
829        }
830       
831        /**
832        * Adds a field to the index
833        *
834        * @param string $name Field name
835        * @return string Field list
836        */
837        function addField( $attributes ) {
838                if( isset( $attributes['NAME'] ) ) {
839                        $name = $attributes['NAME'];
840                } else {
841                        $name = count($this->data[$this->row]);
842                }
843               
844                // Set the field index so we know where we are
845                $this->current_field = $this->FieldID( $name );
846        }
847       
848        /**
849        * Adds options to the index
850        *
851        * @param string $opt Comma-separated list of index options.
852        * @return string Option list
853        */
854        function addData( $cdata ) {
855                if( !isset( $this->data[$this->row] ) ) {
856                        $this->data[$this->row] = array();
857                }
858               
859                if( !isset( $this->data[$this->row][$this->current_field] ) ) {
860                        $this->data[$this->row][$this->current_field] = '';
861                }
862               
863                $this->data[$this->row][$this->current_field] .= $cdata;
864        }
865       
866        /**
867        * Generates the SQL that will create the index in the database
868        *
869        * @param object $xmls adoSchema object
870        * @return array Array containing index creation SQL
871        */
872        function create( &$xmls ) {
873                $table = $xmls->dict->TableName($this->parent->name);
874                $table_field_count = count($this->parent->fields);
875                $sql = array();
876               
877                // eliminate any columns that aren't in the table
878                foreach( $this->data as $row ) {
879                        $table_fields = $this->parent->fields;
880                        $fields = array();
881                       
882                        foreach( $row as $field_id => $field_data ) {
883                                if( !array_key_exists( $field_id, $table_fields ) ) {
884                                        if( is_numeric( $field_id ) ) {
885                                                $field_id = reset( array_keys( $table_fields ) );
886                                        } else {
887                                                continue;
888                                        }
889                                }
890                               
891                                $name = $table_fields[$field_id]['NAME'];
892                               
893                                switch( $table_fields[$field_id]['TYPE'] ) {
894                                        case 'C':
895                                        case 'C2':
896                                        case 'X':
897                                        case 'X2':
898                                                $fields[$name] = $xmls->db->qstr( $field_data );
899                                                break;
900                                        case 'I':
901                                        case 'I1':
902                                        case 'I2':
903                                        case 'I4':
904                                        case 'I8':
905                                                $fields[$name] = intval($field_data);
906                                                break;
907                                        default:
908                                                $fields[$name] = $field_data;
909                                }
910                               
911                                unset($table_fields[$field_id]);
912                        }
913                       
914                        // check that at least 1 column is specified
915                        if( empty( $fields ) ) {
916                                continue;
917                        }
918                       
919                        // check that no required columns are missing
920                        if( count( $fields ) < $table_field_count ) {
921                                foreach( $table_fields as $field ) {
922                                        if( ( in_array( 'NOTNULL', $field['OPTS'] ) || in_array( 'KEY', $field['OPTS'] ) ) && !in_array( 'AUTOINCREMENT', $field['OPTS'] ) ) {
923                                                continue(2);
924                                        }
925                                }
926                        }
927                       
928                        $sql[] = 'INSERT INTO '. $table .' ('. implode( ',', array_keys( $fields ) ) .') VALUES ('. implode( ',', $fields ) .')';
929                }
930               
931                return $sql;
932        }
933}
934
935/**
936* Creates the SQL to execute a list of provided SQL queries
937*
938* @package axmls
939* @access private
940*/
941class dbQuerySet extends dbObject {
942       
943        /**
944        * @var array    List of SQL queries
945        */
946        var $queries = array();
947       
948        /**
949        * @var string   String used to build of a query line by line
950        */
951        var $query;
952       
953        /**
954        * @var string   Query prefix key
955        */
956        var $prefixKey = '';
957       
958        /**
959        * @var boolean  Auto prefix enable (TRUE)
960        */
961        var $prefixMethod = 'AUTO';
962       
963        /**
964        * Initializes the query set.
965        *
966        * @param object $parent Parent object
967        * @param array $attributes Attributes
968        */
969        function dbQuerySet( &$parent, $attributes = NULL ) {
970                $this->parent =& $parent;
971                       
972                // Overrides the manual prefix key
973                if( isset( $attributes['KEY'] ) ) {
974                        $this->prefixKey = $attributes['KEY'];
975                }
976               
977                $prefixMethod = isset( $attributes['PREFIXMETHOD'] ) ? strtoupper( trim( $attributes['PREFIXMETHOD'] ) ) : '';
978               
979                // Enables or disables automatic prefix prepending
980                switch( $prefixMethod ) {
981                        case 'AUTO':
982                                $this->prefixMethod = 'AUTO';
983                                break;
984                        case 'MANUAL':
985                                $this->prefixMethod = 'MANUAL';
986                                break;
987                        case 'NONE':
988                                $this->prefixMethod = 'NONE';
989                                break;
990                }
991        }
992       
993        /**
994        * XML Callback to process start elements. Elements currently
995        * processed are: QUERY.
996        *
997        * @access private
998        */
999        function _tag_open( &$parser, $tag, $attributes ) {
1000                $this->currentElement = strtoupper( $tag );
1001               
1002                switch( $this->currentElement ) {
1003                        case 'QUERY':
1004                                // Create a new query in a SQL queryset.
1005                                // Ignore this query set if a platform is specified and it's different than the
1006                                // current connection platform.
1007                                if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
1008                                        $this->newQuery();
1009                                } else {
1010                                        $this->discardQuery();
1011                                }
1012                                break;
1013                        default:
1014                                // print_r( array( $tag, $attributes ) );
1015                }
1016        }
1017       
1018        /**
1019        * XML Callback to process CDATA elements
1020        */
1021        function _tag_cdata( &$parser, $cdata ) {
1022                switch( $this->currentElement ) {
1023                        // Line of queryset SQL data
1024                        case 'QUERY':
1025                                $this->buildQuery( $cdata );
1026                                break;
1027                        default:
1028                               
1029                }
1030        }
1031       
1032        /**
1033        * XML Callback to process end elements
1034        *
1035        * @access private
1036        */
1037        function _tag_close( &$parser, $tag ) {
1038                $this->currentElement = '';
1039               
1040                switch( strtoupper( $tag ) ) {
1041                        case 'QUERY':
1042                                // Add the finished query to the open query set.
1043                                $this->addQuery();
1044                                break;
1045                        case 'SQL':
1046                                $this->parent->addSQL( $this->create( $this->parent ) );
1047                                xml_set_object( $parser, $this->parent );
1048                                $this->destroy();
1049                                break;
1050                        default:
1051                               
1052                }
1053        }
1054       
1055        /**
1056        * Re-initializes the query.
1057        *
1058        * @return boolean TRUE
1059        */
1060        function newQuery() {
1061                $this->query = '';
1062               
1063                return TRUE;
1064        }
1065       
1066        /**
1067        * Discards the existing query.
1068        *
1069        * @return boolean TRUE
1070        */
1071        function discardQuery() {
1072                unset( $this->query );
1073               
1074                return TRUE;
1075        }
1076       
1077        /**
1078        * Appends a line to a query that is being built line by line
1079        *
1080        * @param string $data Line of SQL data or NULL to initialize a new query
1081        * @return string SQL query string.
1082        */
1083        function buildQuery( $sql = NULL ) {
1084                if( !isset( $this->query ) OR empty( $sql ) ) {
1085                        return FALSE;
1086                }
1087               
1088                $this->query .= $sql;
1089               
1090                return $this->query;
1091        }
1092       
1093        /**
1094        * Adds a completed query to the query list
1095        *
1096        * @return string        SQL of added query
1097        */
1098        function addQuery() {
1099                if( !isset( $this->query ) ) {
1100                        return FALSE;
1101                }
1102               
1103                $this->queries[] = $return = trim($this->query);
1104               
1105                unset( $this->query );
1106               
1107                return $return;
1108        }
1109       
1110        /**
1111        * Creates and returns the current query set
1112        *
1113        * @param object $xmls adoSchema object
1114        * @return array Query set
1115        */
1116        function create( &$xmls ) {
1117                foreach( $this->queries as $id => $query ) {
1118                        switch( $this->prefixMethod ) {
1119                                case 'AUTO':
1120                                        // Enable auto prefix replacement
1121                                       
1122                                        // Process object prefix.
1123                                        // Evaluate SQL statements to prepend prefix to objects
1124                                        $query = $this->prefixQuery( '/^\s*((?is)INSERT\s+(INTO\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix );
1125                                        $query = $this->prefixQuery( '/^\s*((?is)UPDATE\s+(FROM\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix );
1126                                        $query = $this->prefixQuery( '/^\s*((?is)DELETE\s+(FROM\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix );
1127                                       
1128                                        // SELECT statements aren't working yet
1129                                        #$data = preg_replace( '/(?ias)(^\s*SELECT\s+.*\s+FROM)\s+(\W\s*,?\s*)+((?i)\s+WHERE.*$)/', "\1 $prefix\2 \3", $data );
1130                                       
1131                                case 'MANUAL':
1132                                        // If prefixKey is set and has a value then we use it to override the default constant XMLS_PREFIX.
1133                                        // If prefixKey is not set, we use the default constant XMLS_PREFIX
1134                                        if( isset( $this->prefixKey ) AND( $this->prefixKey !== '' ) ) {
1135                                                // Enable prefix override
1136                                                $query = str_replace( $this->prefixKey, $xmls->objectPrefix, $query );
1137                                        } else {
1138                                                // Use default replacement
1139                                                $query = str_replace( XMLS_PREFIX , $xmls->objectPrefix, $query );
1140                                        }
1141                        }
1142                       
1143                        $this->queries[$id] = trim( $query );
1144                }
1145               
1146                // Return the query set array
1147                return $this->queries;
1148        }
1149       
1150        /**
1151        * Rebuilds the query with the prefix attached to any objects
1152        *
1153        * @param string $regex Regex used to add prefix
1154        * @param string $query SQL query string
1155        * @param string $prefix Prefix to be appended to tables, indices, etc.
1156        * @return string Prefixed SQL query string.
1157        */
1158        function prefixQuery( $regex, $query, $prefix = NULL ) {
1159                if( !isset( $prefix ) ) {
1160                        return $query;
1161                }
1162               
1163                if( preg_match( $regex, $query, $match ) ) {
1164                        $preamble = $match[1];
1165                        $postamble = $match[5];
1166                        $objectList = explode( ',', $match[3] );
1167                        // $prefix = $prefix . '_';
1168                       
1169                        $prefixedList = '';
1170                       
1171                        foreach( $objectList as $object ) {
1172                                if( $prefixedList !== '' ) {
1173                                        $prefixedList .= ', ';
1174                                }
1175                               
1176                                $prefixedList .= $prefix . trim( $object );
1177                        }
1178                       
1179                        $query = $preamble . ' ' . $prefixedList . ' ' . $postamble;
1180                }
1181               
1182                return $query;
1183        }
1184}
1185
1186/**
1187* Loads and parses an XML file, creating an array of "ready-to-run" SQL statements
1188*
1189* This class is used to load and parse the XML file, to create an array of SQL statements
1190* that can be used to build a database, and to build the database using the SQL array.
1191*
1192* @tutorial getting_started.pkg
1193*
1194* @author Richard Tango-Lowy & Dan Cech
1195*
1196* @package axmls
1197*/
1198class adoSchema {
1199       
1200        /**
1201        * @var array    Array containing SQL queries to generate all objects
1202        * @access private
1203        */
1204        var $sqlArray;
1205       
1206        /**
1207        * @var object   ADOdb connection object
1208        * @access private
1209        */
1210        var $db;
1211       
1212        /**
1213        * @var object   ADOdb Data Dictionary
1214        * @access private
1215        */
1216        var $dict;
1217       
1218        /**
1219        * @var string Current XML element
1220        * @access private
1221        */
1222        var $currentElement = '';
1223       
1224        /**
1225        * @var string If set (to 'ALTER' or 'REPLACE'), upgrade an existing database
1226        * @access private
1227        */
1228        var $upgrade = '';
1229       
1230        /**
1231        * @var string Optional object prefix
1232        * @access private
1233        */
1234        var $objectPrefix = '';
1235       
1236        /**
1237        * @var long     Original Magic Quotes Runtime value
1238        * @access private
1239        */
1240        var $mgq;
1241       
1242        /**
1243        * @var long     System debug
1244        * @access private
1245        */
1246        var $debug;
1247       
1248        /**
1249        * @var string Regular expression to find schema version
1250        * @access private
1251        */
1252        var $versionRegex = '/<schema.*?( version="([^"]*)")?.*?>/';
1253       
1254        /**
1255        * @var string Current schema version
1256        * @access private
1257        */
1258        var $schemaVersion;
1259       
1260        /**
1261        * @var int      Success of last Schema execution
1262        */
1263        var $success;
1264       
1265        /**
1266        * @var bool     Execute SQL inline as it is generated
1267        */
1268        var $executeInline;
1269       
1270        /**
1271        * @var bool     Continue SQL execution if errors occur
1272        */
1273        var $continueOnError;
1274       
1275        /**
1276        * Creates an adoSchema object
1277        *
1278        * Creating an adoSchema object is the first step in processing an XML schema.
1279        * The only parameter is an ADOdb database connection object, which must already
1280        * have been created.
1281        *
1282        * @param object $db ADOdb database connection object.
1283        */
1284        function adoSchema( &$db ) {
1285                // Initialize the environment
1286                $this->mgq = get_magic_quotes_runtime();
1287                set_magic_quotes_runtime(0);
1288               
1289                $this->db =& $db;
1290                $this->debug = $this->db->debug;
1291                $this->dict = NewDataDictionary( $this->db );
1292                $this->sqlArray = array();
1293                $this->schemaVersion = XMLS_SCHEMA_VERSION;
1294                $this->executeInline( XMLS_EXECUTE_INLINE );
1295                $this->continueOnError( XMLS_CONTINUE_ON_ERROR );
1296                $this->setUpgradeMethod();
1297        }
1298       
1299        /**
1300        * Sets the method to be used for upgrading an existing database
1301        *
1302        * Use this method to specify how existing database objects should be upgraded.
1303        * The method option can be set to ALTER, REPLACE, BEST, or NONE. ALTER attempts to
1304        * alter each database object directly, REPLACE attempts to rebuild each object
1305        * from scratch, BEST attempts to determine the best upgrade method for each
1306        * object, and NONE disables upgrading.
1307        *
1308        * This method is not yet used by AXMLS, but exists for backward compatibility.
1309        * The ALTER method is automatically assumed when the adoSchema object is
1310        * instantiated; other upgrade methods are not currently supported.
1311        *
1312        * @param string $method Upgrade method (ALTER|REPLACE|BEST|NONE)
1313        * @returns string Upgrade method used
1314        */
1315        function SetUpgradeMethod( $method = '' ) {
1316                if( !is_string( $method ) ) {
1317                        return FALSE;
1318                }
1319               
1320                $method = strtoupper( $method );
1321               
1322                // Handle the upgrade methods
1323                switch( $method ) {
1324                        case 'ALTER':
1325                                $this->upgrade = $method;
1326                                break;
1327                        case 'REPLACE':
1328                                $this->upgrade = $method;
1329                                break;
1330                        case 'BEST':
1331                                $this->upgrade = 'ALTER';
1332                                break;
1333                        case 'NONE':
1334                                $this->upgrade = 'NONE';
1335                                break;
1336                        default:
1337                                // Use default if no legitimate method is passed.
1338                                $this->upgrade = XMLS_DEFAULT_UPGRADE_METHOD;
1339                }
1340               
1341                return $this->upgrade;
1342        }
1343       
1344        /**
1345        * Enables/disables inline SQL execution.
1346        *
1347        * Call this method to enable or disable inline execution of the schema. If the mode is set to TRUE (inline execution),
1348        * AXMLS applies the SQL to the database immediately as each schema entity is parsed. If the mode
1349        * is set to FALSE (post execution), AXMLS parses the entire schema and you will need to call adoSchema::ExecuteSchema()
1350        * to apply the schema to the database.
1351        *
1352        * @param bool $mode execute
1353        * @return bool current execution mode
1354        *
1355        * @see ParseSchema(), ExecuteSchema()
1356        */
1357        function ExecuteInline( $mode = NULL ) {
1358                if( is_bool( $mode ) ) {
1359                        $this->executeInline = $mode;
1360                }
1361               
1362                return $this->executeInline;
1363        }
1364       
1365        /**
1366        * Enables/disables SQL continue on error.
1367        *
1368        * Call this method to enable or disable continuation of SQL execution if an error occurs.
1369        * If the mode is set to TRUE (continue), AXMLS will continue to apply SQL to the database, even if an error occurs.
1370        * If the mode is set to FALSE (halt), AXMLS will halt execution of generated sql if an error occurs, though parsing
1371        * of the schema will continue.
1372        *
1373        * @param bool $mode execute
1374        * @return bool current continueOnError mode
1375        *
1376        * @see addSQL(), ExecuteSchema()
1377        */
1378        function ContinueOnError( $mode = NULL ) {
1379                if( is_bool( $mode ) ) {
1380                        $this->continueOnError = $mode;
1381                }
1382               
1383                return $this->continueOnError;
1384        }
1385       
1386        /**
1387        * Loads an XML schema from a file and converts it to SQL.
1388        *
1389        * Call this method to load the specified schema (see the DTD for the proper format) from
1390        * the filesystem and generate the SQL necessary to create the database described.
1391        * @see ParseSchemaString()
1392        *
1393        * @param string $file Name of XML schema file.
1394        * @param bool $returnSchema Return schema rather than parsing.
1395        * @return array Array of SQL queries, ready to execute
1396        */
1397        function ParseSchema( $filename, $returnSchema = FALSE ) {
1398                return $this->ParseSchemaString( $this->ConvertSchemaFile( $filename ), $returnSchema );
1399        }
1400       
1401        /**
1402        * Loads an XML schema from a file and converts it to SQL.
1403        *
1404        * Call this method to load the specified schema from a file (see the DTD for the proper format)
1405        * and generate the SQL necessary to create the database described by the schema.
1406        *
1407        * @param string $file Name of XML schema file.
1408        * @param bool $returnSchema Return schema rather than parsing.
1409        * @return array Array of SQL queries, ready to execute.
1410        *
1411        * @deprecated Replaced by adoSchema::ParseSchema() and adoSchema::ParseSchemaString()
1412        * @see ParseSchema(), ParseSchemaString()
1413        */
1414        function ParseSchemaFile( $filename, $returnSchema = FALSE ) {
1415                // Open the file
1416                if( !($fp = fopen( $filename, 'r' )) ) {
1417                        // die( 'Unable to open file' );
1418                        return FALSE;
1419                }
1420               
1421                // do version detection here
1422                if( $this->SchemaFileVersion( $filename ) != $this->schemaVersion ) {
1423                        return FALSE;
1424                }
1425               
1426                if ( $returnSchema )
1427                {
1428                        return $xmlstring;
1429                }
1430               
1431                $this->success = 2;
1432               
1433                $xmlParser = $this->create_parser();
1434               
1435                // Process the file
1436                while( $data = fread( $fp, 4096 ) ) {
1437                        if( !xml_parse( $xmlParser, $data, feof( $fp ) ) ) {
1438                                die( sprintf(
1439                                        "XML error: %s at line %d",
1440                                        xml_error_string( xml_get_error_code( $xmlParser) ),
1441                                        xml_get_current_line_number( $xmlParser)
1442                                ) );
1443                        }
1444                }
1445               
1446                xml_parser_free( $xmlParser );
1447               
1448                return $this->sqlArray;
1449        }
1450       
1451        /**
1452        * Converts an XML schema string to SQL.
1453        *
1454        * Call this method to parse a string containing an XML schema (see the DTD for the proper format)
1455        * and generate the SQL necessary to create the database described by the schema.
1456        * @see ParseSchema()
1457        *
1458        * @param string $xmlstring XML schema string.
1459        * @param bool $returnSchema Return schema rather than parsing.
1460        * @return array Array of SQL queries, ready to execute.
1461        */
1462        function ParseSchemaString( $xmlstring, $returnSchema = FALSE ) {
1463                if( !is_string( $xmlstring ) OR empty( $xmlstring ) ) {
1464                        return FALSE;
1465                }
1466               
1467                // do version detection here
1468                if( $this->SchemaStringVersion( $xmlstring ) != $this->schemaVersion ) {
1469                        return FALSE;
1470                }
1471               
1472                if ( $returnSchema )
1473                {
1474                        return $xmlstring;
1475                }
1476               
1477                $this->success = 2;
1478               
1479                $xmlParser = $this->create_parser();
1480               
1481                if( !xml_parse( $xmlParser, $xmlstring, TRUE ) ) {
1482                        die( sprintf(
1483                                "XML error: %s at line %d",
1484                                xml_error_string( xml_get_error_code( $xmlParser) ),
1485                                xml_get_current_line_number( $xmlParser)
1486                        ) );
1487                }
1488               
1489                xml_parser_free( $xmlParser );
1490               
1491                return $this->sqlArray;
1492        }
1493       
1494        /**
1495        * Loads an XML schema from a file and converts it to uninstallation SQL.
1496        *
1497        * Call this method to load the specified schema (see the DTD for the proper format) from
1498        * the filesystem and generate the SQL necessary to remove the database described.
1499        * @see RemoveSchemaString()
1500        *
1501        * @param string $file Name of XML schema file.
1502        * @param bool $returnSchema Return schema rather than parsing.
1503        * @return array Array of SQL queries, ready to execute
1504        */
1505        function RemoveSchema( $filename, $returnSchema = FALSE ) {
1506                return $this->RemoveSchemaString( $this->ConvertSchemaFile( $filename ), $returnSchema );
1507        }
1508       
1509        /**
1510        * Converts an XML schema string to uninstallation SQL.
1511        *
1512        * Call this method to parse a string containing an XML schema (see the DTD for the proper format)
1513        * and generate the SQL necessary to uninstall the database described by the schema.
1514        * @see RemoveSchema()
1515        *
1516        * @param string $schema XML schema string.
1517        * @param bool $returnSchema Return schema rather than parsing.
1518        * @return array Array of SQL queries, ready to execute.
1519        */
1520        function RemoveSchemaString( $schema, $returnSchema = FALSE ) {
1521               
1522                // grab current version
1523                if( !( $version = $this->SchemaStringVersion( $schema ) ) ) {
1524                        return FALSE;
1525                }
1526               
1527                return $this->ParseSchemaString( $this->TransformSchema( $schema, 'remove-' . $version), $returnSchema );
1528        }
1529       
1530        /**
1531        * Applies the current XML schema to the database (post execution).
1532        *
1533        * Call this method to apply the current schema (generally created by calling
1534        * ParseSchema() or ParseSchemaString() ) to the database (creating the tables, indexes,
1535        * and executing other SQL specified in the schema) after parsing.
1536        * @see ParseSchema(), ParseSchemaString(), ExecuteInline()
1537        *
1538        * @param array $sqlArray Array of SQL statements that will be applied rather than
1539        *               the current schema.
1540        * @param boolean $continueOnErr Continue to apply the schema even if an error occurs.
1541        * @returns integer 0 if failure, 1 if errors, 2 if successful.
1542        */
1543        function ExecuteSchema( $sqlArray = NULL, $continueOnErr =  NULL ) {
1544                if( !is_bool( $continueOnErr ) ) {
1545                        $continueOnErr = $this->ContinueOnError();
1546                }
1547               
1548                if( !isset( $sqlArray ) ) {
1549                        $sqlArray = $this->sqlArray;
1550                }
1551               
1552                if( !is_array( $sqlArray ) ) {
1553                        $this->success = 0;
1554                } else {
1555                        $this->success = $this->dict->ExecuteSQLArray( $sqlArray, $continueOnErr );
1556                }
1557               
1558                return $this->success;
1559        }
1560       
1561        /**
1562        * Returns the current SQL array.
1563        *
1564        * Call this method to fetch the array of SQL queries resulting from
1565        * ParseSchema() or ParseSchemaString().
1566        *
1567        * @param string $format Format: HTML, TEXT, or NONE (PHP array)
1568        * @return array Array of SQL statements or FALSE if an error occurs
1569        */
1570        function PrintSQL( $format = 'NONE' ) {
1571                return $this->getSQL( $format, $sqlArray );
1572        }
1573       
1574        /**
1575        * Saves the current SQL array to the local filesystem as a list of SQL queries.
1576        *
1577        * Call this method to save the array of SQL queries (generally resulting from a
1578        * parsed XML schema) to the filesystem.
1579        *
1580        * @param string $filename Path and name where the file should be saved.
1581        * @return boolean TRUE if save is successful, else FALSE.
1582        */
1583        function SaveSQL( $filename = './schema.sql' ) {
1584               
1585                if( !isset( $sqlArray ) ) {
1586                        $sqlArray = $this->sqlArray;
1587                }
1588                if( !isset( $sqlArray ) ) {
1589                        return FALSE;
1590                }
1591               
1592                $fp = fopen( $filename, "w" );
1593               
1594                foreach( $sqlArray as $key => $query ) {
1595                        fwrite( $fp, $query . ";\n" );
1596                }
1597                fclose( $fp );
1598        }
1599       
1600        /**
1601        * Create an xml parser
1602        *
1603        * @return object PHP XML parser object
1604        *
1605        * @access private
1606        */
1607        function &create_parser() {
1608                // Create the parser
1609                $xmlParser = xml_parser_create();
1610                xml_set_object( $xmlParser, $this );
1611               
1612                // Initialize the XML callback functions
1613                xml_set_element_handler( $xmlParser, '_tag_open', '_tag_close' );
1614                xml_set_character_data_handler( $xmlParser, '_tag_cdata' );
1615               
1616                return $xmlParser;
1617        }
1618       
1619        /**
1620        * XML Callback to process start elements
1621        *
1622        * @access private
1623        */
1624        function _tag_open( &$parser, $tag, $attributes ) {
1625                switch( strtoupper( $tag ) ) {
1626                        case 'TABLE':
1627                                $this->obj = new dbTable( $this, $attributes );
1628                                xml_set_object( $parser, $this->obj );
1629                                break;
1630                        case 'SQL':
1631                                if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
1632                                        $this->obj = new dbQuerySet( $this, $attributes );
1633                                        xml_set_object( $parser, $this->obj );
1634                                }
1635                                break;
1636                        default:
1637                                // print_r( array( $tag, $attributes ) );
1638                }
1639               
1640        }
1641       
1642        /**
1643        * XML Callback to process CDATA elements
1644        *
1645        * @access private
1646        */
1647        function _tag_cdata( &$parser, $cdata ) {
1648        }
1649       
1650        /**
1651        * XML Callback to process end elements
1652        *
1653        * @access private
1654        * @internal
1655        */
1656        function _tag_close( &$parser, $tag ) {
1657               
1658        }
1659       
1660        /**
1661        * Converts an XML schema string to the specified DTD version.
1662        *
1663        * Call this method to convert a string containing an XML schema to a different AXMLS
1664        * DTD version. For instance, to convert a schema created for an pre-1.0 version for
1665        * AXMLS (DTD version 0.1) to a newer version of the DTD (e.g. 0.2). If no DTD version
1666        * parameter is specified, the schema will be converted to the current DTD version.
1667        * If the newFile parameter is provided, the converted schema will be written to the specified
1668        * file.
1669        * @see ConvertSchemaFile()
1670        *
1671        * @param string $schema String containing XML schema that will be converted.
1672        * @param string $newVersion DTD version to convert to.
1673        * @param string $newFile File name of (converted) output file.
1674        * @return string Converted XML schema or FALSE if an error occurs.
1675        */
1676        function ConvertSchemaString( $schema, $newVersion = NULL, $newFile = NULL ) {
1677               
1678                // grab current version
1679                if( !( $version = $this->SchemaStringVersion( $schema ) ) ) {
1680                        return FALSE;
1681                }
1682               
1683                if( !isset ($newVersion) ) {
1684                        $newVersion = $this->schemaVersion;
1685                }
1686               
1687                if( $version == $newVersion ) {
1688                        $result = $schema;
1689                } else {
1690                        $result = $this->TransformSchema( $schema, 'convert-' . $version . '-' . $newVersion);
1691                }
1692               
1693                if( is_string( $result ) AND is_string( $newFile ) AND ( $fp = fopen( $newFile, 'w' ) ) ) {
1694                        fwrite( $fp, $result );
1695                        fclose( $fp );
1696                }
1697               
1698                return $result;
1699        }
1700       
1701        /**
1702        * Converts an XML schema file to the specified DTD version.
1703        *
1704        * Call this method to convert the specified XML schema file to a different AXMLS
1705        * DTD version. For instance, to convert a schema created for an pre-1.0 version for
1706        * AXMLS (DTD version 0.1) to a newer version of the DTD (e.g. 0.2). If no DTD version
1707        * parameter is specified, the schema will be converted to the current DTD version.
1708        * If the newFile parameter is provided, the converted schema will be written to the specified
1709        * file.
1710        * @see ConvertSchemaString()
1711        *
1712        * @param string $filename Name of XML schema file that will be converted.
1713        * @param string $newVersion DTD version to convert to.
1714        * @param string $newFile File name of (converted) output file.
1715        * @return string Converted XML schema or FALSE if an error occurs.
1716        */
1717        function ConvertSchemaFile( $filename, $newVersion = NULL, $newFile = NULL ) {
1718               
1719                // grab current version
1720                if( !( $version = $this->SchemaFileVersion( $filename ) ) ) {
1721                        return FALSE;
1722                }
1723               
1724                if( !isset ($newVersion) ) {
1725                        $newVersion = $this->schemaVersion;
1726                }
1727               
1728                if( $version == $newVersion ) {
1729                        $result = file_get_contents( $filename );
1730                       
1731                        // remove unicode BOM if present
1732                        if( substr( $result, 0, 3 ) == sprintf( '%c%c%c', 239, 187, 191 ) ) {
1733                                $result = substr( $result, 3 );
1734                        }
1735                } else {
1736                        $result = $this->TransformSchema( $filename, 'convert-' . $version . '-' . $newVersion, 'file' );
1737                }
1738               
1739                if( is_string( $result ) AND is_string( $newFile ) AND ( $fp = fopen( $newFile, 'w' ) ) ) {
1740                        fwrite( $fp, $result );
1741                        fclose( $fp );
1742                }
1743               
1744                return $result;
1745        }
1746       
1747        function TransformSchema( $schema, $xsl, $schematype='string' )
1748        {
1749                // Fail if XSLT extension is not available
1750                if( ! function_exists( 'xslt_create' ) ) {
1751                        return FALSE;
1752                }
1753               
1754                $xsl_file = dirname( __FILE__ ) . '/xsl/' . $xsl . '.xsl';
1755               
1756                // look for xsl
1757                if( !is_readable( $xsl_file ) ) {
1758                        return FALSE;
1759                }
1760               
1761                switch( $schematype )
1762                {
1763                        case 'file':
1764                                if( !is_readable( $schema ) ) {
1765                                        return FALSE;
1766                                }
1767                               
1768                                $schema = file_get_contents( $schema );
1769                                break;
1770                        case 'string':
1771                        default:
1772                                if( !is_string( $schema ) ) {
1773                                        return FALSE;
1774                                }
1775                }
1776               
1777                $arguments = array (
1778                        '/_xml' => $schema,
1779                        '/_xsl' => file_get_contents( $xsl_file )
1780                );
1781               
1782                // create an XSLT processor
1783                $xh = xslt_create ();
1784               
1785                // set error handler
1786                xslt_set_error_handler ($xh, array (&$this, 'xslt_error_handler'));
1787               
1788                // process the schema
1789                $result = xslt_process ($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments);
1790               
1791                xslt_free ($xh);
1792               
1793                return $result;
1794        }
1795       
1796        /**
1797        * Processes XSLT transformation errors
1798        *
1799        * @param object $parser XML parser object
1800        * @param integer $errno Error number
1801        * @param integer $level Error level
1802        * @param array $fields Error information fields
1803        *
1804        * @access private
1805        */
1806        function xslt_error_handler( $parser, $errno, $level, $fields ) {
1807                if( is_array( $fields ) ) {
1808                        $msg = array(
1809                                'Message Type' => ucfirst( $fields['msgtype'] ),
1810                                'Message Code' => $fields['code'],
1811                                'Message' => $fields['msg'],
1812                                'Error Number' => $errno,
1813                                'Level' => $level
1814                        );
1815                       
1816                        switch( $fields['URI'] ) {
1817                                case 'arg:/_xml':
1818                                        $msg['Input'] = 'XML';
1819                                        break;
1820                                case 'arg:/_xsl':
1821                                        $msg['Input'] = 'XSL';
1822                                        break;
1823                                default:
1824                                        $msg['Input'] = $fields['URI'];
1825                        }
1826                       
1827                        $msg['Line'] = $fields['line'];
1828                } else {
1829                        $msg = array(
1830                                'Message Type' => 'Error',
1831                                'Error Number' => $errno,
1832                                'Level' => $level,
1833                                'Fields' => var_export( $fields, TRUE )
1834                        );
1835                }
1836               
1837                $error_details = $msg['Message Type'] . ' in XSLT Transformation' . "\n"
1838                                           . '<table>' . "\n";
1839               
1840                foreach( $msg as $label => $details ) {
1841                        $error_details .= '<tr><td><b>' . $label . ': </b></td><td>' . htmlentities( $details ) . '</td></tr>' . "\n";
1842                }
1843               
1844                $error_details .= '</table>';
1845               
1846                trigger_error( $error_details, E_USER_ERROR );
1847        }
1848       
1849        /**
1850        * Returns the AXMLS Schema Version of the requested XML schema file.
1851        *
1852        * Call this method to obtain the AXMLS DTD version of the requested XML schema file.
1853        * @see SchemaStringVersion()
1854        *
1855        * @param string $filename AXMLS schema file
1856        * @return string Schema version number or FALSE on error
1857        */
1858        function SchemaFileVersion( $filename ) {
1859                // Open the file
1860                if( !($fp = fopen( $filename, 'r' )) ) {
1861                        // die( 'Unable to open file' );
1862                        return FALSE;
1863                }
1864               
1865                // Process the file
1866                while( $data = fread( $fp, 4096 ) ) {
1867                        if( preg_match( $this->versionRegex, $data, $matches ) ) {
1868                                return !empty( $matches[2] ) ? $matches[2] : XMLS_DEFAULT_SCHEMA_VERSION;
1869                        }
1870                }
1871               
1872                return FALSE;
1873        }
1874       
1875        /**
1876        * Returns the AXMLS Schema Version of the provided XML schema string.
1877        *
1878        * Call this method to obtain the AXMLS DTD version of the provided XML schema string.
1879        * @see SchemaFileVersion()
1880        *
1881        * @param string $xmlstring XML schema string
1882        * @return string Schema version number or FALSE on error
1883        */
1884        function SchemaStringVersion( $xmlstring ) {
1885                if( !is_string( $xmlstring ) OR empty( $xmlstring ) ) {
1886                        return FALSE;
1887                }
1888               
1889                if( preg_match( $this->versionRegex, $xmlstring, $matches ) ) {
1890                        return !empty( $matches[2] ) ? $matches[2] : XMLS_DEFAULT_SCHEMA_VERSION;
1891                }
1892               
1893                return FALSE;
1894        }
1895       
1896        /**
1897        * Extracts an XML schema from an existing database.
1898        *
1899        * Call this method to create an XML schema string from an existing database.
1900        * If the data parameter is set to TRUE, AXMLS will include the data from the database
1901        * in the schema.
1902        *
1903        * @param boolean $data Include data in schema dump
1904        * @return string Generated XML schema
1905        */
1906        function ExtractSchema( $data = FALSE ) {
1907                $old_mode = $this->db->SetFetchMode( ADODB_FETCH_NUM );
1908               
1909                $schema = '<?xml version="1.0"?>' . "\n"
1910                                . '<schema version="' . $this->schemaVersion . '">' . "\n";
1911               
1912                if( is_array( $tables = $this->db->MetaTables( 'TABLES' ) ) ) {
1913                        foreach( $tables as $table ) {
1914                                $schema .= '    <table name="' . $table . '">' . "\n";
1915                               
1916                                // grab details from database
1917                                $rs = $this->db->Execute( 'SELECT * FROM ' . $table . ' WHERE -1' );
1918                                $fields = $this->db->MetaColumns( $table );
1919                                $indexes = $this->db->MetaIndexes( $table );
1920                               
1921                                if( is_array( $fields ) ) {
1922                                        foreach( $fields as $details ) {
1923                                                $extra = '';
1924                                                $content = array();
1925                                               
1926                                                if( $details->max_length > 0 ) {
1927                                                        $extra .= ' size="' . $details->max_length . '"';
1928                                                }
1929                                               
1930                                                if( $details->primary_key ) {
1931                                                        $content[] = '<KEY/>';
1932                                                } elseif( $details->not_null ) {
1933                                                        $content[] = '<NOTNULL/>';
1934                                                }
1935                                               
1936                                                if( $details->has_default ) {
1937                                                        $content[] = '<DEFAULT value="' . $details->default_value . '"/>';
1938                                                }
1939                                               
1940                                                if( $details->auto_increment ) {
1941                                                        $content[] = '<AUTOINCREMENT/>';
1942                                                }
1943                                               
1944                                                // this stops the creation of 'R' columns,
1945                                                // AUTOINCREMENT is used to create auto columns
1946                                                $details->primary_key = 0;
1947                                                $type = $rs->MetaType( $details );
1948                                               
1949                                                $schema .= '            <field name="' . $details->name . '" type="' . $type . '"' . $extra . '>';
1950                                               
1951                                                if( !empty( $content ) ) {
1952                                                        $schema .= "\n                  " . implode( "\n                        ", $content ) . "\n             ";
1953                                                }
1954                                               
1955                                                $schema .= '</field>' . "\n";
1956                                        }
1957                                }
1958                               
1959                                if( is_array( $indexes ) ) {
1960                                        foreach( $indexes as $index => $details ) {
1961                                                $schema .= '            <index name="' . $index . '">' . "\n";
1962                                               
1963                                                if( $details['unique'] ) {
1964                                                        $schema .= '                    <UNIQUE/>' . "\n";
1965                                                }
1966                                               
1967                                                foreach( $details['columns'] as $column ) {
1968                                                        $schema .= '                    <col>' . $column . '</col>' . "\n";
1969                                                }
1970                                               
1971                                                $schema .= '            </index>' . "\n";
1972                                        }
1973                                }
1974                               
1975                                if( $data ) {
1976                                        $rs = $this->db->Execute( 'SELECT * FROM ' . $table );
1977                                       
1978                                        if( is_object( $rs ) ) {
1979                                                $schema .= '            <data>' . "\n";
1980                                               
1981                                                while( $row = $rs->FetchRow() ) {
1982                                                        foreach( $row as $key => $val ) {
1983                                                                $row[$key] = htmlentities($row);
1984                                                        }
1985                                                       
1986                                                        $schema .= '                    <row><f>' . implode( '</f><f>', $row ) . '</f></row>' . "\n";
1987                                                }
1988                                               
1989                                                $schema .= '            </data>' . "\n";
1990                                        }
1991                                }
1992                               
1993                                $schema .= '    </table>' . "\n";
1994                        }
1995                }
1996               
1997                $this->db->SetFetchMode( $old_mode );
1998               
1999                $schema .= '</schema>';
2000                return $schema;
2001        }
2002       
2003        /**
2004        * Sets a prefix for database objects
2005        *
2006        * Call this method to set a standard prefix that will be prepended to all database tables
2007        * and indices when the schema is parsed. Calling setPrefix with no arguments clears the prefix.
2008        *
2009        * @param string $prefix Prefix that will be prepended.
2010        * @param boolean $underscore If TRUE, automatically append an underscore character to the prefix.
2011        * @return boolean TRUE if successful, else FALSE
2012        */
2013        function SetPrefix( $prefix = '', $underscore = TRUE ) {
2014                switch( TRUE ) {
2015                        // clear prefix
2016                        case empty( $prefix ):
2017                                logMsg( 'Cleared prefix' );
2018                                $this->objectPrefix = '';
2019                                return TRUE;
2020                        // prefix too long
2021                        case strlen( $prefix ) > XMLS_PREFIX_MAXLEN:
2022                        // prefix contains invalid characters
2023                        case !preg_match( '/^[a-z][a-z0-9_]+$/i', $prefix ):
2024                                logMsg( 'Invalid prefix: ' . $prefix );
2025                                return FALSE;
2026                }
2027               
2028                if( $underscore AND substr( $prefix, -1 ) != '_' ) {
2029                        $prefix .= '_';
2030                }
2031               
2032                // prefix valid
2033                logMsg( 'Set prefix: ' . $prefix );
2034                $this->objectPrefix = $prefix;
2035                return TRUE;
2036        }
2037       
2038        /**
2039        * Returns an object name with the current prefix prepended.
2040        *
2041        * @param string $name Name
2042        * @return string        Prefixed name
2043        *
2044        * @access private
2045        */
2046        function prefix( $name = '' ) {
2047                // if prefix is set
2048                if( !empty( $this->objectPrefix ) ) {
2049                        // Prepend the object prefix to the table name
2050                        // prepend after quote if used
2051                        return preg_replace( '/^(`?)(.+)$/', '$1' . $this->objectPrefix . '$2', $name );
2052                }
2053               
2054                // No prefix set. Use name provided.
2055                return $name;
2056        }
2057       
2058        /**
2059        * Checks if element references a specific platform
2060        *
2061        * @param string $platform Requested platform
2062        * @returns boolean TRUE if platform check succeeds
2063        *
2064        * @access private
2065        */
2066        function supportedPlatform( $platform = NULL ) {
2067                $regex = '/^(\w*\|)*' . $this->db->databaseType . '(\|\w*)*$/';
2068               
2069                if( !isset( $platform ) OR preg_match( $regex, $platform ) ) {
2070                        logMsg( "Platform $platform is supported" );
2071                        return TRUE;
2072                } else {
2073                        logMsg( "Platform $platform is NOT supported" );
2074                        return FALSE;
2075                }
2076        }
2077       
2078        /**
2079        * Clears the array of generated SQL.
2080        *
2081        * @access private
2082        */
2083        function clearSQL() {
2084                $this->sqlArray = array();
2085        }
2086       
2087        /**
2088        * Adds SQL into the SQL array.
2089        *
2090        * @param mixed $sql SQL to Add
2091        * @return boolean TRUE if successful, else FALSE.
2092        *
2093        * @access private
2094        */     
2095        function addSQL( $sql = NULL ) {
2096                if( is_array( $sql ) ) {
2097                        foreach( $sql as $line ) {
2098                                $this->addSQL( $line );
2099                        }
2100                       
2101                        return TRUE;
2102                }
2103               
2104                if( is_string( $sql ) ) {
2105                        $this->sqlArray[] = $sql;
2106                       
2107                        // if executeInline is enabled, and either no errors have occurred or continueOnError is enabled, execute SQL.
2108                        if( $this->ExecuteInline() && ( $this->success == 2 || $this->ContinueOnError() ) ) {
2109                                $saved = $this->db->debug;
2110                                $this->db->debug = $this->debug;
2111                                $ok = $this->db->Execute( $sql );
2112                                $this->db->debug = $saved;
2113                               
2114                                if( !$ok ) {
2115                                        if( $this->debug ) {
2116                                                ADOConnection::outp( $this->db->ErrorMsg() );
2117                                        }
2118                                       
2119                                        $this->success = 1;
2120                                }
2121                        }
2122                       
2123                        return TRUE;
2124                }
2125               
2126                return FALSE;
2127        }
2128       
2129        /**
2130        * Gets the SQL array in the specified format.
2131        *
2132        * @param string $format Format
2133        * @return mixed SQL
2134        *       
2135        * @access private
2136        */
2137        function getSQL( $format = NULL, $sqlArray = NULL ) {
2138                if( !is_array( $sqlArray ) ) {
2139                        $sqlArray = $this->sqlArray;
2140                }
2141               
2142                if( !is_array( $sqlArray ) ) {
2143                        return FALSE;
2144                }
2145               
2146                switch( strtolower( $format ) ) {
2147                        case 'string':
2148                        case 'text':
2149                                return !empty( $sqlArray ) ? implode( ";\n\n", $sqlArray ) . ';' : '';
2150                        case'html':
2151                                return !empty( $sqlArray ) ? nl2br( htmlentities( implode( ";\n\n", $sqlArray ) . ';' ) ) : '';
2152                }
2153               
2154                return $this->sqlArray;
2155        }
2156       
2157        /**
2158        * Destroys an adoSchema object.
2159        *
2160        * Call this method to clean up after an adoSchema object that is no longer in use.
2161        * @deprecated adoSchema now cleans up automatically.
2162        */
2163        function Destroy() {
2164                set_magic_quotes_runtime( $this->mgq );
2165                unset( $this );
2166        }
2167}
2168
2169/**
2170* Message logging function
2171*
2172* @access private
2173*/
2174function logMsg( $msg, $title = NULL, $force = FALSE ) {
2175        if( XMLS_DEBUG or $force ) {
2176                echo '<pre>';
2177               
2178                if( isset( $title ) ) {
2179                        echo '<h3>' . htmlentities( $title ) . '</h3>';
2180                }
2181               
2182                if( is_object( $this ) ) {
2183                        echo '[' . get_class( $this ) . '] ';
2184                }
2185               
2186                print_r( $msg );
2187               
2188                echo '</pre>';
2189        }
2190}
2191?>
Note: See TracBrowser for help on using the repository browser.