1
0

adodb-xmlschema03.inc.php 61 KB

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