PageRenderTime 50ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/dbFormHandler.php

https://github.com/reshadf/Library
PHP | 1734 lines | 1189 code | 117 blank | 428 comment | 152 complexity | a5803487e9573fa7d8f52dda75d0f599 MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. /**
  3. * Database extension class for FormHandler
  4. *
  5. * @package FormHandler
  6. */
  7. // include the "basic" formhandler
  8. include_once( dirname(__FILE__).'/class.FormHandler.php' );
  9. // make sure this file is not accessed directly
  10. if(strtolower(basename($_SERVER['PHP_SELF'])) == strtolower(basename(__FILE__)))
  11. {
  12. die('This file cannot be accessed directly! Include it in your script instead!');
  13. }
  14. /**
  15. * class dbFormHandler
  16. *
  17. * Extension of FormHandler with all db functions in it.
  18. *
  19. * @author Teye Heimans
  20. * @link http://www.formhandler.net
  21. * @see FormHandler
  22. */
  23. class dbFormHandler extends FormHandler
  24. {
  25. var $_onSaved; // string: the callback function when the form is saved
  26. var $_sql; // array: contains the names of the added values which are sql functions
  27. var $_dontSave; // array: dont save these fields
  28. var $_db; // object: contains the database object if the option is used
  29. var $_id; // array: the id(s) which we are editing
  30. var $_dbData; // array: the database data
  31. var $_table; // string: the table name where we should save the data in
  32. var $_editName; // name of the primary key to edit
  33. // public
  34. var $insert; // boolean: if the form is an insert-form
  35. var $edit; // boolean: if the form is an edit-form
  36. var $dieOnQuery; // boolean: debugging option... show query which is going to be executed
  37. protected $_tableConfig = array();
  38. /**
  39. * dbFormHandler::dbFormHandler()
  40. *
  41. * Constructor: initialize some needed vars
  42. *
  43. * @param string $name: the name for the form (used in the <form> tag
  44. * @param string $action: the action for the form (used in <form action="xxx">)
  45. * @param string $extra: extra css or js which is included in the <form> tag
  46. * @author Teye Heimans
  47. * @return dbFormHandler
  48. */
  49. function dbFormHandler( $name = null, $action = null, $extra = null )
  50. {
  51. $this->_sql = array();
  52. $this->_dbData = array();
  53. $this->_dontSave = array();
  54. $this->_id = array();
  55. $this->dieOnQuery = false;
  56. parent::FormHandler( $name, $action, $extra );
  57. $this->setEditName( FH_EDIT_NAME );
  58. $this->initFHEditName();
  59. }
  60. /**
  61. * Initialize the editName
  62. *
  63. */
  64. function initFHEditName()
  65. {
  66. // initialisation
  67. $this->insert = !isset($_GET[$this->_editName]);
  68. $this->edit = !$this->insert;
  69. // get the ID if it's an edit form
  70. if($this->edit)
  71. {
  72. $this->_id = $_GET[$this->_editName];
  73. if( !is_array($this->_id) )
  74. {
  75. $this->_id = array( $this->_id );
  76. }
  77. }
  78. }
  79. /**
  80. * Set the id which we are watching in the URL of the form is an edit form
  81. *
  82. * @param srting $sEditName
  83. *
  84. * @author Remco van Arkelen & Johan Wiegel
  85. * @since 01-03-2010
  86. */
  87. function setEditName( $sEditName )
  88. {
  89. if( isset( $this->_table ) )
  90. {
  91. trigger_error( 'Function setEditName should be use before dbInfo and/or dbConnect' );
  92. }
  93. else
  94. {
  95. $this->_editName = $sEditName;
  96. $this->initFHEditName();
  97. }
  98. }
  99. /********************************************************/
  100. /************* FIELDS ***********************************/
  101. /********************************************************/
  102. /**
  103. * dbFormHandler::dbCheckBox()
  104. *
  105. * Create a CheckBox on the form with records loaded from a table
  106. *
  107. * @param string $title: The title of the field
  108. * @param string $name: The name of the field
  109. * @param string $table: The table where the records are retrieved from
  110. * @param mixed $fields: String or array with the field(s) which are retrieved from the table and put into the select field
  111. * @param string $extraSQL: Extra SQL
  112. * @param string $validator: The validator which should be used to validate the value of the field
  113. * @param string $extra: CSS, Javascript or other which are inserted into the HTML tag
  114. * @param string $mask: if more the 1 options are given, glue the fields together with this mask
  115. * @return void
  116. * @access public
  117. * @author Johan Wiegel
  118. * @since 11-04-2008
  119. */
  120. function dbCheckBox(
  121. $title,
  122. $name,
  123. $table,
  124. $fields,
  125. $extraSQL = null,
  126. $validator = null,
  127. $extra = null,
  128. $sMask = null)
  129. {
  130. require_once(FH_INCLUDE_DIR.'fields/class.CheckBox.php');
  131. require_once(FH_INCLUDE_DIR.'fields/class.dbCheckBox.php');
  132. if( !is_object($this->_db) )
  133. {
  134. trigger_error(
  135. 'Error, you have to make use of the database option to make use of the field dbSelectField. '.
  136. 'Use selectField() instead!',
  137. E_USER_WARNING
  138. );
  139. return;
  140. }
  141. // create new checkbox
  142. $fld = new dbCheckBox( $this, $name, $this->_db, $table, $fields, $extraSQL );
  143. if(!empty($validator)) $fld->setValidator( $validator );
  144. if(!empty($extra)) $fld->setExtra( $extra );
  145. if(!empty($sMask)) $fld->setMask( $sMask );
  146. // register the field
  147. $this->_registerField( $name, $fld, $title );
  148. }
  149. /**
  150. * dbFormHandler::dbTextSelectField()
  151. *
  152. * Create a TextSelectField on the form with records loaded from a table
  153. *
  154. * @param string $title: The title of the field
  155. * @param string $name: The name of the field
  156. * @param string $table: The table where the records are retrieved from
  157. * @param string $field: String with the field which are retrieved from the table and put into the select part of this text field
  158. * @param string $extraSQL: Extra SQL
  159. * @param string $validator: The validator which should be used to validate the value of the field
  160. * @param string $extra: CSS, Javascript or other which are inserted into the HTML tag
  161. * @return void
  162. * @access public
  163. * @author Johan Wiegel
  164. * @since 22-10-2008
  165. */
  166. function dbTextSelectField(
  167. $title,
  168. $name,
  169. $table,
  170. $field,
  171. $extraSQL = null,
  172. $validator = null,
  173. $extra = null
  174. )
  175. {
  176. require_once(FH_INCLUDE_DIR.'fields/class.TextField.php');
  177. require_once(FH_INCLUDE_DIR.'fields/class.TextSelectField.php');
  178. require_once(FH_INCLUDE_DIR.'fields/class.dbTextSelectField.php');
  179. if( !is_object($this->_db) )
  180. {
  181. trigger_error(
  182. 'Error, you have to make use of the database option to make use of the field dbSelectField. '.
  183. 'Use selectField() instead!',
  184. E_USER_WARNING
  185. );
  186. return;
  187. }
  188. // create new checkbox
  189. $fld = new dbTextSelectField( $this, $name, $this->_db, $table, $field, $extraSQL );
  190. if(!empty($validator)) $fld->setValidator( $validator );
  191. if(!empty($extra)) $fld->setExtra( $extra );
  192. // register the field
  193. $this->_registerField( $name, $fld, $title );
  194. }
  195. /**
  196. * dbFormHandler::dbRadioButton()
  197. *
  198. * Create a RadioButton on the form with records loaded from a table
  199. *
  200. * @param string $title: The title of the field
  201. * @param string $name: The name of the field
  202. * @param string $table: The table where the records are retrieved from
  203. * @param mixed $fields: String or array with the field(s) which are retrieved from the table and put into the select field
  204. * @param string $extraSQL: Extra SQL
  205. * @param string $validator: The validator which should be used to validate the value of the field
  206. * @param string $extra: CSS, Javascript or other which are inserted into the HTML tag
  207. * @param string $mask: if more the 1 options are given, glue the fields together with this mask
  208. * @return void
  209. * @access public
  210. * @author Johan Wiegel
  211. * @since 11-04-2008
  212. */
  213. function dbRadioButton(
  214. $title,
  215. $name,
  216. $table,
  217. $fields,
  218. $extraSQL = null,
  219. $validator = null,
  220. $extra = null,
  221. $sMask = null)
  222. {
  223. require_once(FH_INCLUDE_DIR.'fields/class.RadioButton.php');
  224. require_once(FH_INCLUDE_DIR.'fields/class.dbRadioButton.php');
  225. if( !is_object($this->_db) )
  226. {
  227. trigger_error(
  228. 'Error, you have to make use of the database option to make use of the field dbSelectField. '.
  229. 'Use selectField() instead!',
  230. E_USER_WARNING
  231. );
  232. return;
  233. }
  234. // create new RadioButton
  235. $fld = new dbRadioButton( $this, $name, $this->_db, $table, $fields, $extraSQL );
  236. if(!empty($validator)) $fld->setValidator( $validator );
  237. if(!empty($extra)) $fld->setExtra( $extra );
  238. if(!empty($sMask)) $fld->setMask( $sMask );
  239. // register the field
  240. $this->_registerField( $name, $fld, $title );
  241. }
  242. /**
  243. * dbFormHandler::dbSelectField()
  244. *
  245. * Create a selectField on the form with records loaded from a table
  246. *
  247. * @param string $title: The title of the field
  248. * @param string $name: The name of the field
  249. * @param string $table: The table where the records are retrieved from
  250. * @param mixed $fields: String or array with the field(s) which are retrieved from the table and put into the select field
  251. * @param string $extraSQL: Extra SQL
  252. * @param string $validator: The validator which should be used to validate the value of the field
  253. * @param boolean $multiple: Should it be possible to select multiple options ? (Default: false)
  254. * @param int $size: The size of the field (how many options are displayed)
  255. * @param string $extra: CSS, Javascript or other which are inserted into the HTML tag
  256. * @param array $mergeArray: Default value(s) for the field
  257. * @return void
  258. * @access public
  259. * @author Teye Heimans
  260. */
  261. function dbSelectField(
  262. $title,
  263. $name,
  264. $table,
  265. $fields,
  266. $extraSQL = null,
  267. $validator = null,
  268. $multiple = null,
  269. $size = null,
  270. $extra = null,
  271. $mergeArray = null)
  272. {
  273. require_once(FH_INCLUDE_DIR.'fields/class.SelectField.php');
  274. require_once(FH_INCLUDE_DIR.'fields/class.dbSelectField.php');
  275. if( !is_object($this->_db) )
  276. {
  277. trigger_error(
  278. 'Error, you have to make use of the database option to make use of the field dbSelectField. '.
  279. 'Use selectField() instead!',
  280. E_USER_WARNING
  281. );
  282. return;
  283. }
  284. // create new selectfield
  285. $fld = new dbSelectField( $this, $name, $this->_db, $table, $fields, $extraSQL, $mergeArray );
  286. if(!empty($validator)) $fld->setValidator( $validator );
  287. if($multiple) $fld->setMultiple( $multiple );
  288. if(!empty($extra)) $fld->setExtra( $extra );
  289. // set the size if given
  290. if(!empty($size))
  291. {
  292. $fld->setSize( $size );
  293. }
  294. // if no size is set and multiple is enabled, set the size default to 4
  295. else if( $multiple )
  296. {
  297. $fld->setSize( 4 );
  298. }
  299. // register the field
  300. $this->_registerField( $name, $fld, $title );
  301. }
  302. /**
  303. * dbFormHandler::dbListField()
  304. *
  305. * Creates a listfield with values retrieved from the database
  306. *
  307. * @param string $title: The title of the field
  308. * @param string $name: The name of the field
  309. * @param string $table: The table where the records are retrieved from
  310. * @param mixed $fields: String or array with the field(s) which are retrieved from the table and put into the select field
  311. * @param string $validator: The validator which should be used to validate the value of the field
  312. * @param string $onTitle: The title used above the ON section of the field
  313. * @param string $offTitle: The title used above the OFF section of the field
  314. * @param int $size: The size of the field (how many options are displayed)
  315. * @param string $extra: CSS, Javascript or other which are inserted into the HTML tag
  316. * @param string $verticalMode: Verticale mode
  317. * @return void
  318. * @access public
  319. * @author Teye Heimans
  320. */
  321. function dbListField(
  322. $title,
  323. $name,
  324. $table,
  325. $fields,
  326. $extraSQL = null,
  327. $validator = null,
  328. $onTitle = null,
  329. $offTitle = null,
  330. $size = null,
  331. $extra = null,
  332. $verticalMode = null
  333. )
  334. {
  335. require_once(FH_INCLUDE_DIR.'fields/class.SelectField.php');
  336. require_once(FH_INCLUDE_DIR.'fields/class.ListField.php');
  337. require_once(FH_INCLUDE_DIR.'fields/class.dbListField.php');
  338. if( !is_object($this->_db) )
  339. {
  340. trigger_error(
  341. 'Error, you have to make use of the database option to make use of the field dbListField. '.
  342. 'Use listField() instead!',
  343. E_USER_WARNING
  344. );
  345. return;
  346. }
  347. // create new selectfield
  348. $fld = new dbListField( $this, $name, $this->_db, $table, $fields, $extraSQL );
  349. if(!empty($validator)) $fld -> setValidator( $validator );
  350. if(!empty($extra)) $fld -> setExtra ( $extra );
  351. if(!empty($onTitle)) $fld -> setOnTitle ( $onTitle );
  352. if(!empty($offTitle)) $fld -> setOffTitle ( $offTitle );
  353. if(!empty($verticalMode)) $fld->setVerticalMode( $verticalMode );
  354. // set the size if given
  355. if(!empty($size))
  356. {
  357. $fld->setSize( $size );
  358. }
  359. // register the field
  360. $this->_registerField( $name, $fld, $title );
  361. }
  362. /********************************************************/
  363. /************* Data handling ****************************/
  364. /********************************************************/
  365. /**
  366. * dbFormHandler::getDBValue()
  367. *
  368. * Get the value of the requested field from the database
  369. *
  370. * @param string $sField
  371. * @return string
  372. *
  373. * @since 17-02-2010
  374. * @author Winus van Heumen
  375. */
  376. function getDBValue( $sField )
  377. {
  378. if( array_key_exists( $sField, $this->_dbData ) )
  379. {
  380. return $this->_dbData[$sField];
  381. }
  382. /**
  383. * Field not found.
  384. */
  385. trigger_error(
  386. ' field ('.$sField.') is not found.',
  387. E_USER_WARNING
  388. );
  389. return '';
  390. }
  391. /**
  392. * dbFormHandler::value()
  393. *
  394. * Get the value of the requested field
  395. *
  396. * @param string $field: The field which value we have to return
  397. * @return string
  398. * @access public
  399. * @author Teye Heimans
  400. */
  401. function value( $field )
  402. {
  403. if(!_global) global $_POST;
  404. // is it a field?
  405. if( isset( $this->_fields[$field] ) && is_object($this->_fields[$field][1]) && method_exists($this->_fields[$field][1], 'getvalue') )
  406. {
  407. return $this->_fields[$field][1]->getValue();
  408. }
  409. // is it an user added value ?
  410. else if( isset($this->_add[$field]) )
  411. {
  412. return $this->_add[$field];
  413. }
  414. // _chache contains the values of the fields after flush() is called
  415. // (because then all objects are removed from the memory)
  416. else if( isset( $this->_cache[$field]) )
  417. {
  418. return $this->_cache[$field];
  419. }
  420. // is it a set value of a field which does not exists yet ?
  421. else if( isset( $this->_buffer[$field]) )
  422. {
  423. return $this->_buffer[$field][1];
  424. }
  425. // is it a value from the $_POST array ?
  426. else if( isset( $_POST[$field] ) )
  427. {
  428. // give a notice
  429. //trigger_error(
  430. // 'Notice: the value retrieved from the field "'.$field.'" could '.
  431. // 'only be fetched from the $_POST array. The field is not found in the form...',
  432. // E_USER_NOTICE
  433. //);
  434. return $_POST[$field];
  435. }
  436. // is the database function used ?
  437. else if( isset( $this->_db ) && is_object( $this->_db ) && !empty( $this->_table ) )
  438. {
  439. // fetch the database fields
  440. $fields = $this->_db->getFieldNames( $this->_table );
  441. // does the field exists in the table ?
  442. if( in_array( $field, $fields ) )
  443. {
  444. // is an edit value known ?
  445. if( is_array( $this->_dbData ) && array_key_exists( $field, $this->_dbData ) )
  446. {
  447. return $this->_dbData[$field];
  448. }
  449. // no db value known
  450. else
  451. {
  452. // return an empty string.. the field is a table column
  453. return '';
  454. }
  455. }
  456. }
  457. trigger_error(
  458. 'Try to get the value of an unknown field "'.$field.'"!',
  459. E_USER_WARNING
  460. );
  461. return null;
  462. }
  463. /**
  464. * dbFormHandler::setValue()
  465. *
  466. * Set the value of the specified field
  467. *
  468. * @param string $field: The field which value we have to set
  469. * @param string $value: The value we have to set
  470. * @param boolean $overwriteCurrentValue: Do we have to overwrite the current value of the field (posted or db-loaded values)
  471. * @return void
  472. * @access public
  473. * @author Teye Heimans
  474. */
  475. function setValue( $sField, $sValue, $bOverwriteCurrentValue = false )
  476. {
  477. if( is_array( $sValue ) )
  478. {
  479. $sValue = implode(', ',$sValue );
  480. }
  481. // check if the field exists
  482. if( $this->fieldExists( $sField ) )
  483. {
  484. // if the field does not exists in the database and there is no post value,
  485. // or when we want to overwrite the current value
  486. if( $bOverwriteCurrentValue || (!isset($this->_dbData[$sField]) && !$this->isPosted() ) ||
  487. // only set the value if the page is not 'done' yet, otherwise
  488. // we will overwrite it
  489. $this->_curPage < $this->_pageCounter )
  490. {
  491. $this->_fields[$sField][1]->setValue( $sValue );
  492. }
  493. }
  494. // the field does not exists. Save the value in the buffer.
  495. // the field will check this buffer and use it value when it's created
  496. else
  497. {
  498. // save the data untill the field exists
  499. $this->_buffer[$sField] = array( $bOverwriteCurrentValue, $sValue );
  500. }
  501. }
  502. /********************************************************/
  503. /************* DATABASE METHODS *************************/
  504. /********************************************************/
  505. /**
  506. * Add a juintionTable
  507. *
  508. * @param string $sTable
  509. * @param string $sDestinationField foreign key to the table
  510. * @param string $sSourceField foreign key to this id
  511. * @return mixed
  512. */
  513. public function addJunctionTable( $sTable, $sDestinationField, $sSourceField )
  514. {
  515. if( !isset( $this->_tableConfig[$sTable] ) )
  516. {
  517. $this->_tableConfig[$sTable] = array( $sDestinationField, $sSourceField );
  518. // Only create a juntion if the field exists
  519. if( !isset( $this->_fields[ $sDestinationField ] ) )
  520. {
  521. trigger_error(
  522. "The field '$sDestinationField' doesn't exist in the form",
  523. E_USER_WARNING
  524. );
  525. return;
  526. }
  527. // Laad de data
  528. if( $this->edit )
  529. {
  530. $this->_loadDbData();
  531. }
  532. return true;
  533. }
  534. else
  535. {
  536. trigger_error(
  537. "The junctiontable '$sTable' is already defined",
  538. E_USER_WARNING
  539. );
  540. return;
  541. }
  542. }
  543. /**
  544. * dbFormHandler::dbInfo()
  545. *
  546. * Set the DBInfo.
  547. *
  548. * @param string $db: the db which we are using
  549. * @param string $table: the table where we have to save the data
  550. * @param string $type: the type of db which is used
  551. * @return void
  552. * @access public
  553. * @author Teye Heimans
  554. */
  555. function dbInfo( $db, $table, $type = null )
  556. {
  557. require_once( FH_YADAL_DIR . 'class.Yadal.php' );
  558. // if no db-type is given, set the default
  559. if(is_null($type))
  560. {
  561. $type = FH_DEFAULT_DB_TYPE;
  562. }
  563. // set the table to use
  564. $this->_table = $table;
  565. // create a new yadal object
  566. $this->_db = newYadal( $db, $type );
  567. // try to fetch the database data if we are connected
  568. if( $this->edit && $this->_db->isConnected() )
  569. {
  570. $this->_loadDbData();
  571. }
  572. }
  573. /**
  574. * dbFormHandler::dbConnect()
  575. *
  576. * Connect to the database
  577. *
  578. * @param string $username: the username used to login
  579. * @param string $password: the password used to login
  580. * @return void
  581. * @access public
  582. * @author Teye Heimans
  583. */
  584. function dbConnect($host = null, $username = '', $password = '')
  585. {
  586. // check if the database info is set
  587. if( is_object( $this->_db ) )
  588. {
  589. // if no host is given, use the default host
  590. if(is_null($host))
  591. {
  592. $host = FH_DEFAULT_DB_HOST;
  593. }
  594. // try to connect
  595. if( !$this->_db->connect( $host, $username, $password ) )
  596. {
  597. // connection failed..
  598. trigger_error(
  599. 'Error, database connection failed: '.$this->_db->getError(),
  600. E_USER_WARNING
  601. );
  602. return false;
  603. }
  604. }
  605. // the database info is not set yet!
  606. else
  607. {
  608. // trigger an error
  609. trigger_error(
  610. 'No database object available! Make sure you call DBInfo() first '.
  611. 'or use setConnectionResource() to use an already opend connection!',
  612. E_USER_WARNING
  613. );
  614. $this->_db = null;
  615. return;
  616. }
  617. // load the database values only on a edit form...
  618. if( $this->edit && ( !is_array($this->_dbData) || sizeof($this->_dbData) == 0) )
  619. {
  620. $this->_loadDbData();
  621. }
  622. }
  623. /**
  624. * dbFormHandler::setConnectionResource()
  625. *
  626. * Use an already opened connection instead of opening a new one.
  627. *
  628. * @param resource $conn:
  629. * @param string $table: The table which should be used to save the data in
  630. * @param string type: The type of database you are using
  631. * @return void
  632. * @access public
  633. * @author Teye Heimans
  634. */
  635. function setConnectionResource( $conn, $table = null, $type = null )
  636. {
  637. require_once( FH_YADAL_DIR.'class.Yadal.php' );
  638. // if no db-type is given, set the default
  639. if(is_null($type))
  640. {
  641. $type = FH_DEFAULT_DB_TYPE;
  642. }
  643. // make this function backwards compatible ( $table, $conn, $type as arguments )
  644. if( is_string( $conn ) && is_resource( $table ) )
  645. {
  646. $tmp = $table;
  647. unset( $table );
  648. $table = $conn;
  649. unset( $conn );
  650. $conn = $tmp;
  651. unset( $tmp );
  652. }
  653. // save the table name
  654. $this->_table = $table;
  655. // create the yadal object
  656. $this->_db = newYadal(null, $type);
  657. // set the sql resource which we should use
  658. $this->_db->setConnectionResource( $conn );
  659. // try to fetch the database data already
  660. if( $this->edit )
  661. {
  662. $this->_loadDbData();
  663. }
  664. }
  665. /**
  666. * dbFormHandler::onSaved()
  667. *
  668. * Set the function which has to be called when the form data is saved in the database
  669. *
  670. * @param string $callback: The name of the function
  671. * @return void
  672. * @access public
  673. * @author Teye Heimans
  674. */
  675. function onSaved( $callback )
  676. {
  677. // is the given value a string ?
  678. if(!is_array($callback))
  679. {
  680. // does the function exists ?
  681. if( function_exists($callback) )
  682. {
  683. $this->_onSaved = $callback;
  684. }
  685. // the given callback function does not exists
  686. else
  687. {
  688. trigger_error(
  689. 'Error, the onSaved function "'.$callback.'" does not exists!',
  690. E_USER_ERROR
  691. );
  692. }
  693. }
  694. // we have to call a mehtod
  695. else
  696. {
  697. // check if the method exists in the given object
  698. if( method_exists( $callback[0], $callback[1]) )
  699. {
  700. $this->_onSaved = $callback;
  701. }
  702. // the method does not exists
  703. else
  704. {
  705. trigger_error(
  706. 'Error, the onSaved method "'.$callback[1].'" does not exists in the given object'.
  707. (is_object($callback[0]) ? ' "'.get_class($callback[0]).'"!' : '!'),
  708. E_USER_ERROR
  709. );
  710. }
  711. }
  712. }
  713. /********************************************************/
  714. /************* GENERAL **********************************/
  715. /********************************************************/
  716. /**
  717. * dbFormHandler::isCorrect()
  718. *
  719. * Return if the form is filled correctly (for the fields which are set!)
  720. *
  721. * @return boolean: the form values valid or not
  722. * @access public
  723. * @author Teye Heimans
  724. */
  725. function isCorrect()
  726. {
  727. $result = parent::isCorrect();
  728. // check if there is no unique field error when the field is completly correct
  729. if( $result )
  730. {
  731. return $this->_checkUniqueFields();
  732. }
  733. return false;
  734. }
  735. /**
  736. * dbFormHandler::flush()
  737. *
  738. * prints or returns the form
  739. *
  740. * @return string: the form or null when the form should be printed
  741. * @access public
  742. * @author Teye Heimans
  743. */
  744. function flush( $return = false )
  745. {
  746. if( $this->_ajaxValidator === true )
  747. {
  748. require_once( FH_INCLUDE_DIR . 'includes/class.AjaxValidator.php' );
  749. $oAjaxValidator = new AjaxValidator( $this->_ajaxValidatorScript );
  750. $oAjaxValidator->CreateObservers( $this );
  751. }
  752. // when the form is not posted or the form is not valid
  753. if( !$this->isPosted() || !$this->isCorrect() )
  754. {
  755. // check if a value is set of an unknown field
  756. if( sizeof( $this->_buffer ) > 0 )
  757. {
  758. // error messages for the values for unknown fields
  759. foreach($this->_buffer as $sField => $a)
  760. {
  761. trigger_error('Value set of unknown field "'.$sField.'"', E_USER_WARNING );
  762. }
  763. }
  764. // get the form
  765. $form = $this->_getForm();
  766. }
  767. // when the form is not totaly completed yet (multiple pages)
  768. else if( $this->_curPage < $this->_pageCounter )
  769. {
  770. // upload and convert uploads
  771. $this->_handleUploads();
  772. // get the next form
  773. $form = $this->_getForm( $this -> _curPage + 1 );
  774. }
  775. // when the form is valid
  776. else
  777. {
  778. // upload and convert uploads
  779. $this->_handleUploads();
  780. // generate the data array
  781. $data = array();
  782. foreach($this->_fields as $name => $fld)
  783. {
  784. if( is_object( $fld[1] ) && method_exists($fld[1], 'getValue') && $name != $this->_name.'_submit')
  785. {
  786. $data[$name] = $fld[1]->getValue();
  787. }
  788. }
  789. // add the user added data to the array
  790. $data = array_merge( $data, $this->_add );
  791. // call the users oncorrect function
  792. if(!empty($this->_onCorrect))
  793. {
  794. if(is_array($this->_onSaved))
  795. {
  796. $hideForm = call_user_func_array( array(&$this->_onCorrect[0], $this->_onCorrect[1]), array($data, &$this) );
  797. }
  798. else
  799. {
  800. $hideForm = call_user_func_array( $this->_onCorrect, array($data, &$this) );
  801. }
  802. }
  803. // add the user added data again to the array (could have been changed!)
  804. $data = array_merge( $data, $this->_add );
  805. // if the db option is used
  806. if( !is_null($this->_db) && !empty($this->_table) && (!isset($hideForm) || $hideForm) )
  807. {
  808. // save the data into the databse
  809. $id = $this->_saveDbData( $data );
  810. // query error ?
  811. if( $id === -1 )
  812. {
  813. // something went wrong with the query.. display the form again
  814. $hideForm = false;
  815. }
  816. else
  817. {
  818. // got id back ?
  819. if(is_array($id) && sizeof($id) == 1)
  820. {
  821. $id = $id[0];
  822. }
  823. // call the onsaved function
  824. if(!is_null($this->_onSaved))
  825. {
  826. if(is_array($this->_onSaved))
  827. {
  828. $hideForm = call_user_func_array( array(&$this->_onSaved[0], $this->_onSaved[1]), array($id, $data, &$this) );
  829. }
  830. else
  831. {
  832. $hideForm = call_user_func_array( $this->_onSaved, array($id, $data, &$this) );
  833. }
  834. }
  835. }
  836. }
  837. // display the form again if wanted..
  838. if(isset($hideForm) && $hideForm === false)
  839. {
  840. $form = $this->_getForm();
  841. }
  842. // the user want's to display something else..
  843. else if(isset($hideForm) && is_string($hideForm))
  844. {
  845. $form = $hideForm;
  846. }
  847. // dont display the form..
  848. else
  849. {
  850. $form = '';
  851. }
  852. }
  853. // cache all the fields values for the function value()
  854. foreach( $this->_fields as $fld => $value )
  855. {
  856. // check if it's a field
  857. if( is_object($this->_fields[$fld][1]) && method_exists($this->_fields[$fld][1], "getvalue"))
  858. {
  859. $this->_cache[ $fld ] = $this->_fields[$fld][1]->getValue();
  860. }
  861. }
  862. /*
  863. // remove all vars to free memory
  864. foreach( get_object_vars($this) as $name => $value )
  865. {
  866. // remove all vars except these ones..
  867. if( !in_array($name, array('_cache', 'edit', 'insert', '_posted', '_name' ) ) )
  868. {
  869. unset( $this->{$name} );
  870. }
  871. }*/
  872. // disable our error handler!
  873. if( FH_DISPLAY_ERRORS )
  874. {
  875. restore_error_handler();
  876. }
  877. // return or print the form
  878. if( $return )
  879. {
  880. return $form;
  881. }
  882. else
  883. {
  884. echo $form;
  885. return null;
  886. }
  887. }
  888. /********************************************************/
  889. /************* BELOW IS ALL PRIVATE!! *******************/
  890. /********************************************************/
  891. /**
  892. * dbFormHandler::_checkUniqueFields()
  893. *
  894. * Check if there are no double values for unique fields
  895. *
  896. * @return boolean: false if the value is double, true otherwise
  897. * @access private
  898. * @author Teye Heimans
  899. */
  900. function _checkUniqueFields()
  901. {
  902. // only check for unique fields if the rest of the field is correct and
  903. // the database option is used...
  904. if( isset( $this->_db ) && is_object( $this->_db ) && !empty( $this->_table ))
  905. {
  906. // alias for the database object
  907. $db = $this->_db;
  908. // get the unique, not null fields and the the column types of the fields
  909. $unique = $db -> getUniqueFields ( $this->_table );
  910. $notnull = $db -> getNotNullFields( $this->_table );
  911. $columns = $db -> getFieldTypes ( $this->_table );
  912. $keys = $db -> getPrKeys ( $this->_table );
  913. // any unique fields found ?
  914. if( sizeof( $unique ) > 0)
  915. {
  916. // walk all unique indexes
  917. foreach( $unique as $index => $fields)
  918. {
  919. $fieldInForm = false;
  920. $extra = array(); // extra query info for the where clause
  921. $quoted = array(); // fields which are already quoted
  922. // walk all unique fields by this index
  923. foreach( $fields as $field )
  924. {
  925. // is the field a value which the user has added ?
  926. if( array_key_exists($field, $this->_add) )
  927. {
  928. // get hte value
  929. $value = $this->_add[$field];
  930. // if the value is not a sql function, quote it
  931. if( !in_array( $field, $this->_sql) )
  932. {
  933. $value = "'".$db->escapeString( $value )."'";
  934. }
  935. }
  936. // does the unique field exists in the form ?
  937. elseif( $this->fieldExists( $field ) )
  938. {
  939. $fieldInForm = $field;
  940. // is the field a datefield (in the form)?
  941. if( in_array( $field, $this->_date ) )
  942. {
  943. // get the column type (in the table)
  944. $type = strtolower( $columns[$field][0] );
  945. // is the field's type a date field ?
  946. if( strpos( strtolower($type), 'date') !== false )
  947. {
  948. // get the d, m and y value
  949. list( $y, $m, $d ) = $this->_fields[$field][1]->getAsArray();
  950. // all empty ?
  951. if( $d == '' && $y == '' && $m == '')
  952. {
  953. // can we save null ?
  954. if( !in_array( $field, $notnull ) )
  955. {
  956. $value = 'NULL';
  957. }
  958. // we cant save null. use 0000-00-00 instead
  959. else
  960. {
  961. $value = '0000-00-00';
  962. }
  963. }
  964. // not all fields are empty
  965. else
  966. {
  967. // make sure that there are values for each "field"
  968. if( $d == '' ) $d = 1;
  969. if( $m == '' ) $m = 1;
  970. if( $y == '' ) $y = date('Y');
  971. // save the value as date
  972. $value = $db->dbDate( $y, $m, $d );
  973. $quoted[] = $field;
  974. }
  975. }
  976. }
  977. else
  978. // it's not a datefield
  979. {
  980. // get the form-value of the field
  981. $value = $db->escapeString( $this->_fields[$field][1]->getValue() );
  982. }
  983. // is the value null ?
  984. if( empty( $value ) && !in_array( $field, $notnull ) )
  985. {
  986. $value = 'NULL';
  987. }
  988. // is it an number and do we have to quote it ?
  989. else if(preg_match("/^-?([0-9]*\.?[0-9]+)$/", $value))
  990. {
  991. if( $db->_quoteNumbers )
  992. {
  993. $value = "'".$value."'";
  994. }
  995. }
  996. // quote the value
  997. else if( !in_array($field, $quoted))
  998. {
  999. $value = "'".$value."'";
  1000. }
  1001. }
  1002. // the field does not exists in the form and is not
  1003. // added by the user.
  1004. else
  1005. {
  1006. // is the field not a primary key ?
  1007. if( !in_array( $field, $keys ) )
  1008. {
  1009. /* new since 15 feb 2005 */
  1010. // get the database value of the field
  1011. $value = "'". $db -> escapeString( $this -> getValue( $field ) ) ."'" ;
  1012. }
  1013. // it's a primary key field..
  1014. // the _getWhereClause is taking care of that ones..
  1015. else
  1016. {
  1017. // we do not have a value for the field
  1018. // so dont use it in the where clause.
  1019. continue;
  1020. }
  1021. }
  1022. $extra[$field] = $value;
  1023. }
  1024. $where = $this->_getWhereClause( '<>', $extra );
  1025. // is there a selection filter ?
  1026. if( is_array( $extra ) && sizeof( $extra ) > 0 )
  1027. {
  1028. // check if the entry is double
  1029. $sql = $db->query(
  1030. 'SELECT COUNT(1) AS num FROM '.$db->quote( $this->_table ). $where
  1031. );
  1032. // query succeeded ?
  1033. if( $sql )
  1034. {
  1035. // if so, set the error message and return false;
  1036. if( $db->result( $sql, 0, 'num' ) > 0 )
  1037. {
  1038. if( !empty($fieldInForm) )
  1039. {
  1040. // get the error message
  1041. $error =
  1042. sizeof($unique[$index]) == 1 ?
  1043. sprintf(
  1044. $this->_text(35),
  1045. $this->_fields[$fieldInForm][1]->getValue()
  1046. ) :
  1047. sprintf(
  1048. $this->_text(39),
  1049. implode(', ', $unique[$index]),
  1050. $index
  1051. )
  1052. ;
  1053. // set the error message
  1054. $this->_fields[$fieldInForm][1]->_sError = $error;
  1055. }
  1056. /* new since 21 aug 2006*/
  1057. // no field in the form (propably added with addValue)
  1058. else
  1059. {
  1060. // get the error message
  1061. $error =
  1062. sizeof($unique[$index]) == 1 ?
  1063. sprintf(
  1064. $this->_text(35),
  1065. $unique[$index][0]
  1066. ) :
  1067. sprintf(
  1068. $this->_text(39),
  1069. implode(', ', $unique[$index]),
  1070. $index
  1071. )
  1072. ;
  1073. //echo $error;
  1074. // known bug: when using multple forms, the line is not added to the current page
  1075. $this->addLine($error);
  1076. }
  1077. // return false (the form is not correct)
  1078. return false;
  1079. }
  1080. }
  1081. // query failed
  1082. else
  1083. {
  1084. trigger_error(
  1085. "Could not check for unique values bacause of a query error!\n".
  1086. "Error: ". $this->_db->getError()."\n".
  1087. "Query: ". $this->_db->getLastQuery(),
  1088. E_USER_WARNING
  1089. );
  1090. }
  1091. }
  1092. }
  1093. }
  1094. }
  1095. return true;
  1096. }
  1097. /**
  1098. * Remove data from thye junction table
  1099. *
  1100. * @param string $tableName
  1101. * @param string $keyField
  1102. * @param string $keyValue
  1103. * @return mixed
  1104. *
  1105. * @author Remco van Arkelen
  1106. * @since 01-03-2010
  1107. */
  1108. function deleteJunctionData( $tableName, $keyField, $keyValue )
  1109. {
  1110. $query = "DELETE FROM " . $tableName . " WHERE " . $keyField . " = '" . $keyValue . "';";
  1111. return $this->_db->query( $query );
  1112. }
  1113. /**
  1114. * Insert data into junction tbale
  1115. *
  1116. * @param string $tableName
  1117. * @param string $keyField
  1118. * @param string $destinationField
  1119. * @param string $keyValue
  1120. *
  1121. * @author Remco van Arkelen
  1122. * @since 01-03-2010
  1123. */
  1124. function insertJunctionData( $tableName, $keyField, $destinationField, $keyValue )
  1125. {
  1126. /*@var $field Field*/
  1127. $field = $this->_fields[ $keyField ][1];
  1128. if( is_array( $field->getValue() ) )
  1129. {
  1130. foreach( $field->getValue() as $value )
  1131. {
  1132. $query = "INSERT INTO " . $tableName . "
  1133. (" . $destinationField . ", " . $keyField . ")
  1134. VALUES ('".$keyValue."', '".$value."');";
  1135. $this->_db->query( $query );
  1136. }
  1137. }
  1138. }
  1139. /**
  1140. * dbFormHandler::_loadDbData()
  1141. *
  1142. * Load the data from the database when it's a edit form
  1143. *
  1144. * @return void
  1145. * @access private
  1146. * @author Teye Heimans
  1147. */
  1148. function _loadDbData()
  1149. {
  1150. // get the data from the database
  1151. $sql = $this->_db->query(
  1152. 'SELECT * FROM ' . $this->_db->quote( $this->_table ) . $this->_getWhereClause()
  1153. );
  1154. // query succeeded?
  1155. if( $sql )
  1156. {
  1157. // any records found?
  1158. if( $this->_db->recordCount( $sql ) >= 1)
  1159. {
  1160. if( count( $this->_dbData ) == 0 )
  1161. {
  1162. $this->_dbData = $this->_db->getRecord( $sql );
  1163. }
  1164. if( $this->edit )
  1165. {
  1166. // Get data from juntion table
  1167. foreach( $this->_tableConfig as $tableName => $fields )
  1168. {
  1169. $qrySelectJunctiondata = "SELECT " . $fields[0] . " AS ".$fields[0]." FROM " . $tableName . " WHERE " . $fields[1] . "='".pos( $this->_id )."'";
  1170. $sql = $this->_db->query( $qrySelectJunctiondata );
  1171. $values = array();
  1172. while( $rs = $this->_db->getRecord( $sql ) )
  1173. {
  1174. $values[] = $rs[ $fields[0] ];
  1175. }
  1176. $this->setValue( $fields[0], $values );
  1177. }
  1178. }
  1179. }
  1180. // no records found, auto insert ?
  1181. else if(FH_AUTO_INSERT)
  1182. {
  1183. // get the keys
  1184. $keys = $this->_db->getPrKeys( $this->_table );
  1185. // add the primary key values to the fields
  1186. $size1 = sizeof( $keys );
  1187. $size2 = sizeof( $this->_id );
  1188. $size = ( $size1 > $size2 ? $size2 : $size1 );
  1189. for($i = 0; $i < $size; $i++ )
  1190. {
  1191. $this->addValue( $keys[$i], $this->_id[$i] );
  1192. }
  1193. // change the form type from update to insert
  1194. $this->insert = true;
  1195. $this->edit = false;
  1196. }
  1197. // record not found and no auto insert..
  1198. // trigger error message
  1199. else
  1200. {
  1201. trigger_error( 'Try to edit a none existing record!', E_USER_ERROR );
  1202. }
  1203. }
  1204. else
  1205. // query error, trigger error
  1206. {
  1207. trigger_error(
  1208. "Could not load database values in the form bacause of a query error!\n".
  1209. "Error: ". $this->_db->getError()."\n".
  1210. "Query: ". $this->_db->getLastQuery(),
  1211. E_USER_WARNING
  1212. );
  1213. }
  1214. }
  1215. /**
  1216. * dbFormHandler::_saveData()
  1217. *
  1218. * Save the data into the database
  1219. *
  1220. * @param array $data: associative array with the fields => values which should be saved
  1221. * @return int: the id which was used to save the record
  1222. * @access private
  1223. * @author Teye Heimans
  1224. */
  1225. function _saveDbData( $data )
  1226. {
  1227. // get the not-null fields from the table
  1228. $notNullFields = $this->_db->getNotNullFields( $this->_table );
  1229. // get the data which should be saved
  1230. foreach( $data as $field => $value )
  1231. {
  1232. if( is_array( $value ) )
  1233. {
  1234. $value = implode(', ', $value);
  1235. }
  1236. // remove unneeded spaces
  1237. $value = trim( $value );
  1238. // do we have to save the field ?
  1239. if(
  1240. !in_array($field, $this->_dontSave) && # in dont save array
  1241. ( !isset( $this -> _fields[$field] ) || # not in the fields.. (so from the addValue array)
  1242. !method_exists($this -> _fields[$field][1], 'getViewMode' ) || # or NOT in view mode!
  1243. !$this -> _fields[$field][1] -> getViewMode() )
  1244. )
  1245. {
  1246. // is the value empty and it can contain NULL, then save NULL
  1247. if($value == '' && !in_array($field, $notNullFields) )
  1248. {
  1249. $value = 'NULL';
  1250. $this->_sql[] = $field;
  1251. // overwrite the old value with the new one
  1252. $data[$field] = $value;
  1253. }
  1254. }
  1255. // we dont have to save this value... remove it
  1256. else
  1257. {
  1258. unset( $data[$field] );
  1259. }
  1260. }
  1261. // get the column types of the fields
  1262. $fields = $this->_db->getFieldTypes( $this->_table );
  1263. // walk all datefields
  1264. foreach( $this->_date as $field )
  1265. {
  1266. // do we still have to convert the value ?
  1267. if( isset( $data[$field]) && $data[$field] != 'NULL' )
  1268. {
  1269. // does the field exists in the table?
  1270. if( isset( $fields[$field] ) )
  1271. {
  1272. // get the fields type
  1273. $type = strtolower( $fields[$field][0] );
  1274. // is the field's type a date field ?
  1275. if( strpos( strtolower($type), 'date') !== false )
  1276. {
  1277. // get the value from the field
  1278. list( $y, $m, $d) = $this->_fields[$field][1]->getAsArray();
  1279. // are all fields empty ?
  1280. if( empty($d) && empty($m) && empty($y) )
  1281. {
  1282. // save NULL if possible, otherwise 0000-00-00
  1283. if( in_array( $field, $notNullFields ) )
  1284. {
  1285. // this field cannot contain NULL
  1286. $data[$field] = '0000-00-00';
  1287. }
  1288. // the field can contain null
  1289. else
  1290. {
  1291. $data[$field] = 'NULL';
  1292. $this -> _sql[] = $field;
  1293. }
  1294. }
  1295. // not all fields are empty
  1296. else
  1297. {
  1298. // make sure that there are values for each "field"
  1299. if( $d == '' ) $d = '00';
  1300. if( $m == '' ) $m = '00';
  1301. if( $y == '' ) $y = '0000'; //date('Y');
  1302. // save the value as date
  1303. $data[$field] = $this->_db->dbDate( $y, $m, $d );
  1304. $this->_sql[] = $field;
  1305. }
  1306. }
  1307. }
  1308. }
  1309. }
  1310. // get the query
  1311. $query = $this->_getQuery( $this->_table, $data, $this->_sql, $this->edit, $this->_id );
  1312. // for debugging.. die when we got the query
  1313. //$this->dieOnQuery = true;
  1314. if( isset( $this->dieOnQuery ) && $this->dieOnQuery )
  1315. {
  1316. echo "<pre>";
  1317. echo $query;
  1318. echo "</pre>";
  1319. exit;
  1320. }
  1321. // make sure that there is something to save...
  1322. if( !$query ) {
  1323. return 0;
  1324. }
  1325. // execute the query
  1326. $sql = $this->_db->query( $query );
  1327. // query failed?
  1328. if( !$sql )
  1329. {
  1330. trigger_error(
  1331. "Error, query failed!<br />\n".
  1332. "<b>Error message:</b> ".$this->_db->getError()."<br />\n".
  1333. "<b>Query:</b> ". $query,
  1334. E_USER_WARNING
  1335. );
  1336. return -1;
  1337. }
  1338. // query succeeded
  1339. else
  1340. {
  1341. // is it an edit form ? Then return the known edit id's
  1342. if( $this->edit )
  1343. {
  1344. $return = $this->_id;
  1345. }
  1346. // it's an insert form
  1347. else
  1348. {
  1349. // get the inserted id
  1350. $id = $this->_db->getInsertId( $this->_table );
  1351. // got an id ?
  1352. if( $id )
  1353. {
  1354. $return = $id;
  1355. }
  1356. // no id retrieved from the getInsertId!!
  1357. // check if the id exists in the form
  1358. else
  1359. {
  1360. // fetch the keys from the table
  1361. $keys = $this->_db->getPrKeys( $this->_table );
  1362. // walk the keys
  1363. $result = array();
  1364. foreach( $keys as $key )
  1365. {
  1366. // check if the key exists in the "save" data
  1367. if( array_key_exists( $key, $data ) )
  1368. {
  1369. // replace possible quotes arround the data
  1370. $result[] = trim($data[$key], "'" );
  1371. }
  1372. }
  1373. $size = sizeof( $result );
  1374. $return = ($size > 1) ? $result : ( $size == 1 ? $result[0] : null);
  1375. }
  1376. }
  1377. }
  1378. // execute actions on the junction table
  1379. if( isset( $id ) || isset( $return ) )
  1380. {
  1381. $pk = isset( $id ) ? $id : pos( $return );
  1382. foreach( $this->_tableConfig as $tableName => $fields )
  1383. {
  1384. if( !$this -> _fields[$fields[0]][1] -> getViewMode() )
  1385. {
  1386. $this->deleteJunctionData( $tableName, $fields[1], $pk );
  1387. $this->insertJunctionData( $tableName, $fields[0], $fields[1], $pk );
  1388. }
  1389. }
  1390. }
  1391. // unset the database object (we dont need it anymore)
  1392. unset( $this->_db );
  1393. return $return;
  1394. }
  1395. /**
  1396. * dbFormHandler::_getQuery()
  1397. *
  1398. * Generate a query from the given data and return it
  1399. *
  1400. * @param string $table: The table name
  1401. * @param array $data: array of field => value which should be saved
  1402. * @param array $sqlFields: array of field which value is an SQL function (so it should not be quoted)
  1403. * @param boolean $edit: do we have to generate an edit or insert query
  1404. * @param array $keys: the primary key values
  1405. * @return string: the query
  1406. * @access private
  1407. * @author Teye Heimans
  1408. */
  1409. function _getQuery( $table, $data, $sqlFields, $edit, $keys = null )
  1410. {
  1411. // get the field names from the table
  1412. $fieldNames = $this->_db->getFieldNames( $this->_table );
  1413. // check if we got the fieldnames
  1414. if( !$fieldNames )
  1415. {
  1416. trigger_error(
  1417. 'Could not fetch the fieldnames of the table '. $this->_table,
  1418. E_USER_WARNING
  1419. );
  1420. return false;
  1421. }
  1422. // walk the data from the form
  1423. foreach( $data as $field => $value )
  1424. {
  1425. // does the field exists in the table?
  1426. if( !in_array($field, $fieldNames) )
  1427. {
  1428. // field does not exists, remove it from the data array (we dont need it )
  1429. unset( $data[$field] );
  1430. }
  1431. // the field exists in the table
  1432. else
  1433. {
  1434. // is the value an array? Implode it!
  1435. if( is_array($value) )
  1436. {
  1437. $value = implode(', ', $value);
  1438. }
  1439. // remove spaces etc
  1440. $value = trim( $value );
  1441. // if the value is not a SQL function...
  1442. if(!in_array($field, $sqlFields) )
  1443. {
  1444. // ecape the value for saving it into the database
  1445. $value = $this->_db->escapeString( $value );
  1446. // is the value a number or float?
  1447. if( preg_match('/^-?\d*\.?\d+$/', $value))
  1448. {
  1449. // do we have to quote it ?
  1450. if( $this->_db->quoteNumbers() )
  1451. {
  1452. $value = "'".$value."'";
  1453. }
  1454. }
  1455. // the value is not a number.. just quote it
  1456. else
  1457. {
  1458. $value = "'".$value."'";
  1459. }
  1460. // save the value. It's now db ready
  1461. $data[$field] = $value;
  1462. }
  1463. }
  1464. }
  1465. // check if there is still something left to save...
  1466. if( sizeof( $data ) == 0 )
  1467. {
  1468. return false;
  1469. }
  1470. // if it's an edit form
  1471. if($edit)
  1472. {
  1473. // generate the update query
  1474. $query = 'UPDATE '.$this->_db->quote( $this->_table )." SET \n";
  1475. // walk all fields and add them to the query
  1476. foreach($data as $field => $value)
  1477. {
  1478. $query .= ' '.$this->_db->quote( $field ).' = '.$value.", \n";
  1479. }
  1480. // add the where clause to the query
  1481. $query = substr($query, 0, -3) . $this->_getWhereClause();
  1482. }
  1483. // the form is an insert form..
  1484. else
  1485. {
  1486. // generate the insert query
  1487. $query = 'INSERT INTO '.$this->_db->quote( $this->_table )." (\n";
  1488. // add the field names to the query
  1489. foreach( array_keys($data) as $field )
  1490. {
  1491. $query .= ' '. $this->_db->quote( $field ) .", \n";
  1492. }
  1493. // add the values to the query
  1494. $query = substr($query, 0, -3) . ") VALUES (\n ";
  1495. $query .= implode(",\n ", $data)."\n);";
  1496. }
  1497. // return the query
  1498. return $query;
  1499. }
  1500. /**
  1501. * dbFormHandler::_getWhereClause()
  1502. *
  1503. * Get the where clause for a query
  1504. *
  1505. * @param string $operator The operator used for the primary key's and their values
  1506. * @param array $extra: extra where clause arguments
  1507. * @param string $extraOperator: operator used for the extra arguments
  1508. * @return string
  1509. * @access public
  1510. * @author Teye Heimans
  1511. */
  1512. function _getWhereClause( $operator = '=', $extra = array(), $extraOperator = '=' )
  1513. {
  1514. // get the primary key fields from the table
  1515. $keys = $this->_db->getPrKeys( $this->_table );
  1516. // get the values for the key fields
  1517. $record = $this->_id;
  1518. // walk untill the field's or values are all handled
  1519. $size1 = sizeof( $record );
  1520. $size2 = sizeof( $keys );
  1521. $size = ($size1 < $size2 ? $size1 : $size2);
  1522. $data = array();
  1523. for($i = 0; $i < $size; $i++ )
  1524. {
  1525. // is the key added by the user?
  1526. if( isset( $extra[$keys[$i]] ) && $extra[$keys[$i]] == $record[$i] )
  1527. {
  1528. unset( $extra[$keys[$i]] );
  1529. }
  1530. else
  1531. {
  1532. // is the value an float or integer ?
  1533. if( preg_match("/^-?\d*\.?\d+$/", $record[$i]) )
  1534. {
  1535. // do we need to quote integers ?
  1536. if( $this->_db->quoteNumbers() )
  1537. {
  1538. // query the value
  1539. $record[$i] = "'".$record[$i]."'";
  1540. }
  1541. }
  1542. // just quote the value
  1543. else
  1544. {
  1545. $record[$i] = "'".$record[$i]."'";
  1546. }
  1547. // save the where clause data
  1548. $data[] = ' '.$this->_db->quote( $keys[$i] ) .' '.$operator.' '.$record[$i].' ';
  1549. }
  1550. }
  1551. // prepare the other data
  1552. foreach ( $extra as $field => $value )
  1553. {
  1554. // quote the fieldname
  1555. $field = $this -> _db -> quote( $field );
  1556. // null value ?
  1557. if( is_null( $value) || strtoupper( $value ) == 'NULL' )
  1558. {
  1559. $data[] = $field .' IS NULL ';
  1560. }
  1561. // not a null value
  1562. else
  1563. {
  1564. $data[] = $field .' '.$extraOperator .' '.$value;
  1565. }
  1566. }
  1567. // return the where clause
  1568. return (sizeof($data) ? " WHERE \n " . implode("\n AND ", $data) : '');
  1569. }
  1570. }
  1571. ?>