PageRenderTime 46ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/include/core/class_core.php

https://github.com/timschofield/2.8
PHP | 681 lines | 305 code | 6 blank | 370 comment | 73 complexity | 23d45be6433d424b88f8bf74f275b40d MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, GPL-2.0
  1. <?php
  2. /**
  3. * Care2x API package
  4. * @package care_api
  5. */
  6. /**
  7. * Core methods. Will be extended by other classes.
  8. * Note this class should be instantiated only after a "$db" adodb connector object
  9. * has been established by an adodb instance
  10. * @author Elpidio Latorilla, Gjergj Sheldija, Robert Meggle
  11. * @version beta 3.0.0
  12. * @copyright 2002 - 2010: Elpidio Latorilla; 2011 - Today: Mauri Niemi
  13. * @package care_api
  14. */
  15. class Core {
  16. /**
  17. * @public string Table name used for core routines. Default table name.
  18. */
  19. public $coretable;
  20. /**
  21. * @public string Holder for SQL query. Can be extracted with the "getLastQuery()" method.
  22. */
  23. public $sql='';
  24. /**
  25. * @public array Contains fieldnames of the table named in the $coretable. For internal update/insert operations.
  26. */
  27. public $ref_array=array();
  28. /**
  29. * @public array For internal update/insert operations
  30. */
  31. public $data_array=array();
  32. /**
  33. * @public array For internal update/insert operations
  34. */
  35. public $buffer_array=array();
  36. /**
  37. * @public ADODB record object For sql query results.
  38. */
  39. public $result;
  40. /**
  41. * @public string For update sql queries condition
  42. */
  43. public $where;
  44. /**
  45. * @public int For counting resulting rows. Can be extracted w/ the "LastRecordCount()" method.
  46. */
  47. public $rec_count;
  48. /**
  49. * @public mixed
  50. */
  51. public $buffer;
  52. /**
  53. * @public array Used for containing results returned as pointer.
  54. */
  55. public $res=array();
  56. /**
  57. * @public boolean
  58. * @access private
  59. */
  60. private $do_intern;
  61. /**
  62. * @private boolean
  63. * @access private
  64. */
  65. private $ok;
  66. /**
  67. *
  68. * */
  69. public $is_preloaded=FALSE;
  70. /**
  71. * Internal error message usually used in debugging.
  72. * @public string
  73. * @access private
  74. */
  75. public $error_msg='';
  76. /**
  77. * Status items used in sql queries "IN (???)"
  78. * @public string
  79. * @access private
  80. */
  81. public $dead_stat="'deleted','hidden','inactive','void'";
  82. /**
  83. * Status items used in sql queries "IN (???)"
  84. * @public string
  85. * @access private
  86. */
  87. public $normal_stat="'','normal'";
  88. /**
  89. * Sets the coretable variable to the name of the database table.
  90. *
  91. * This points the core object to that database table and all core routines will use this table
  92. * until the core table is reset or replaced with another table name
  93. * @param string Table name
  94. * @return void
  95. */
  96. function setTable($table) {
  97. $this->coretable=$table;
  98. }
  99. /**
  100. * Points the reference variable $ref_array to the field names' array.
  101. *
  102. * This field names array corresponds to the database table set by the setTable() method
  103. * @param array By reference, the associative array containing the field names.
  104. * @return boolean
  105. */
  106. function setRefArray(&$array) {
  107. if(!is_array($array)){
  108. return FALSE;
  109. }else{
  110. $this->ref_array=$array;
  111. return TRUE;
  112. }
  113. }
  114. /**
  115. * Points the core data array to the external array that holds the data to be stored.
  116. * @param array By reference, the associative array holding the data.
  117. */
  118. function setDataArray(&$array){
  119. $this->data_array=$array;
  120. }
  121. /**
  122. * Checks if a certain database record exists based onthe supplied query condition.
  123. *
  124. * Should be used privately.
  125. * @param string The query "where" condition without the WHERE word.
  126. * @return boolean
  127. */
  128. function _RecordExists($cond=''){
  129. global $db;
  130. if(empty($cond)) return FALSE;
  131. if($this->result=$db->Execute("SELECT create_time FROM $this->coretable WHERE $cond")){
  132. if($this->result->RecordCount()){
  133. return TRUE;
  134. }else{return FALSE;}
  135. }else{return FALSE;}
  136. }
  137. /**
  138. * Sets the internal sql query variable to the sql query.
  139. * @param string Query statement.
  140. */
  141. function setSQL(&$sql){
  142. $this->sql=$sql;
  143. }
  144. /**
  145. * Transaction routine, ADODB transaction. It internally uses the ADODB transaction routine.
  146. *
  147. * <code>
  148. * $sql="INSERT INTO care_users (item) VALUES ('value')";
  149. * $core->Transact($sql);
  150. * </code>
  151. * If the query parameter is empty, the method will use the sql query stored internally.
  152. * This internal sql query statement must be set with the setSQL() method or direct setting of variable before Transact() is called.
  153. *
  154. * <code>
  155. * $sql="INSERT INTO care_users (item) VALUES ('value')";
  156. * $core->setSQL($sql);
  157. * $core->Transact();
  158. * </code>
  159. *
  160. * or internally in class extensions
  161. *
  162. * <code>
  163. * $this->sql="INSERT INTO care_users (item) VALUES ('value')";
  164. * $this->Transact();
  165. * </code>
  166. *
  167. * @param string sql SQL query statement.
  168. * @return TRUE/FALSE
  169. * @global ADODB db link
  170. * @access public
  171. */
  172. function Transact($sql='') {
  173. global $db;
  174. if(!empty($sql)) $this->sql=$sql;
  175. $db->BeginTrans();
  176. $this->ok=$db->Execute($this->sql);
  177. if($this->ok) {
  178. $db->CommitTrans();
  179. return TRUE;
  180. } else {
  181. $db->RollbackTrans();
  182. return FALSE;
  183. }
  184. }
  185. /**
  186. * Filters the data array intended for saving, removing the key-value pairs that do not correspond to the table's field names.
  187. * @access private
  188. * @return int Size of the resulting data array.
  189. */
  190. function _prepSaveArray(){
  191. $x='';
  192. $v='';
  193. reset($this->ref_array);
  194. reset($this->data_array);
  195. while(list($x,$v)=each($this->ref_array)) {
  196. // Gjergj Sheldija :
  197. // deleted && ($this->data_array[$v]!='') gives me errors when public value == 0
  198. if(isset($this->data_array[$v]) ) {
  199. $this->buffer_array[$v]=$this->data_array[$v];
  200. if($v=='create_time' && $this->data['create_time']!='') $this->buffer_array[$v] = date('YmdHis');
  201. }
  202. }
  203. // Reset the source array index to start
  204. reset($this->ref_array);
  205. return sizeof($this->buffer_array);
  206. }
  207. /**
  208. * Inserts data from the internal array previously filled with data by the <var>setDataArray()</var> method.
  209. *
  210. * This method also uses the field names from the internal array $ref_array previously set by "use????" methods that point
  211. * the core object to the proper table and fields names.
  212. * @access public
  213. * @return boolean
  214. */
  215. function insertDataFromInternalArray() {
  216. //$this->data_array=NULL;
  217. $this->_prepSaveArray();
  218. // Check if "create_time" key has a value, if no, create a new value
  219. return $this->insertDataFromArray($this->buffer_array);
  220. }
  221. /**
  222. * Returns all records with the needed items from the table.
  223. *
  224. * The table name must be set in the coretable first by <var>setTable()</var> method.
  225. * @param string items By reference. Items to be returned from each record fetched from the table. The items should be separted with commas.
  226. * @return mixed ADODB record object or boolean
  227. *
  228. * Example:
  229. *
  230. * <code>
  231. * $items="pid, name_last, name_first, birth_date, sex";
  232. * $core->setTable('care_person');
  233. * $persons = $core->getAllItemsObject($items);
  234. * while($row=$persons->FetchRow()){
  235. * ...
  236. * }
  237. * </code>
  238. *
  239. */
  240. function getAllItemsObject(&$items) {
  241. global $db;
  242. $this->sql="SELECT $items FROM $this->coretable";
  243. if($this->res['gaio']=$db->Execute($this->sql)) {
  244. if($this->rec_count=$this->res['gaio']->RecordCount()) {
  245. return $this->res['gaio'];
  246. } else { return FALSE; }
  247. } else { return FALSE; }
  248. }
  249. /**
  250. * Returns all records with all items from the table.
  251. *
  252. * The table name must be set in the coretable first by setTable() method.
  253. * @return mixed ADODB record object or boolean
  254. *
  255. * Example:
  256. *
  257. * <code>
  258. * $core->setTable('care_person');
  259. * $persons = $core->getAllDataObject();
  260. * while($row=$persons->FetchRow()){
  261. * ...
  262. * }
  263. * </code>
  264. */
  265. function getAllDataObject() {
  266. global $db;
  267. $this->sql="SELECT * FROM $this->coretable";
  268. if($this->res['gado']=$db->Execute($this->sql)) {
  269. if($this->rec_count=$this->res['gado']->RecordCount()) {
  270. return $this->res['gado'];
  271. } else { return FALSE; }
  272. } else { return FALSE; }
  273. }
  274. /**
  275. * Similar to getAllItemsObject() method but returns the records in an associative array.
  276. *
  277. * Returns all records with the needed items from the table. The table name must be set in the coretable first by <var>setTable()</var> method.
  278. *
  279. * Example:
  280. * <code>
  281. * $items="pid, name_last, name_first, birth_date, sex";
  282. * $core->setTable('care_person');
  283. * $persons = $core->getAllItemsArray($items);
  284. * while(list($x,$v)=each($persons)){
  285. * ...
  286. * }
  287. * </code>
  288. *
  289. * @param string items By reference. Items to be returned from each record fetched from the table. The items should be separted with commas.
  290. * @return array associative
  291. * @access private
  292. */
  293. function getAllItemsArray(&$items) {
  294. global $db;
  295. $this->sql="SELECT $items FROM $this->coretable";
  296. if($this->result=$db->Execute($this->sql)) {
  297. if($this->result->RecordCount()) {
  298. return $this->result->GetArray();
  299. } else { return FALSE; }
  300. } else { return FALSE; }
  301. }
  302. /**
  303. * Returns all records with the all items from the table.
  304. *
  305. * The table name must be set in the coretable first by setTable() method.
  306. * @return mixed ADODB record object or boolean
  307. * @global ADODB db link
  308. *
  309. * Example:
  310. * <code>
  311. * $core->setTable('care_person');
  312. * $persons = $core->getAllDataArray();
  313. * while(list($x,$v)=each($persons)){
  314. * ...
  315. * }
  316. * </code>
  317. */
  318. function getAllDataArray() {
  319. global $db;
  320. $this->sql="SELECT * FROM $this->coretable";
  321. if($this->result=$db->Execute($this->sql)) {
  322. if($this->result->RecordCount()) {
  323. while($this->ref_array=$this->result->FetchRow());
  324. return $this->ref_array;
  325. } else { return FALSE; }
  326. } else { return FALSE; }
  327. }
  328. /**
  329. * Inserts data from an array (passed by reference) into a table.
  330. *
  331. * This method uses the table and field names from internal variables previously set by "use????" methods that point
  332. * the object to the proper table and fields names. Private or public (preferably private being called by other methods).
  333. * @access private
  334. * @param array By reference. The array containing the data. Note: the array keys must correspond to the table field names.
  335. * @return boolean
  336. */
  337. function insertDataFromArray(&$array) {
  338. global $dbtype;
  339. $x='';
  340. $v='';
  341. $index='';
  342. $values='';
  343. //gjergji : bug for concat when inserting...
  344. if($dbtype=='postgres7'||$dbtype=='postgres') $concatfx='||';
  345. else $concatfx='concat';
  346. if(!is_array($array)){ return FALSE;}
  347. while(list($x,$v)=each($array)) {
  348. // use backquoting for mysql and no-quoting for other dbs
  349. if ($dbtype=='mysql') $index.="`$x`,";
  350. else $index.="$x,";
  351. if(stristr($v,$concatfx)||stristr($v,'null')) $values.=" $v,";
  352. else $values.="'$v',";
  353. }
  354. reset($array);
  355. $index=substr_replace($index,'',(strlen($index))-1);
  356. $values=substr_replace($values,'',(strlen($values))-1);
  357. $this->sql="INSERT INTO $this->coretable ($index) VALUES ($values)";
  358. reset($array);
  359. return $this->Transact();
  360. }
  361. /**
  362. * Updates a record with the data from an array (passed by reference) based on the primary key.
  363. *
  364. * This method also uses the field names from an internal array previously set by "use????" methods that point
  365. * the object to the proper table and fields names.
  366. * private or public (preferably private being called by other methods)
  367. * @param array Data. By reference. Note: the array keys must correspond to the table field names
  368. * @param int Key used in the update queries' "where" condition
  369. * @param boolean Flags if the param $item_nr should be strictly numeric or not. Defaults to TRUE = strictly numeric.
  370. * @return boolean
  371. */
  372. function updateDataFromArray(&$array,$item_nr='',$isnum=TRUE) {
  373. global $dbtype;
  374. $x='';
  375. $v='';
  376. $elems='';
  377. if($dbtype=='postgres7'||$dbtype=='postgres') $concatfx='||';
  378. else $concatfx='concat';
  379. if(empty($array)) return FALSE;
  380. if(empty($item_nr)||($isnum&&!is_numeric($item_nr))) return FALSE;
  381. while(list($x,$v)=each($array)) {
  382. // use backquoting for mysql and no-quoting for other dbs.
  383. if ($dbtype=='mysql') $elems.="`$x`=";
  384. else $elems.="$x=";
  385. if(stristr($v,$concatfx)||stristr($v,'null')) $elems.=" $v,";
  386. else $elems.="'$v',";
  387. }
  388. reset($array);
  389. $elems=substr_replace($elems,'',(strlen($elems))-1);
  390. if(empty($this->where)) $this->where="nr=$item_nr";
  391. $this->sql="UPDATE $this->coretable SET $elems WHERE $this->where";
  392. $this->where='';
  393. return $this->Transact();
  394. }
  395. /**
  396. * Updates a table using data from an internal array previously filled with data by the <var>setDataArray()</var> method.
  397. *
  398. * Update the record based on the primary key.
  399. * This method also uses the field names from an internal array previously set by "use????" methods that point
  400. * the object to the proper table and fields names.
  401. * @access public
  402. * @param int Key used in the update queries' "where" condition
  403. * @param boolean Flags if the param $item_nr should be strictly numeric or not. Defaults to TRUE = strictly numeric.
  404. * @return boolean
  405. */
  406. function updateDataFromInternalArray($item_nr='',$isnum=TRUE) {
  407. if(empty($item_nr)||($isnum&&!is_numeric($item_nr))) return FALSE;
  408. $this->_prepSaveArray();
  409. return $this->updateDataFromArray($this->buffer_array,$item_nr,$isnum);
  410. }
  411. /**
  412. * Returns the the last sql query string
  413. * @return string
  414. */
  415. function getLastQuery(){
  416. return $this->sql;
  417. }
  418. /**
  419. * Feturns the value of result
  420. * @return mixed
  421. */
  422. function getResult(){
  423. return $this->result;
  424. }
  425. /**
  426. * Feturns the value of error_msg, the internal error message.
  427. * @return string
  428. */
  429. function getErrorMsg(){
  430. return $this->error_msg;
  431. }
  432. /**
  433. * Sets the "where" condition in an update query used with the updateDataFromInternalArray() method.
  434. *
  435. * The where condition defaults to "nr='$nr'".
  436. * @access private
  437. * @param string cond The constraint for the sql query.
  438. * @return void
  439. */
  440. function setWhereCondition($cond){
  441. $this->where=$cond;
  442. }
  443. /**
  444. * Returns the value of is_preloaded that is set by methods that preload large number of data.
  445. * @return boolean
  446. */
  447. function isPreLoaded(){
  448. return $this->is_preloaded;
  449. }
  450. /**
  451. * Returns the value of rec_count
  452. * @return int
  453. */
  454. function LastRecordCount(){
  455. return $this->rec_count;
  456. }
  457. /**
  458. * Saves temporary data to a cache in database.
  459. * @access public
  460. * @param string Cached data identification
  461. * @param mixed By referece. Data to be saved.
  462. * @param boolean Signals the type of the data contained in the param $data. FALSE=nonbinary data, TRUE=binary
  463. * @return boolean
  464. */
  465. function saveDBCache($id,&$data,$bin=FALSE){
  466. if($bin) $elem='cbinary';
  467. else $elem='ctext';
  468. $this->sql="INSERT INTO care_cache (id,$elem,tstamp) VALUES ('$id','$data','".date('YmdHis')."')";
  469. return $this->Transact();
  470. }
  471. /**
  472. * Gets temporary data from the database cache.
  473. * @access public
  474. * @param string Cached data identification
  475. * @param mixed By reference. Variable for the data to be fetched.
  476. * @param boolean Signals the type of data contained in the $data. FALSE=nonbinary data, TRUE=binary.
  477. * @return mixed string, binary or boolean
  478. */
  479. function getDBCache($id,&$data,$bin=FALSE){
  480. global $db;
  481. $buf;
  482. $row;
  483. if($bin) $elem='cbinary';
  484. else $elem='ctext';
  485. $this->sql="SELECT $elem FROM care_cache WHERE id = '$id'";
  486. if($buf=$db->Execute($this->sql)) {
  487. if($buf->RecordCount()) {
  488. $row=$buf->FetchRow();
  489. $data=$row[$elem];
  490. return TRUE;
  491. } else { return FALSE; }
  492. } else { return FALSE; }
  493. }
  494. /**
  495. * Deletes data from the database cache based on the id key.
  496. * @access public
  497. * @param char ID of data for deletion.
  498. * @return boolean
  499. */
  500. function deleteDBCache($id){
  501. global $sql_LIKE;
  502. if(empty($id)) return FALSE;
  503. $this->sql="DELETE FROM care_cache WHERE id = '$id'";
  504. return $this->Transact();
  505. }
  506. /**
  507. * Deletes data from a database table based on the job_id and
  508. * batch_nr. Used in the update action for the laboratory tables
  509. * ( chemlabor and baclabor )
  510. * @access public
  511. * @param varchar $batch_nr
  512. * @param varchar $job_id
  513. * @return boolean
  514. */
  515. function deleteOldValues($batch_nr, $encounter_nr){
  516. if(empty($batch_nr) || empty($encounter_nr)) return FALSE;
  517. $this->sql="DELETE FROM $this->coretable WHERE batch_nr = '$batch_nr' AND encounter_nr = '$encounter_nr'";
  518. return $this->Transact();
  519. }
  520. /**
  521. * Returns the core field names of the core table in an array.
  522. * @access public
  523. * @return array
  524. */
  525. function coreFieldNames(){
  526. return $this->ref_array;
  527. }
  528. /**
  529. * Returns a list of filename within a path in array.
  530. * @access public
  531. * @param string Path of the filenames relative to the root path.
  532. * @param string Discriminator string.
  533. * @param string The sort direction (ASC or DESC) defaults to ASC (ascending)
  534. * @return mixed array or boolean
  535. */
  536. function FilesListArray($path='',$filter='',$sort='ASC'){
  537. $localpath=$path.'/.';
  538. //echo "<br>$localpath<br>";
  539. $this->res['fla']=array();
  540. if(file_exists($localpath)){
  541. $handle=opendir($path);
  542. $count=0;
  543. while (FALSE!==($file = readdir($handle))) {
  544. if ($file != "." && $file != ".."){
  545. if(!empty($filter)){
  546. if(stristr($file,$filter)){
  547. $this->res['fla'][$count]=$file;
  548. $count++;
  549. }
  550. }else{
  551. $this->res['fla'][$count]=$file;
  552. $count++;
  553. }
  554. }
  555. }
  556. closedir($handle);
  557. if($count){
  558. $this->rec_count=$count;
  559. if($sort=='ASC'){
  560. @sort($this->res['fla']);
  561. }elseif($sort=='DESC'){
  562. @rsort($this->res['fla']);
  563. }
  564. return $this->res['fla'];
  565. }
  566. }else{
  567. return FALSE;
  568. }
  569. }
  570. /**
  571. * Returns the value of the primary key of a row based on the column OID key
  572. *
  573. * Special for postgre and other dbms that returns OID after an insert query
  574. * @param str Table name
  575. * @param str Field name of the primary key
  576. * @param int OID value
  577. * @return int Non-zero if value ok, else zero if not found
  578. */
  579. function postgre_Insert_ID($table,$pk,$oid=0){
  580. global $db;
  581. if(empty($oid)){
  582. return 0;
  583. }else{
  584. $this->sql="SELECT $pk FROM $table WHERE oid=$oid";
  585. if($result=$db->Execute($this->sql)) {
  586. if($result->RecordCount()) {
  587. $buf=$result->FetchRow();
  588. return $buf[$pk];
  589. } else { return 0; }
  590. } else { return 0; }
  591. }
  592. }
  593. /**
  594. * Returns the value of the last inserted primary key of a row based on the column field name
  595. *
  596. * This function uses the core table set by the child class
  597. * @param str Field name of the primary key
  598. * @param int OID value
  599. * @return int Non-zero if value ok, else zero if not found
  600. */
  601. function LastInsertPK($pk='',$oid=0){
  602. global $dbtype;
  603. if(empty($pk)||empty($oid)){
  604. return $oid;
  605. }else{
  606. switch($dbtype){
  607. case 'mysql': return $oid;
  608. break;
  609. case 'postgres': return $this->postgre_Insert_ID($this->coretable,$pk,$oid);
  610. break;
  611. case 'postgres7': return $this->postgre_Insert_ID($this->coretable,$pk,$oid);
  612. break;
  613. default: return $oid;
  614. }
  615. }
  616. }
  617. /**
  618. * Returns a field concat string for sql query.
  619. *
  620. * This function resolves the problems of concatenating a field value with a string in different db types
  621. * @param str Field name
  622. * @param str String to concate
  623. * @return string
  624. */
  625. function ConcatFieldString($fieldname,$str=''){
  626. global $dbtype;
  627. switch($dbtype){
  628. case 'mysql': return "CONCAT($fieldname,'$str')";
  629. break;
  630. case 'postgres': return "$fieldname || '$str'";
  631. break;
  632. case 'postgres7':return "$fieldname || '$str'";
  633. break;
  634. default: return "$fieldname || '$str'";
  635. }
  636. }
  637. /**
  638. * Returns a "history" field concat string for sql query.
  639. *
  640. * This function resolves the problems of concatenating the "history" field value with a string in different db types
  641. * @param str String
  642. * @return string
  643. */
  644. function ConcatHistory($str=''){
  645. return $this->ConcatFieldString('history',$str);
  646. }
  647. /**
  648. * Returns a "notes" field concat string for sql query.
  649. *
  650. * This function resolves the problems of concatenating the "note" field value with a string in different db types
  651. * @param str String
  652. * @return string
  653. */
  654. function ConcatNotes($str=''){
  655. return $this->ConcatFieldString('notes',$str);
  656. }
  657. /**
  658. * Returns a field's string for sql query. Portions of the string is replaced by a string.
  659. *
  660. * This function resolves the problems of replacing a field value with a string in different db types
  661. * @param str Field name
  662. * @param str String to be replaced
  663. * @param str Replacement string
  664. * @return string
  665. */
  666. function ReplaceFieldString($fieldname,$str1='',$str2=''){
  667. global $dbtype;
  668. switch($dbtype){
  669. case 'mysql': return "REPLACE($fieldname,'$str1','$str2')";
  670. break;
  671. default: return "REPLACE($fieldname,'$str1','$str2')";
  672. }
  673. }
  674. }
  675. ?>