Data_Source.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  1. <?php
  2. Lib::loadClass('SqlQueryWhereBuilder');
  3. /**
  4. * API:
  5. * get($field_name) - source field value
  6. * get_item($id) - get item by ID
  7. */
  8. class Data_Source {
  9. var $_db;
  10. var $_tbl;// sql table name, TODO: or zasob ID
  11. var $_default_sql_limit;
  12. var $_fields_type;// array of fields ( name => type )
  13. var $_fields_perm;// array of field perm ( name => perm )
  14. var $_cols = array();
  15. var $_vCols = array();// setVirtualCols - TODO: use Typespecial
  16. var $_col_types = array();// TODO: array( col_name => TYPE )
  17. var $_sql_where;// sql where
  18. var $_sql_limit;
  19. var $_sql_offset;
  20. var $_sql_left_join;// TODO: left join in table
  21. var $_isAccessFltrAllowed = null;
  22. private $_geomFields = array();
  23. private $_fieldOwner = null;
  24. private $_fieldGroupWrite = null;
  25. private $_fieldGroupRead = null;
  26. function __construct($db = null) {
  27. if ($db) {
  28. $this->_db = DB::getDB($db);
  29. } else {
  30. $this->_db = DB::getDB();
  31. }
  32. $this->_default_sql_limit = 10;
  33. $this->_geomFields = array('the_geom');
  34. }
  35. function set_table($tbl) {// TODO: RMME
  36. $this->setTable($tbl);
  37. }
  38. public function setTable($tbl) {
  39. $this->_tbl = $tbl;
  40. $this->_fields_type = array();
  41. $this->_fields_perm = array();
  42. }
  43. function get_cols() {
  44. // TODO: cache in session
  45. if (empty($this->_cols)) {
  46. if (!$this->_tbl) {
  47. return $this->_tbl;
  48. }
  49. $sql = "show fields from `{$this->_tbl}` ; ";
  50. $res = $this->_db->query($sql);
  51. while ($r = $this->_db->fetch($res)) {
  52. $this->_cols[$r->Field] = $r->Field;
  53. $this->_col_types[$r->Field] = $r->Type . ';' . $r->Default;
  54. }
  55. }
  56. return $this->_cols;
  57. }
  58. public function getFieldTypes() {
  59. $fieldTypes = array();
  60. //$dbID = $this->getDB();
  61. $db = $this->_db;//(TableAcl) DB::getDB($dbID);
  62. $tblName = $this->_tbl;//(TableAcl) $this->getName();
  63. if (!$db) {
  64. throw new Exception('DataSource is not defined');
  65. }
  66. $res = $db->query("show fields from `{$tblName}` ");
  67. while ($h = $db->fetch_row($res)) {
  68. $fieldName = $h[0];
  69. $fieldType = $h[1];
  70. $fieldTypes[$fieldName] = array('type'=>$h[1], 'null'=>('YES' == $h[2]), 'default'=>$h[4]);
  71. }
  72. return $fieldTypes;
  73. }
  74. public function getUniqueKeys() {
  75. $sqlKeys = array();
  76. //$dbID = $this->getDB();
  77. $db = $this->_db;//(TableAcl) DB::getDB($dbID);
  78. $tblName = $this->_tbl;//(TableAcl) $this->getName();
  79. if (!$db) {
  80. throw new Exception('DataSource is not defined');
  81. }
  82. $sql = "SHOW KEYS FROM `{$tblName}`";
  83. $res = $db->query($sql);
  84. while ($r = $db->fetch($res)) {
  85. if ($r->Non_unique == '0') {
  86. $sqlKeys[$r->Column_name] = true;
  87. }
  88. }
  89. $sqlKeys = array_keys($sqlKeys);
  90. return $sqlKeys;
  91. }
  92. function set_cols($cols) {// TODO: RMME
  93. $this->setCols($cols);
  94. }
  95. function setCols($cols) {
  96. foreach ($cols as $v_field_name) {
  97. $this->_cols[$v_field_name] = $v_field_name;
  98. }
  99. }
  100. public function setColTypes($types) {
  101. $this->_col_types = $types;
  102. // TableAcl->getTypes(): $this->_types[$fieldName] = array('type'=>$h[1], 'null'=>('YES' == $h[2]), 'default'=>$h[4]);
  103. }
  104. public function getColDefault($fieldName) {
  105. $fldType = V::get($fieldName, '', $this->_col_types);
  106. if (!$fldType) return '';
  107. return V::get('default', '', $fldType);
  108. }
  109. function setVirtualCols($cols) {
  110. foreach ($cols as $v_field_name) {
  111. $this->_vCols[$v_field_name] = $v_field_name;
  112. }
  113. }
  114. public function setFieldGroupWrite($fieldName, $fieldExists = false) {
  115. if ($fieldExists) {
  116. $this->_fieldGroupWrite = $fieldName;
  117. $this->_cols[$fieldName] = $fieldName;
  118. }
  119. }
  120. public function setFieldGroupRead($fieldName, $fieldExists = false) {
  121. if ($fieldExists) {
  122. $this->_fieldGroupRead = $fieldName;
  123. $this->_cols[$fieldName] = $fieldName;
  124. }
  125. }
  126. public function setFieldOwner($fieldName, $fieldExists = false) {
  127. if ($fieldExists) {
  128. $this->_fieldOwner = $fieldName;
  129. $this->_cols[$fieldName] = $fieldName;
  130. }
  131. }
  132. public function getFieldGroupWrite() {
  133. return $this->_fieldGroupWrite;
  134. }
  135. public function getFieldGroupRead() {
  136. return $this->_fieldGroupRead;
  137. }
  138. public function getFieldOwner() {
  139. return $this->_fieldOwner;
  140. }
  141. function _get_sql_cols() {
  142. $sql_cols = "t.*";
  143. if (!empty($this->_cols)) {
  144. $sql_cols_arr = array();
  145. foreach ($this->_cols as $k_field => $v_field_label) {
  146. if ($this->isGeomField($k_field)) {
  147. $sqlFld = "AsWKT(t.`{$k_field}`) as {$k_field}";
  148. } else {
  149. $sqlFld = "t.`{$k_field}`";
  150. }
  151. $sql_cols_arr[] = $sqlFld;
  152. }
  153. $sql_cols = implode(", ", $sql_cols_arr);
  154. }
  155. if(V::get('DBG_DS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql_cols (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql_cols);echo'</pre>'."\n\n";}
  156. return $sql_cols;
  157. }
  158. public function setAccessFltrAllowed($isAccessFltrAllowed) {
  159. $this->_isAccessFltrAllowed = $isAccessFltrAllowed;
  160. }
  161. public function isAccessFltrAllowed() {
  162. if (false === $this->_isAccessFltrAllowed) {
  163. return false;
  164. }
  165. else if ($this->hasAclGroupFields()) {
  166. return true;
  167. }
  168. return false;
  169. }
  170. public function hasAclGroupFields() {
  171. if ( !empty($this->_fieldGroupWrite)
  172. && !empty($this->_fieldGroupRead)
  173. && array_key_exists('A_ADM_COMPANY', $this->_cols)
  174. && array_key_exists('A_CLASSIFIED', $this->_cols)
  175. ) {
  176. return true;
  177. }
  178. return false;
  179. }
  180. function getSpecialFilters() {
  181. $fltrs = array();
  182. if (array_key_exists('A_PROBLEM', $this->_cols)) {
  183. $fltrs['Problemy'] = new stdClass();
  184. $fltrs['Problemy']->icon = 'glyphicon glyphicon-warning-sign';
  185. $fltrs['Problemy']->btns = array();
  186. $fltrs['Problemy']->btns['PROBLEMY'] = (object)array('value'=>'PROBLEM');
  187. $fltrs['Problemy']->btns['OSTRZEZENIA'] = (object)array('value'=>'WARNING');
  188. $fltrs['Problemy']->btns['BEZ_PROBLEM.'] = (object)array('value'=>'NORMAL');
  189. }
  190. if (array_key_exists('A_STATUS', $this->_cols)) {
  191. $fltrs['Status'] = new stdClass();
  192. $fltrs['Status']->icon = 'glyphicon glyphicon-question-sign';
  193. $fltrs['Status']->btns = array();
  194. $fltrs['Status']->btns['OCZEKUJACY'] = (object)array('value'=>'WAITING');
  195. $fltrs['Status']->btns['AKTYWNI'] = (object)array('value'=>'AKTYWNI');
  196. }
  197. if (array_key_exists('L_APPOITMENT_DATE', $this->_cols)) {
  198. $fltrs['Spotkania'] = new stdClass();
  199. $fltrs['Spotkania']->icon = 'glyphicon glyphicon-calendar';
  200. $fltrs['Spotkania']->btns = array();
  201. $fltrs['Spotkania']->btns['STARE'] = (object)array('value'=>'OLD');
  202. $fltrs['Spotkania']->btns['ZARAZ'] = (object)array('value'=>'NOW');
  203. $fltrs['Spotkania']->btns['DZISIAJ'] = (object)array('value'=>'TODAY');
  204. $fltrs['Spotkania']->btns['BRAK'] = (object)array('value'=>'BRAK');
  205. }
  206. if ($this->isAccessFltrAllowed()) {
  207. $fltrs['Access'] = new stdClass();
  208. $fltrs['Access']->icon = 'glyphicon glyphicon-lock';
  209. $fltrs['Access']->btns = array();
  210. $fltrs['Access']->btns['Pokaż'] = (object)array('value'=>'SHOW');
  211. }
  212. return $fltrs;
  213. }
  214. public function _parseOgcFilter($ogcFilter) {
  215. $ogcFilterXmlString = <<<OGC_FILTER_XML_FILE
  216. <?xml version="1.0" encoding="UTF-8"?>
  217. <filter xmlns="https://biuro.biall-net.pl/SE/version-git/schema/filter.xsd"
  218. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  219. xmlns:ogc="http://www.opengis.net/ogc">
  220. {$ogcFilter}
  221. </filter>
  222. OGC_FILTER_XML_FILE;
  223. $convertedGuiXml = $this->_convertGuiXmlToCmdList($ogcFilterXmlString);
  224. DBG::_('DBG_DS_OGC', '>1', "convertedGuiXml(".strlen($convertedGuiXml).")", $convertedGuiXml, __CLASS__, __FUNCTION__, __LINE__);
  225. $tags = array();
  226. $parserXml = xml_parser_create();
  227. xml_parser_set_option($parserXml, XML_OPTION_CASE_FOLDING, 0);
  228. xml_parser_set_option($parserXml, XML_OPTION_SKIP_WHITE, 1);
  229. if (0 == xml_parse_into_struct($parserXml, $convertedGuiXml, $tags)) {
  230. throw new Exception("Parse Request xml error #" . __LINE__ . ": parse converted transaction failed");
  231. }
  232. xml_parser_free($parserXml);
  233. if (empty($tags)) {
  234. throw new Exception("Parse Request xml error #" . __LINE__ . ": parse converted transaction returns empty structure");
  235. }
  236. $queryWhereBuilder = new SqlQueryWhereBuilder();
  237. foreach ($tags as $tag) {
  238. switch ($tag['tag']) {
  239. case 'filter': {// root tag
  240. }
  241. break;
  242. case 'sql_filter_comparisonFieldToValue': {
  243. $fieldName = V::get('fieldName', '', $tag['attributes']);
  244. $comparisonSign = V::get('comparisonSign', '', $tag['attributes']);
  245. $value = V::get('value', '', $tag['attributes']);
  246. DBG::_('DBG_DS_OGC', '>3', "sql_filter_comparisonFieldToValue comparisonSign", $comparisonSign, __CLASS__, __FUNCTION__, __LINE__);
  247. if ('like' == $comparisonSign) {
  248. $wildCard = V::get('wildCard', '', $tag['attributes']);
  249. $singleChar = V::get('singleChar', '', $tag['attributes']);
  250. $escapeChar = V::get('escapeChar', '', $tag['attributes']);
  251. // wildCard="*" singleChar="#" escapeChar="!" => sql: % _ \
  252. // '*ORMA!*' => '%ORMA\*'
  253. // TODO: first replace every escapeChar
  254. $valLength = strlen($value);
  255. $valCharsAllowReplace = array(); for ($i = 0; $i < $valLength; $i++) $valCharsAllowReplace[] = true;
  256. {// escapeChar
  257. $lastOffset = 0;
  258. while (false !== ($pos = strpos($value, $escapeChar, $lastOffset))) {
  259. DBG::_('DBG_DS_OGC', '>3', "sql_filter_comparisonFieldToValue like value({$value}) escapeChar({$escapeChar}) pos({$pos}) lastOffset({$lastOffset})", null, __CLASS__, __FUNCTION__, __LINE__);
  260. $value[$pos] = '\\';
  261. $valCharsAllowReplace[$pos] = false;
  262. if ($pos + 1 < $valLength) $valCharsAllowReplace[$pos + 1] = false;
  263. $lastOffset = $pos + 1;
  264. }
  265. }
  266. {// singleChar
  267. $lastOffset = 0;
  268. while (false !== ($pos = strpos($value, $singleChar, $lastOffset))) {
  269. DBG::_('DBG_DS_OGC', '>3', "sql_filter_comparisonFieldToValue like value({$value}) singleChar({$singleChar}) pos({$pos}) lastOffset({$lastOffset})", null, __CLASS__, __FUNCTION__, __LINE__);
  270. if ($valCharsAllowReplace[$pos]) {
  271. $value[$pos] = '_';
  272. $valCharsAllowReplace[$pos] = false;
  273. }
  274. $lastOffset = $pos + 1;
  275. }
  276. }
  277. {// wildCard
  278. $lastOffset = 0;
  279. while (false !== ($pos = strpos($value, $wildCard, $lastOffset))) {
  280. DBG::_('DBG_DS_OGC', '>3', "sql_filter_comparisonFieldToValue like value({$value}) wildCard({$wildCard}) pos({$pos}) lastOffset({$lastOffset})", null, __CLASS__, __FUNCTION__, __LINE__);
  281. if ($valCharsAllowReplace[$pos]) {
  282. $value[$pos] = '%';
  283. $valCharsAllowReplace[$pos] = false;
  284. }
  285. $lastOffset = $pos + 1;
  286. }
  287. }
  288. }
  289. DBG::_('DBG_DS_OGC', '>3', "sql_filter_comparisonFieldToValue value({$value})", null, __CLASS__, __FUNCTION__, __LINE__);
  290. $queryWhereBuilder->addComparisonFieldToValue($fieldName, $comparisonSign, $value);
  291. }
  292. break;
  293. case 'sql_filter_openBlock': {
  294. $blockType = V::get('type', '', $tag['attributes']);
  295. DBG::_('DBG_DS_OGC', '>2', "sql_filter_openBlock block Type {$blockType} attrs", json_encode($tag), __CLASS__, __FUNCTION__, __LINE__);
  296. $queryWhereBuilder->openBlock($blockType);
  297. }
  298. break;
  299. case 'sql_filter_closeBlock': {
  300. $blockType = V::get('type', '', $tag['attributes']);
  301. $queryWhereBuilder->closeBlock($blockType);
  302. }
  303. break;
  304. default: {
  305. DBG::_('DBG_DS_OGC', '>1', "TODO: tag {$tag['tag']}", $queryWhereBuilder, __CLASS__, __FUNCTION__, __LINE__);
  306. throw new Exception("TODO: tag {$tag['tag']}");
  307. }
  308. }
  309. }
  310. $queryWhereBuilder->parseQueryWhere();
  311. DBG::_('DBG_DS_OGC', '>1', "queryWhereBuilder", $queryWhereBuilder, __CLASS__, __FUNCTION__, __LINE__);
  312. return $queryWhereBuilder->getQueryWhere('t');
  313. }
  314. public function _convertGuiXmlToCmdList($ogcFilterXmlString) {
  315. $convertOgcFilterXslString = <<<XSL_CONVERT_OGC_FILTER_TO_XML_TASK_LIST
  316. <?xml version="1.0" encoding="UTF-8"?>
  317. <xsl:stylesheet version="1.0"
  318. xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  319. xmlns:filter="https://biuro.biall-net.pl/SE/version-git/schema/filter.xsd"
  320. xmlns:ogc="http://www.opengis.net/ogc"
  321. >
  322. <xsl:output method="xml" omit-xml-declaration="yes" indent="no"/>
  323. <xsl:template match="/">
  324. <xsl:element name="filter">
  325. <xsl:apply-templates select="filter:filter/ogc:Filter"/>
  326. </xsl:element>
  327. </xsl:template>
  328. <xsl:template match="ogc:Filter">
  329. <xsl:apply-templates/>
  330. </xsl:template>
  331. <xsl:template match="ogc:Or">
  332. <xsl:element name="sql_filter_openBlock">
  333. <xsl:attribute name="type"><xsl:value-of select="'or'" /></xsl:attribute>
  334. </xsl:element>
  335. <xsl:apply-templates/>
  336. <xsl:element name="sql_filter_closeBlock">
  337. <xsl:attribute name="type"><xsl:value-of select="'or'" /></xsl:attribute>
  338. </xsl:element>
  339. </xsl:template>
  340. <xsl:template match="ogc:And">
  341. <xsl:element name="sql_filter_openBlock">
  342. <xsl:attribute name="type"><xsl:value-of select="'and'" /></xsl:attribute>
  343. </xsl:element>
  344. <xsl:apply-templates/>
  345. <xsl:element name="sql_filter_closeBlock">
  346. <xsl:attribute name="type"><xsl:value-of select="'and'" /></xsl:attribute>
  347. </xsl:element>
  348. </xsl:template>
  349. <xsl:template match="ogc:PropertyIsEqualTo">
  350. <xsl:element name="sql_filter_comparisonFieldToValue">
  351. <xsl:attribute name="fieldName"><xsl:value-of select="ogc:PropertyName" /></xsl:attribute>
  352. <xsl:attribute name="comparisonSign"><xsl:value-of select="'='" /></xsl:attribute>
  353. <xsl:attribute name="value"><xsl:value-of select="ogc:Literal" /></xsl:attribute>
  354. </xsl:element>
  355. </xsl:template>
  356. <xsl:template match="ogc:PropertyIsLike">
  357. <xsl:element name="sql_filter_comparisonFieldToValue">
  358. <xsl:attribute name="fieldName"><xsl:value-of select="ogc:PropertyName" /></xsl:attribute>
  359. <xsl:attribute name="comparisonSign"><xsl:value-of select="'like'" /></xsl:attribute>
  360. <xsl:attribute name="value"><xsl:value-of select="ogc:Literal" /></xsl:attribute>
  361. <xsl:attribute name="wildCard"><xsl:value-of select="@wildCard" /></xsl:attribute>
  362. <xsl:attribute name="singleChar"><xsl:value-of select="@singleChar" /></xsl:attribute>
  363. <xsl:attribute name="escapeChar"><xsl:value-of select="@escapeChar" /></xsl:attribute>
  364. </xsl:element>
  365. </xsl:template>
  366. </xsl:stylesheet>
  367. XSL_CONVERT_OGC_FILTER_TO_XML_TASK_LIST;
  368. $requestXml = new DOMDocument();
  369. $requestXml->loadXml($ogcFilterXmlString);
  370. $convertOgcFilterXsl = new DOMDocument();
  371. $convertOgcFilterXsl->loadXml($convertOgcFilterXslString);
  372. $proc = new XSLTProcessor();
  373. $proc->importStylesheet($convertOgcFilterXsl);
  374. return $proc->transformToXML($requestXml);
  375. }
  376. function _parseSpecialFilter($fltr, $value) {
  377. $sqlFltr = "";
  378. switch ($fltr) {
  379. case 'Problemy':
  380. if (array_key_exists('A_PROBLEM', $this->_cols)) {
  381. switch ($value) {
  382. case 'PROBLEM':
  383. $sqlFltr = " t.`A_PROBLEM`!='' ";
  384. break;
  385. case 'WARNING':
  386. $sqlFltr = " t.`A_PROBLEM`='WARNING' ";
  387. break;
  388. case 'NORMAL':
  389. $sqlFltr = " t.`A_PROBLEM`='' ";
  390. break;
  391. }
  392. }
  393. break;
  394. case 'Status':
  395. if (array_key_exists('A_STATUS', $this->_cols)) {
  396. switch ($value) {
  397. case 'WAITING':
  398. $sqlFltr = " t.`A_STATUS`='WAITING' ";
  399. break;
  400. case 'AKTYWNI':
  401. $sqlFltr = " t.`A_STATUS` in('NORMAL', 'WARNING') ";
  402. // TODO: $_SESSION['USERS_FILTER_STATUS_SQL']="and (( $thiss->DETECT_TABLE_NAME.A_STATUS='NORMAL' or $thiss->DETECT_TABLE_NAME.A_STATUS='WARNING' ) or ( $thiss->DETECT_TABLE_NAME.A_STATUS='OFF_SOFT' and $thiss->DETECT_TABLE_NAME.A_PROBLEM_DESC not like '%odla%fizy%' and $thiss->DETECT_TABLE_NAME.A_PROBLEM!='' ) or ( $thiss->DETECT_TABLE_NAME.A_STATUS='OFF_SOFT' and $thiss->DETECT_TABLE_NAME.A_PROBLEM='' )) ";
  403. // if ($thiss->DETECT_TABLE_NAME == 'KSIEG_DOKUMENTY') $_SESSION['USERS_FILTER_STATUS_SQL']="and ( $thiss->DETECT_TABLE_NAME.A_STATUS='NORMAL' or $thiss->DETECT_TABLE_NAME.A_STATUS='WARNING' ) ";
  404. break;
  405. }
  406. }
  407. break;
  408. case 'Spotkania':
  409. if (array_key_exists('L_APPOITMENT_DATE', $this->_cols)) {
  410. switch ($value) {
  411. case 'OLD':
  412. $sqlFltr = " UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)<UNIX_TIMESTAMP(now()) and t.`L_APPOITMENT_DATE`!='' ";
  413. break;
  414. case 'NOW':
  415. $sqlFltr = " UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)<UNIX_TIMESTAMP(now())+3600 and UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)>UNIX_TIMESTAMP(now())-3600 ";
  416. break;
  417. case 'TODAY':
  418. $start = mktime(0,0,0, date("m"), date("d"), date("Y"));
  419. $end = mktime(0,0,0, date("m"), date("d") + 1, date("Y"));
  420. $sqlFltr = " UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)>'{$start}' and UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)<'{$end}' ";
  421. break;
  422. case 'TOMORROW':
  423. $start = mktime(0,0,0, date("m"), date("d") + 1, date("Y"));
  424. $end = mktime(0,0,0, date("m"), date("d") + 2, date("Y"));
  425. $sqlFltr = " UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)>'{$start}' and UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)<'{$end}' ";
  426. break;
  427. case 'YESTERDAY':
  428. $start = mktime(0,0,0, date("m"), date("d") - 1, date("Y"));
  429. $end = mktime(0,0,0, date("m"), date("d") - 2, date("Y"));
  430. $sqlFltr = " UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)>'{$start}' and UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)<'{$end}' ";
  431. break;
  432. case 'BRAK':
  433. $start = mktime(0,0,0, date("m"), date("d") - 1, date("Y"));
  434. $end = mktime(0,0,0, date("m"), date("d") - 2, date("Y"));
  435. $sqlFltr = " t.`L_APPOITMENT_DATE`='' ";
  436. break;
  437. }
  438. }
  439. break;
  440. case 'Access':
  441. if ('SHOW' != $value && $this->isAccessFltrAllowed()) {
  442. $userLogin = User::getLogin();
  443. $usrAclGroups = User::getLdapGroupsNames();
  444. $usrAclGroups[] = '';// TODO: allow empty for everyone?
  445. $sqlUsrAclGroups = "'" . implode("','", $usrAclGroups) . "'";
  446. $sqlFltr = "
  447. t.`{$this->_fieldGroupWrite}` in({$sqlUsrAclGroups})
  448. and t.`{$this->_fieldGroupRead}` in({$sqlUsrAclGroups})
  449. ";
  450. if (array_key_exists('L_APPOITMENT_USER', $this->_cols)) {
  451. $sqlFltr = "
  452. (
  453. ({$sqlFltr})
  454. or t.`L_APPOITMENT_USER`='{$userLogin}'
  455. )
  456. ";
  457. }
  458. }
  459. break;
  460. default:
  461. }
  462. /*
  463. //USERS_FILTER_PROBLEM
  464. // PROBLEMY https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_PROBLEM&USERS_FILTER_PROBLEM=PROBLEM
  465. // OSTRZEZENIA https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_PROBLEM&USERS_FILTER_PROBLEM=WARNING
  466. // BEZ_PROBLEM. https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_PROBLEM&USERS_FILTER_PROBLEM=NORMAL
  467. // KASUJ-FILTR https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_PROBLEM&USERS_FILTER_PROBLEM=
  468. //USERS_FILTER_STATUS
  469. // OCZEKUJACY https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_STATUS&USERS_FILTER_STATUS=WAITING
  470. // AKTYWNI https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_STATUS&USERS_FILTER_STATUS=AKTYWNI
  471. // KASUJ-FILTR https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_STATUS&USERS_FILTER_STATUS=
  472. //USERS_FILTER_APPOINTMENT
  473. // A_STARE https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_APPOINTMENT&USERS_FILTER_APPOINTMENT=OLD
  474. // A_ZARAZ https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_APPOINTMENT&USERS_FILTER_APPOINTMENT=NOW
  475. // A_DZISIAJ https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_APPOINTMENT&USERS_FILTER_APPOINTMENT=TODAY
  476. // APP_ALL https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_APPOINTMENT&USERS_FILTER_APPOINTMENT=
  477. // btn class: active, disabled
  478. {// USERS_FILTER_PROBLEM
  479. var groupHtml = $('<div class="btn-group"></div>');
  480. $('<button class="btn btn-xs" title="Problemy"><i class="glyphicon glyphicon-warning-sign"></i></button>').appendTo(groupHtml);
  481. $('<button class="btn btn-xs">PROBLEMY</button>').appendTo(groupHtml);
  482. $('<button class="btn btn-xs">OSTRZEZENIA</button>').appendTo(groupHtml);
  483. $('<button class="btn btn-xs active">BEZ_PROBLEM.</button>').appendTo(groupHtml);
  484. $('<button class="btn btn-xs disabled" title="Kasuj filtr"><i class="glyphicon glyphicon-remove"></i></button>').appendTo(groupHtml);
  485. groupHtml.appendTo(_headSpecialFilter);
  486. }
  487. {// USERS_FILTER_STATUS
  488. var groupHtml = $('<div class="btn-group"></div>');
  489. $('<button class="btn btn-xs" title="Status"><i class="glyphicon glyphicon-question-sign"></i></button>').appendTo(groupHtml);
  490. $('<button class="btn btn-xs">OCZEKUJACY</button>').appendTo(groupHtml);
  491. $('<button class="btn btn-xs">AKTYWNI</button>').appendTo(groupHtml);
  492. $('<button class="btn btn-xs disabled" title="Kasuj filtr"><i class="glyphicon glyphicon-remove"></i></button>').appendTo(groupHtml);
  493. groupHtml.appendTo(_headSpecialFilter);
  494. }
  495. {// USERS_FILTER_APPOINTMENT
  496. var groupHtml = $('<div class="btn-group"></div>');
  497. $('<button class="btn btn-xs" title="Spotkania"><i class="glyphicon glyphicon-calendar"></i></button>').appendTo(groupHtml);
  498. $('<button class="btn btn-xs">A_STARE</button>').appendTo(groupHtml);
  499. $('<button class="btn btn-xs">A_ZARAZ</button>').appendTo(groupHtml);
  500. $('<button class="btn btn-xs active">A_DZISIAJ</button>').appendTo(groupHtml);
  501. $('<button class="btn btn-xs disabled" title="Kasuj filtr"><i class="glyphicon glyphicon-remove"></i></button>').appendTo(groupHtml);// To samo co KASUJ-FILTR
  502. groupHtml.appendTo(_headSpecialFilter);
  503. }
  504. */
  505. return $sqlFltr;
  506. }
  507. private function isColTypeNumber($colName) {
  508. if ($colName == 'ID') {
  509. return true;
  510. }
  511. $type = V::get($colName, null, $this->_col_types);
  512. if(V::get('DBG_DS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">type['.$colName.'] (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('type'=>$type, '!empty'=>(!empty($type['type']['type']))));echo'</pre>'."\n\n";}
  513. if (!empty($type['type'])) {
  514. $sqlType = $type['type'];
  515. if (substr($sqlType, 0, 3) == 'int'
  516. || substr($sqlType, 0, 7) == 'tinyint'
  517. || substr($sqlType, 0, 8) == 'smallint'
  518. ) {
  519. return true;
  520. }
  521. }
  522. return false;
  523. }
  524. public function _parseSqlWhere($params = array()) {
  525. // default filter value
  526. if (empty($params['sf_Access'])) $params['sf_Access'] = 'HIDE';
  527. $sql_where = '';
  528. // ... parse filters
  529. $sql_where_and = array();
  530. foreach ($params as $k => $v) {
  531. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_') {
  532. //$v = trim($v, '% ');
  533. //$sql_where_and[] = "t.`" . substr($k, 2) . "` like '%" . DB::_($v) . "%'";
  534. $fldName = substr($k, 2);
  535. if ($this->isGeomField($fldName)) {
  536. $sqlFilter = $this->_sqlValueForGeomField($fldName, $v, 't');
  537. if ($sqlFilter) $sql_where_and[] = $sqlFilter;
  538. continue;
  539. }
  540. if ($this->isCsvNumericField($fldName)) {
  541. $sqlFilter = $this->_sqlValueForCsvNumericField($fldName, $v, 't');
  542. if ($sqlFilter) $sql_where_and[] = $sqlFilter;
  543. continue;
  544. }
  545. if (substr($v, 0, 1) == '=') {
  546. $v = $this->_db->_(substr($v, 1));
  547. if (strlen($v)) $sql_where_and[] = "t.`{$fldName}`='{$v}'";
  548. }
  549. else if ($v == '!NULL' || $v == 'IS NOT NULL') {
  550. $sql_where_and[] = "t.`{$fldName}` is not null";
  551. }
  552. else if (substr($v, 0, 1) == '!') {
  553. $v = $this->_db->_(substr($v, 1));
  554. if (strlen($v)) $sql_where_and[] = "t.`{$fldName}` not like '{$v}'";
  555. }
  556. else if (substr($v, 0, 2) == '<=') {
  557. $v = $this->_db->_(substr($v, 2));
  558. if (strlen($v)) $sql_where_and[] = "t.`{$fldName}`<='{$v}'";
  559. }
  560. else if (substr($v, 0, 2) == '>=') {
  561. $v = $this->_db->_(substr($v, 2));
  562. if (strlen($v)) $sql_where_and[] = "t.`{$fldName}`>='{$v}'";
  563. }
  564. else if (substr($v, 0, 1) == '<') {
  565. $v = $this->_db->_(substr($v, 1));
  566. if (strlen($v)) $sql_where_and[] = "t.`{$fldName}`<'{$v}'";
  567. }
  568. else if (substr($v, 0, 1) == '>') {
  569. $v = $this->_db->_(substr($v, 1));
  570. if (strlen($v)) $sql_where_and[] = "t.`{$fldName}`>'{$v}'";
  571. }
  572. else if (false !== strpos($v, '%')) {
  573. $sql_where_and[] = "t.`{$fldName}` like '{$v}'";
  574. }
  575. else if ($this->isColTypeNumber($fldName)) {
  576. $v = $this->_db->_($v);
  577. $sql_where_and[] = "t.`{$fldName}`='{$v}'";
  578. }
  579. else {
  580. $queryWhereBuilder = new SqlQueryWhereBuilder();
  581. $searchWords = $queryWhereBuilder->splitQueryToWords($v);
  582. $sqlWhereWords = array();
  583. if (!empty($searchWords)) {
  584. foreach ($searchWords as $word) {
  585. $sqlWord = $this->_db->_($word);
  586. $sqlWhereWords[] = "t.`{$fldName}` like '%{$sqlWord}%'";
  587. }
  588. }
  589. if (!empty($searchWords)) {
  590. $sql_where_and[] = "(" . implode(" and ", $sqlWhereWords) . ")";
  591. }
  592. }
  593. }
  594. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_') {
  595. $sqlFltr = $this->_parseSpecialFilter(substr($k, 3), $v);
  596. if (!empty($sqlFltr)) {
  597. $sql_where_and[] = $sqlFltr;
  598. }
  599. }
  600. else if ('ogc:Filter' == $k) {
  601. $sqlFltr = $this->_parseOgcFilter($v);
  602. if (!empty($sqlFltr)) {
  603. $sql_where_and[] = $sqlFltr;
  604. }
  605. }
  606. }
  607. if (!empty($sql_where_and)) {
  608. $sql_where = implode(" and ", $sql_where_and);
  609. }
  610. if (!$sql_where) $sql_where = "1=1";
  611. if(V::get('DBG_DS', 0, $_GET) > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql_where (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql_where);echo'</pre>'."\n\n";}
  612. return $sql_where;
  613. }
  614. private function _sqlValueForGeomField($fldName, $fltrValue, $tblPrefix = 't') {
  615. $sqlFilter = false;
  616. // example: BBOX:54.40993961633866,18.583889010112824,54.337945760687454,18.397121431987586
  617. if ('BBOX:' == substr($fltrValue, 0, 5)) {
  618. $val = substr($fltrValue, 5);
  619. $valParts = explode(',', $val);
  620. if (count($valParts) == 4) {
  621. $isAllNumeric = true;
  622. foreach ($valParts as $v) {
  623. if (!is_numeric($v)) $isAllNumeric = false;
  624. }
  625. if ($isAllNumeric) {
  626. $bounds = "POLYGON((
  627. {$valParts[3]} {$valParts[2]},
  628. {$valParts[3]} {$valParts[0]},
  629. {$valParts[1]} {$valParts[0]},
  630. {$valParts[1]} {$valParts[2]},
  631. {$valParts[3]} {$valParts[2]}
  632. ))";
  633. // for mysql 5.6 use ST_Contains() @see http://dev.mysql.com/doc/refman/5.6/en/spatial-relation-functions.html
  634. $sqlFilter = "Intersects(GeomFromText('{$bounds}'), GeomFromText(AsWKT({$tblPrefix}.`{$fldName}`)))=1";
  635. }
  636. }
  637. }
  638. else if ('GeometryType=' == substr($fltrValue, 0, 13)) {
  639. $sqlFilter = "GeometryType({$tblPrefix}.`{$fldName}`)='" . substr($fltrValue, 13) . "'";
  640. }
  641. return $sqlFilter;
  642. }
  643. private function _sqlValueForCsvNumericField($fldName, $fltrValue, $tblPrefix = 't') {
  644. $sqlFilter = false;
  645. if (is_numeric($fltrValue)) {
  646. $sqlFilter = "FIND_IN_SET('{$fltrValue}', `{$fldName}`)>0";
  647. } else if (false !== strpos($fltrValue, ' ')) {
  648. $sqlGlue = " or ";
  649. $fltrValues = $fltrValue;
  650. if ('&' == substr($fltrValues, 0, 1)) {
  651. $fltrValues = substr($fltrValues, 1);
  652. $sqlGlue = " and ";
  653. }
  654. $fltrValues = explode(' ', $fltrValues);
  655. $sqlNumericValues = array();
  656. foreach ($fltrValues as $fltrVal) {
  657. if (is_numeric($fltrVal)) {
  658. $sqlNumericValues[] = "FIND_IN_SET('{$fltrVal}', `{$fldName}`)>0";
  659. }
  660. }
  661. if (!empty($sqlNumericValues)) {
  662. $sqlFilter = "(" . implode($sqlGlue, $sqlNumericValues) . ")";
  663. }
  664. }
  665. return $sqlFilter;
  666. }
  667. function get_item($id) {// TODO: RMME
  668. $this->getItem($id);
  669. }
  670. /**
  671. * @returns object
  672. */
  673. public function getItem($primaryKey) {
  674. $primaryKeyField = $this->getPrimaryKeyField();
  675. $ret = null;
  676. $sql_cols = $this->_get_sql_cols();
  677. $primaryKey = intval($primaryKey);// TODO: validate $primaryKey
  678. $sql = "select {$sql_cols}
  679. from `{$this->_tbl}` as t
  680. where t.`{$primaryKeyField}`='{$primaryKey}'
  681. ";
  682. // TODO: use PDO
  683. $res = $this->_db->query($sql);
  684. if ($r = $this->_db->fetch($res)) {
  685. $ret = $r;
  686. }
  687. return $ret;
  688. }
  689. function get_items($params = array()) {// TODO: RMME
  690. $this->getItems($params);
  691. }
  692. public function getItems($params = array()) {
  693. $primaryKeyField = $this->getPrimaryKeyField();
  694. $items = array();
  695. $sql_limit = V::get('limit', $this->_default_sql_limit, $params, 'int');
  696. $sql_offset = V::get('limitstart', 0, $params, 'int');
  697. $sql_order_by = V::get('order_by', '', $params);
  698. if ($sql_order_by) {
  699. $sql_order_dir = V::get('order_dir', '', $params);
  700. // prevent from sorting by special columns
  701. if (!array_key_exists($sql_order_by, $this->_cols)) {
  702. $sql_order_by = null;
  703. $sql_order_dir = null;
  704. }
  705. }
  706. if ($sql_order_by) {
  707. $sql_order_by = "order by t.`{$sql_order_by}`";
  708. if ($sql_order_dir) {
  709. $sql_order_by = "{$sql_order_by} {$sql_order_dir}";
  710. }
  711. }
  712. $sql_cols = $this->_get_sql_cols();
  713. $sql_where = $this->_parseSqlWhere($params);
  714. $sql = "select {$sql_cols}
  715. from {$this->_tbl} as t
  716. where {$sql_where}
  717. {$sql_order_by}
  718. limit {$sql_limit} offset {$sql_offset}
  719. ";
  720. if(V::get('DBG_DS', 0, $_GET) > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>'."\n\n";}
  721. $res = $this->_db->query($sql);
  722. while ($r = $this->_db->fetch($res)) {
  723. $items[$r->{$primaryKeyField}] = $r;
  724. }
  725. return $items;
  726. }
  727. function get_hist_items($id) {// TODO: RMME
  728. $this->getHistItems($id);
  729. }
  730. public function getHistItems($id, $params = array()) {
  731. $ret = array();
  732. $sql_tbl = $this->_tbl . "_HIST";
  733. $sql_cols = $this->_get_sql_cols();
  734. $sql_where = "t.`ID_USERS2`='{$id}'";
  735. $paramNotEmptyFlds = V::get('notEmptyFlds', '', $params);
  736. if (!empty($paramNotEmptyFlds) && is_array($paramNotEmptyFlds)) {
  737. $sqlWhereOr = array();
  738. foreach ($paramNotEmptyFlds as $fldName) {
  739. if (array_key_exists($fldName, $this->_cols)) {
  740. $sqlWhereOr[] = "t.`{$fldName}`!='N/S;'";
  741. }
  742. }
  743. if (!empty($sqlWhereOr)) $sql_where .= "\n and (" . implode(" or ", $sqlWhereOr) . ")";
  744. }
  745. $sql = "select {$sql_cols}
  746. from {$sql_tbl} as t
  747. where {$sql_where}
  748. order by ID DESC
  749. ";
  750. if(V::get('DBG_DS', 0, $_GET) > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>'."\n\n";}
  751. $res = $this->_db->query($sql);
  752. while ($r = $this->_db->fetch($res)) {
  753. $r->_author = $r->A_RECORD_UPDATE_AUTHOR;
  754. $r->_created = $r->A_RECORD_UPDATE_DATE;
  755. if (!$r->_author || $r->_author == 'N/S;') {
  756. $r->_author = $r->A_RECORD_CREATE_AUTHOR;
  757. }
  758. if (!$r->_created || $r->_created == 'N/S;') {
  759. $r->_created = $r->A_RECORD_CREATE_DATE;
  760. }
  761. $ret[$r->ID] = $r;
  762. }
  763. return $ret;
  764. }
  765. function get_total($params = array()) {// TODO: RMME
  766. $this->getTotal($params);
  767. }
  768. public function getTotal($params = array()) {
  769. $ret = 0;
  770. $sql_where = $this->_parseSqlWhere($params);
  771. $sql = "select count(1) as cnt
  772. from {$this->_tbl} as t
  773. where {$sql_where}
  774. ";
  775. $res = $this->_db->query($sql);
  776. if ($r = $this->_db->fetch($res)) {
  777. $ret = $r->cnt;
  778. }
  779. return $ret;
  780. }
  781. function set_sql_where($sql_where) {
  782. $this->_sql_where = $sql_where;
  783. }
  784. function set_field_sql_type($field, $sql_type) {
  785. $this->_fields_type[$field] = $sql_type;
  786. }
  787. function get_field_sql_type($field) {
  788. if (array_key_exists($field, $this->_fields_type)) {
  789. return $this->_fields_type[$field];
  790. }
  791. return 'varchar(255)';
  792. }
  793. function set_field_perm($field, $perm) {
  794. $this->_fields_perm[$field] = $perm;
  795. }
  796. function get_field_perm($field) {
  797. if (array_key_exists($field, $this->_fields_perm)) {
  798. return $this->_fields_perm[$field];
  799. }
  800. return '';
  801. }
  802. function field_allow_write($field_name) {
  803. return (strpos($this->get_field_perm($field_name), 'W') !== false)? true : false;
  804. }
  805. function field_allow_read($field_name) {
  806. return (strpos($this->get_field_perm($field_name), 'R') !== false)? true : false;
  807. }
  808. function field_allow_create($field_name) {
  809. return (strpos($this->get_field_perm($field_name), 'C') !== false)? true : false;
  810. }
  811. public function add_col($col_name, $label = '', $type = 'string') {
  812. if (!$label) $label = $col_name;
  813. $this->_cols[$col_name] = $label;
  814. $this->_col_types[$col_name] = $type;
  815. }
  816. public function addCol($col_name) {
  817. $this->_cols[$col_name] = $col_name;
  818. }
  819. function count() {
  820. $ret = 0;
  821. $sql_where = ($this->_sql_where)? $this->_sql_where : "1=1";
  822. $sql = "select count(1) as cnt
  823. from `{$this->_tbl}`
  824. where {$sql_where}
  825. ";
  826. $res = $this->_db->query($sql);
  827. if ($r = $this->_db->fetch($res)) {
  828. $ret = $r->cnt;
  829. }
  830. return $ret;
  831. }
  832. function fetch_list($limit = 10, $offset = 0) {
  833. $primaryKeyField = $this->getPrimaryKeyField();
  834. $ret = array();
  835. $this->_sql_limit = $limit;
  836. $this->_sql_offset = $offset;
  837. $sql_cols = (!empty($this->_cols))? implode(',', array_keys($this->_cols)) : "*";
  838. $sql_where = ($this->_sql_where)? $this->_sql_where : "1=1";
  839. $sql = "
  840. select {$sql_cols}
  841. from {$this->_tbl}
  842. where {$sql_where}
  843. limit {$this->_sql_limit} offset {$this->_sql_offset}
  844. ";
  845. $res = $this->_db->query($sql);
  846. while ($r = $this->_db->fetch($res)) {
  847. $ret[$r->{$primaryKeyField}] = $r;
  848. }
  849. return $ret;
  850. }
  851. function field_check_value($field_name, $val) {
  852. if (!$this->field_allow_write($field_name)) {
  853. return false;
  854. }
  855. // post verify
  856. // get type, and check if value is correct
  857. // TODO: if typespecial use it
  858. return true;
  859. }
  860. function save_item(&$item, $values, $prefix) {
  861. if (!$item->ID) {
  862. return null;
  863. }
  864. $sql_obj = new stdClass();
  865. $sql_obj->ID = $item->ID;
  866. foreach ($values as $k_field_with_prefix => $v_field) {
  867. if (substr($k_field_with_prefix, 0, strlen($prefix)) != $prefix) {
  868. continue;
  869. }
  870. $k_field = substr($k_field_with_prefix, strlen($prefix));
  871. if ($this->field_allow_write($k_field)) {
  872. if ($this->field_check_value($k_field, $v_field)) {
  873. $sql_obj->$k_field = $v_field;
  874. }
  875. }
  876. }
  877. $affected = $this->_db->PDATE_OBJ($this->_tbl, $sql_obj);
  878. return $affected;
  879. }
  880. function add_item($values, $prefix) {
  881. $sql_obj = new stdClass();
  882. foreach ($values as $k_field_with_prefix => $v_field) {
  883. if (substr($k_field_with_prefix, 0, strlen($prefix)) != $prefix) {
  884. continue;
  885. }
  886. $k_field = substr($k_field_with_prefix, strlen($prefix));
  887. if ($this->field_allow_create($k_field)) {
  888. if ($this->field_check_value($k_field, $v_field)) {
  889. $sql_obj->$k_field = $v_field;
  890. }
  891. }
  892. }
  893. $insert_id = $this->_db->ADD_NEW_OBJ($this->_tbl, $sql_obj);
  894. return $insert_id;
  895. }
  896. public function getGeomFields() {
  897. return $this->_geomFields;
  898. }
  899. public function isGeomField($fldName) {
  900. return in_array($fldName, $this->_geomFields);
  901. }
  902. public function isCsvNumericField($fldName) {
  903. return ('_CSV_NUM' == substr($fldName, -8));
  904. }
  905. public function updateItem($itemPatch) {
  906. // TODO: $item as array and copy from $db->UPDATE_OBJ using PDO
  907. if (is_object($itemPatch)) {
  908. $itemPatch = (array)$itemPatch;
  909. } else if (!is_array($itemPatch)) {
  910. throw new HttpException('Item patch is not array', 400);
  911. }
  912. if (empty($itemPatch)) {
  913. //throw new Exception('Item patch is empty');
  914. return 0;// nothing to change
  915. }
  916. $primaryKeyField = $this->getPrimaryKeyField();
  917. if (empty($itemPatch[$primaryKeyField])) {
  918. throw new HttpException("Item Primary Key not set!", 400);
  919. }
  920. // the geom fix
  921. foreach ($itemPatch as $fld => $val) {
  922. if ($this->isGeomField($fld)) {
  923. if (!empty($val)
  924. && 'NULL' !== $val
  925. && 'GeomFromText' != substr($val, 0, strlen('GeomFromText'))
  926. ) {
  927. $itemPatch[$fld] = "GeomFromText('{$val}')";
  928. }
  929. }
  930. }
  931. $itemPatch = (object)$itemPatch;
  932. $affected = $this->_db->UPDATE_OBJ($this->_tbl, $itemPatch);
  933. if ($affected < 0) {
  934. $dsErrors = $this->getDbErrors();
  935. //$dsErrors = "Wystąpiły błędy!\n" . implode("\n", $dsErrors);
  936. if (!empty($dsErrors)) {
  937. throw new StorageException($dsErrors);
  938. }
  939. }
  940. return $affected;
  941. }
  942. public function addItem($item) {
  943. // TODO: $item as array and copy from $db->ADD_NEW_OBJ using PDO
  944. if (is_object($item)) {
  945. $item = (array)$item;
  946. } else if (!is_array($item)) {
  947. throw new HttpException('Item is not array', 400);
  948. }
  949. if (empty($item)) {
  950. //throw new Exception('Item patch is empty');
  951. return 0;// nothing to insert
  952. }
  953. // the geom fix
  954. foreach ($item as $fld => $val) {
  955. if ($this->isGeomField($fld)) {
  956. if (!empty($val)
  957. && 'NULL' !== $val
  958. && 'GeomFromText' != substr($val, 0, strlen('GeomFromText'))
  959. ) {
  960. $item[$fld] = "GeomFromText('{$val}')";
  961. }
  962. }
  963. }
  964. $item = (object)$item;
  965. $primaryKey = $this->_db->ADD_NEW_OBJ($this->_tbl, $item);
  966. if ($primaryKey < 0) {
  967. $dsErrors = $this->getDbErrors();
  968. $dsErrors = "Wystąpiły błędy!\n" . implode("\n", $dsErrors);
  969. throw new Exception($dsErrors);
  970. }
  971. return $primaryKey;
  972. }
  973. public function getDbErrors() {
  974. $errors = array();
  975. if ($this->_db->has_errors()) {
  976. $errorsSql = $this->_db->get_errors();
  977. foreach ($errorsSql as $vErr) {
  978. if ('SQL QUERY FAILED: ' == substr($vErr, 0, 18)) {
  979. $vErr = substr($vErr, 18);
  980. }
  981. //$errors[] = StorageException::parseMessage($vErr);
  982. $errors[] = $vErr;
  983. }
  984. }
  985. return $errors;
  986. }
  987. public function getPrimaryKeyField() {
  988. return 'ID';// TODO: read from struct - jest funkcja w Mysql.php my Psql.php
  989. }
  990. }