Data_Source.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  1. <?php
  2. Lib::loadClass('SqlQueryWhereBuilder');
  3. Lib::loadClass('ParseOgcFilter');
  4. Lib::loadClass('DBG');
  5. /**
  6. * API:
  7. * get($field_name) - source field value
  8. * get_item($id) - get item by ID
  9. */
  10. class Data_Source {
  11. var $_db;
  12. var $_tbl;// sql table name, TODO: or zasob ID
  13. var $_default_sql_limit;
  14. var $_fields_type;// array of fields ( name => type )
  15. var $_fields_perm;// array of field perm ( name => perm )
  16. var $_cols = array();
  17. var $_vCols = array();// setVirtualCols - TODO: use Typespecial
  18. var $_col_types = array();// TODO: array( col_name => TYPE )
  19. var $_sql_where;// sql where
  20. var $_sql_limit;
  21. var $_sql_offset;
  22. var $_sql_left_join;// TODO: left join in table
  23. var $_isAccessFltrAllowed = null;
  24. private $_fieldOwner = null;
  25. private $_fieldGroupWrite = null;
  26. private $_fieldGroupRead = null;
  27. private $_showMsgsSpecialFilter = false;
  28. function __construct($db = null) {
  29. $this->_idDatabase = ($db) ? $db : null;
  30. // if ($db) { // TODO: RM use DB::getPDO($this->_idDatabase)
  31. // $this->_db = DB::getDB($db); // TODO: RM
  32. // } else {
  33. // $this->_db = DB::getDB(); // TODO: RM
  34. // }
  35. $this->_default_sql_limit = 10;
  36. $this->_showMsgsSpecialFilter = true;// TODO: allow by acl, procesy?
  37. }
  38. function getDB() {
  39. return ($this->_idDatabase) ? DB::getDB($this->_idDatabase) : DB::getDB();
  40. }
  41. function set_table($tbl) {// TODO: RMME
  42. $this->setTable($tbl);
  43. }
  44. public function setTable($tbl) {
  45. $this->_tbl = $tbl;
  46. $this->_fields_type = array();
  47. $this->_fields_perm = array();
  48. }
  49. function get_cols() {
  50. if (empty($this->_cols)) {
  51. if (!$this->_tbl) return null;
  52. foreach (DB::getPDO($this->_idDatabase)->fetchAll(" show fields from `{$this->_tbl}` ") as $row) {
  53. $fieldName = $row['Field'];
  54. $this->_cols[ $fieldName ] = $fieldName;
  55. $this->_col_types[ $fieldName ] = "{$row['Type']};{$row['Default']}";
  56. }
  57. }
  58. return $this->_cols;
  59. }
  60. public function getFieldTypes() {
  61. $fieldTypes = array();
  62. foreach (DB::getPDO($this->_idDatabase)->fetchAll(" show fields from `{$this->_tbl}` ") as $row) {
  63. $fieldName = $row['Field'];
  64. $fieldType = $row['Type'];
  65. $fieldTypes[ $fieldName ] = [
  66. 'type' => $fieldType,
  67. 'null' => ('YES' == $row['Null']),
  68. 'default' => $row['Default']
  69. ];
  70. }
  71. DBG::log($fieldTypes, 'array', "types({$this->_tbl})");
  72. return $fieldTypes;
  73. }
  74. public function getUniqueKeys() {
  75. $sqlKeys = array();
  76. //$dbID = $this->getDB();
  77. $db = $this->getDB();
  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 _getSqlCols($colsList = null) {
  142. $sqlCols = "t.*";
  143. if (!empty($this->_cols)) {
  144. $sqlColsList = array();
  145. if (null === $colsList || empty($colsList)) {
  146. $colsList = array_keys($this->_cols);
  147. }
  148. foreach ($colsList as $fieldName) {
  149. if (!array_key_exists($fieldName, $this->_cols)) throw new Exception("Field not exists '{$fieldName}'!");
  150. if ($this->isGeomField($fieldName)) {
  151. $sqlFld = "AsWKT(t.`{$fieldName}`) as {$fieldName}";
  152. } else {
  153. $sqlFld = "t.`{$fieldName}`";
  154. }
  155. $sqlColsList[] = $sqlFld;
  156. }
  157. $sqlCols = implode(", ", $sqlColsList);
  158. }
  159. return $sqlCols;
  160. }
  161. public function setAccessFltrAllowed($isAccessFltrAllowed) {
  162. $this->_isAccessFltrAllowed = $isAccessFltrAllowed;
  163. }
  164. public function isAccessFltrAllowed() {
  165. if (false === $this->_isAccessFltrAllowed) {
  166. return false;
  167. }
  168. else if ($this->hasAclGroupFields()) {
  169. return true;
  170. }
  171. return false;
  172. }
  173. public function hasAclGroupFields() {
  174. if ( !empty($this->_fieldGroupWrite)
  175. && !empty($this->_fieldGroupRead)
  176. && array_key_exists('A_ADM_COMPANY', $this->_cols)
  177. && array_key_exists('A_CLASSIFIED', $this->_cols)
  178. ) {
  179. return true;
  180. }
  181. return false;
  182. }
  183. function getSpecialFilters() {
  184. $fltrs = array();
  185. if ($this->_showMsgsSpecialFilter) {
  186. $fltrs['Msgs'] = new stdClass();
  187. $fltrs['Msgs']->icon = 'glyphicon glyphicon-envelope';
  188. $fltrs['Msgs']->label = 'Wiadomości';
  189. $fltrs['Msgs']->btns = array();
  190. $fltrs['Msgs']->btns['WIADOMOSCI'] = (object)array('value'=>'HAS_MSGS');
  191. $fltrs['Msgs']->btns['NOWE'] = (object)array('value'=>'NEW_MSGS');
  192. $fltrs['Msgs']->btns['BRAK_WIAD.'] = (object)array('value'=>'NO_MSGS');
  193. }
  194. if (array_key_exists('A_PROBLEM', $this->_cols)) {
  195. $fltrs['Problemy'] = new stdClass();
  196. $fltrs['Problemy']->icon = 'glyphicon glyphicon-warning-sign';
  197. $fltrs['Problemy']->btns = array();
  198. $fltrs['Problemy']->btns['PROBLEMY'] = (object)array('value'=>'PROBLEM');
  199. $fltrs['Problemy']->btns['OSTRZEZENIA'] = (object)array('value'=>'WARNING');
  200. $fltrs['Problemy']->btns['BEZ_PROBLEM.'] = (object)array('value'=>'NORMAL');
  201. }
  202. if (array_key_exists('A_STATUS', $this->_cols)) {
  203. $fltrs['Status'] = new stdClass();
  204. $fltrs['Status']->icon = 'glyphicon glyphicon-question-sign';
  205. $fltrs['Status']->btns = array();
  206. $fltrs['Status']->btns['OCZEKUJACY'] = (object)array('value'=>'WAITING');
  207. $fltrs['Status']->btns['AKTYWNI'] = (object)array('value'=>'AKTYWNI');
  208. }
  209. if (array_key_exists('L_APPOITMENT_DATE', $this->_cols)) {
  210. $fltrs['Spotkania'] = new stdClass();
  211. $fltrs['Spotkania']->icon = 'glyphicon glyphicon-calendar';
  212. $fltrs['Spotkania']->btns = array();
  213. $fltrs['Spotkania']->btns['STARE'] = (object)array('value'=>'OLD');
  214. $fltrs['Spotkania']->btns['ZARAZ'] = (object)array('value'=>'NOW');
  215. $fltrs['Spotkania']->btns['DZISIAJ'] = (object)array('value'=>'TODAY');
  216. $fltrs['Spotkania']->btns['BRAK'] = (object)array('value'=>'BRAK');
  217. }
  218. if ($this->isAccessFltrAllowed()) {
  219. $fltrs['Access'] = new stdClass();
  220. $fltrs['Access']->icon = 'glyphicon glyphicon-lock';
  221. $fltrs['Access']->btns = array();
  222. $fltrs['Access']->btns['Pokaż'] = (object)array('value'=>'SHOW');
  223. }
  224. return $fltrs;
  225. }
  226. public function _parseOgcFilter($ogcFilter) {
  227. $parser = new ParseOgcFilter();
  228. $parser->loadOgcFilter($ogcFilter);
  229. $queryWhereBuilder = $parser->convertToSqlQueryWhereBuilder();
  230. return $queryWhereBuilder->getQueryWhere('t');
  231. }
  232. function _parseSpecialFilter($fltr, $value) {
  233. $sqlFltr = "";
  234. switch ($fltr) {
  235. case 'Msgs':
  236. if ($this->_showMsgsSpecialFilter) {
  237. $sqHasFltrMsgs = "
  238. select 1
  239. from `CRM_UI_MSGS` m
  240. where m.`uiTargetName`=CONCAT('{$this->_tbl}.', t.`ID`)
  241. and m.`uiTargetType`='default_db_table_record'
  242. and m.`A_STATUS` not in('DELETED')
  243. limit 1
  244. ";
  245. switch ($value) {
  246. case 'NEW_MSGS':
  247. $sqNewFltrMsgs = "
  248. select 1
  249. from `CRM_UI_MSGS` m
  250. where m.`uiTargetName`=CONCAT('{$this->_tbl}.', t.`ID`)
  251. and m.`uiTargetType`='default_db_table_record'
  252. and m.`A_STATUS` in('WAITING')
  253. limit 1
  254. ";
  255. $sqlFltr = " ({$sqNewFltrMsgs})=1 ";
  256. break;
  257. case 'HAS_MSGS':
  258. $sqlFltr = " ({$sqHasFltrMsgs})=1 ";
  259. break;
  260. case 'NO_MSGS':
  261. $sqlFltr = " ({$sqHasFltrMsgs}) is null ";
  262. break;
  263. }
  264. }
  265. break;
  266. case 'Problemy':
  267. if (array_key_exists('A_PROBLEM', $this->_cols)) {
  268. switch ($value) {
  269. case 'PROBLEM':
  270. $sqlFltr = " t.`A_PROBLEM`!='' ";
  271. break;
  272. case 'WARNING':
  273. $sqlFltr = " t.`A_PROBLEM`='WARNING' ";
  274. break;
  275. case 'NORMAL':
  276. $sqlFltr = " t.`A_PROBLEM`='' ";
  277. break;
  278. }
  279. }
  280. break;
  281. case 'Status':
  282. if (array_key_exists('A_STATUS', $this->_cols)) {
  283. switch ($value) {
  284. case 'WAITING':
  285. $sqlFltr = " t.`A_STATUS`='WAITING' ";
  286. break;
  287. case 'AKTYWNI':
  288. $sqlFltr = " t.`A_STATUS` in('NORMAL', 'WARNING') ";
  289. // 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='' )) ";
  290. // 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' ) ";
  291. break;
  292. }
  293. }
  294. break;
  295. case 'Spotkania':
  296. if (array_key_exists('L_APPOITMENT_DATE', $this->_cols)) {
  297. switch ($value) {
  298. case 'OLD':
  299. $sqlFltr = "
  300. COALESCE(UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`), 0) < UNIX_TIMESTAMP(now())
  301. and t.`L_APPOITMENT_DATE` != ''
  302. and t.`L_APPOITMENT_DATE` != '0000-00-00 00:00:00'
  303. ";
  304. break;
  305. case 'NOW':
  306. $sqlFltr = "
  307. COALESCE(UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`), 0) < UNIX_TIMESTAMP(now())+3600
  308. and COALESCE(UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`), 0) > UNIX_TIMESTAMP(now())-3600
  309. ";
  310. break;
  311. case 'TODAY':
  312. $start = mktime(0,0,0, date("m"), date("d"), date("Y"));
  313. $end = mktime(0,0,0, date("m"), date("d") + 1, date("Y"));
  314. $sqlFltr = "
  315. COALESCE(UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`), 0) > '{$start}'
  316. and COALESCE(UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`), 0) < '{$end}'
  317. ";
  318. break;
  319. case 'TOMORROW':
  320. $start = mktime(0,0,0, date("m"), date("d") + 1, date("Y"));
  321. $end = mktime(0,0,0, date("m"), date("d") + 2, date("Y"));
  322. $sqlFltr = "
  323. COALESCE(UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`), 0) > '{$start}'
  324. and COALESCE(UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`), 0) < '{$end}'
  325. ";
  326. break;
  327. case 'YESTERDAY':
  328. $start = mktime(0,0,0, date("m"), date("d") - 1, date("Y"));
  329. $end = mktime(0,0,0, date("m"), date("d") - 2, date("Y"));
  330. $sqlFltr = "
  331. COALESCE(UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`), 0) > '{$start}'
  332. and COALESCE(UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`), 0) < '{$end}'
  333. ";
  334. break;
  335. case 'BRAK':
  336. $start = mktime(0,0,0, date("m"), date("d") - 1, date("Y"));
  337. $end = mktime(0,0,0, date("m"), date("d") - 2, date("Y"));
  338. $sqlFltr = "
  339. (t.`L_APPOITMENT_DATE` = ''
  340. or t.`L_APPOITMENT_DATE` = '0000-00-00 00:00:00')
  341. ";
  342. break;
  343. }
  344. }
  345. break;
  346. case 'Access':
  347. if ('SHOW' != $value && $this->isAccessFltrAllowed()) {
  348. $userLogin = User::getLogin();
  349. $usrAclGroups = User::getLdapGroupsNames();
  350. $usrAclGroups[] = '';// TODO: allow empty for everyone?
  351. $sqlUsrAclGroups = "'" . implode("','", $usrAclGroups) . "'";
  352. $sqlFltr = "
  353. ( t.`{$this->_fieldGroupWrite}` in({$sqlUsrAclGroups})
  354. or t.`{$this->_fieldGroupRead}` in({$sqlUsrAclGroups})
  355. )
  356. ";
  357. if (array_key_exists('L_APPOITMENT_USER', $this->_cols)) {
  358. $sqlFltr = "
  359. (
  360. ({$sqlFltr})
  361. or t.`L_APPOITMENT_USER`='{$userLogin}'
  362. )
  363. ";
  364. }
  365. }
  366. break;
  367. default:
  368. }
  369. /*
  370. //USERS_FILTER_PROBLEM
  371. // PROBLEMY https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_PROBLEM&USERS_FILTER_PROBLEM=PROBLEM
  372. // OSTRZEZENIA https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_PROBLEM&USERS_FILTER_PROBLEM=WARNING
  373. // BEZ_PROBLEM. https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_PROBLEM&USERS_FILTER_PROBLEM=NORMAL
  374. // KASUJ-FILTR https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_PROBLEM&USERS_FILTER_PROBLEM=
  375. //USERS_FILTER_STATUS
  376. // OCZEKUJACY https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_STATUS&USERS_FILTER_STATUS=WAITING
  377. // AKTYWNI https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_STATUS&USERS_FILTER_STATUS=AKTYWNI
  378. // KASUJ-FILTR https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_STATUS&USERS_FILTER_STATUS=
  379. //USERS_FILTER_APPOINTMENT
  380. // A_STARE https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_APPOINTMENT&USERS_FILTER_APPOINTMENT=OLD
  381. // A_ZARAZ https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_APPOINTMENT&USERS_FILTER_APPOINTMENT=NOW
  382. // A_DZISIAJ https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_APPOINTMENT&USERS_FILTER_APPOINTMENT=TODAY
  383. // APP_ALL https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_APPOINTMENT&USERS_FILTER_APPOINTMENT=
  384. // btn class: active, disabled
  385. {// USERS_FILTER_PROBLEM
  386. var groupHtml = $('<div class="btn-group"></div>');
  387. $('<button class="btn btn-xs" title="Problemy"><i class="glyphicon glyphicon-warning-sign"></i></button>').appendTo(groupHtml);
  388. $('<button class="btn btn-xs">PROBLEMY</button>').appendTo(groupHtml);
  389. $('<button class="btn btn-xs">OSTRZEZENIA</button>').appendTo(groupHtml);
  390. $('<button class="btn btn-xs active">BEZ_PROBLEM.</button>').appendTo(groupHtml);
  391. $('<button class="btn btn-xs disabled" title="Kasuj filtr"><i class="glyphicon glyphicon-remove"></i></button>').appendTo(groupHtml);
  392. groupHtml.appendTo(_headSpecialFilter);
  393. }
  394. {// USERS_FILTER_STATUS
  395. var groupHtml = $('<div class="btn-group"></div>');
  396. $('<button class="btn btn-xs" title="Status"><i class="glyphicon glyphicon-question-sign"></i></button>').appendTo(groupHtml);
  397. $('<button class="btn btn-xs">OCZEKUJACY</button>').appendTo(groupHtml);
  398. $('<button class="btn btn-xs">AKTYWNI</button>').appendTo(groupHtml);
  399. $('<button class="btn btn-xs disabled" title="Kasuj filtr"><i class="glyphicon glyphicon-remove"></i></button>').appendTo(groupHtml);
  400. groupHtml.appendTo(_headSpecialFilter);
  401. }
  402. {// USERS_FILTER_APPOINTMENT
  403. var groupHtml = $('<div class="btn-group"></div>');
  404. $('<button class="btn btn-xs" title="Spotkania"><i class="glyphicon glyphicon-calendar"></i></button>').appendTo(groupHtml);
  405. $('<button class="btn btn-xs">A_STARE</button>').appendTo(groupHtml);
  406. $('<button class="btn btn-xs">A_ZARAZ</button>').appendTo(groupHtml);
  407. $('<button class="btn btn-xs active">A_DZISIAJ</button>').appendTo(groupHtml);
  408. $('<button class="btn btn-xs disabled" title="Kasuj filtr"><i class="glyphicon glyphicon-remove"></i></button>').appendTo(groupHtml);// To samo co KASUJ-FILTR
  409. groupHtml.appendTo(_headSpecialFilter);
  410. }
  411. */
  412. return $sqlFltr;
  413. }
  414. private function isColTypeNumber($colName) {
  415. if ($colName == 'ID') {
  416. return true;
  417. }
  418. $type = V::get($colName, null, $this->_col_types);
  419. 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";}
  420. if (!empty($type['type'])) {
  421. $sqlType = $type['type'];
  422. if (substr($sqlType, 0, 3) == 'int'
  423. || substr($sqlType, 0, 7) == 'tinyint'
  424. || substr($sqlType, 0, 8) == 'smallint'
  425. ) {
  426. return true;
  427. }
  428. }
  429. return false;
  430. }
  431. public function _parseSqlWhere($params = array()) {
  432. if (empty($params['sf_Access'])) $params['sf_Access'] = 'HIDE'; // default filter value
  433. $sql_where = '';
  434. // ... parse filters
  435. $sql_where_and = array();
  436. foreach ($params as $k => $v) {
  437. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_') {
  438. //$v = trim($v, '% ');
  439. //$sql_where_and[] = "t.`" . substr($k, 2) . "` like '%" . DB::_($v) . "%'";
  440. $fldName = substr($k, 2);
  441. if ($this->isGeomField($fldName)) {
  442. $sqlFilter = $this->_sqlValueForGeomField($fldName, $v, 't');
  443. if ($sqlFilter) $sql_where_and[] = $sqlFilter;
  444. continue;
  445. }
  446. if ($this->isCsvNumericField($fldName)) {
  447. $sqlFilter = $this->_sqlValueForCsvNumericField($fldName, $v, 't');
  448. if ($sqlFilter) $sql_where_and[] = $sqlFilter;
  449. continue;
  450. }
  451. if (substr($v, 0, 1) == '=') {
  452. $v = $this->getDB()->_(substr($v, 1));
  453. if (strlen($v)) $sql_where_and[] = "t.`{$fldName}`='{$v}'";
  454. }
  455. else if ($v == '!NULL' || $v == 'IS NOT NULL') {
  456. $sql_where_and[] = "t.`{$fldName}` is not null";
  457. }
  458. else if (substr($v, 0, 1) == '!') {
  459. $v = $this->getDB()->_(substr($v, 1));
  460. if (strlen($v)) $sql_where_and[] = "t.`{$fldName}` not like '{$v}'";
  461. }
  462. else if (substr($v, 0, 2) == '<=') {
  463. $v = $this->getDB()->_(substr($v, 2));
  464. if (strlen($v)) $sql_where_and[] = "t.`{$fldName}`<='{$v}'";
  465. }
  466. else if (substr($v, 0, 2) == '>=') {
  467. $v = $this->getDB()->_(substr($v, 2));
  468. if (strlen($v)) $sql_where_and[] = "t.`{$fldName}`>='{$v}'";
  469. }
  470. else if (substr($v, 0, 1) == '<') {
  471. $v = $this->getDB()->_(substr($v, 1));
  472. if (strlen($v)) $sql_where_and[] = "t.`{$fldName}`<'{$v}'";
  473. }
  474. else if (substr($v, 0, 1) == '>') {
  475. $v = $this->getDB()->_(substr($v, 1));
  476. if (strlen($v)) $sql_where_and[] = "t.`{$fldName}`>'{$v}'";
  477. }
  478. else if (false !== strpos($v, '%')) {
  479. $sql_where_and[] = "t.`{$fldName}` like '{$v}'";
  480. }
  481. else if ($this->isColTypeNumber($fldName)) {
  482. $v = $this->getDB()->_($v);
  483. $sql_where_and[] = "t.`{$fldName}`='{$v}'";
  484. }
  485. else {
  486. $queryWhereBuilder = new SqlQueryWhereBuilder();
  487. $searchWords = $queryWhereBuilder->splitQueryToWords($v);
  488. $sqlWhereWords = array();
  489. if (!empty($searchWords)) {
  490. foreach ($searchWords as $word) {
  491. $sqlWord = $this->getDB()->_($word);
  492. $sqlWhereWords[] = "t.`{$fldName}` like '%{$sqlWord}%'";
  493. }
  494. }
  495. if (!empty($searchWords)) {
  496. $sql_where_and[] = "(" . implode(" and ", $sqlWhereWords) . ")";
  497. }
  498. }
  499. }
  500. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_') {
  501. $sqlFltr = $this->_parseSpecialFilter(substr($k, 3), $v);
  502. if (!empty($sqlFltr)) {
  503. $sql_where_and[] = $sqlFltr;
  504. }
  505. }
  506. else if ('ogc:Filter' == $k) {
  507. $sqlFltr = $this->_parseOgcFilter($v);
  508. if (!empty($sqlFltr)) {
  509. $sql_where_and[] = $sqlFltr;
  510. }
  511. }
  512. else if ('primaryKey' == $k) {
  513. if (!empty($v)) {
  514. $primaryKeyField = $this->getPrimaryKeyField();
  515. $sql_where_and[] = "t.`{$primaryKeyField}` = '" . $this->getDB()->_($v) . "'";
  516. }
  517. }
  518. }
  519. if (!empty($sql_where_and)) {
  520. $sql_where = implode(" and ", $sql_where_and);
  521. }
  522. if (!$sql_where) $sql_where = "1=1";
  523. 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"\n".'params: ';print_r($params);echo'</pre>'."\n\n";}
  524. return $sql_where;
  525. }
  526. private function _sqlValueForGeomField($fldName, $fltrValue, $tblPrefix = 't') {
  527. $sqlFilter = false;
  528. // example: BBOX:54.40993961633866,18.583889010112824,54.337945760687454,18.397121431987586
  529. if ('BBOX:' == substr($fltrValue, 0, 5)) {
  530. $val = substr($fltrValue, 5);
  531. $valParts = explode(',', $val);
  532. if (count($valParts) == 4) {
  533. $isAllNumeric = true;
  534. foreach ($valParts as $v) {
  535. if (!is_numeric($v)) $isAllNumeric = false;
  536. }
  537. if ($isAllNumeric) {
  538. $bounds = "POLYGON((
  539. {$valParts[3]} {$valParts[2]},
  540. {$valParts[3]} {$valParts[0]},
  541. {$valParts[1]} {$valParts[0]},
  542. {$valParts[1]} {$valParts[2]},
  543. {$valParts[3]} {$valParts[2]}
  544. ))";
  545. // for mysql 5.6 use ST_Contains() @see http://dev.mysql.com/doc/refman/5.6/en/spatial-relation-functions.html
  546. $sqlFilter = "Intersects(GeomFromText('{$bounds}'), {$tblPrefix}.`{$fldName}`)=1";
  547. }
  548. }
  549. }
  550. else if ('GeometryType=' == substr($fltrValue, 0, 13)) {
  551. $sqlFilter = "GeometryType({$tblPrefix}.`{$fldName}`)='" . substr($fltrValue, 13) . "'";
  552. }
  553. return $sqlFilter;
  554. }
  555. private function _sqlValueForCsvNumericField($fldName, $fltrValue, $tblPrefix = 't') {
  556. $sqlFilter = false;
  557. if (is_numeric($fltrValue)) {
  558. $sqlFilter = "FIND_IN_SET('{$fltrValue}', `{$fldName}`)>0";
  559. } else if (false !== strpos($fltrValue, ' ')) {
  560. $sqlGlue = " or ";
  561. $fltrValues = $fltrValue;
  562. if ('&' == substr($fltrValues, 0, 1)) {
  563. $fltrValues = substr($fltrValues, 1);
  564. $sqlGlue = " and ";
  565. }
  566. $fltrValues = explode(' ', $fltrValues);
  567. $sqlNumericValues = array();
  568. foreach ($fltrValues as $fltrVal) {
  569. if (is_numeric($fltrVal)) {
  570. $sqlNumericValues[] = "FIND_IN_SET('{$fltrVal}', `{$fldName}`)>0";
  571. }
  572. }
  573. if (!empty($sqlNumericValues)) {
  574. $sqlFilter = "(" . implode($sqlGlue, $sqlNumericValues) . ")";
  575. }
  576. }
  577. return $sqlFilter;
  578. }
  579. function get_item($id) {// TODO: RMME
  580. $this->getItem($id);
  581. }
  582. /**
  583. * @returns object
  584. */
  585. public function getItem($primaryKey, $params = []) {
  586. $primaryKeyField = $this->getPrimaryKeyField();
  587. $ret = null;
  588. $sql_cols = $this->_getSqlCols();
  589. $primaryKey = intval($primaryKey);// TODO: validate $primaryKey
  590. $sql = "select {$sql_cols}
  591. from `{$this->_tbl}` as t
  592. where t.`{$primaryKeyField}`='{$primaryKey}'
  593. ";
  594. // TODO: use PDO
  595. $res = $this->getDB()->query($sql);
  596. if ($r = $this->getDB()->fetch($res)) {
  597. $ret = $r;
  598. }
  599. return $ret;
  600. }
  601. function get_items($params = array()) {// TODO: RMME
  602. $this->getItems($params);
  603. }
  604. public function getItems($params = array()) {
  605. $primaryKeyField = $this->getPrimaryKeyField();
  606. DBG::log("Data_Source::getItems - \$primaryKeyField({$primaryKeyField})");
  607. $items = array();
  608. $sql = new stdClass();
  609. $sql->_cols = V::get('cols', null, $params);
  610. if (!is_array($sql->_cols) || empty($sql->_cols)) {
  611. $sql->_cols = null;
  612. }
  613. $sql->limit = V::get('limit', $this->_default_sql_limit, $params, 'int');
  614. $sql->offset = V::get('limitstart', 0, $params, 'int');
  615. $sql->orderBy = '';
  616. $sql->_orderBy = V::get('order_by', '', $params);
  617. $sql->_sortBy = V::get('sortBy', '', $params);
  618. if ($sql->_sortBy) {// ID A,COL_X D,COL_Y A,...
  619. $sql->_sortByList = array();
  620. $sortByEx = explode(',', $sql->_sortBy);
  621. foreach ($sortByEx as $sortPart) {
  622. $sortPart = trim($sortPart);
  623. if (empty($sortPart)) continue;
  624. $sortPartEx = explode(' ', $sortPart);
  625. if (count($sortPartEx) > 2) throw new Exception("SortBy parse error #" . __LINE__);
  626. $sortColName = trim($sortPartEx[0]);
  627. if (!array_key_exists($sortColName, $this->_cols)) throw new Exception("SortBy parse error - no column name '{$sortColName}' #" . __LINE__);
  628. $colSortDir = 'ASC';
  629. if (count($sortPartEx) == 2) {
  630. if ('A' == $sortPartEx[1] || 'ASC' == $sortPartEx[1]) {
  631. } else if ('D' == $sortPartEx[1] || 'DESC' == $sortPartEx[1]) {
  632. $colSortDir = 'DESC';
  633. } else throw new Exception("SortBy parse error - unknown sort order '{$sortPartEx[1]}' #" . __LINE__);
  634. }
  635. $sql->_sortByList[] = "t.`{$sortColName}` {$colSortDir}";
  636. }
  637. if (!empty($sql->_sortByList)) {
  638. $sql->orderBy = "order by " . implode(", ", $sql->_sortByList);
  639. }
  640. } else {
  641. if ($sql->_orderBy) {
  642. $sql->_orderDir = V::get('order_dir', '', $params);
  643. // prevent from sorting by special columns
  644. if (!array_key_exists($sql->_orderBy, $this->_cols)) {
  645. $sql->_orderBy = null;
  646. $sql->_orderDir = null;
  647. }
  648. }
  649. if ($sql->_orderBy) {
  650. $sql->orderBy = "order by t.`{$sql->_orderBy}`";
  651. if ($sql->_orderDir) {
  652. $sql->orderBy = "{$sql->orderBy} {$sql->_orderDir}";
  653. }
  654. }
  655. }
  656. $sql->where = $this->_parseSqlWhere($params);
  657. $sql->cols = $this->_getSqlCols($sql->_cols);
  658. $sql->query = "select {$sql->cols}
  659. from `{$this->_tbl}` t
  660. where {$sql->where}
  661. {$sql->orderBy}
  662. limit {$sql->limit} offset {$sql->offset}
  663. ";
  664. DBG::log([ 'msg'=>"Data_Source::getItems - \$sql", '$sql'=>$sql ]);
  665. $res = $this->getDB()->query($sql->query);
  666. while ($r = $this->getDB()->fetch($res)) {
  667. $items[$r->{$primaryKeyField}] = $r;
  668. }
  669. return $items;
  670. }
  671. function get_hist_items($id) {// TODO: RMME
  672. $this->getHistItems($id);
  673. }
  674. public function getHistItems($id, $params = array()) {
  675. $ret = array();
  676. DBG::_('DBG_DS', '>1', "params", $params, __CLASS__, __FUNCTION__, __LINE__);
  677. $sql_tbl = $this->_tbl . "_HIST";
  678. $sql_cols = $this->_getSqlCols();
  679. $sql_where = "t.`ID_USERS2`='{$id}'";
  680. $idHist = V::get('ID', 0, $params, 'int');
  681. if ($idHist > 0) {
  682. $sql_where .= "\n and t.`ID`='{$idHist}'";
  683. }
  684. $paramNotEmptyFlds = V::get('notEmptyFlds', '', $params);
  685. if (!empty($paramNotEmptyFlds) && is_array($paramNotEmptyFlds)) {
  686. $sqlWhereOr = array();
  687. foreach ($paramNotEmptyFlds as $fldName) {
  688. if (array_key_exists($fldName, $this->_cols)) {
  689. $sqlWhereOr[] = "t.`{$fldName}`!='N/S;'";
  690. }
  691. }
  692. if (!empty($sqlWhereOr)) $sql_where .= "\n and (" . implode(" or ", $sqlWhereOr) . ")";
  693. }
  694. $sql = "select {$sql_cols}
  695. from {$sql_tbl} as t
  696. where {$sql_where}
  697. order by ID DESC
  698. ";
  699. DBG::_('DBG_DS', '>1', "sql", $sql, __CLASS__, __FUNCTION__, __LINE__);
  700. $res = $this->getDB()->query($sql);
  701. while ($r = $this->getDB()->fetch($res)) {
  702. $r->_author = $r->A_RECORD_UPDATE_AUTHOR;
  703. $r->_created = $r->A_RECORD_UPDATE_DATE;
  704. if (!$r->_author || $r->_author == 'N/S;') {
  705. $r->_author = $r->A_RECORD_CREATE_AUTHOR;
  706. }
  707. if (!$r->_created || $r->_created == 'N/S;') {
  708. $r->_created = $r->A_RECORD_CREATE_DATE;
  709. }
  710. $ret[$r->ID] = $r;
  711. }
  712. DBG::_('DBG_DS', '>2', "ret", $ret, __CLASS__, __FUNCTION__, __LINE__);
  713. return $ret;
  714. }
  715. function get_total($params = array()) {// TODO: RMME
  716. $this->getTotal($params);
  717. }
  718. public function getTotal($params = array()) {
  719. $ret = 0;
  720. $sql_where = $this->_parseSqlWhere($params);
  721. $sql = "select count(1) as cnt
  722. from {$this->_tbl} as t
  723. where {$sql_where}
  724. ";
  725. $res = $this->getDB()->query($sql);
  726. if ($r = $this->getDB()->fetch($res)) {
  727. $ret = $r->cnt;
  728. }
  729. return $ret;
  730. }
  731. function set_sql_where($sql_where) {
  732. $this->_sql_where = $sql_where;
  733. }
  734. function set_field_sql_type($field, $sql_type) {
  735. $this->_fields_type[$field] = $sql_type;
  736. }
  737. function get_field_sql_type($field) {
  738. if (array_key_exists($field, $this->_fields_type)) {
  739. return $this->_fields_type[$field];
  740. }
  741. return 'varchar(255)';
  742. }
  743. function set_field_perm($field, $perm) {
  744. $this->_fields_perm[$field] = $perm;
  745. }
  746. function get_field_perm($field) {
  747. if (array_key_exists($field, $this->_fields_perm)) {
  748. return $this->_fields_perm[$field];
  749. }
  750. return '';
  751. }
  752. function field_allow_write($field_name) {
  753. return (strpos($this->get_field_perm($field_name), 'W') !== false)? true : false;
  754. }
  755. function field_allow_read($field_name) {
  756. return (strpos($this->get_field_perm($field_name), 'R') !== false)? true : false;
  757. }
  758. function field_allow_create($field_name) {
  759. return (strpos($this->get_field_perm($field_name), 'C') !== false)? true : false;
  760. }
  761. public function add_col($col_name, $label = '', $type = 'string') {
  762. if (!$label) $label = $col_name;
  763. $this->_cols[$col_name] = $label;
  764. $this->_col_types[$col_name] = $type;
  765. }
  766. public function addCol($col_name) {
  767. $this->_cols[$col_name] = $col_name;
  768. }
  769. function count() {
  770. $ret = 0;
  771. $sql_where = ($this->_sql_where)? $this->_sql_where : "1=1";
  772. $sql = "select count(1) as cnt
  773. from `{$this->_tbl}`
  774. where {$sql_where}
  775. ";
  776. $res = $this->getDB()->query($sql);
  777. if ($r = $this->getDB()->fetch($res)) {
  778. $ret = $r->cnt;
  779. }
  780. return $ret;
  781. }
  782. function fetch_list($limit = 10, $offset = 0) {
  783. $primaryKeyField = $this->getPrimaryKeyField();
  784. $ret = array();
  785. $this->_sql_limit = $limit;
  786. $this->_sql_offset = $offset;
  787. $sql_cols = (!empty($this->_cols))? implode(',', array_keys($this->_cols)) : "*";
  788. $sql_where = ($this->_sql_where)? $this->_sql_where : "1=1";
  789. $sql = "
  790. select {$sql_cols}
  791. from {$this->_tbl}
  792. where {$sql_where}
  793. limit {$this->_sql_limit} offset {$this->_sql_offset}
  794. ";
  795. $res = $this->getDB()->query($sql);
  796. while ($r = $this->getDB()->fetch($res)) {
  797. $ret[$r->{$primaryKeyField}] = $r;
  798. }
  799. return $ret;
  800. }
  801. function field_check_value($field_name, $val) {
  802. if (!$this->field_allow_write($field_name)) {
  803. return false;
  804. }
  805. // post verify
  806. // get type, and check if value is correct
  807. // TODO: if typespecial use it
  808. return true;
  809. }
  810. function save_item(&$item, $values, $prefix) {
  811. if (!$item->ID) {
  812. return null;
  813. }
  814. $sql_obj = new stdClass();
  815. $sql_obj->ID = $item->ID;
  816. foreach ($values as $k_field_with_prefix => $v_field) {
  817. if (substr($k_field_with_prefix, 0, strlen($prefix)) != $prefix) {
  818. continue;
  819. }
  820. $k_field = substr($k_field_with_prefix, strlen($prefix));
  821. if ($this->field_allow_write($k_field)) {
  822. if ($this->field_check_value($k_field, $v_field)) {
  823. $sql_obj->$k_field = $v_field;
  824. }
  825. }
  826. }
  827. $affected = $this->getDB()->PDATE_OBJ($this->_tbl, $sql_obj);
  828. return $affected;
  829. }
  830. function add_item($values, $prefix) {
  831. $sql_obj = new stdClass();
  832. foreach ($values as $k_field_with_prefix => $v_field) {
  833. if (substr($k_field_with_prefix, 0, strlen($prefix)) != $prefix) {
  834. continue;
  835. }
  836. $k_field = substr($k_field_with_prefix, strlen($prefix));
  837. if ($this->field_allow_create($k_field)) {
  838. if ($this->field_check_value($k_field, $v_field)) {
  839. $sql_obj->$k_field = $v_field;
  840. }
  841. }
  842. }
  843. $insert_id = $this->getDB()->ADD_NEW_OBJ($this->_tbl, $sql_obj);
  844. return $insert_id;
  845. }
  846. public function isGeomField($fldName) {
  847. return ('the_geom' == $fldName);
  848. }
  849. public function isCsvNumericField($fldName) {
  850. return ('_CSV_NUM' == substr($fldName, -8));
  851. }
  852. public function updateItem($itemPatch) {
  853. // TODO: $item as array and copy from $db->UPDATE_OBJ using PDO
  854. if (is_object($itemPatch)) {
  855. $itemPatch = (array)$itemPatch;
  856. } else if (!is_array($itemPatch)) {
  857. throw new HttpException('Item patch is not array', 400);
  858. }
  859. if (empty($itemPatch)) {
  860. //throw new Exception('Item patch is empty');
  861. return 0;// nothing to change
  862. }
  863. $primaryKeyField = $this->getPrimaryKeyField();
  864. if (empty($itemPatch[$primaryKeyField])) {
  865. throw new HttpException("Item Primary Key not set!", 400);
  866. }
  867. // the geom fix
  868. foreach ($itemPatch as $fld => $val) {
  869. if ($this->isGeomField($fld)) {
  870. if (!empty($val)
  871. && 'NULL' !== $val
  872. && 'GeomFromText' != substr($val, 0, strlen('GeomFromText'))
  873. ) {
  874. $itemPatch[$fld] = "GeomFromText('{$val}')";
  875. }
  876. }
  877. }
  878. $itemPatch = (object)$itemPatch;
  879. $affected = $this->getDB()->UPDATE_OBJ($this->_tbl, $itemPatch);
  880. if ($affected < 0) {
  881. $dsErrors = $this->getDbErrors();
  882. //$dsErrors = "Wystąpiły błędy!\n" . implode("\n", $dsErrors);
  883. if (!empty($dsErrors)) {
  884. throw new StorageException($dsErrors);
  885. }
  886. }
  887. return $affected;
  888. }
  889. public function addItem($item) {
  890. // TODO: $item as array and copy from $db->ADD_NEW_OBJ using PDO
  891. if (is_object($item)) {
  892. $item = (array)$item;
  893. } else if (!is_array($item)) {
  894. throw new HttpException('Item is not array', 400);
  895. }
  896. // add empty record is allowed - empty($item)
  897. // the geom fix
  898. foreach ($item as $fld => $val) {
  899. if ($this->isGeomField($fld)) {
  900. if (!empty($val)
  901. && 'NULL' !== $val
  902. && 'GeomFromText' != substr($val, 0, strlen('GeomFromText'))
  903. ) {
  904. $item[$fld] = "GeomFromText('{$val}')";
  905. }
  906. }
  907. }
  908. $primaryKey = $this->getDB()->ADD_NEW_OBJ($this->_tbl, (object)$item);
  909. if ($primaryKey <= 0) {
  910. $dsErrors = $this->getDbErrors();
  911. $dsErrors = "Wystąpiły błędy!\n" . implode("\n", $dsErrors);
  912. throw new Exception($dsErrors);
  913. }
  914. return $primaryKey;
  915. }
  916. public function getDbErrors() {
  917. $errors = array();
  918. if ($this->getDB()->has_errors()) {
  919. $errorsSql = $this->getDB()->get_errors();
  920. foreach ($errorsSql as $vErr) {
  921. if ('SQL QUERY FAILED: ' == substr($vErr, 0, 18)) {
  922. $vErr = substr($vErr, 18);
  923. }
  924. //$errors[] = StorageException::parseMessage($vErr);
  925. $errors[] = $vErr;
  926. }
  927. }
  928. return $errors;
  929. }
  930. public function getPrimaryKeyField() {
  931. return 'ID';// TODO: read from struct - jest funkcja w Mysql.php my Psql.php
  932. }
  933. }