Data_Source.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101
  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. case 'not_implemented_tag': {
  305. $tagName = V::get('name', '', $tag['attributes']);
  306. DBG::_('DBG_DS_OGC', '>1', "Not Implemented tag '{$tagName}'", $queryWhereBuilder, __CLASS__, __FUNCTION__, __LINE__);
  307. throw new HttpException("Not Implemented tag '{$tagName}'", 501);
  308. }
  309. break;
  310. default: {
  311. DBG::_('DBG_DS_OGC', '>1', "TODO: tag {$tag['tag']}", $queryWhereBuilder, __CLASS__, __FUNCTION__, __LINE__);
  312. throw new Exception("TODO: tag {$tag['tag']}");
  313. }
  314. }
  315. }
  316. $queryWhereBuilder->parseQueryWhere();
  317. DBG::_('DBG_DS_OGC', '>1', "queryWhereBuilder", $queryWhereBuilder, __CLASS__, __FUNCTION__, __LINE__);
  318. return $queryWhereBuilder->getQueryWhere('t');
  319. }
  320. public function _convertGuiXmlToCmdList($ogcFilterXmlString) {
  321. $convertOgcFilterXslString = <<<XSL_CONVERT_OGC_FILTER_TO_XML_TASK_LIST
  322. <?xml version="1.0" encoding="UTF-8"?>
  323. <xsl:stylesheet version="1.0"
  324. xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  325. xmlns:filter="https://biuro.biall-net.pl/SE/version-git/schema/filter.xsd"
  326. xmlns:ogc="http://www.opengis.net/ogc"
  327. >
  328. <xsl:output method="xml" omit-xml-declaration="yes" indent="no"/>
  329. <xsl:template match="/">
  330. <xsl:element name="filter">
  331. <xsl:apply-templates select="filter:filter/ogc:Filter"/>
  332. </xsl:element>
  333. </xsl:template>
  334. <xsl:template match="ogc:Filter">
  335. <xsl:apply-templates/>
  336. </xsl:template>
  337. <xsl:template match="*">
  338. <xsl:element name="not_implemented_tag">
  339. <xsl:attribute name="name"><xsl:value-of select="name()"/></xsl:attribute>
  340. <xsl:apply-templates/>
  341. </xsl:element>
  342. </xsl:template>
  343. <xsl:template match="ogc:Or">
  344. <xsl:element name="sql_filter_openBlock">
  345. <xsl:attribute name="type"><xsl:value-of select="'or'" /></xsl:attribute>
  346. </xsl:element>
  347. <xsl:apply-templates/>
  348. <xsl:element name="sql_filter_closeBlock">
  349. <xsl:attribute name="type"><xsl:value-of select="'or'" /></xsl:attribute>
  350. </xsl:element>
  351. </xsl:template>
  352. <xsl:template match="ogc:And">
  353. <xsl:element name="sql_filter_openBlock">
  354. <xsl:attribute name="type"><xsl:value-of select="'and'" /></xsl:attribute>
  355. </xsl:element>
  356. <xsl:apply-templates/>
  357. <xsl:element name="sql_filter_closeBlock">
  358. <xsl:attribute name="type"><xsl:value-of select="'and'" /></xsl:attribute>
  359. </xsl:element>
  360. </xsl:template>
  361. <xsl:template match="ogc:PropertyIsEqualTo">
  362. <xsl:element name="sql_filter_comparisonFieldToValue">
  363. <xsl:attribute name="fieldName"><xsl:value-of select="ogc:PropertyName" /></xsl:attribute>
  364. <xsl:attribute name="comparisonSign"><xsl:value-of select="'='" /></xsl:attribute>
  365. <xsl:attribute name="value"><xsl:value-of select="ogc:Literal" /></xsl:attribute>
  366. </xsl:element>
  367. </xsl:template>
  368. <xsl:template match="ogc:PropertyIsLike">
  369. <xsl:element name="sql_filter_comparisonFieldToValue">
  370. <xsl:attribute name="fieldName"><xsl:value-of select="ogc:PropertyName" /></xsl:attribute>
  371. <xsl:attribute name="comparisonSign"><xsl:value-of select="'like'" /></xsl:attribute>
  372. <xsl:attribute name="value"><xsl:value-of select="ogc:Literal" /></xsl:attribute>
  373. <xsl:attribute name="wildCard"><xsl:value-of select="@wildCard" /></xsl:attribute>
  374. <xsl:attribute name="singleChar"><xsl:value-of select="@singleChar" /></xsl:attribute>
  375. <xsl:attribute name="escapeChar"><xsl:value-of select="@escapeChar" /></xsl:attribute>
  376. </xsl:element>
  377. </xsl:template>
  378. </xsl:stylesheet>
  379. XSL_CONVERT_OGC_FILTER_TO_XML_TASK_LIST;
  380. $requestXml = new DOMDocument();
  381. $requestXml->loadXml($ogcFilterXmlString);
  382. $convertOgcFilterXsl = new DOMDocument();
  383. $convertOgcFilterXsl->loadXml($convertOgcFilterXslString);
  384. $proc = new XSLTProcessor();
  385. $proc->importStylesheet($convertOgcFilterXsl);
  386. return $proc->transformToXML($requestXml);
  387. }
  388. function _parseSpecialFilter($fltr, $value) {
  389. $sqlFltr = "";
  390. switch ($fltr) {
  391. case 'Problemy':
  392. if (array_key_exists('A_PROBLEM', $this->_cols)) {
  393. switch ($value) {
  394. case 'PROBLEM':
  395. $sqlFltr = " t.`A_PROBLEM`!='' ";
  396. break;
  397. case 'WARNING':
  398. $sqlFltr = " t.`A_PROBLEM`='WARNING' ";
  399. break;
  400. case 'NORMAL':
  401. $sqlFltr = " t.`A_PROBLEM`='' ";
  402. break;
  403. }
  404. }
  405. break;
  406. case 'Status':
  407. if (array_key_exists('A_STATUS', $this->_cols)) {
  408. switch ($value) {
  409. case 'WAITING':
  410. $sqlFltr = " t.`A_STATUS`='WAITING' ";
  411. break;
  412. case 'AKTYWNI':
  413. $sqlFltr = " t.`A_STATUS` in('NORMAL', 'WARNING') ";
  414. // 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='' )) ";
  415. // 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' ) ";
  416. break;
  417. }
  418. }
  419. break;
  420. case 'Spotkania':
  421. if (array_key_exists('L_APPOITMENT_DATE', $this->_cols)) {
  422. switch ($value) {
  423. case 'OLD':
  424. $sqlFltr = " UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)<UNIX_TIMESTAMP(now()) and t.`L_APPOITMENT_DATE`!='' ";
  425. break;
  426. case 'NOW':
  427. $sqlFltr = " UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)<UNIX_TIMESTAMP(now())+3600 and UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)>UNIX_TIMESTAMP(now())-3600 ";
  428. break;
  429. case 'TODAY':
  430. $start = mktime(0,0,0, date("m"), date("d"), date("Y"));
  431. $end = mktime(0,0,0, date("m"), date("d") + 1, date("Y"));
  432. $sqlFltr = " UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)>'{$start}' and UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)<'{$end}' ";
  433. break;
  434. case 'TOMORROW':
  435. $start = mktime(0,0,0, date("m"), date("d") + 1, date("Y"));
  436. $end = mktime(0,0,0, date("m"), date("d") + 2, date("Y"));
  437. $sqlFltr = " UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)>'{$start}' and UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)<'{$end}' ";
  438. break;
  439. case 'YESTERDAY':
  440. $start = mktime(0,0,0, date("m"), date("d") - 1, date("Y"));
  441. $end = mktime(0,0,0, date("m"), date("d") - 2, date("Y"));
  442. $sqlFltr = " UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)>'{$start}' and UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)<'{$end}' ";
  443. break;
  444. case 'BRAK':
  445. $start = mktime(0,0,0, date("m"), date("d") - 1, date("Y"));
  446. $end = mktime(0,0,0, date("m"), date("d") - 2, date("Y"));
  447. $sqlFltr = " t.`L_APPOITMENT_DATE`='' ";
  448. break;
  449. }
  450. }
  451. break;
  452. case 'Access':
  453. if ('SHOW' != $value && $this->isAccessFltrAllowed()) {
  454. $userLogin = User::getLogin();
  455. $usrAclGroups = User::getLdapGroupsNames();
  456. $usrAclGroups[] = '';// TODO: allow empty for everyone?
  457. $sqlUsrAclGroups = "'" . implode("','", $usrAclGroups) . "'";
  458. $sqlFltr = "
  459. t.`{$this->_fieldGroupWrite}` in({$sqlUsrAclGroups})
  460. and t.`{$this->_fieldGroupRead}` in({$sqlUsrAclGroups})
  461. ";
  462. if (array_key_exists('L_APPOITMENT_USER', $this->_cols)) {
  463. $sqlFltr = "
  464. (
  465. ({$sqlFltr})
  466. or t.`L_APPOITMENT_USER`='{$userLogin}'
  467. )
  468. ";
  469. }
  470. }
  471. break;
  472. default:
  473. }
  474. /*
  475. //USERS_FILTER_PROBLEM
  476. // PROBLEMY https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_PROBLEM&USERS_FILTER_PROBLEM=PROBLEM
  477. // OSTRZEZENIA https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_PROBLEM&USERS_FILTER_PROBLEM=WARNING
  478. // BEZ_PROBLEM. https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_PROBLEM&USERS_FILTER_PROBLEM=NORMAL
  479. // KASUJ-FILTR https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_PROBLEM&USERS_FILTER_PROBLEM=
  480. //USERS_FILTER_STATUS
  481. // OCZEKUJACY https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_STATUS&USERS_FILTER_STATUS=WAITING
  482. // AKTYWNI https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_STATUS&USERS_FILTER_STATUS=AKTYWNI
  483. // KASUJ-FILTR https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_STATUS&USERS_FILTER_STATUS=
  484. //USERS_FILTER_APPOINTMENT
  485. // A_STARE https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_APPOINTMENT&USERS_FILTER_APPOINTMENT=OLD
  486. // A_ZARAZ https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_APPOINTMENT&USERS_FILTER_APPOINTMENT=NOW
  487. // A_DZISIAJ https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_APPOINTMENT&USERS_FILTER_APPOINTMENT=TODAY
  488. // APP_ALL https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_APPOINTMENT&USERS_FILTER_APPOINTMENT=
  489. // btn class: active, disabled
  490. {// USERS_FILTER_PROBLEM
  491. var groupHtml = $('<div class="btn-group"></div>');
  492. $('<button class="btn btn-xs" title="Problemy"><i class="glyphicon glyphicon-warning-sign"></i></button>').appendTo(groupHtml);
  493. $('<button class="btn btn-xs">PROBLEMY</button>').appendTo(groupHtml);
  494. $('<button class="btn btn-xs">OSTRZEZENIA</button>').appendTo(groupHtml);
  495. $('<button class="btn btn-xs active">BEZ_PROBLEM.</button>').appendTo(groupHtml);
  496. $('<button class="btn btn-xs disabled" title="Kasuj filtr"><i class="glyphicon glyphicon-remove"></i></button>').appendTo(groupHtml);
  497. groupHtml.appendTo(_headSpecialFilter);
  498. }
  499. {// USERS_FILTER_STATUS
  500. var groupHtml = $('<div class="btn-group"></div>');
  501. $('<button class="btn btn-xs" title="Status"><i class="glyphicon glyphicon-question-sign"></i></button>').appendTo(groupHtml);
  502. $('<button class="btn btn-xs">OCZEKUJACY</button>').appendTo(groupHtml);
  503. $('<button class="btn btn-xs">AKTYWNI</button>').appendTo(groupHtml);
  504. $('<button class="btn btn-xs disabled" title="Kasuj filtr"><i class="glyphicon glyphicon-remove"></i></button>').appendTo(groupHtml);
  505. groupHtml.appendTo(_headSpecialFilter);
  506. }
  507. {// USERS_FILTER_APPOINTMENT
  508. var groupHtml = $('<div class="btn-group"></div>');
  509. $('<button class="btn btn-xs" title="Spotkania"><i class="glyphicon glyphicon-calendar"></i></button>').appendTo(groupHtml);
  510. $('<button class="btn btn-xs">A_STARE</button>').appendTo(groupHtml);
  511. $('<button class="btn btn-xs">A_ZARAZ</button>').appendTo(groupHtml);
  512. $('<button class="btn btn-xs active">A_DZISIAJ</button>').appendTo(groupHtml);
  513. $('<button class="btn btn-xs disabled" title="Kasuj filtr"><i class="glyphicon glyphicon-remove"></i></button>').appendTo(groupHtml);// To samo co KASUJ-FILTR
  514. groupHtml.appendTo(_headSpecialFilter);
  515. }
  516. */
  517. return $sqlFltr;
  518. }
  519. private function isColTypeNumber($colName) {
  520. if ($colName == 'ID') {
  521. return true;
  522. }
  523. $type = V::get($colName, null, $this->_col_types);
  524. 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";}
  525. if (!empty($type['type'])) {
  526. $sqlType = $type['type'];
  527. if (substr($sqlType, 0, 3) == 'int'
  528. || substr($sqlType, 0, 7) == 'tinyint'
  529. || substr($sqlType, 0, 8) == 'smallint'
  530. ) {
  531. return true;
  532. }
  533. }
  534. return false;
  535. }
  536. public function _parseSqlWhere($params = array()) {
  537. // default filter value
  538. if (empty($params['sf_Access'])) $params['sf_Access'] = 'HIDE';
  539. $sql_where = '';
  540. // ... parse filters
  541. $sql_where_and = array();
  542. foreach ($params as $k => $v) {
  543. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_') {
  544. //$v = trim($v, '% ');
  545. //$sql_where_and[] = "t.`" . substr($k, 2) . "` like '%" . DB::_($v) . "%'";
  546. $fldName = substr($k, 2);
  547. if ($this->isGeomField($fldName)) {
  548. $sqlFilter = $this->_sqlValueForGeomField($fldName, $v, 't');
  549. if ($sqlFilter) $sql_where_and[] = $sqlFilter;
  550. continue;
  551. }
  552. if ($this->isCsvNumericField($fldName)) {
  553. $sqlFilter = $this->_sqlValueForCsvNumericField($fldName, $v, 't');
  554. if ($sqlFilter) $sql_where_and[] = $sqlFilter;
  555. continue;
  556. }
  557. if (substr($v, 0, 1) == '=') {
  558. $v = $this->_db->_(substr($v, 1));
  559. if (strlen($v)) $sql_where_and[] = "t.`{$fldName}`='{$v}'";
  560. }
  561. else if ($v == '!NULL' || $v == 'IS NOT NULL') {
  562. $sql_where_and[] = "t.`{$fldName}` is not null";
  563. }
  564. else if (substr($v, 0, 1) == '!') {
  565. $v = $this->_db->_(substr($v, 1));
  566. if (strlen($v)) $sql_where_and[] = "t.`{$fldName}` not like '{$v}'";
  567. }
  568. else if (substr($v, 0, 2) == '<=') {
  569. $v = $this->_db->_(substr($v, 2));
  570. if (strlen($v)) $sql_where_and[] = "t.`{$fldName}`<='{$v}'";
  571. }
  572. else if (substr($v, 0, 2) == '>=') {
  573. $v = $this->_db->_(substr($v, 2));
  574. if (strlen($v)) $sql_where_and[] = "t.`{$fldName}`>='{$v}'";
  575. }
  576. else if (substr($v, 0, 1) == '<') {
  577. $v = $this->_db->_(substr($v, 1));
  578. if (strlen($v)) $sql_where_and[] = "t.`{$fldName}`<'{$v}'";
  579. }
  580. else if (substr($v, 0, 1) == '>') {
  581. $v = $this->_db->_(substr($v, 1));
  582. if (strlen($v)) $sql_where_and[] = "t.`{$fldName}`>'{$v}'";
  583. }
  584. else if (false !== strpos($v, '%')) {
  585. $sql_where_and[] = "t.`{$fldName}` like '{$v}'";
  586. }
  587. else if ($this->isColTypeNumber($fldName)) {
  588. $v = $this->_db->_($v);
  589. $sql_where_and[] = "t.`{$fldName}`='{$v}'";
  590. }
  591. else {
  592. $queryWhereBuilder = new SqlQueryWhereBuilder();
  593. $searchWords = $queryWhereBuilder->splitQueryToWords($v);
  594. $sqlWhereWords = array();
  595. if (!empty($searchWords)) {
  596. foreach ($searchWords as $word) {
  597. $sqlWord = $this->_db->_($word);
  598. $sqlWhereWords[] = "t.`{$fldName}` like '%{$sqlWord}%'";
  599. }
  600. }
  601. if (!empty($searchWords)) {
  602. $sql_where_and[] = "(" . implode(" and ", $sqlWhereWords) . ")";
  603. }
  604. }
  605. }
  606. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_') {
  607. $sqlFltr = $this->_parseSpecialFilter(substr($k, 3), $v);
  608. if (!empty($sqlFltr)) {
  609. $sql_where_and[] = $sqlFltr;
  610. }
  611. }
  612. else if ('ogc:Filter' == $k) {
  613. $sqlFltr = $this->_parseOgcFilter($v);
  614. if (!empty($sqlFltr)) {
  615. $sql_where_and[] = $sqlFltr;
  616. }
  617. }
  618. }
  619. if (!empty($sql_where_and)) {
  620. $sql_where = implode(" and ", $sql_where_and);
  621. }
  622. if (!$sql_where) $sql_where = "1=1";
  623. 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";}
  624. return $sql_where;
  625. }
  626. private function _sqlValueForGeomField($fldName, $fltrValue, $tblPrefix = 't') {
  627. $sqlFilter = false;
  628. // example: BBOX:54.40993961633866,18.583889010112824,54.337945760687454,18.397121431987586
  629. if ('BBOX:' == substr($fltrValue, 0, 5)) {
  630. $val = substr($fltrValue, 5);
  631. $valParts = explode(',', $val);
  632. if (count($valParts) == 4) {
  633. $isAllNumeric = true;
  634. foreach ($valParts as $v) {
  635. if (!is_numeric($v)) $isAllNumeric = false;
  636. }
  637. if ($isAllNumeric) {
  638. $bounds = "POLYGON((
  639. {$valParts[3]} {$valParts[2]},
  640. {$valParts[3]} {$valParts[0]},
  641. {$valParts[1]} {$valParts[0]},
  642. {$valParts[1]} {$valParts[2]},
  643. {$valParts[3]} {$valParts[2]}
  644. ))";
  645. // for mysql 5.6 use ST_Contains() @see http://dev.mysql.com/doc/refman/5.6/en/spatial-relation-functions.html
  646. $sqlFilter = "Intersects(GeomFromText('{$bounds}'), GeomFromText(AsWKT({$tblPrefix}.`{$fldName}`)))=1";
  647. }
  648. }
  649. }
  650. else if ('GeometryType=' == substr($fltrValue, 0, 13)) {
  651. $sqlFilter = "GeometryType({$tblPrefix}.`{$fldName}`)='" . substr($fltrValue, 13) . "'";
  652. }
  653. return $sqlFilter;
  654. }
  655. private function _sqlValueForCsvNumericField($fldName, $fltrValue, $tblPrefix = 't') {
  656. $sqlFilter = false;
  657. if (is_numeric($fltrValue)) {
  658. $sqlFilter = "FIND_IN_SET('{$fltrValue}', `{$fldName}`)>0";
  659. } else if (false !== strpos($fltrValue, ' ')) {
  660. $sqlGlue = " or ";
  661. $fltrValues = $fltrValue;
  662. if ('&' == substr($fltrValues, 0, 1)) {
  663. $fltrValues = substr($fltrValues, 1);
  664. $sqlGlue = " and ";
  665. }
  666. $fltrValues = explode(' ', $fltrValues);
  667. $sqlNumericValues = array();
  668. foreach ($fltrValues as $fltrVal) {
  669. if (is_numeric($fltrVal)) {
  670. $sqlNumericValues[] = "FIND_IN_SET('{$fltrVal}', `{$fldName}`)>0";
  671. }
  672. }
  673. if (!empty($sqlNumericValues)) {
  674. $sqlFilter = "(" . implode($sqlGlue, $sqlNumericValues) . ")";
  675. }
  676. }
  677. return $sqlFilter;
  678. }
  679. function get_item($id) {// TODO: RMME
  680. $this->getItem($id);
  681. }
  682. /**
  683. * @returns object
  684. */
  685. public function getItem($primaryKey) {
  686. $primaryKeyField = $this->getPrimaryKeyField();
  687. $ret = null;
  688. $sql_cols = $this->_get_sql_cols();
  689. $primaryKey = intval($primaryKey);// TODO: validate $primaryKey
  690. $sql = "select {$sql_cols}
  691. from `{$this->_tbl}` as t
  692. where t.`{$primaryKeyField}`='{$primaryKey}'
  693. ";
  694. // TODO: use PDO
  695. $res = $this->_db->query($sql);
  696. if ($r = $this->_db->fetch($res)) {
  697. $ret = $r;
  698. }
  699. return $ret;
  700. }
  701. function get_items($params = array()) {// TODO: RMME
  702. $this->getItems($params);
  703. }
  704. public function getItems($params = array()) {
  705. $primaryKeyField = $this->getPrimaryKeyField();
  706. $items = array();
  707. $sql_limit = V::get('limit', $this->_default_sql_limit, $params, 'int');
  708. $sql_offset = V::get('limitstart', 0, $params, 'int');
  709. $sql_order_by = V::get('order_by', '', $params);
  710. if ($sql_order_by) {
  711. $sql_order_dir = V::get('order_dir', '', $params);
  712. // prevent from sorting by special columns
  713. if (!array_key_exists($sql_order_by, $this->_cols)) {
  714. $sql_order_by = null;
  715. $sql_order_dir = null;
  716. }
  717. }
  718. if ($sql_order_by) {
  719. $sql_order_by = "order by t.`{$sql_order_by}`";
  720. if ($sql_order_dir) {
  721. $sql_order_by = "{$sql_order_by} {$sql_order_dir}";
  722. }
  723. }
  724. $sql_cols = $this->_get_sql_cols();
  725. $sql_where = $this->_parseSqlWhere($params);
  726. $sql = "select {$sql_cols}
  727. from {$this->_tbl} as t
  728. where {$sql_where}
  729. {$sql_order_by}
  730. limit {$sql_limit} offset {$sql_offset}
  731. ";
  732. 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";}
  733. $res = $this->_db->query($sql);
  734. while ($r = $this->_db->fetch($res)) {
  735. $items[$r->{$primaryKeyField}] = $r;
  736. }
  737. return $items;
  738. }
  739. function get_hist_items($id) {// TODO: RMME
  740. $this->getHistItems($id);
  741. }
  742. public function getHistItems($id, $params = array()) {
  743. $ret = array();
  744. $sql_tbl = $this->_tbl . "_HIST";
  745. $sql_cols = $this->_get_sql_cols();
  746. $sql_where = "t.`ID_USERS2`='{$id}'";
  747. $paramNotEmptyFlds = V::get('notEmptyFlds', '', $params);
  748. if (!empty($paramNotEmptyFlds) && is_array($paramNotEmptyFlds)) {
  749. $sqlWhereOr = array();
  750. foreach ($paramNotEmptyFlds as $fldName) {
  751. if (array_key_exists($fldName, $this->_cols)) {
  752. $sqlWhereOr[] = "t.`{$fldName}`!='N/S;'";
  753. }
  754. }
  755. if (!empty($sqlWhereOr)) $sql_where .= "\n and (" . implode(" or ", $sqlWhereOr) . ")";
  756. }
  757. $sql = "select {$sql_cols}
  758. from {$sql_tbl} as t
  759. where {$sql_where}
  760. order by ID DESC
  761. ";
  762. 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";}
  763. $res = $this->_db->query($sql);
  764. while ($r = $this->_db->fetch($res)) {
  765. $r->_author = $r->A_RECORD_UPDATE_AUTHOR;
  766. $r->_created = $r->A_RECORD_UPDATE_DATE;
  767. if (!$r->_author || $r->_author == 'N/S;') {
  768. $r->_author = $r->A_RECORD_CREATE_AUTHOR;
  769. }
  770. if (!$r->_created || $r->_created == 'N/S;') {
  771. $r->_created = $r->A_RECORD_CREATE_DATE;
  772. }
  773. $ret[$r->ID] = $r;
  774. }
  775. return $ret;
  776. }
  777. function get_total($params = array()) {// TODO: RMME
  778. $this->getTotal($params);
  779. }
  780. public function getTotal($params = array()) {
  781. $ret = 0;
  782. $sql_where = $this->_parseSqlWhere($params);
  783. $sql = "select count(1) as cnt
  784. from {$this->_tbl} as t
  785. where {$sql_where}
  786. ";
  787. $res = $this->_db->query($sql);
  788. if ($r = $this->_db->fetch($res)) {
  789. $ret = $r->cnt;
  790. }
  791. return $ret;
  792. }
  793. function set_sql_where($sql_where) {
  794. $this->_sql_where = $sql_where;
  795. }
  796. function set_field_sql_type($field, $sql_type) {
  797. $this->_fields_type[$field] = $sql_type;
  798. }
  799. function get_field_sql_type($field) {
  800. if (array_key_exists($field, $this->_fields_type)) {
  801. return $this->_fields_type[$field];
  802. }
  803. return 'varchar(255)';
  804. }
  805. function set_field_perm($field, $perm) {
  806. $this->_fields_perm[$field] = $perm;
  807. }
  808. function get_field_perm($field) {
  809. if (array_key_exists($field, $this->_fields_perm)) {
  810. return $this->_fields_perm[$field];
  811. }
  812. return '';
  813. }
  814. function field_allow_write($field_name) {
  815. return (strpos($this->get_field_perm($field_name), 'W') !== false)? true : false;
  816. }
  817. function field_allow_read($field_name) {
  818. return (strpos($this->get_field_perm($field_name), 'R') !== false)? true : false;
  819. }
  820. function field_allow_create($field_name) {
  821. return (strpos($this->get_field_perm($field_name), 'C') !== false)? true : false;
  822. }
  823. public function add_col($col_name, $label = '', $type = 'string') {
  824. if (!$label) $label = $col_name;
  825. $this->_cols[$col_name] = $label;
  826. $this->_col_types[$col_name] = $type;
  827. }
  828. public function addCol($col_name) {
  829. $this->_cols[$col_name] = $col_name;
  830. }
  831. function count() {
  832. $ret = 0;
  833. $sql_where = ($this->_sql_where)? $this->_sql_where : "1=1";
  834. $sql = "select count(1) as cnt
  835. from `{$this->_tbl}`
  836. where {$sql_where}
  837. ";
  838. $res = $this->_db->query($sql);
  839. if ($r = $this->_db->fetch($res)) {
  840. $ret = $r->cnt;
  841. }
  842. return $ret;
  843. }
  844. function fetch_list($limit = 10, $offset = 0) {
  845. $primaryKeyField = $this->getPrimaryKeyField();
  846. $ret = array();
  847. $this->_sql_limit = $limit;
  848. $this->_sql_offset = $offset;
  849. $sql_cols = (!empty($this->_cols))? implode(',', array_keys($this->_cols)) : "*";
  850. $sql_where = ($this->_sql_where)? $this->_sql_where : "1=1";
  851. $sql = "
  852. select {$sql_cols}
  853. from {$this->_tbl}
  854. where {$sql_where}
  855. limit {$this->_sql_limit} offset {$this->_sql_offset}
  856. ";
  857. $res = $this->_db->query($sql);
  858. while ($r = $this->_db->fetch($res)) {
  859. $ret[$r->{$primaryKeyField}] = $r;
  860. }
  861. return $ret;
  862. }
  863. function field_check_value($field_name, $val) {
  864. if (!$this->field_allow_write($field_name)) {
  865. return false;
  866. }
  867. // post verify
  868. // get type, and check if value is correct
  869. // TODO: if typespecial use it
  870. return true;
  871. }
  872. function save_item(&$item, $values, $prefix) {
  873. if (!$item->ID) {
  874. return null;
  875. }
  876. $sql_obj = new stdClass();
  877. $sql_obj->ID = $item->ID;
  878. foreach ($values as $k_field_with_prefix => $v_field) {
  879. if (substr($k_field_with_prefix, 0, strlen($prefix)) != $prefix) {
  880. continue;
  881. }
  882. $k_field = substr($k_field_with_prefix, strlen($prefix));
  883. if ($this->field_allow_write($k_field)) {
  884. if ($this->field_check_value($k_field, $v_field)) {
  885. $sql_obj->$k_field = $v_field;
  886. }
  887. }
  888. }
  889. $affected = $this->_db->PDATE_OBJ($this->_tbl, $sql_obj);
  890. return $affected;
  891. }
  892. function add_item($values, $prefix) {
  893. $sql_obj = new stdClass();
  894. foreach ($values as $k_field_with_prefix => $v_field) {
  895. if (substr($k_field_with_prefix, 0, strlen($prefix)) != $prefix) {
  896. continue;
  897. }
  898. $k_field = substr($k_field_with_prefix, strlen($prefix));
  899. if ($this->field_allow_create($k_field)) {
  900. if ($this->field_check_value($k_field, $v_field)) {
  901. $sql_obj->$k_field = $v_field;
  902. }
  903. }
  904. }
  905. $insert_id = $this->_db->ADD_NEW_OBJ($this->_tbl, $sql_obj);
  906. return $insert_id;
  907. }
  908. public function getGeomFields() {
  909. return $this->_geomFields;
  910. }
  911. public function isGeomField($fldName) {
  912. return in_array($fldName, $this->_geomFields);
  913. }
  914. public function isCsvNumericField($fldName) {
  915. return ('_CSV_NUM' == substr($fldName, -8));
  916. }
  917. public function updateItem($itemPatch) {
  918. // TODO: $item as array and copy from $db->UPDATE_OBJ using PDO
  919. if (is_object($itemPatch)) {
  920. $itemPatch = (array)$itemPatch;
  921. } else if (!is_array($itemPatch)) {
  922. throw new HttpException('Item patch is not array', 400);
  923. }
  924. if (empty($itemPatch)) {
  925. //throw new Exception('Item patch is empty');
  926. return 0;// nothing to change
  927. }
  928. $primaryKeyField = $this->getPrimaryKeyField();
  929. if (empty($itemPatch[$primaryKeyField])) {
  930. throw new HttpException("Item Primary Key not set!", 400);
  931. }
  932. // the geom fix
  933. foreach ($itemPatch as $fld => $val) {
  934. if ($this->isGeomField($fld)) {
  935. if (!empty($val)
  936. && 'NULL' !== $val
  937. && 'GeomFromText' != substr($val, 0, strlen('GeomFromText'))
  938. ) {
  939. $itemPatch[$fld] = "GeomFromText('{$val}')";
  940. }
  941. }
  942. }
  943. $itemPatch = (object)$itemPatch;
  944. $affected = $this->_db->UPDATE_OBJ($this->_tbl, $itemPatch);
  945. if ($affected < 0) {
  946. $dsErrors = $this->getDbErrors();
  947. //$dsErrors = "Wystąpiły błędy!\n" . implode("\n", $dsErrors);
  948. if (!empty($dsErrors)) {
  949. throw new StorageException($dsErrors);
  950. }
  951. }
  952. return $affected;
  953. }
  954. public function addItem($item) {
  955. // TODO: $item as array and copy from $db->ADD_NEW_OBJ using PDO
  956. if (is_object($item)) {
  957. $item = (array)$item;
  958. } else if (!is_array($item)) {
  959. throw new HttpException('Item is not array', 400);
  960. }
  961. if (empty($item)) {
  962. //throw new Exception('Item patch is empty');
  963. return 0;// nothing to insert
  964. }
  965. // the geom fix
  966. foreach ($item as $fld => $val) {
  967. if ($this->isGeomField($fld)) {
  968. if (!empty($val)
  969. && 'NULL' !== $val
  970. && 'GeomFromText' != substr($val, 0, strlen('GeomFromText'))
  971. ) {
  972. $item[$fld] = "GeomFromText('{$val}')";
  973. }
  974. }
  975. }
  976. $item = (object)$item;
  977. $primaryKey = $this->_db->ADD_NEW_OBJ($this->_tbl, $item);
  978. if ($primaryKey < 0) {
  979. $dsErrors = $this->getDbErrors();
  980. $dsErrors = "Wystąpiły błędy!\n" . implode("\n", $dsErrors);
  981. throw new Exception($dsErrors);
  982. }
  983. return $primaryKey;
  984. }
  985. public function getDbErrors() {
  986. $errors = array();
  987. if ($this->_db->has_errors()) {
  988. $errorsSql = $this->_db->get_errors();
  989. foreach ($errorsSql as $vErr) {
  990. if ('SQL QUERY FAILED: ' == substr($vErr, 0, 18)) {
  991. $vErr = substr($vErr, 18);
  992. }
  993. //$errors[] = StorageException::parseMessage($vErr);
  994. $errors[] = $vErr;
  995. }
  996. }
  997. return $errors;
  998. }
  999. public function getPrimaryKeyField() {
  1000. return 'ID';// TODO: read from struct - jest funkcja w Mysql.php my Psql.php
  1001. }
  1002. }