adodb-xmlschema03.inc.php 61 KB

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