PageRenderTime 48ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/concreteOLD/libraries/3rdparty/adodb/adodb-lib.inc.php

https://bitbucket.org/selfeky/xclusivescardwebsite
PHP | 1193 lines | 781 code | 179 blank | 233 comment | 308 complexity | 2c526d6194791eb9f3b96b37218a8deb MD5 | raw file
  1. <?php
  2. // security - hide paths
  3. if (!defined('ADODB_DIR')) die();
  4. global $ADODB_INCLUDED_LIB;
  5. $ADODB_INCLUDED_LIB = 1;
  6. /*
  7. @version V5.06 16 Oct 2008 (c) 2000-2009 John Lim (jlim\@natsoft.com.my). All rights reserved.
  8. Released under both BSD license and Lesser GPL library license.
  9. Whenever there is any discrepancy between the two licenses,
  10. the BSD license will take precedence. See License.txt.
  11. Set tabs to 4 for best viewing.
  12. Less commonly used functions are placed here to reduce size of adodb.inc.php.
  13. */
  14. function adodb_strip_order_by($sql)
  15. {
  16. $rez = preg_match('/(\sORDER\s+BY\s[^)]*)/is',$sql,$arr);
  17. if ($arr)
  18. if (strpos($arr[0],'(') !== false) {
  19. $at = strpos($sql,$arr[0]);
  20. $cntin = 0;
  21. for ($i=$at, $max=strlen($sql); $i < $max; $i++) {
  22. $ch = $sql[$i];
  23. if ($ch == '(') {
  24. $cntin += 1;
  25. } elseif($ch == ')') {
  26. $cntin -= 1;
  27. if ($cntin < 0) {
  28. break;
  29. }
  30. }
  31. }
  32. $sql = substr($sql,0,$at).substr($sql,$i);
  33. } else
  34. $sql = str_replace($arr[0], '', $sql);
  35. return $sql;
  36. }
  37. if (false) {
  38. $sql = 'select * from (select a from b order by a(b),b(c) desc)';
  39. $sql = '(select * from abc order by 1)';
  40. die(adodb_strip_order_by($sql));
  41. }
  42. function adodb_probetypes(&$array,&$types,$probe=8)
  43. {
  44. // probe and guess the type
  45. $types = array();
  46. if ($probe > sizeof($array)) $max = sizeof($array);
  47. else $max = $probe;
  48. for ($j=0;$j < $max; $j++) {
  49. $row = $array[$j];
  50. if (!$row) break;
  51. $i = -1;
  52. foreach($row as $v) {
  53. $i += 1;
  54. if (isset($types[$i]) && $types[$i]=='C') continue;
  55. //print " ($i ".$types[$i]. "$v) ";
  56. $v = trim($v);
  57. if (!preg_match('/^[+-]{0,1}[0-9\.]+$/',$v)) {
  58. $types[$i] = 'C'; // once C, always C
  59. continue;
  60. }
  61. if ($j == 0) {
  62. // If empty string, we presume is character
  63. // test for integer for 1st row only
  64. // after that it is up to testing other rows to prove
  65. // that it is not an integer
  66. if (strlen($v) == 0) $types[$i] = 'C';
  67. if (strpos($v,'.') !== false) $types[$i] = 'N';
  68. else $types[$i] = 'I';
  69. continue;
  70. }
  71. if (strpos($v,'.') !== false) $types[$i] = 'N';
  72. }
  73. }
  74. }
  75. function adodb_transpose(&$arr, &$newarr, &$hdr, &$fobjs)
  76. {
  77. $oldX = sizeof(reset($arr));
  78. $oldY = sizeof($arr);
  79. if ($hdr) {
  80. $startx = 1;
  81. $hdr = array('Fields');
  82. for ($y = 0; $y < $oldY; $y++) {
  83. $hdr[] = $arr[$y][0];
  84. }
  85. } else
  86. $startx = 0;
  87. for ($x = $startx; $x < $oldX; $x++) {
  88. if ($fobjs) {
  89. $o = $fobjs[$x];
  90. $newarr[] = array($o->name);
  91. } else
  92. $newarr[] = array();
  93. for ($y = 0; $y < $oldY; $y++) {
  94. $newarr[$x-$startx][] = $arr[$y][$x];
  95. }
  96. }
  97. }
  98. // Force key to upper.
  99. // See also http://www.php.net/manual/en/function.array-change-key-case.php
  100. function _array_change_key_case($an_array)
  101. {
  102. if (is_array($an_array)) {
  103. $new_array = array();
  104. foreach($an_array as $key=>$value)
  105. $new_array[strtoupper($key)] = $value;
  106. return $new_array;
  107. }
  108. return $an_array;
  109. }
  110. function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc)
  111. {
  112. if (count($fieldArray) == 0) return 0;
  113. $first = true;
  114. $uSet = '';
  115. if (!is_array($keyCol)) {
  116. $keyCol = array($keyCol);
  117. }
  118. foreach($fieldArray as $k => $v) {
  119. if ($v === null) {
  120. $v = 'NULL';
  121. $fieldArray[$k] = $v;
  122. } else if ($autoQuote && /*!is_numeric($v) /*and strncmp($v,"'",1) !== 0 -- sql injection risk*/ strcasecmp($v,$zthis->null2null)!=0) {
  123. $v = $zthis->qstr($v);
  124. $fieldArray[$k] = $v;
  125. }
  126. if (in_array($k,$keyCol)) continue; // skip UPDATE if is key
  127. if ($first) {
  128. $first = false;
  129. $uSet = "$k=$v";
  130. } else
  131. $uSet .= ",$k=$v";
  132. }
  133. $where = false;
  134. foreach ($keyCol as $v) {
  135. if (isset($fieldArray[$v])) {
  136. if ($where) $where .= ' and '.$v.'='.$fieldArray[$v];
  137. else $where = $v.'='.$fieldArray[$v];
  138. }
  139. }
  140. if ($uSet && $where) {
  141. $update = "UPDATE $table SET $uSet WHERE $where";
  142. $rs = $zthis->Execute($update);
  143. if ($rs) {
  144. if ($zthis->poorAffectedRows) {
  145. /*
  146. The Select count(*) wipes out any errors that the update would have returned.
  147. http://phplens.com/lens/lensforum/msgs.php?id=5696
  148. */
  149. if ($zthis->ErrorNo()<>0) return 0;
  150. # affected_rows == 0 if update field values identical to old values
  151. # for mysql - which is silly.
  152. $cnt = $zthis->GetOne("select count(*) from $table where $where");
  153. if ($cnt > 0) return 1; // record already exists
  154. } else {
  155. if (($zthis->Affected_Rows()>0)) return 1;
  156. }
  157. } else
  158. return 0;
  159. }
  160. // print "<p>Error=".$this->ErrorNo().'<p>';
  161. $first = true;
  162. foreach($fieldArray as $k => $v) {
  163. if ($has_autoinc && in_array($k,$keyCol)) continue; // skip autoinc col
  164. if ($first) {
  165. $first = false;
  166. $iCols = "$k";
  167. $iVals = "$v";
  168. } else {
  169. $iCols .= ",$k";
  170. $iVals .= ",$v";
  171. }
  172. }
  173. $insert = "INSERT INTO $table ($iCols) VALUES ($iVals)";
  174. $rs = $zthis->Execute($insert);
  175. return ($rs) ? 2 : 0;
  176. }
  177. // Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM
  178. function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false,
  179. $size=0, $selectAttr='',$compareFields0=true)
  180. {
  181. $hasvalue = false;
  182. if ($multiple or is_array($defstr)) {
  183. if ($size==0) $size=5;
  184. $attr = ' multiple size="'.$size.'"';
  185. if (!strpos($name,'[]')) $name .= '[]';
  186. } else if ($size) $attr = ' size="'.$size.'"';
  187. else $attr ='';
  188. $s = '<select name="'.$name.'"'.$attr.' '.$selectAttr.'>';
  189. if ($blank1stItem)
  190. if (is_string($blank1stItem)) {
  191. $barr = explode(':',$blank1stItem);
  192. if (sizeof($barr) == 1) $barr[] = '';
  193. $s .= "\n<option value=\"".$barr[0]."\">".$barr[1]."</option>";
  194. } else $s .= "\n<option></option>";
  195. if ($zthis->FieldCount() > 1) $hasvalue=true;
  196. else $compareFields0 = true;
  197. $value = '';
  198. $optgroup = null;
  199. $firstgroup = true;
  200. $fieldsize = $zthis->FieldCount();
  201. while(!$zthis->EOF) {
  202. $zval = rtrim(reset($zthis->fields));
  203. if ($blank1stItem && $zval=="") {
  204. $zthis->MoveNext();
  205. continue;
  206. }
  207. if ($fieldsize > 1) {
  208. if (isset($zthis->fields[1]))
  209. $zval2 = rtrim($zthis->fields[1]);
  210. else
  211. $zval2 = rtrim(next($zthis->fields));
  212. }
  213. $selected = ($compareFields0) ? $zval : $zval2;
  214. $group = '';
  215. if ($fieldsize > 2) {
  216. $group = rtrim($zthis->fields[2]);
  217. }
  218. /*
  219. if ($optgroup != $group) {
  220. $optgroup = $group;
  221. if ($firstgroup) {
  222. $firstgroup = false;
  223. $s .="\n<optgroup label='". htmlspecialchars($group) ."'>";
  224. } else {
  225. $s .="\n</optgroup>";
  226. $s .="\n<optgroup label='". htmlspecialchars($group) ."'>";
  227. }
  228. }
  229. */
  230. if ($hasvalue)
  231. $value = " value='".htmlspecialchars($zval2)."'";
  232. if (is_array($defstr)) {
  233. if (in_array($selected,$defstr))
  234. $s .= "\n<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
  235. else
  236. $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
  237. }
  238. else {
  239. if (strcasecmp($selected,$defstr)==0)
  240. $s .= "\n<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
  241. else
  242. $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
  243. }
  244. $zthis->MoveNext();
  245. } // while
  246. // closing last optgroup
  247. if($optgroup != null) {
  248. $s .= "\n</optgroup>";
  249. }
  250. return $s ."\n</select>\n";
  251. }
  252. // Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM
  253. function _adodb_getmenu_gp(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false,
  254. $size=0, $selectAttr='',$compareFields0=true)
  255. {
  256. $hasvalue = false;
  257. if ($multiple or is_array($defstr)) {
  258. if ($size==0) $size=5;
  259. $attr = ' multiple size="'.$size.'"';
  260. if (!strpos($name,'[]')) $name .= '[]';
  261. } else if ($size) $attr = ' size="'.$size.'"';
  262. else $attr ='';
  263. $s = '<select name="'.$name.'"'.$attr.' '.$selectAttr.'>';
  264. if ($blank1stItem)
  265. if (is_string($blank1stItem)) {
  266. $barr = explode(':',$blank1stItem);
  267. if (sizeof($barr) == 1) $barr[] = '';
  268. $s .= "\n<option value=\"".$barr[0]."\">".$barr[1]."</option>";
  269. } else $s .= "\n<option></option>";
  270. if ($zthis->FieldCount() > 1) $hasvalue=true;
  271. else $compareFields0 = true;
  272. $value = '';
  273. $optgroup = null;
  274. $firstgroup = true;
  275. $fieldsize = sizeof($zthis->fields);
  276. while(!$zthis->EOF) {
  277. $zval = rtrim(reset($zthis->fields));
  278. if ($blank1stItem && $zval=="") {
  279. $zthis->MoveNext();
  280. continue;
  281. }
  282. if ($fieldsize > 1) {
  283. if (isset($zthis->fields[1]))
  284. $zval2 = rtrim($zthis->fields[1]);
  285. else
  286. $zval2 = rtrim(next($zthis->fields));
  287. }
  288. $selected = ($compareFields0) ? $zval : $zval2;
  289. $group = '';
  290. if (isset($zthis->fields[2])) {
  291. $group = rtrim($zthis->fields[2]);
  292. }
  293. if ($optgroup != $group) {
  294. $optgroup = $group;
  295. if ($firstgroup) {
  296. $firstgroup = false;
  297. $s .="\n<optgroup label='". htmlspecialchars($group) ."'>";
  298. } else {
  299. $s .="\n</optgroup>";
  300. $s .="\n<optgroup label='". htmlspecialchars($group) ."'>";
  301. }
  302. }
  303. if ($hasvalue)
  304. $value = " value='".htmlspecialchars($zval2)."'";
  305. if (is_array($defstr)) {
  306. if (in_array($selected,$defstr))
  307. $s .= "\n<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
  308. else
  309. $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
  310. }
  311. else {
  312. if (strcasecmp($selected,$defstr)==0)
  313. $s .= "\n<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
  314. else
  315. $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
  316. }
  317. $zthis->MoveNext();
  318. } // while
  319. // closing last optgroup
  320. if($optgroup != null) {
  321. $s .= "\n</optgroup>";
  322. }
  323. return $s ."\n</select>\n";
  324. }
  325. /*
  326. Count the number of records this sql statement will return by using
  327. query rewriting heuristics...
  328. Does not work with UNIONs, except with postgresql and oracle.
  329. Usage:
  330. $conn->Connect(...);
  331. $cnt = _adodb_getcount($conn, $sql);
  332. */
  333. function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0)
  334. {
  335. $qryRecs = 0;
  336. if (!empty($zthis->_nestedSQL) || preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) ||
  337. preg_match('/\s+GROUP\s+BY\s+/is',$sql) ||
  338. preg_match('/\s+UNION\s+/is',$sql)) {
  339. $rewritesql = adodb_strip_order_by($sql);
  340. // ok, has SELECT DISTINCT or GROUP BY so see if we can use a table alias
  341. // but this is only supported by oracle and postgresql...
  342. if ($zthis->dataProvider == 'oci8') {
  343. // Allow Oracle hints to be used for query optimization, Chris Wrye
  344. if (preg_match('#/\\*+.*?\\*\\/#', $sql, $hint)) {
  345. $rewritesql = "SELECT ".$hint[0]." COUNT(*) FROM (".$rewritesql.")";
  346. } else
  347. $rewritesql = "SELECT COUNT(*) FROM (".$rewritesql.")";
  348. } else if (strncmp($zthis->databaseType,'postgres',8) == 0 || strncmp($zthis->databaseType,'mysql',5) == 0) {
  349. $rewritesql = "SELECT COUNT(*) FROM ($rewritesql) _ADODB_ALIAS_";
  350. } else {
  351. $rewritesql = "SELECT COUNT(*) FROM ($rewritesql)";
  352. }
  353. } else {
  354. // now replace SELECT ... FROM with SELECT COUNT(*) FROM
  355. $rewritesql = preg_replace(
  356. '/^\s*SELECT\s.*\s+FROM\s/Uis','SELECT COUNT(*) FROM ',$sql);
  357. // fix by alexander zhukov, alex#unipack.ru, because count(*) and 'order by' fails
  358. // with mssql, access and postgresql. Also a good speedup optimization - skips sorting!
  359. // also see http://phplens.com/lens/lensforum/msgs.php?id=12752
  360. $rewritesql = adodb_strip_order_by($rewritesql);
  361. }
  362. if (isset($rewritesql) && $rewritesql != $sql) {
  363. if (preg_match('/\sLIMIT\s+[0-9]+/i',$sql,$limitarr)) $rewritesql .= $limitarr[0];
  364. if ($secs2cache) {
  365. // we only use half the time of secs2cache because the count can quickly
  366. // become inaccurate if new records are added
  367. $qryRecs = $zthis->CacheGetOne($secs2cache/2,$rewritesql,$inputarr);
  368. } else {
  369. $qryRecs = $zthis->GetOne($rewritesql,$inputarr);
  370. }
  371. if ($qryRecs !== false) return $qryRecs;
  372. }
  373. //--------------------------------------------
  374. // query rewrite failed - so try slower way...
  375. // strip off unneeded ORDER BY if no UNION
  376. if (preg_match('/\s*UNION\s*/is', $sql)) $rewritesql = $sql;
  377. else $rewritesql = $rewritesql = adodb_strip_order_by($sql);
  378. if (preg_match('/\sLIMIT\s+[0-9]+/i',$sql,$limitarr)) $rewritesql .= $limitarr[0];
  379. $rstest = $zthis->Execute($rewritesql,$inputarr);
  380. if (!$rstest) $rstest = $zthis->Execute($sql,$inputarr);
  381. if ($rstest) {
  382. $qryRecs = $rstest->RecordCount();
  383. if ($qryRecs == -1) {
  384. global $ADODB_EXTENSION;
  385. // some databases will return -1 on MoveLast() - change to MoveNext()
  386. if ($ADODB_EXTENSION) {
  387. while(!$rstest->EOF) {
  388. adodb_movenext($rstest);
  389. }
  390. } else {
  391. while(!$rstest->EOF) {
  392. $rstest->MoveNext();
  393. }
  394. }
  395. $qryRecs = $rstest->_currentRow;
  396. }
  397. $rstest->Close();
  398. if ($qryRecs == -1) return 0;
  399. }
  400. return $qryRecs;
  401. }
  402. /*
  403. Code originally from "Cornel G" <conyg@fx.ro>
  404. This code might not work with SQL that has UNION in it
  405. Also if you are using CachePageExecute(), there is a strong possibility that
  406. data will get out of synch. use CachePageExecute() only with tables that
  407. rarely change.
  408. */
  409. function _adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page,
  410. $inputarr=false, $secs2cache=0)
  411. {
  412. $atfirstpage = false;
  413. $atlastpage = false;
  414. $lastpageno=1;
  415. // If an invalid nrows is supplied,
  416. // we assume a default value of 10 rows per page
  417. if (!isset($nrows) || $nrows <= 0) $nrows = 10;
  418. $qryRecs = false; //count records for no offset
  419. $qryRecs = _adodb_getcount($zthis,$sql,$inputarr,$secs2cache);
  420. $lastpageno = (int) ceil($qryRecs / $nrows);
  421. $zthis->_maxRecordCount = $qryRecs;
  422. // ***** Here we check whether $page is the last page or
  423. // whether we are trying to retrieve
  424. // a page number greater than the last page number.
  425. if ($page >= $lastpageno) {
  426. $page = $lastpageno;
  427. $atlastpage = true;
  428. }
  429. // If page number <= 1, then we are at the first page
  430. if (empty($page) || $page <= 1) {
  431. $page = 1;
  432. $atfirstpage = true;
  433. }
  434. // We get the data we want
  435. $offset = $nrows * ($page-1);
  436. if ($secs2cache > 0)
  437. $rsreturn = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);
  438. else
  439. $rsreturn = $zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
  440. // Before returning the RecordSet, we set the pagination properties we need
  441. if ($rsreturn) {
  442. $rsreturn->_maxRecordCount = $qryRecs;
  443. $rsreturn->rowsPerPage = $nrows;
  444. $rsreturn->AbsolutePage($page);
  445. $rsreturn->AtFirstPage($atfirstpage);
  446. $rsreturn->AtLastPage($atlastpage);
  447. $rsreturn->LastPageNo($lastpageno);
  448. }
  449. return $rsreturn;
  450. }
  451. // Iván Oliva version
  452. function _adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputarr=false, $secs2cache=0)
  453. {
  454. $atfirstpage = false;
  455. $atlastpage = false;
  456. if (!isset($page) || $page <= 1) { // If page number <= 1, then we are at the first page
  457. $page = 1;
  458. $atfirstpage = true;
  459. }
  460. if ($nrows <= 0) $nrows = 10; // If an invalid nrows is supplied, we assume a default value of 10 rows per page
  461. // ***** Here we check whether $page is the last page or whether we are trying to retrieve a page number greater than
  462. // the last page number.
  463. $pagecounter = $page + 1;
  464. $pagecounteroffset = ($pagecounter * $nrows) - $nrows;
  465. if ($secs2cache>0) $rstest = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
  466. else $rstest = $zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
  467. if ($rstest) {
  468. while ($rstest && $rstest->EOF && $pagecounter>0) {
  469. $atlastpage = true;
  470. $pagecounter--;
  471. $pagecounteroffset = $nrows * ($pagecounter - 1);
  472. $rstest->Close();
  473. if ($secs2cache>0) $rstest = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
  474. else $rstest = $zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
  475. }
  476. if ($rstest) $rstest->Close();
  477. }
  478. if ($atlastpage) { // If we are at the last page or beyond it, we are going to retrieve it
  479. $page = $pagecounter;
  480. if ($page == 1) $atfirstpage = true; // We have to do this again in case the last page is the same as the first
  481. //... page, that is, the recordset has only 1 page.
  482. }
  483. // We get the data we want
  484. $offset = $nrows * ($page-1);
  485. if ($secs2cache > 0) $rsreturn = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);
  486. else $rsreturn = $zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
  487. // Before returning the RecordSet, we set the pagination properties we need
  488. if ($rsreturn) {
  489. $rsreturn->rowsPerPage = $nrows;
  490. $rsreturn->AbsolutePage($page);
  491. $rsreturn->AtFirstPage($atfirstpage);
  492. $rsreturn->AtLastPage($atlastpage);
  493. }
  494. return $rsreturn;
  495. }
  496. function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq=false,$force=2)
  497. {
  498. global $ADODB_QUOTE_FIELDNAMES;
  499. if (!$rs) {
  500. printf(ADODB_BAD_RS,'GetUpdateSQL');
  501. return false;
  502. }
  503. $fieldUpdatedCount = 0;
  504. $arrFields = _array_change_key_case($arrFields);
  505. $hasnumeric = isset($rs->fields[0]);
  506. $setFields = '';
  507. // Loop through all of the fields in the recordset
  508. for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
  509. // Get the field from the recordset
  510. $field = $rs->FetchField($i);
  511. // If the recordset field is one
  512. // of the fields passed in then process.
  513. $upperfname = strtoupper($field->name);
  514. if (adodb_key_exists($upperfname,$arrFields,$force)) {
  515. // If the existing field value in the recordset
  516. // is different from the value passed in then
  517. // go ahead and append the field name and new value to
  518. // the update query.
  519. if ($hasnumeric) $val = $rs->fields[$i];
  520. else if (isset($rs->fields[$upperfname])) $val = $rs->fields[$upperfname];
  521. else if (isset($rs->fields[$field->name])) $val = $rs->fields[$field->name];
  522. else if (isset($rs->fields[strtolower($upperfname)])) $val = $rs->fields[strtolower($upperfname)];
  523. else $val = '';
  524. if ($forceUpdate || strcmp($val, $arrFields[$upperfname])) {
  525. // Set the counter for the number of fields that will be updated.
  526. $fieldUpdatedCount++;
  527. // Based on the datatype of the field
  528. // Format the value properly for the database
  529. $type = $rs->MetaType($field->type);
  530. if ($type == 'null') {
  531. $type = 'C';
  532. }
  533. if ((strpos($upperfname,' ') !== false) || ($ADODB_QUOTE_FIELDNAMES))
  534. $fnameq = $zthis->nameQuote.$upperfname.$zthis->nameQuote;
  535. else
  536. $fnameq = $upperfname;
  537. // is_null requires php 4.0.4
  538. //********************************************************//
  539. if (is_null($arrFields[$upperfname])
  540. || (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0)
  541. || $arrFields[$upperfname] === $zthis->null2null
  542. )
  543. {
  544. switch ($force) {
  545. //case 0:
  546. // //Ignore empty values. This is allready handled in "adodb_key_exists" function.
  547. //break;
  548. case 1:
  549. //Set null
  550. $setFields .= $field->name . " = null, ";
  551. break;
  552. case 2:
  553. //Set empty
  554. $arrFields[$upperfname] = "";
  555. $setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq,$arrFields, $magicq);
  556. break;
  557. default:
  558. case 3:
  559. //Set the value that was given in array, so you can give both null and empty values
  560. if (is_null($arrFields[$upperfname]) || $arrFields[$upperfname] === $zthis->null2null) {
  561. $setFields .= $field->name . " = null, ";
  562. } else {
  563. $setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq,$arrFields, $magicq);
  564. }
  565. break;
  566. }
  567. //********************************************************//
  568. } else {
  569. //we do this so each driver can customize the sql for
  570. //DB specific column types.
  571. //Oracle needs BLOB types to be handled with a returning clause
  572. //postgres has special needs as well
  573. $setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq,
  574. $arrFields, $magicq);
  575. }
  576. }
  577. }
  578. }
  579. // If there were any modified fields then build the rest of the update query.
  580. if ($fieldUpdatedCount > 0 || $forceUpdate) {
  581. // Get the table name from the existing query.
  582. if (!empty($rs->tableName)) $tableName = $rs->tableName;
  583. else {
  584. preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName);
  585. $tableName = $tableName[1];
  586. }
  587. // Get the full where clause excluding the word "WHERE" from
  588. // the existing query.
  589. preg_match('/\sWHERE\s(.*)/is', $rs->sql, $whereClause);
  590. $discard = false;
  591. // not a good hack, improvements?
  592. if ($whereClause) {
  593. #var_dump($whereClause);
  594. if (preg_match('/\s(ORDER\s.*)/is', $whereClause[1], $discard));
  595. else if (preg_match('/\s(LIMIT\s.*)/is', $whereClause[1], $discard));
  596. else if (preg_match('/\s(FOR UPDATE.*)/is', $whereClause[1], $discard));
  597. else preg_match('/\s.*(\) WHERE .*)/is', $whereClause[1], $discard); # see http://sourceforge.net/tracker/index.php?func=detail&aid=1379638&group_id=42718&atid=433976
  598. } else
  599. $whereClause = array(false,false);
  600. if ($discard)
  601. $whereClause[1] = substr($whereClause[1], 0, strlen($whereClause[1]) - strlen($discard[1]));
  602. $sql = 'UPDATE '.$tableName.' SET '.substr($setFields, 0, -2);
  603. if (strlen($whereClause[1]) > 0)
  604. $sql .= ' WHERE '.$whereClause[1];
  605. return $sql;
  606. } else {
  607. return false;
  608. }
  609. }
  610. function adodb_key_exists($key, &$arr,$force=2)
  611. {
  612. if ($force<=0) {
  613. // the following is the old behaviour where null or empty fields are ignored
  614. return (!empty($arr[$key])) || (isset($arr[$key]) && strlen($arr[$key])>0);
  615. }
  616. if (isset($arr[$key])) return true;
  617. ## null check below
  618. if (ADODB_PHPVER >= 0x4010) return array_key_exists($key,$arr);
  619. return false;
  620. }
  621. /**
  622. * There is a special case of this function for the oci8 driver.
  623. * The proper way to handle an insert w/ a blob in oracle requires
  624. * a returning clause with bind variables and a descriptor blob.
  625. *
  626. *
  627. */
  628. function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false,$force=2)
  629. {
  630. static $cacheRS = false;
  631. static $cacheSig = 0;
  632. static $cacheCols;
  633. global $ADODB_QUOTE_FIELDNAMES;
  634. $tableName = '';
  635. $values = '';
  636. $fields = '';
  637. $recordSet = null;
  638. $arrFields = _array_change_key_case($arrFields);
  639. $fieldInsertedCount = 0;
  640. if (is_string($rs)) {
  641. //ok we have a table name
  642. //try and get the column info ourself.
  643. $tableName = $rs;
  644. //we need an object for the recordSet
  645. //because we have to call MetaType.
  646. //php can't do a $rsclass::MetaType()
  647. $rsclass = $zthis->rsPrefix.$zthis->databaseType;
  648. $recordSet = new $rsclass(-1,$zthis->fetchMode);
  649. $recordSet->connection = $zthis;
  650. if (is_string($cacheRS) && $cacheRS == $rs) {
  651. $columns = $cacheCols;
  652. } else {
  653. $columns = $zthis->MetaColumns( $tableName );
  654. $cacheRS = $tableName;
  655. $cacheCols = $columns;
  656. }
  657. } else if (is_subclass_of($rs, 'adorecordset')) {
  658. if (isset($rs->insertSig) && is_integer($cacheRS) && $cacheRS == $rs->insertSig) {
  659. $columns = $cacheCols;
  660. } else {
  661. for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++)
  662. $columns[] = $rs->FetchField($i);
  663. $cacheRS = $cacheSig;
  664. $cacheCols = $columns;
  665. $rs->insertSig = $cacheSig++;
  666. }
  667. $recordSet = $rs;
  668. } else {
  669. printf(ADODB_BAD_RS,'GetInsertSQL');
  670. return false;
  671. }
  672. // Loop through all of the fields in the recordset
  673. foreach( $columns as $field ) {
  674. $upperfname = strtoupper($field->name);
  675. if (adodb_key_exists($upperfname,$arrFields,$force)) {
  676. $bad = false;
  677. if ((strpos($upperfname,' ') !== false) || ($ADODB_QUOTE_FIELDNAMES))
  678. $fnameq = $zthis->nameQuote.$upperfname.$zthis->nameQuote;
  679. else
  680. $fnameq = $upperfname;
  681. $type = $recordSet->MetaType($field->type);
  682. /********************************************************/
  683. if (is_null($arrFields[$upperfname])
  684. || (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0)
  685. || $arrFields[$upperfname] === $zthis->null2null
  686. )
  687. {
  688. switch ($force) {
  689. case 0: // we must always set null if missing
  690. $bad = true;
  691. break;
  692. case 1:
  693. $values .= "null, ";
  694. break;
  695. case 2:
  696. //Set empty
  697. $arrFields[$upperfname] = "";
  698. $values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq,$arrFields, $magicq);
  699. break;
  700. default:
  701. case 3:
  702. //Set the value that was given in array, so you can give both null and empty values
  703. if (is_null($arrFields[$upperfname]) || $arrFields[$upperfname] === $zthis->null2null) {
  704. $values .= "null, ";
  705. } else {
  706. $values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq, $arrFields, $magicq);
  707. }
  708. break;
  709. } // switch
  710. /*********************************************************/
  711. } else {
  712. //we do this so each driver can customize the sql for
  713. //DB specific column types.
  714. //Oracle needs BLOB types to be handled with a returning clause
  715. //postgres has special needs as well
  716. $values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq,
  717. $arrFields, $magicq);
  718. }
  719. if ($bad) continue;
  720. // Set the counter for the number of fields that will be inserted.
  721. $fieldInsertedCount++;
  722. // Get the name of the fields to insert
  723. $fields .= $fnameq . ", ";
  724. }
  725. }
  726. // If there were any inserted fields then build the rest of the insert query.
  727. if ($fieldInsertedCount <= 0) return false;
  728. // Get the table name from the existing query.
  729. if (!$tableName) {
  730. if (!empty($rs->tableName)) $tableName = $rs->tableName;
  731. else if (preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName))
  732. $tableName = $tableName[1];
  733. else
  734. return false;
  735. }
  736. // Strip off the comma and space on the end of both the fields
  737. // and their values.
  738. $fields = substr($fields, 0, -2);
  739. $values = substr($values, 0, -2);
  740. // Append the fields and their values to the insert query.
  741. return 'INSERT INTO '.$tableName.' ( '.$fields.' ) VALUES ( '.$values.' )';
  742. }
  743. /**
  744. * This private method is used to help construct
  745. * the update/sql which is generated by GetInsertSQL and GetUpdateSQL.
  746. * It handles the string construction of 1 column -> sql string based on
  747. * the column type. We want to do 'safe' handling of BLOBs
  748. *
  749. * @param string the type of sql we are trying to create
  750. * 'I' or 'U'.
  751. * @param string column data type from the db::MetaType() method
  752. * @param string the column name
  753. * @param array the column value
  754. *
  755. * @return string
  756. *
  757. */
  758. function _adodb_column_sql_oci8(&$zthis,$action, $type, $fname, $fnameq, $arrFields, $magicq)
  759. {
  760. $sql = '';
  761. // Based on the datatype of the field
  762. // Format the value properly for the database
  763. switch($type) {
  764. case 'B':
  765. //in order to handle Blobs correctly, we need
  766. //to do some magic for Oracle
  767. //we need to create a new descriptor to handle
  768. //this properly
  769. if (!empty($zthis->hasReturningInto)) {
  770. if ($action == 'I') {
  771. $sql = 'empty_blob(), ';
  772. } else {
  773. $sql = $fnameq. '=empty_blob(), ';
  774. }
  775. //add the variable to the returning clause array
  776. //so the user can build this later in
  777. //case they want to add more to it
  778. $zthis->_returningArray[$fname] = ':xx'.$fname.'xx';
  779. } else if (empty($arrFields[$fname])){
  780. if ($action == 'I') {
  781. $sql = 'empty_blob(), ';
  782. } else {
  783. $sql = $fnameq. '=empty_blob(), ';
  784. }
  785. } else {
  786. //this is to maintain compatibility
  787. //with older adodb versions.
  788. $sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false);
  789. }
  790. break;
  791. case "X":
  792. //we need to do some more magic here for long variables
  793. //to handle these correctly in oracle.
  794. //create a safe bind var name
  795. //to avoid conflicts w/ dupes.
  796. if (!empty($zthis->hasReturningInto)) {
  797. if ($action == 'I') {
  798. $sql = ':xx'.$fname.'xx, ';
  799. } else {
  800. $sql = $fnameq.'=:xx'.$fname.'xx, ';
  801. }
  802. //add the variable to the returning clause array
  803. //so the user can build this later in
  804. //case they want to add more to it
  805. $zthis->_returningArray[$fname] = ':xx'.$fname.'xx';
  806. } else {
  807. //this is to maintain compatibility
  808. //with older adodb versions.
  809. $sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false);
  810. }
  811. break;
  812. default:
  813. $sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false);
  814. break;
  815. }
  816. return $sql;
  817. }
  818. function _adodb_column_sql(&$zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq, $recurse=true)
  819. {
  820. if ($recurse) {
  821. switch($zthis->dataProvider) {
  822. case 'postgres':
  823. if ($type == 'L') $type = 'C';
  824. break;
  825. case 'oci8':
  826. return _adodb_column_sql_oci8($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq);
  827. }
  828. }
  829. switch($type) {
  830. case "C":
  831. case "X":
  832. case 'B':
  833. $val = $zthis->qstr($arrFields[$fname],$magicq);
  834. break;
  835. case "D":
  836. $val = $zthis->DBDate($arrFields[$fname]);
  837. break;
  838. case "T":
  839. $val = $zthis->DBTimeStamp($arrFields[$fname]);
  840. break;
  841. case "N":
  842. $val = $arrFields[$fname];
  843. if (!is_numeric($val)) $val = str_replace(',', '.', (float)$val);
  844. break;
  845. case "I":
  846. case "R":
  847. $val = $arrFields[$fname];
  848. if (!is_numeric($val)) $val = (integer) $val;
  849. break;
  850. default:
  851. $val = str_replace(array("'"," ","("),"",$arrFields[$fname]); // basic sql injection defence
  852. if (empty($val)) $val = '0';
  853. break;
  854. }
  855. if ($action == 'I') return $val . ", ";
  856. return $fnameq . "=" . $val . ", ";
  857. }
  858. function _adodb_debug_execute(&$zthis, $sql, $inputarr)
  859. {
  860. $ss = '';
  861. if ($inputarr) {
  862. foreach($inputarr as $kk=>$vv) {
  863. if (is_string($vv) && strlen($vv)>64) $vv = substr($vv,0,64).'...';
  864. if (is_null($vv)) $ss .= "($kk=>null) ";
  865. else $ss .= "($kk=>'$vv') ";
  866. }
  867. $ss = "[ $ss ]";
  868. }
  869. $sqlTxt = is_array($sql) ? $sql[0] : $sql;
  870. /*str_replace(', ','##1#__^LF',is_array($sql) ? $sql[0] : $sql);
  871. $sqlTxt = str_replace(',',', ',$sqlTxt);
  872. $sqlTxt = str_replace('##1#__^LF', ', ' ,$sqlTxt);
  873. */
  874. // check if running from browser or command-line
  875. $inBrowser = isset($_SERVER['HTTP_USER_AGENT']);
  876. $dbt = $zthis->databaseType;
  877. if (isset($zthis->dsnType)) $dbt .= '-'.$zthis->dsnType;
  878. if ($inBrowser) {
  879. if ($ss) {
  880. $ss = '<code>'.htmlspecialchars($ss).'</code>';
  881. }
  882. if ($zthis->debug === -1)
  883. ADOConnection::outp( "<br>\n($dbt): ".htmlspecialchars($sqlTxt)." &nbsp; $ss\n<br>\n",false);
  884. else if ($zthis->debug !== -99)
  885. ADOConnection::outp( "<hr>\n($dbt): ".htmlspecialchars($sqlTxt)." &nbsp; $ss\n<hr>\n",false);
  886. } else {
  887. $ss = "\n ".$ss;
  888. if ($zthis->debug !== -99)
  889. ADOConnection::outp("-----<hr>\n($dbt): ".$sqlTxt." $ss\n-----<hr>\n",false);
  890. }
  891. $qID = $zthis->_query($sql,$inputarr);
  892. /*
  893. Alexios Fakios notes that ErrorMsg() must be called before ErrorNo() for mssql
  894. because ErrorNo() calls Execute('SELECT @ERROR'), causing recursion
  895. */
  896. if ($zthis->databaseType == 'mssql') {
  897. // ErrorNo is a slow function call in mssql, and not reliable in PHP 4.0.6
  898. if($emsg = $zthis->ErrorMsg()) {
  899. if ($err = $zthis->ErrorNo()) {
  900. if ($zthis->debug === -99)
  901. ADOConnection::outp( "<hr>\n($dbt): ".htmlspecialchars($sqlTxt)." &nbsp; $ss\n<hr>\n",false);
  902. ADOConnection::outp($err.': '.$emsg);
  903. }
  904. }
  905. } else if (!$qID) {
  906. if ($zthis->debug === -99)
  907. if ($inBrowser) ADOConnection::outp( "<hr>\n($dbt): ".htmlspecialchars($sqlTxt)." &nbsp; $ss\n<hr>\n",false);
  908. else ADOConnection::outp("-----<hr>\n($dbt): ".$sqlTxt."$ss\n-----<hr>\n",false);
  909. ADOConnection::outp($zthis->ErrorNo() .': '. $zthis->ErrorMsg());
  910. }
  911. if ($zthis->debug === 99) _adodb_backtrace(true,9999,2);
  912. return $qID;
  913. }
  914. # pretty print the debug_backtrace function
  915. function _adodb_backtrace($printOrArr=true,$levels=9999,$skippy=0,$ishtml=null)
  916. {
  917. if (!function_exists('debug_backtrace')) return '';
  918. if ($ishtml === null) $html = (isset($_SERVER['HTTP_USER_AGENT']));
  919. else $html = $ishtml;
  920. $fmt = ($html) ? "</font><font color=#808080 size=-1> %% line %4d, file: <a href=\"file:/%s\">%s</a></font>" : "%% line %4d, file: %s";
  921. $MAXSTRLEN = 128;
  922. $s = ($html) ? '<pre align=left>' : '';
  923. if (is_array($printOrArr)) $traceArr = $printOrArr;
  924. else $traceArr = debug_backtrace();
  925. array_shift($traceArr);
  926. array_shift($traceArr);
  927. $tabs = sizeof($traceArr)-2;
  928. foreach ($traceArr as $arr) {
  929. if ($skippy) {$skippy -= 1; continue;}
  930. $levels -= 1;
  931. if ($levels < 0) break;
  932. $args = array();
  933. for ($i=0; $i < $tabs; $i++) $s .= ($html) ? ' &nbsp; ' : "\t";
  934. $tabs -= 1;
  935. if ($html) $s .= '<font face="Courier New,Courier">';
  936. if (isset($arr['class'])) $s .= $arr['class'].'.';
  937. if (isset($arr['args']))
  938. foreach($arr['args'] as $v) {
  939. if (is_null($v)) $args[] = 'null';
  940. else if (is_array($v)) $args[] = 'Array['.sizeof($v).']';
  941. else if (is_object($v)) $args[] = 'Object:'.get_class($v);
  942. else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
  943. else {
  944. $v = (string) @$v;
  945. $str = htmlspecialchars(str_replace(array("\r","\n"),' ',substr($v,0,$MAXSTRLEN)));
  946. if (strlen($v) > $MAXSTRLEN) $str .= '...';
  947. $args[] = $str;
  948. }
  949. }
  950. $s .= $arr['function'].'('.implode(', ',$args).')';
  951. $s .= @sprintf($fmt, $arr['line'],$arr['file'],basename($arr['file']));
  952. $s .= "\n";
  953. }
  954. if ($html) $s .= '</pre>';
  955. if ($printOrArr) print $s;
  956. return $s;
  957. }
  958. /*
  959. function _adodb_find_from($sql)
  960. {
  961. $sql = str_replace(array("\n","\r"), ' ', $sql);
  962. $charCount = strlen($sql);
  963. $inString = false;
  964. $quote = '';
  965. $parentheseCount = 0;
  966. $prevChars = '';
  967. $nextChars = '';
  968. for($i = 0; $i < $charCount; $i++) {
  969. $char = substr($sql,$i,1);
  970. $prevChars = substr($sql,0,$i);
  971. $nextChars = substr($sql,$i+1);
  972. if((($char == "'" || $char == '"' || $char == '`') && substr($prevChars,-1,1) != '\\') && $inString === false) {
  973. $quote = $char;
  974. $inString = true;
  975. }
  976. elseif((($char == "'" || $char == '"' || $char == '`') && substr($prevChars,-1,1) != '\\') && $inString === true && $quote == $char) {
  977. $quote = "";
  978. $inString = false;
  979. }
  980. elseif($char == "(" && $inString === false)
  981. $parentheseCount++;
  982. elseif($char == ")" && $inString === false && $parentheseCount > 0)
  983. $parentheseCount--;
  984. elseif($parentheseCount <= 0 && $inString === false && $char == " " && strtoupper(substr($prevChars,-5,5)) == " FROM")
  985. return $i;
  986. }
  987. }
  988. */
  989. ?>