TableAcl.php 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903
  1. <?php
  2. Lib::loadClass('Core_AclBase');
  3. Lib::loadClass('SchemaException');
  4. Lib::loadClass('Typespecial');
  5. Lib::loadClass('ProcesHelper');
  6. Lib::loadClass('Schema_TableFactory');
  7. Lib::loadClass('DataSourceFactory');
  8. /**
  9. * $_SESSION['TableAcl_cache'][$tableID] = array(
  10. * [db] => DB zasob ID
  11. * [name] => Table name
  12. * [opis] => Table opis
  13. * [fields] => array(
  14. * [$fieldID] => array(
  15. * [name] => name
  16. * [perms] => perms (FORM_TREAT)
  17. * [opis] => opis
  18. * )
  19. * )
  20. * [types] => array(
  21. * [$fieldID] => array(
  22. * [type] => type
  23. * [null] => bool
  24. * [default] => default value
  25. * )
  26. * )
  27. * );
  28. */
  29. class TableAcl extends Core_AclBase {
  30. public $_rootTableName = null;
  31. public $_zasobID = '';
  32. public $_db = '';
  33. public $_name = '';
  34. public $_label = '';
  35. public $_opis = '';
  36. public $_fields = array();
  37. public $_types = array();
  38. public $_virtualFieldsIdList = array();
  39. public $_schemaLoaded = false;
  40. public function __construct($zasobID) { $this->_zasobID = $zasobID; }
  41. public function getNamespace() { return 'default_db/' . $this->getName(); }
  42. public function getSourceName() { return 'default_db'; }
  43. public function getName() { return $this->_name; }
  44. public function getRootTableName() {
  45. if (empty($this->_name)) return null;// throw new Exception("Table name not defined");
  46. if ($this->_rootTableName) return $this->_rootTableName;
  47. if (!$this->_db) return null;// throw new Exception("Database not defined in table {$this->_zasobID}");
  48. DBG::simpleLog('auth', "TableAcl::getRootTableName(name: '{$this->_name}')");
  49. $dbName = DB::getPDO($this->_db)->getDatabaseName();
  50. $this->_rootTableName = DB::getPDO()->fetchValue("
  51. select t.TABLE_NAME
  52. from `information_schema`.`TABLES` t
  53. where t.TABLE_SCHEMA = '{$dbName}'
  54. and t.TABLE_NAME LIKE '{$this->_name}'
  55. ");
  56. if (!$this->_rootTableName) return null;// throw new Exception("Table '{$this->_name}' not exists!");
  57. DBG::log("TableAcl({$this->_zasobID})->getRootTableName (\$this->_name='{$this->_name}', \$this->_rootTableName='{$this->_rootTableName}')");
  58. if ($this->_rootTableName != $this->_name) {
  59. if ($this->_zasobID) {
  60. $affected = DB::getPDO()->update('CRM_LISTA_ZASOBOW', 'ID', $this->_zasobID, [
  61. 'DESC' => $this->_rootTableName
  62. ]);
  63. DBG::log("TableAcl({$this->_zasobID})->getRootTableName fixed zasob table name (\$affected={$affected})");
  64. }
  65. $this->_name = $this->_rootTableName;
  66. $this->save();
  67. }
  68. return $this->_rootTableName;
  69. }
  70. public function getID() { return $this->_zasobID; }
  71. public function setName($name) {// TODO: used only by setNameByTableId
  72. DBG::log("setName('{$name}')");
  73. $this->_name = $name;
  74. }
  75. public function setOpis($opis) { $this->_opis = $opis; }
  76. public function getOpis() { return $this->_opis; }
  77. public function setLabel($label) { $this->_label = $label; }
  78. public function getLabel() { return $this->_label; }
  79. public function setNameByTableId($tableID) {
  80. //used for init without knowing table name
  81. $db = DB::getDB();
  82. $sql = "select `DESC` from CRM_LISTA_ZASOBOW where ID={$tableID} and `TYPE`='TABELA'";
  83. $res = $db->query($sql);
  84. $res_ = $db->fetch($res);
  85. //DEBUG_S(-3,'setNameByTableId',$res_,__FILE__,__FUNCTION__,__LINE__);
  86. self::setName($res->DESC);
  87. }
  88. public function getRawOpis() {
  89. $opis = $this->_opis;
  90. if (!$opis) return $this->getRawLabel(100);
  91. $opis = strip_tags($opis);
  92. return $opis;
  93. }
  94. public function getRawLabel($posLimit = 20) {
  95. $label = $this->_label;
  96. if (empty($label) && !empty($this->_opis)) {
  97. $label = $this->_opis;
  98. if (mb_strlen($this->_opis) > $posLimit) {
  99. $pos = strpos($this->_opis, ' - ');
  100. if ($pos > $posLimit || $pos < 5) {
  101. $pos = $posLimit;
  102. $label = mb_substr($this->_opis, 0, $posLimit, 'utf-8') . '...';
  103. } else {
  104. $label = mb_substr($this->_opis, 0, $pos, 'utf-8');
  105. }
  106. }
  107. }
  108. if (empty($label)) {
  109. $label = $this->_name;
  110. }
  111. return $label;
  112. }
  113. public function getShortLabel($posLimit = 20) {
  114. $shortLabel = $this->getRawLabel($posLimit);
  115. $opis = $this->_opis;
  116. $shortLabel = '<span title="' . htmlspecialchars($opis) . '">' . $shortLabel . '</span>';
  117. return $shortLabel;
  118. }
  119. public function getLongLabel($posLimit = 30) {
  120. $longLabel = $this->getRawLabel($posLimit);
  121. $opis = $this->_opis;
  122. if ($longLabel != $this->_name) {
  123. $longLabel .= ' <em>' . $this->_name . '</em>';
  124. }
  125. $longLabel = '<span title="' . htmlspecialchars($opis) . '">' . $longLabel . '</span>';
  126. return $longLabel;
  127. }
  128. public function getLongRawLabel($posLimit = 30) {
  129. $longLabel = $this->getRawLabel($posLimit);
  130. $opis = $this->_opis;
  131. if ($longLabel != $this->_name) {
  132. $longLabel .= ' ' . $this->_name;
  133. }
  134. return $longLabel;
  135. }
  136. public function setDB($db) {
  137. $this->_db = $db;
  138. }
  139. public function getDB() {
  140. return $this->_db;
  141. }
  142. public function addField($fieldID, $name, $opis, $sort_prio, $label = '') {
  143. $field = array();
  144. $field['name'] = $name;
  145. $field['perms'] = '';
  146. $field['opis'] = $opis;
  147. $field['sort_prio'] = $sort_prio;
  148. $field['label'] = $label;
  149. $this->_fields[$fieldID] = $field;
  150. }
  151. public function getTableDbId($tableID) {
  152. return $this->_db;
  153. }
  154. public function getField($fieldID) {
  155. return $this->_fields[$fieldID];
  156. }
  157. public function hasField($fieldID) {
  158. return array_key_exists($fieldID, $this->_fields);
  159. }
  160. public function removeField($fieldID) {
  161. if (array_key_exists($fieldID, $this->_fields)) {
  162. unset($this->_fields[$fieldID]);
  163. }
  164. }
  165. public function getFields() {
  166. return $this->_fields;
  167. }
  168. public function setFieldPerms($fieldID, $perms) {
  169. if (array_key_exists($fieldID, $this->_fields)) {
  170. $this->_fields[$fieldID]['perms'] .= $perms;
  171. }
  172. }
  173. public function getFieldPerms($fieldID) {
  174. if (array_key_exists($fieldID, $this->_fields)) {
  175. $perms = V::get('perms', '', $this->_fields[$fieldID]);
  176. if ($perms) {
  177. return implode(',', array_unique(str_split($perms)));
  178. }
  179. }
  180. return '';
  181. }
  182. public function hasFieldPerm($fieldID, $perm) {// TODO: legacy
  183. if (array_key_exists($fieldID, $this->_fields)) {
  184. if (false !== strpos($this->_fields[$fieldID]['perms'], $perm)) {
  185. return true;
  186. }
  187. return false;
  188. }
  189. return false;
  190. }
  191. public function getFieldIdByName($fieldName) {
  192. $fieldID = 0;
  193. if (empty($fieldName)) {
  194. return;
  195. }
  196. foreach ($this->_fields as $kID => $vField) {
  197. if ($vField['name'] == $fieldName) {
  198. $fieldID = $kID;
  199. }
  200. }
  201. return $fieldID;
  202. }
  203. public function hasEditPerms() {
  204. foreach ($this->_fields as $kFldID => $vFld) {
  205. if ($this->hasFieldPerm($kFldID, 'W')) return true;
  206. if ($this->hasFieldPerm($kFldID, 'C')) return true;
  207. if ($this->hasFieldPerm($kFldID, 'S')) return true;
  208. }
  209. return false;
  210. }
  211. public function hasSuperAccessPerms() {
  212. foreach ($this->_fields as $kFldID => $vFld) {
  213. if ($this->hasFieldPerm($kFldID, 'S')) {
  214. return true;
  215. }
  216. else if ($this->hasFieldPerm($kFldID, 'V')) {
  217. return true;
  218. }
  219. }
  220. return false;
  221. }
  222. public function hasPermSuperWrite() {
  223. foreach ($this->_fields as $kFldID => $vFld) {
  224. if ($this->hasFieldPerm($kFldID, 'S')) {
  225. return true;
  226. }
  227. }
  228. return false;
  229. }
  230. /**
  231. * @param $taskPerm - 'C', 'W', 'R'
  232. */
  233. public function isAllowed($fieldID, $taskPerm, $record = null) {// TODO: legacy - replace with canWriteField, canReadField, canWriteObjectField, canReadObjectField, canCreateField
  234. if (!in_array($taskPerm, array('C', 'W', 'R'))) {
  235. return false;
  236. }
  237. $adminFields = array();
  238. $adminFields[] = 'ID';
  239. $adminFields[] = 'A_RECORD_CREATE_DATE';
  240. $adminFields[] = 'A_RECORD_CREATE_AUTHOR';
  241. $adminFields[] = 'A_RECORD_UPDATE_DATE';
  242. $adminFields[] = 'A_RECORD_UPDATE_AUTHOR';
  243. $fieldName = $this->_fields[$fieldID]['name'];
  244. if ($taskPerm == 'R' && in_array($fieldName, $adminFields)) {
  245. return true;
  246. }
  247. // check perm: allow 'RS', 'WS' - can R/W field even if cant read record
  248. // check 'O' - can read field even if cant read field but can read record
  249. if(V::get('DBG_ACL', '', $_REQUEST) > 1){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('Field'=>$fieldID.'('.$fieldName.')'
  250. ,'taskPerm'=>$taskPerm
  251. ,'fieldPerms'=>V::get('perms', null, V::get($fieldID, null, $this->_fields))
  252. ,'canReadRecord'=>'"'.$this->canReadRecord($record).'"'
  253. ,'hasFieldPerm(O) || canWriteRecord'=>'"'.$this->hasFieldPerm($fieldID, 'O').'" || "'.$this->canReadRecord($record).'"'
  254. ,'hasFieldPerm(S)'=>'"'.$this->hasFieldPerm($fieldID, 'S').'"'
  255. ,'hasFieldPerm(V)'=>'"'.$this->hasFieldPerm($fieldID, 'V').'"'
  256. ));echo'</pre>'; }
  257. if (!$this->hasFieldPerm($fieldID, $taskPerm)) {
  258. if ($taskPerm == 'R' && $this->hasFieldPerm($fieldID, 'V')) {
  259. return true;
  260. } else if ($taskPerm == 'R'
  261. && $record
  262. && $this->hasFieldPerm($fieldID, 'O')
  263. && ($this->canReadRecord($record) || $this->canWriteRecord($record))
  264. ) {
  265. return true;// 'WO' or 'CO'
  266. }
  267. return false;
  268. }
  269. // check 'R' - require can read record, or V - Super View
  270. if ($taskPerm == 'R') {
  271. if ($this->canReadRecord($record) || $this->hasFieldPerm($fieldID, 'V')) {
  272. return true;
  273. } else {
  274. return false;
  275. }
  276. }
  277. // 'C' and 'W' require colType
  278. $colType = $this->getFieldTypeById($fieldID);
  279. if (!$colType) {
  280. return false;
  281. }
  282. if ($taskPerm == 'W') {
  283. if ($record) {
  284. if(V::get('DBG_ACL', '', $_REQUEST) > 1){echo '(Field: '.$fieldID.', canWriteRecord: ' . $this->canWriteRecord($record) . ' || (hasFieldPerm(S): ' . $this->hasFieldPerm($fieldID, 'S') . ' && hasFieldPerm(W): ' . $this->hasFieldPerm($fieldID, 'W') . '))';}
  285. return ($this->canWriteRecord($record)|| $this->hasFieldPerm($fieldID, 'S'));
  286. }
  287. }
  288. return true;
  289. }
  290. public function canCreateField($fieldName) {
  291. $idZasob = $this->getFieldIdByName($fieldName);
  292. return ($idZasob && $this->hasFieldPerm($idZasob, $taskPerm = 'C'));
  293. }
  294. public function canReadField($fieldName) {
  295. $idZasob = $this->getFieldIdByName($fieldName);
  296. if (!$idZasob) return false;
  297. if ('ID' == $fieldName) return true;
  298. if ('A_RECORD_CREATE_DATE' == $fieldName) return true;
  299. if ('A_RECORD_CREATE_AUTHOR' == $fieldName) return true;
  300. if ('A_RECORD_UPDATE_DATE' == $fieldName) return true;
  301. if ('A_RECORD_UPDATE_AUTHOR' == $fieldName) return true;
  302. if ($this->hasFieldPerm($idZasob, $taskPerm = 'R')) return true;
  303. if ($this->hasFieldPerm($idZasob, $taskPerm = 'V')) return true;
  304. return false;
  305. }
  306. public function canReadObjectField($fieldName, $record) {
  307. // if (!$this->canReadField($fieldName)) return false;
  308. if ('ID' == $fieldName) return true;
  309. if ('A_RECORD_CREATE_DATE' == $fieldName) return true;
  310. if ('A_RECORD_CREATE_AUTHOR' == $fieldName) return true;
  311. if ('A_RECORD_UPDATE_DATE' == $fieldName) return true;
  312. if ('A_RECORD_UPDATE_AUTHOR' == $fieldName) return true;
  313. if (!$record) {
  314. if(V::get('DBG_ACL', '', $_REQUEST) > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">canReadObjectField('.$fieldName.', $record) - record not set - return false (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '.var_export($record, true).'</pre>';}
  315. return false;
  316. }
  317. $idZasob = $this->getFieldIdByName($fieldName);
  318. if (!$idZasob) {
  319. if(V::get('DBG_ACL', '', $_REQUEST) > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">canReadObjectField('.$fieldName.', $record) - $idZasob not set - return false (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '.var_export($record, true).'</pre>';}
  320. return false;
  321. }
  322. if (!$this->hasFieldPerm($idZasob, $taskPerm = 'R')) {
  323. if ($this->hasFieldPerm($idZasob, 'V')) return true;
  324. return ($this->hasFieldPerm($idZasob, 'O') && ($this->canReadRecord($record) || $this->canWriteRecord($record)));// 'WO' or 'CO'
  325. }
  326. return ($this->canReadRecord($record) || $this->hasFieldPerm($idZasob, 'V'));// 'R' require
  327. }
  328. public function canWriteField($fieldName) {
  329. $idZasob = $this->getFieldIdByName($fieldName);
  330. if (!$idZasob) return false;
  331. return $this->hasFieldPerm($idZasob, $taskPerm = 'W');
  332. }
  333. public function canWriteObjectField($fieldName, $record) {
  334. if (!$this->canWriteField($fieldName)) return false;
  335. $idZasob = $this->getFieldIdByName($fieldName);
  336. if (!$idZasob) return false;
  337. if(V::get('DBG_ACL', '', $_REQUEST) > 1){echo '(Field: "'.$fieldName.'" ['.$idZasob.'], canWriteRecord: ' . $this->canWriteRecord($record) . ' || (hasFieldPerm(S): ' . $this->hasFieldPerm($idZasob, 'S') . ' && hasFieldPerm(W): ' . $this->hasFieldPerm($idZasob, 'W') . '))';}
  338. return ($this->canWriteRecord($record) || $this->hasFieldPerm($idZasob, 'S'));
  339. }
  340. /**
  341. * @param $taskPerm - 'C', 'W'
  342. */
  343. public function getFormItem($taskPerm, $fieldID, $fName, $fValue, $params = array(), $record = null) {
  344. $out = '';
  345. if (!$this->isAllowed($fieldID, $taskPerm, $record)) {
  346. if ($taskPerm == 'R') throw new Exception("Brak uprawnień do odczytu");
  347. else if ($taskPerm == 'W') throw new Exception("Brak uprawnień do zapisu");
  348. else throw new Exception("Brak uprawnień do tego pola ({$taskPerm})");
  349. }
  350. $colName = $this->_fields[$fieldID]['name'];
  351. if ($colName == 'ID') return;
  352. $colType = $this->getFieldTypeById($fieldID);
  353. if (!$colType) throw new Exception("Error - unknown type");
  354. $item = array();
  355. $item['htmlType'] = '';
  356. $item['value'] = $fValue;
  357. $item['canRead'] = $this->isAllowed($fieldID, 'R', $record);
  358. $item['canWrite'] = $this->isAllowed($fieldID, 'W', $record);
  359. $item['rawColType'] = $colType;
  360. return $item;
  361. $html = new stdClass();
  362. $html->_params = array();
  363. $html->tag = 'input';
  364. $html->cnt = '';
  365. $html->attrs = array();
  366. $html->attrs['id'] = $fName;
  367. $html->attrs['name'] = $fName;
  368. $html->attrs['type'] = 'text';
  369. $html->attrs['value'] = htmlspecialchars($fValue);
  370. if (isset($params['tabindex'])) {
  371. $html->attrs['tabindex'] = $params['tabindex'];
  372. }
  373. if (!$this->hasFieldPerm($fieldID, $taskPerm)) {
  374. $html->attrs['disabled'] = 'disabled';
  375. }
  376. $maxGrid = V::get('maxGrid', 10, $params);
  377. if (substr($colType['type'], 0, 3) == 'int'
  378. || substr($colType['type'], 0, 7) == 'tinyint'
  379. || substr($colType['type'], 0, 8) == 'smallint'
  380. || substr($colType['type'], 0, 6) == 'bigint'
  381. ) {
  382. //$h->Type_value = (int)str_replace(array(' ','(',')'), '', substr($h->Type, 4));
  383. $html->attrs['type'] = 'number';
  384. $html->attrs['class'][] = 'input-small';
  385. }
  386. else if (substr($colType['type'], 0, 6) == 'double') {
  387. $html->attrs['type'] = 'text';
  388. $html->attrs['class'][] = 'input-small';
  389. }
  390. else if (substr($colType['type'], 0, 7) == 'decimal') {
  391. $html->attrs['type'] = 'text';
  392. $html->attrs['class'][] = 'input-small';
  393. }
  394. else if (substr($colType['type'], 0, 7) == 'varchar'
  395. || substr($colType['type'], 0, 4) == 'char'
  396. ) {
  397. //$h->Type_value = (int)str_replace(array(' ','(',')'), '', substr($h->Type, 8));
  398. $html->attrs['type'] = 'text';
  399. $maxLength = (int)str_replace(array(' ','(',')'), '', substr($colType['type'], strpos($colType['type'], '(') + 1, -1));
  400. if ($maxLength > 0) {
  401. $html->attrs['maxlength'] = $maxLength;
  402. }
  403. $valLength = strlen($fValue);
  404. if (isset($params['widthClass'])) {
  405. if ($params['widthClass'] == 'inside-modal') {
  406. $html->attrs['style'] = 'width:98%;';
  407. } else {
  408. $html->attrs['style'] = 'width:98%;';
  409. }
  410. } else {
  411. /*
  412. if ($maxLength < 11) {
  413. $html->attrs['class'][] = 'span2';
  414. } else if ($maxLength < 31) {
  415. $html->attrs['class'][] = 'span5';
  416. } else if ($maxLength < 51) {
  417. $html->attrs['class'][] = (8 <= $maxGrid)? 'span8' : "span{$maxGrid}";
  418. } else if ($maxLength < 101) {
  419. $html->attrs['class'][] = (10 <= $maxGrid)? 'span10' : "span{$maxGrid}";
  420. } else {
  421. $html->attrs['class'][] = (12 <= $maxGrid)? 'span12' : "span{$maxGrid}";
  422. }
  423. */
  424. }
  425. if ($maxLength > 255) {// Fix for long varchar - use textarea
  426. $html->tag = 'textarea';
  427. $html->cnt = htmlspecialchars($fValue);
  428. $html->attrs['rows'] = '3';
  429. unset($html->attrs['type']);
  430. unset($html->attrs['value']);
  431. }
  432. }
  433. else if (substr($colType['type'], 0, 4) == 'date') {
  434. $testDatePicker = true;
  435. if ($testDatePicker) {
  436. $html->attrs['type'] = 'text';
  437. $html->_params[] = 'date';
  438. if (substr($colType['type'], 0, 8) == 'datetime') {
  439. $html->attrs['class'][] = 'se_type-datetime';// datetimepicker';
  440. $html->attrs['data-format'] = 'yyyy-MM-dd hh:mm';
  441. $html->attrs['maxlength'] = 19;
  442. } else {
  443. $html->attrs['class'][] = 'se_type-date';// datetimepicker';
  444. $html->attrs['maxlength'] = 10;
  445. }
  446. if (substr($html->attrs['value'], 0, 10) == '0000-00-00') {
  447. $html->attrs['value'] = '';
  448. }
  449. } else {
  450. $html->attrs['type'] = 'date';
  451. }
  452. }
  453. else if ($colType['type'] == 'time') {
  454. $testDatePicker = true;
  455. if ($testDatePicker) {
  456. $html->attrs['type'] = 'text';
  457. $html->_params[] = 'time';
  458. $html->attrs['class'][] = 'se_type-time';// datetimepicker';
  459. $html->attrs['data-format'] = 'hh:mm:ss';
  460. $html->attrs['maxlength'] = 8;
  461. if (substr($html->attrs['value'], 0, 8) == '00:00:00') {
  462. $html->attrs['value'] = '';
  463. }
  464. } else {
  465. $html->attrs['type'] = 'time';
  466. }
  467. }
  468. else if ($colType['type'] == 'timestamp') {
  469. $testDatePicker = true;
  470. if ($testDatePicker) {
  471. $html->attrs['type'] = 'text';
  472. $html->_params[] = 'date';
  473. $html->attrs['class'][] = 'se_type-datetime';// datetimepicker';
  474. $html->attrs['data-format'] = 'yyyy-MM-dd hh:mm';
  475. $html->attrs['maxlength'] = 19;
  476. if (substr($html->attrs['value'], 0, 10) == '0000-00-00') {
  477. $html->attrs['value'] = '';
  478. }
  479. } else {
  480. $html->attrs['type'] = 'date';
  481. }
  482. }
  483. else if (substr($colType['type'], 0, 4) == 'enum') {
  484. unset($html->attrs['type']);
  485. unset($html->attrs['value']);
  486. $html->tag = 'select';
  487. $values = explode(',', str_replace(array('(',')',"'",'"'), '', substr($colType['type'], 5)));
  488. $selValue = $fValue;
  489. if (empty($selValue) && $selValue !== '0' && !empty($colType['default'])) {
  490. if ($taskPerm == 'C') {
  491. $selValue = $colType['default'];
  492. } else if ($taskPerm == 'W' && $this->isAllowed($fieldID, 'R', $record)) {
  493. $selValue = $colType['default'];
  494. }
  495. }
  496. $html->cnt .= '<option value="">' . "" . '</option>';
  497. if (!empty($selValue) && !in_array($selValue, $values)) {
  498. $html->cnt .= '<option value="' . $selValue . '" selected="selected">' . $selValue . '</option>';
  499. }
  500. foreach ($values as $val) {
  501. $sel = ($selValue == $val)? ' selected="selected"' : '';
  502. $html->cnt .= '<option value="' . $val . '"' . $sel . '>' . $val . '</option>';
  503. }
  504. }
  505. else if (substr($colType['type'], 0, 4) == 'text'
  506. || substr($colType['type'], 0, 8) == 'tinytext'
  507. || substr($colType['type'], 0, 10) == 'mediumtext'
  508. || substr($colType['type'], 0, 8) == 'longtext'
  509. ) {
  510. $html->tag = 'textarea';
  511. $html->cnt = htmlspecialchars($fValue);
  512. if (isset($params['widthClass'])) {
  513. if ($params['widthClass'] == 'inside-modal') {
  514. $html->attrs['style'] = 'width:98%;';
  515. } else {
  516. $html->attrs['style'] = 'width:98%;';
  517. }
  518. } else {
  519. //$html->attrs['class'][] = (8 <= $maxGrid)? 'span8' : "span{$maxGrid}";
  520. }
  521. $html->attrs['rows'] = '3';
  522. unset($html->attrs['type']);
  523. unset($html->attrs['value']);
  524. }
  525. else if ('polygon' == $colType['type']) { return '...'; }// Wielokąt
  526. else if ('multipolygon' == $colType['type']) { return '...'; }// Zbiór wielokątów
  527. else if ('linestring' == $colType['type']) { return '...'; }// Krzywa z interpolacji liniowej pomiędzy punktami
  528. else if ('point' == $colType['type']) { return '...'; }// Punkt w przestrzeni 2-wymiarowej
  529. else if ('geometry' == $colType['type']) { return '...'; }// Typy, które mogą przechowywać geometrię dowolnego typu
  530. else if ('multipoint' == $colType['type']) { return '...'; }// Zbiór punktów
  531. else if ('multilinestring' == $colType['type']) { return '...'; }// Zbiór krzywych z interpolacji liniowej pomiędzy punktami
  532. else if ('geometrycollection' == $colType['type']) { return '...'; }// Zbiór obiektów geometrycznych dowolnego typu
  533. else throw new Exception("unknown Type '{$colType['type']}'");
  534. $html->attrs['class'][] = 'form-control';
  535. $attrsOut = array();
  536. foreach ($html->attrs as $k => $v) {
  537. if (is_array($v)) $v = implode(' ', $v);
  538. $attrsOut[] = "{$k}=\"{$v}\"";
  539. }
  540. if (in_array($html->tag, array('select', 'textarea'))) {
  541. $out .= '<' . $html->tag . '' . (($attrsOut)? ' ' . implode(' ', $attrsOut) : '') . '>';
  542. $out .= $html->cnt;
  543. $out .= '</' . $html->tag . '>';
  544. } else {
  545. $out .= '<' . $html->tag . '' . (($attrsOut)? ' ' . implode(' ', $attrsOut) : '') . ' />';
  546. }
  547. if (in_array('date', $html->_params)) {
  548. $out = '<div class="input-group">' . $out . '<span class="input-group-addon">
  549. <span class="glyphicon glyphicon-calendar"></span>
  550. </span>
  551. </div>';
  552. }
  553. else if (in_array('time', $html->_params)) {
  554. $out = '<div class="input-group">' . $out . '<span class="input-group-addon">
  555. <span class="glyphicon glyphicon-time"></span>
  556. </span>
  557. </div>';
  558. }
  559. if (true == V::get('appendBack', '', $params)
  560. && !in_array('date', $html->_params)
  561. && !in_array('time', $html->_params)
  562. ) {
  563. if ($html->tag == 'input' && $taskPerm == 'W') {
  564. $out = '<div class="input-group show-last-value">' . $out . '<span class="input-group-addon button-appendBack" title="' . htmlspecialchars($fValue) . '"><span class="glyphicon glyphicon-arrow-left"></span></span></div>';
  565. }
  566. }
  567. $typeSpecial = Typespecial::getInstance($fieldID, $colName);
  568. if ($typeSpecial) {
  569. throw new Exception("TODO: TypeSpecial");
  570. $tsParams = array();
  571. $tsValue = V::get('typespecialValue', '', $params);
  572. if (!empty($tsValue)) {
  573. $tsParams['typespecialValue'] = $tsValue;
  574. }
  575. $out .= ' ' . $typeSpecial->showFormItem($this->_zasobID, $fName, $fValue, $tsParams, $record);
  576. }
  577. return $out;
  578. }
  579. /**
  580. * @param $taskPerm - 'C', 'W'
  581. */
  582. public function showFormItem($taskPerm, $fieldID, $fName, $fValue, $params = array(), $record = null) {
  583. $out = '';
  584. if (!$this->isAllowed($fieldID, $taskPerm, $record)) {
  585. if ($taskPerm == 'R') {
  586. $out .= 'Brak uprawnień do odczytu';
  587. }
  588. else if ($taskPerm == 'W') {
  589. $out .= 'Brak uprawnień do zapisu';
  590. } else {
  591. $out .= 'Brak uprawnień do tego pola (' . $taskPerm . ')';
  592. }
  593. return $out;
  594. }
  595. $colName = $this->_fields[$fieldID]['name'];
  596. if ($colName == 'ID') {
  597. return $out;
  598. }
  599. $colType = $this->getFieldTypeById($fieldID);
  600. if (!$colType) {
  601. $out .= 'Error - unknown type';
  602. return $out;
  603. }
  604. $typeSpecial = Typespecial::getInstance($fieldID, $colName);
  605. $html = new stdClass();
  606. $html->_params = array();
  607. $html->tag = 'input';
  608. $html->cnt = '';
  609. $html->attrs = array();
  610. $html->attrs['id'] = $fName;
  611. $html->attrs['name'] = $fName;
  612. $html->attrs['type'] = 'text';
  613. $html->attrs['value'] = htmlspecialchars($fValue);
  614. if (isset($params['tabindex'])) {
  615. $html->attrs['tabindex'] = $params['tabindex'];
  616. }
  617. if (!$this->hasFieldPerm($fieldID, $taskPerm)) {
  618. $html->attrs['disabled'] = 'disabled';
  619. }
  620. $maxGrid = V::get('maxGrid', 10, $params);
  621. if (substr($colType['type'], 0, 3) == 'int'
  622. || substr($colType['type'], 0, 7) == 'tinyint'
  623. || substr($colType['type'], 0, 8) == 'smallint'
  624. || substr($colType['type'], 0, 6) == 'bigint'
  625. ) {
  626. //$h->Type_value = (int)str_replace(array(' ','(',')'), '', substr($h->Type, 4));
  627. $html->attrs['type'] = 'number';
  628. $html->attrs['class'][] = 'input-small';
  629. }
  630. else if (substr($colType['type'], 0, 6) == 'double') {
  631. $html->attrs['type'] = 'text';
  632. $html->attrs['class'][] = 'input-small';
  633. }
  634. else if (substr($colType['type'], 0, 7) == 'decimal') {
  635. $html->attrs['type'] = 'text';
  636. $html->attrs['class'][] = 'input-small';
  637. }
  638. else if (substr($colType['type'], 0, 7) == 'varchar'
  639. || substr($colType['type'], 0, 4) == 'char'
  640. ) {
  641. //$h->Type_value = (int)str_replace(array(' ','(',')'), '', substr($h->Type, 8));
  642. $html->attrs['type'] = 'text';
  643. $maxLength = (int)str_replace(array(' ','(',')'), '', substr($colType['type'], strpos($colType['type'], '(') + 1, -1));
  644. if ($maxLength > 0) {
  645. $html->attrs['maxlength'] = $maxLength;
  646. }
  647. $valLength = strlen($fValue);
  648. if (isset($params['widthClass'])) {
  649. if ($params['widthClass'] == 'inside-modal') {
  650. $html->attrs['style'] = 'width:98%;';
  651. } else {
  652. $html->attrs['style'] = 'width:98%;';
  653. }
  654. } else {
  655. /*
  656. if ($maxLength < 11) {
  657. $html->attrs['class'][] = 'span2';
  658. } else if ($maxLength < 31) {
  659. $html->attrs['class'][] = 'span5';
  660. } else if ($maxLength < 51) {
  661. $html->attrs['class'][] = (8 <= $maxGrid)? 'span8' : "span{$maxGrid}";
  662. } else if ($maxLength < 101) {
  663. $html->attrs['class'][] = (10 <= $maxGrid)? 'span10' : "span{$maxGrid}";
  664. } else {
  665. $html->attrs['class'][] = (12 <= $maxGrid)? 'span12' : "span{$maxGrid}";
  666. }
  667. */
  668. }
  669. if ($maxLength > 255) {// Fix for long varchar - use textarea
  670. $html->tag = 'textarea';
  671. $html->cnt = htmlspecialchars($fValue);
  672. $html->attrs['rows'] = '3';
  673. unset($html->attrs['type']);
  674. unset($html->attrs['value']);
  675. }
  676. }
  677. else if (substr($colType['type'], 0, 4) == 'date') {
  678. $testDatePicker = true;
  679. if ($testDatePicker) {
  680. $html->attrs['type'] = 'text';
  681. $html->_params[] = 'date';
  682. if (substr($colType['type'], 0, 8) == 'datetime') {
  683. $html->attrs['class'][] = 'se_type-datetime';// datetimepicker';
  684. $html->attrs['data-format'] = 'yyyy-MM-dd hh:mm';
  685. $html->attrs['maxlength'] = 19;
  686. } else {
  687. $html->attrs['class'][] = 'se_type-date';// datetimepicker';
  688. $html->attrs['maxlength'] = 10;
  689. }
  690. if (substr($html->attrs['value'], 0, 10) == '0000-00-00') {
  691. $html->attrs['value'] = '';
  692. }
  693. } else {
  694. $html->attrs['type'] = 'date';
  695. }
  696. }
  697. else if ($colType['type'] == 'time') {
  698. $testDatePicker = true;
  699. if ($testDatePicker) {
  700. $html->attrs['type'] = 'text';
  701. $html->_params[] = 'time';
  702. $html->attrs['class'][] = 'se_type-time';// datetimepicker';
  703. $html->attrs['data-format'] = 'hh:mm:ss';
  704. $html->attrs['maxlength'] = 8;
  705. if (substr($html->attrs['value'], 0, 8) == '00:00:00') {
  706. $html->attrs['value'] = '';
  707. }
  708. } else {
  709. $html->attrs['type'] = 'time';
  710. }
  711. }
  712. else if ($colType['type'] == 'timestamp') {
  713. $testDatePicker = true;
  714. if ($testDatePicker) {
  715. $html->attrs['type'] = 'text';
  716. $html->_params[] = 'date';
  717. $html->attrs['class'][] = 'se_type-datetime';// datetimepicker';
  718. $html->attrs['data-format'] = 'yyyy-MM-dd hh:mm';
  719. $html->attrs['maxlength'] = 19;
  720. if (substr($html->attrs['value'], 0, 10) == '0000-00-00') {
  721. $html->attrs['value'] = '';
  722. }
  723. } else {
  724. $html->attrs['type'] = 'date';
  725. }
  726. }
  727. else if (substr($colType['type'], 0, 4) == 'enum') {
  728. unset($html->attrs['type']);
  729. unset($html->attrs['value']);
  730. $html->tag = 'select';
  731. $values = explode(',', str_replace(array('(',')',"'",'"'), '', substr($colType['type'], 5)));
  732. $selValue = $fValue;
  733. if (empty($selValue) && $selValue !== '0' && !empty($colType['default'])) {
  734. if ($taskPerm == 'C') {
  735. $selValue = $colType['default'];
  736. } else if ($taskPerm == 'W' && $this->isAllowed($fieldID, 'R', $record)) {
  737. $selValue = $colType['default'];
  738. }
  739. }
  740. $html->cnt .= '<option value="">' . "" . '</option>';
  741. if (!empty($selValue) && !in_array($selValue, $values)) {
  742. $html->cnt .= '<option value="' . $selValue . '" selected="selected">' . $selValue . '</option>';
  743. }
  744. foreach ($values as $val) {
  745. $sel = ($selValue == $val)? ' selected="selected"' : '';
  746. $html->cnt .= '<option value="' . $val . '"' . $sel . '>' . $val . '</option>';
  747. }
  748. }
  749. else if (substr($colType['type'], 0, 4) == 'text'
  750. || substr($colType['type'], 0, 8) == 'tinytext'
  751. || substr($colType['type'], 0, 10) == 'mediumtext'
  752. || substr($colType['type'], 0, 8) == 'longtext'
  753. ) {
  754. $html->tag = 'textarea';
  755. $html->cnt = htmlspecialchars($fValue);
  756. if (isset($params['widthClass'])) {
  757. if ($params['widthClass'] == 'inside-modal') {
  758. $html->attrs['style'] = 'width:98%;';
  759. } else {
  760. $html->attrs['style'] = 'width:98%;';
  761. }
  762. } else {
  763. //$html->attrs['class'][] = (8 <= $maxGrid)? 'span8' : "span{$maxGrid}";
  764. }
  765. $html->attrs['rows'] = '3';
  766. unset($html->attrs['type']);
  767. unset($html->attrs['value']);
  768. }
  769. else if ('polygon' == $colType['type']) { return '...'; }// Wielokąt
  770. else if ('multipolygon' == $colType['type']) { return '...'; }// Zbiór wielokątów
  771. else if ('linestring' == $colType['type']) { return '...'; }// Krzywa z interpolacji liniowej pomiędzy punktami
  772. else if ('point' == $colType['type']) { return '...'; }// Punkt w przestrzeni 2-wymiarowej
  773. else if ('geometry' == $colType['type']) { return '...'; }// Typy, które mogą przechowywać geometrię dowolnego typu
  774. else if ('multipoint' == $colType['type']) { return '...'; }// Zbiór punktów
  775. else if ('multilinestring' == $colType['type']) { return '...'; }// Zbiór krzywych z interpolacji liniowej pomiędzy punktami
  776. else if ('geometrycollection' == $colType['type']) { return '...'; }// Zbiór obiektów geometrycznych dowolnego typu
  777. else {
  778. return 'unknown Type "'.$colType['type'].'"';
  779. }
  780. $html->attrs['class'][] = 'form-control';
  781. $attrsOut = array();
  782. foreach ($html->attrs as $k => $v) {
  783. if (is_array($v)) $v = implode(' ', $v);
  784. $attrsOut[] = "{$k}=\"{$v}\"";
  785. }
  786. if (in_array($html->tag, array('select', 'textarea'))) {
  787. $out .= '<' . $html->tag . '' . (($attrsOut)? ' ' . implode(' ', $attrsOut) : '') . '>';
  788. $out .= $html->cnt;
  789. $out .= '</' . $html->tag . '>';
  790. } else {
  791. $out .= '<' . $html->tag . '' . (($attrsOut)? ' ' . implode(' ', $attrsOut) : '') . ' />';
  792. }
  793. if (in_array('date', $html->_params)) {
  794. $out = '<div class="input-group">' . $out . '<span class="input-group-addon">
  795. <span class="glyphicon glyphicon-calendar"></span>
  796. </span>
  797. </div>';
  798. }
  799. else if (in_array('time', $html->_params)) {
  800. $out = '<div class="input-group">' . $out . '<span class="input-group-addon">
  801. <span class="glyphicon glyphicon-time"></span>
  802. </span>
  803. </div>';
  804. }
  805. if (true == V::get('appendBack', '', $params)
  806. && !in_array('date', $html->_params)
  807. && !in_array('time', $html->_params)
  808. ) {
  809. if ($html->tag == 'input' && $taskPerm == 'W') {
  810. $out = '<div class="input-group show-last-value">' . $out . '<span class="input-group-addon button-appendBack" title="' . htmlspecialchars($fValue) . '"><span class="glyphicon glyphicon-arrow-left"></span></span></div>';
  811. }
  812. }
  813. if ($typeSpecial) {
  814. $tsParams = array();
  815. $tsValue = V::get('typespecialValue', '', $params);
  816. if (!empty($tsValue)) {
  817. $tsParams['typespecialValue'] = $tsValue;
  818. }
  819. $out .= ' ' . $typeSpecial->showFormItem($this->_zasobID, $fName, $fValue, $tsParams, $record);
  820. }
  821. return $out;
  822. }
  823. /**
  824. * List table ids by database
  825. *
  826. *
  827. */
  828. public static function GetTablesByDbId($db) {
  829. DEBUG_S(3,'TableAcl_cache',$_SESSION['TableAcl_cache'],__FILE__,__FUNCTION__,__LINE__);
  830. static $_cache;
  831. $return=array();
  832. if (!$_cache) $_cache = array();
  833. if (!empty($_SESSION['TableAcl_cache'])) {
  834. foreach($_SESSION['TableAcl_cache'] as $tableID=>$obj) {
  835. //if($obj->db==$db)
  836. $return[$obj['name']]=$tableID;
  837. }
  838. return $return;
  839. }
  840. return null;
  841. }
  842. /**
  843. * Get column object. Not initialize
  844. * @returns object - column instance if exists else null
  845. *
  846. * static
  847. */
  848. public static function getInstance($idTable) {
  849. static $_cache;
  850. if (!$_cache) $_cache = array();
  851. if (array_key_exists($idTable, $_cache)) {
  852. return $_cache[$idTable];
  853. }
  854. if (!empty($_SESSION['TableAcl_cache'][$idTable])) {
  855. $tableAcl = new TableAcl($idTable);
  856. $tableAcl->fromArray($_SESSION['TableAcl_cache'][$idTable]);
  857. $_cache[$idTable] = $tableAcl;
  858. return $_cache[$idTable];
  859. }
  860. return null;
  861. }
  862. public static function buildInstance($idTable, $tableConfig) {
  863. static $_cache;
  864. if (!$_cache) $_cache = array();
  865. if (array_key_exists($idTable, $_cache)) {
  866. return $_cache[$idTable];
  867. }
  868. if (empty($tableConfig)) {
  869. throw new Exception("Brak danych konfiguracyjnych do tabeli nr {$idTable} #TACL" . __LINE__);
  870. $zasobObj = ProcesHelper::getZasobTableInfo($idTable);
  871. if (!$zasobObj) {
  872. return null;// TODO: throw new Exception("Zasob TABELA ID={$idTable} nie istnieje");
  873. }
  874. $tableConfig['db'] = $zasobObj->P__ID;
  875. $tableConfig['name'] = $zasobObj->DESC;
  876. $tableConfig['label'] = $zasobObj->DESC_PL;
  877. $tableConfig['opis'] = $zasobObj->OPIS;
  878. $userAcl = User::getAcl();
  879. $userPermsForTable = $userAcl->getPermsForTable($idTable);
  880. if (!$userPermsForTable) {
  881. return null;// TODO: throw new Exception("Brak uprawnień do pól Tabeli nr {$idTable} '{$zasobObj->DESC}'");
  882. }
  883. echo'<pre>$userPermsForTable('.$idTable.') ';print_r($userPermsForTable);echo'</pre>';
  884. if(0){// TODO: from UserAcl big query
  885. $foundTbls[$r->ZASOB_PARENT_ID]->addField($r->ID_ZASOB, $r->ZASOB_DESC, $r->ZASOB_OPIS, $r->z__SORT_PRIO, $r->ZASOB_DESC_PL);
  886. $foundTbls[$r->ZASOB_PARENT_ID]->setFieldPerms($r->ID_ZASOB, $r->FORM_TREAT);
  887. $tableConfig['fields'];// $this->_fields
  888. $tableConfig['virtualFieldsIdList'];// $this->_virtualFieldsIdList
  889. //$tableConfig['types'];// $this->_types
  890. }
  891. }
  892. if (empty($tableConfig)) {
  893. throw new Exception("Brak danych konfiguracyjnych do tabeli nr {$idTable} #TACL" . __LINE__);
  894. }
  895. $obj = new TableAcl($idTable);
  896. $obj->fromArray($tableConfig);
  897. $obj->getRootTableName();
  898. $obj->save();
  899. $_cache[$idTable] = $obj;
  900. return $_cache[$idTable];
  901. }
  902. public function loadSchema() {
  903. if ($this->_schemaLoaded) return;
  904. $srvName = $_SERVER['SERVER_NAME'];
  905. $this->_schemaClass = Schema_TableFactory::build($this->_name, $this->_db, $srvName);
  906. $this->_schemaLoaded = true;
  907. }
  908. public function init($force = false) {
  909. $this->loadSchema();
  910. if (empty($this->_fields)) {
  911. $this->_types = array();// clear _types @see $this->isInitialized
  912. $userAcl = User::getAcl();
  913. $fieldsConfig = $userAcl->getPermsForTable($this->_zasobID);
  914. DBG::log(['msg'=>"INIT({$this->_zasobID})::initFieldsFromConfig \$fieldsConfig", '$fieldsConfig'=>$fieldsConfig]);
  915. $this->initFieldsFromConfig($fieldsConfig);
  916. //DBG::_('DBG_SCH', '1', "INIT::\$fieldsConfig({$this->_zasobID}) fields(".count($this->_fields).")", $this, __CLASS__, __FUNCTION__, __LINE__ );
  917. }
  918. if ($this->isInitialized() && $force == false) {
  919. return;
  920. }
  921. DBG::simpleLog('auth', "TableAcl::init(name: '{$this->_name}')");
  922. DBG::log(['msg'=>"INIT({$this->_zasobID}):: \$this", '$this'=>$this, 'name'=>$this->getName()]);
  923. $ds = $this->getDataSource();
  924. DBG::log(['msg'=>"INIT({$this->_zasobID})::getDataSource \$ds", '$ds'=>$ds]);
  925. $this->_types = $ds->getFieldTypes();
  926. DBG::log(['msg'=>"INIT({$this->_zasobID})::getFieldTypes \$this->_types", '$this->_types'=>$this->_types]);
  927. uasort($this->_fields, array($this, 'sortFieldsCallback'));
  928. $this->_fixTypes();
  929. DBG::log(['msg'=>"INIT({$this->_zasobID})::after fixTypes \$this->_types", '$this->_types'=>$this->_types]);
  930. $this->save();
  931. }
  932. public function _fixTypes() {
  933. $this->_fixDateFields();
  934. $this->_sortEnumFields();
  935. $this->_fixProjectType();
  936. if ($this->_schemaClass) $this->_types = $this->_schemaClass->fixTypes($this->_types);
  937. //DBG::_(true, true, "this->_types", $this->_types, __CLASS__, __FUNCTION__, __LINE__);
  938. // fixGeomTypesFromSimpleType
  939. foreach ($this->_types as $fieldName => $field) {
  940. // [the_geom] => Array(
  941. // [type] => geometry
  942. // [null] => 1
  943. // [default] =>
  944. // [simpleType] => linestring
  945. if ('geometry' == $field['type']) {
  946. if (!empty($field['simpleType'])) {
  947. switch ($field['simpleType']) {
  948. case 'gml:LineStringPropertyType': $this->_types[ $fieldName ][ 'type' ] = 'linestring'; break;
  949. }
  950. }
  951. $dbName = DB::getPDO()->getDatabaseName();
  952. $tableName = $this->getName();
  953. $geomType = DB::getPDO()->fetchValue("
  954. select DATA_TYPE
  955. from `information_schema`.`COLUMNS`
  956. where TABLE_SCHEMA='{$dbName}'
  957. and TABLE_NAME='{$tableName}'
  958. and COLUMN_NAME='{$fieldName}'
  959. ");
  960. if (!empty($geomType)) $this->_types[ $fieldName ][ 'type' ] = $geomType;
  961. }
  962. }
  963. {// TODO: replace this by $this->_schemaClass (from DataSourceFactory::build(...))
  964. $fieldIds = array_keys($this->_fields);
  965. $vColsIdList = Typespecial::initFields($fieldIds);
  966. if (!empty($vColsIdList)) {
  967. $this->_virtualFieldsIdList = $vColsIdList;
  968. }
  969. }
  970. }
  971. public function initFieldsFromConfig($fieldsConfig) {
  972. foreach ($fieldsConfig as $idField => $vFieldConfig) {
  973. if ((int)$idField <= 0) {
  974. DBG::_('DBG_SCH', '1', "BUG key must be integer - skipping '{$idField}'", $vFieldConfig, __CLASS__, __FUNCTION__, __LINE__ );
  975. trigger_error("BUG " . __CLASS__ . "->" . __FUNCTION__ . "(\$fieldsConfig) key must be integer - skipping '{$idField}'", E_USER_NOTICE);
  976. continue;
  977. }
  978. //echo'<pre>INIT::$permField('.$vFieldConfig->ID_CELL.') hasFld('.$this->hasField($vFieldConfig->ID_CELL).') ';echo'</pre>';
  979. if (!$this->hasField($vFieldConfig['ID_CELL'])) {
  980. //echo'<pre>INIT::$permField('.$vFieldConfig['ID_CELL'].') addFld('.$vFieldConfig['ID_CELL'] . ', ' . $vFieldConfig['CELL_NAME'] . ', ' . $vFieldConfig['CELL_DESC'] . ', ' . $vFieldConfig['SORT_PRIO'] . ', ' . $vFieldConfig['CELL_LABEL'].') ';echo'</pre>';
  981. $this->addField($vFieldConfig['ID_CELL'], $vFieldConfig['CELL_NAME'], $vFieldConfig['CELL_DESC'], $vFieldConfig['SORT_PRIO'], $vFieldConfig['CELL_LABEL']);
  982. }
  983. //echo'<pre>INIT::$permField('.$vFieldConfig['ID_CELL'].') hasFld('.$this->hasField($vFieldConfig['ID_CELL']).') ';echo'</pre>';
  984. if (!isset($vFieldConfig['FORM_TREAT'])) {// TODO: convert to legacy perms
  985. $vFieldConfig['FORM_TREAT'] = '';
  986. if ($vFieldConfig['PERM_R'] > 0) $vFieldConfig['FORM_TREAT'] .= 'R';
  987. if ($vFieldConfig['PERM_W'] > 0) $vFieldConfig['FORM_TREAT'] .= 'W';
  988. if ($vFieldConfig['PERM_X'] > 0) $vFieldConfig['FORM_TREAT'] .= 'X';
  989. if ($vFieldConfig['PERM_C'] > 0) $vFieldConfig['FORM_TREAT'] .= 'C';
  990. if ($vFieldConfig['PERM_S'] > 0) $vFieldConfig['FORM_TREAT'] .= 'S';
  991. if ($vFieldConfig['PERM_O'] > 0) $vFieldConfig['FORM_TREAT'] .= 'O';
  992. if ($vFieldConfig['PERM_V'] > 0) $vFieldConfig['FORM_TREAT'] .= 'V';
  993. if ($vFieldConfig['PERM_E'] > 0) $vFieldConfig['FORM_TREAT'] .= 'E';
  994. }
  995. //echo'<pre>INIT::$permField('.$vFieldConfig['ID_CELL'].') ';print_r($vFieldConfig);echo'</pre>';
  996. if (!empty($vFieldConfig['FORM_TREAT'])) {
  997. $this->setFieldPerms($vFieldConfig['ID_CELL'], $vFieldConfig['FORM_TREAT']);
  998. }
  999. }
  1000. }
  1001. private function _fixProjectType() {
  1002. $tblName = $this->getName();
  1003. $fldName = 'M_DIST_TYPE';
  1004. if ($tblName == 'IN7_MK_BAZA_DYSTRYBUCJI') {
  1005. foreach ($this->_fields as $kFldId => $vFld) {
  1006. if ($vFld['name'] == $fldName) {
  1007. $sqlTypes = array();
  1008. if (!empty($this->_types[$fldName])) {
  1009. if (substr($this->_types[$fldName]['type'], 0, 4) == 'enum') {
  1010. $sqlTypes = explode(',', str_replace(array('(',')',"'",'"'), '', substr($this->_types[$fldName]['type'], 5)));
  1011. }
  1012. }
  1013. if (!empty($sqlTypes)) {
  1014. $allowedTypes = array();
  1015. $db = DB::getDB();
  1016. $sql = "select z.DESC
  1017. from `CRM_LISTA_ZASOBOW` as z
  1018. where z.`A_STATUS`='NORMAL'
  1019. and z.`PARENT_ID`={$kFldId}
  1020. order by z.`DESC` asc
  1021. ";
  1022. $res = $db->query($sql);
  1023. while ($r = $db->fetch($res)) {
  1024. if (in_array($r->DESC, $sqlTypes)) {
  1025. $allowedTypes[] = $r->DESC;
  1026. }
  1027. }
  1028. sort($allowedTypes);
  1029. if (!empty($allowedTypes)) {
  1030. $this->_types[$fldName]['type'] = "enum('" . implode("','", $allowedTypes) . "')";
  1031. }
  1032. }
  1033. }
  1034. }
  1035. }
  1036. }
  1037. private function _sortEnumFields() {
  1038. foreach ($this->_fields as $kFldId => $vFld) {
  1039. $type = $this->getFieldTypeById($kFldId);
  1040. if (!empty($type['type'])) {
  1041. if (substr($type['type'], 0, 4) == 'enum') {
  1042. $sqlTypes = explode(',', str_replace(array('(',')',"'",'"'), '', substr($type['type'], 5)));
  1043. if (!empty($sqlTypes)) {
  1044. sort($sqlTypes);
  1045. $this->_types[$vFld['name']]['type'] = "enum('" . implode("','", $sqlTypes) . "')";
  1046. }
  1047. }
  1048. }
  1049. }
  1050. }
  1051. private function _fixDateFields() {
  1052. foreach ($this->_types as $kFldName => $vType) {
  1053. if ($kFldName == 'L_APPOITMENT_DATE') {
  1054. $this->_types[$kFldName]['type'] = 'datetime';
  1055. } else if ($kFldName == 'A_PROBLEM_DATE') {
  1056. $this->_types[$kFldName]['type'] = 'datetime';
  1057. }
  1058. }
  1059. }
  1060. public function getUniqueKeys() {// TODO: RM NOT USED?
  1061. $sqlKeys = array();
  1062. $dbID = $this->getDB();
  1063. $tblName = $this->getName();
  1064. $db = DB::getDB($dbID);
  1065. if (!$db) {
  1066. die('Error - Brak konfiguracji dla bazy danych ID=' . $dbID);
  1067. }
  1068. $sql = "SHOW KEYS FROM `{$tblName}`";
  1069. $res = $db->query($sql);
  1070. while ($r = $db->fetch($res)) {
  1071. if ($r->Non_unique == '0') {
  1072. $sqlKeys[$r->Column_name] = true;
  1073. }
  1074. }
  1075. $sqlKeys = array_keys($sqlKeys);
  1076. return $sqlKeys;
  1077. }
  1078. public function sortFieldsCallback($a, $b) {
  1079. if ($a['name'] == 'ID') {
  1080. return -1;
  1081. }
  1082. else if ($b['name'] == 'ID') {
  1083. return 1;
  1084. }
  1085. else if ($a['sort_prio'] < $b['sort_prio']) {
  1086. return -1;
  1087. }
  1088. else if ($a['sort_prio'] > $b['sort_prio']) {
  1089. return 1;
  1090. }
  1091. else {
  1092. return 0;
  1093. }
  1094. }
  1095. public function isInitialized() {
  1096. return (!empty($this->_types));
  1097. }
  1098. /**
  1099. * Save data in session cache.
  1100. */
  1101. function save() {
  1102. $_SESSION['TableAcl_cache'][$this->_zasobID] = $this->toArray();
  1103. DBG::log("save(name='{$_SESSION['TableAcl_cache'][$this->_zasobID]['name']}')");
  1104. // DBG::simpleLog('auth', "TableAcl::save(name: '{$this->_name}')");
  1105. }
  1106. public function getFieldTypeById($fieldID) {
  1107. if (!array_key_exists($fieldID, $this->_fields)) return null;
  1108. $fieldName = $this->_fields[$fieldID]['name'];
  1109. if (!array_key_exists($fieldName, $this->_types)) return null;
  1110. return $this->_types[$fieldName];
  1111. }
  1112. public function getFieldType($fieldName) {
  1113. if (!array_key_exists($fieldName, $this->_types)) return null;
  1114. return $this->_types[$fieldName];
  1115. }
  1116. public function hasFieldType($fieldName) {
  1117. return (array_key_exists($fieldName, $this->_types));
  1118. }
  1119. public function getVisibleFieldList() { return $this->getVisibleFieldListByIdZasob(); }
  1120. public function getVisibleFieldListByIdZasob() {
  1121. $cols = array();
  1122. $id = 0;
  1123. foreach ($this->_fields as $kFieldID => $vField) {
  1124. if ($vField['name'] == 'ID') {
  1125. $id = $kFieldID;
  1126. }
  1127. }
  1128. $cols[$id] = 'ID';
  1129. foreach ($this->_fields as $kFieldID => $vField) {
  1130. if ($vField['name'] == 'ID') {
  1131. continue;
  1132. }
  1133. $cols[$kFieldID] = $vField['name'];
  1134. }
  1135. return $cols;
  1136. }
  1137. public function getExportFieldList() {
  1138. $cols = array();
  1139. $realFlds = $this->getRealFieldList();
  1140. foreach ($realFlds as $vFieldName) {
  1141. $fldId = $this->getFieldIdByName($vFieldName);
  1142. if ($fldId > 0 && $this->hasFieldPerm($fldId, 'E')) {
  1143. $cols[] = $vFieldName;
  1144. }
  1145. }
  1146. return $cols;
  1147. }
  1148. /**
  1149. * List of real fields in database.
  1150. */
  1151. public function getRealFieldList() {
  1152. $cols = array();
  1153. $cols[] = 'ID';
  1154. foreach ($this->_fields as $kFieldID => $vField) {
  1155. if ($vField['name'] == 'ID') {
  1156. continue;
  1157. }
  1158. if (array_key_exists($vField['name'], $this->_types)) {
  1159. $cols[] = $vField['name'];
  1160. }
  1161. }
  1162. return $cols;
  1163. }
  1164. public function getFieldListByIdZasob() {
  1165. $cols = array();
  1166. foreach ($this->_fields as $idField => $fld) {
  1167. if ($fld['name'] == 'ID') {
  1168. $cols[$idField] = 'ID';
  1169. }
  1170. }
  1171. foreach ($this->_fields as $idField => $fld) {
  1172. if ($fld['name'] == 'ID') continue;
  1173. $cols[$idField] = $fld['name'];
  1174. }
  1175. return $cols;
  1176. }
  1177. public function getRealFieldListByIdZasob() {
  1178. $cols = array();
  1179. foreach ($this->_fields as $idField => $fld) {
  1180. if ($fld['name'] == 'ID') {
  1181. $cols[$idField] = 'ID';
  1182. }
  1183. }
  1184. foreach ($this->_fields as $idField => $fld) {
  1185. if ($fld['name'] == 'ID') continue;
  1186. if (array_key_exists($fld['name'], $this->_types)) {
  1187. $cols[$idField] = $fld['name'];
  1188. }
  1189. }
  1190. return $cols;
  1191. }
  1192. public function getVirtualFieldListByIdZasob() {
  1193. $cols = array();
  1194. foreach ($this->_fields as $kFieldID => $vField) {
  1195. if ($vField['name'] == 'ID') {
  1196. continue;
  1197. }
  1198. if (in_array($kFieldID, $this->_virtualFieldsIdList)) {
  1199. $cols[$kFieldID] = $vField['name'];
  1200. }
  1201. else if (!array_key_exists($vField['name'], $this->_types)) {
  1202. $cols[$kFieldID] = $vField['name'];
  1203. }
  1204. }
  1205. return $cols;
  1206. }
  1207. public function getFieldLabel($fieldName) {
  1208. $idField = $this->getFieldIdByName($fieldName);
  1209. if (array_key_exists($idField, $this->_fields)) {
  1210. if (!empty($this->_fields[$idField]['label'])) {
  1211. return $this->_fields[$idField]['label'];
  1212. }
  1213. }
  1214. return null;
  1215. }
  1216. public function getFieldOpis($fieldName) {
  1217. $idField = $this->getFieldIdByName($fieldName);
  1218. if (array_key_exists($idField, $this->_fields)) {
  1219. if (!empty($this->_fields[$idField]['opis'])) {
  1220. return $this->_fields[$idField]['opis'];
  1221. }
  1222. }
  1223. return null;
  1224. }
  1225. public function getTypes() {
  1226. return $this->_types;
  1227. }
  1228. public function fixEmptyValueFromUser($fieldID) {
  1229. $value = '';
  1230. $type = $this->getFieldTypeById($fieldID);
  1231. if ($type) {
  1232. if ($type['type'] == 'date') {
  1233. $value = $type['default'];
  1234. }
  1235. if (substr($type['type'], 0, 3) == 'int'
  1236. || substr($type['type'], 0, 7) == 'tinyint'
  1237. || substr($type['type'], 0, 8) == 'smallint'
  1238. || substr($type['type'], 0, 6) == 'bigint'
  1239. ) {
  1240. $value = intval($type['default']);
  1241. }
  1242. // fix bug when field is unique and is null allowed: change empty string to null
  1243. if ($type['null']) {
  1244. $value = 'NULL';
  1245. }
  1246. // fix bug when field is enum and is set to '0': for php '0' is empty
  1247. if (substr($type['type'], 0, 4) == 'enum') {// && $args["f{$fieldID}"] === '0') {
  1248. if (false !== strpos($type['type'], "''")) {
  1249. // enum('', '1','2')
  1250. $value = '';
  1251. } else if (false !== strpos($type['type'], "'0'")) {
  1252. // enum('0', '1','2')
  1253. $value = '0';
  1254. } else {
  1255. $value = $type['default'];
  1256. }
  1257. }
  1258. }
  1259. return $value;
  1260. }
  1261. public function fromArray($arr) {
  1262. DBG::log("fromArray(name='{$arr['name']}')");
  1263. $this->_db = $arr['db'];
  1264. $this->_name = $arr['name'];
  1265. $this->_rootTableName = V::get('_rootTableName', null, $arr);
  1266. $this->_label = $arr['label'];
  1267. $this->_opis = $arr['opis'];
  1268. $this->_fields = V::get('fields', array(), $arr);
  1269. $this->_virtualFieldsIdList = V::get('virtualFieldsIdList', array(), $arr);
  1270. $this->_types = V::get('types', array(), $arr);
  1271. }
  1272. public function toArray() {
  1273. $arr = array();
  1274. $arr['db'] = $this->_db;
  1275. $arr['name'] = $this->_name;
  1276. $arr['_rootTableName'] = $this->_rootTableName;
  1277. $arr['label'] = $this->_label;
  1278. $arr['opis'] = $this->_opis;
  1279. $arr['fields'] = $this->_fields;
  1280. $arr['virtualFieldsIdList'] = $this->_virtualFieldsIdList;
  1281. $arr['types'] = $this->_types;
  1282. return $arr;
  1283. }
  1284. public function convertObjectFromUserInput($userItem, $type = 'array_by_id', $prefix = 'f') {// TODO: rename / Legacy
  1285. $item = $this->parseUserItem($userItem, $type = 'array_by_id', $prefix = 'f');
  1286. foreach ($item as $fieldName => $value) {
  1287. $item[$fieldName] = $this->validateAndFixField($fieldName, $value);
  1288. }
  1289. DBG::log(['userItem' => $userItem, 'item' => $item], '', "after parseUserItem, validateAndFixField");
  1290. return $item;
  1291. }
  1292. public function parseUserItem($userItem, $type = 'array_by_id', $prefix = 'f') {
  1293. $item = [];
  1294. foreach ($this->getFieldsMap() as $userKey => $fieldName) {
  1295. if (!array_key_exists("f{$userKey}", $userItem)) continue;
  1296. $item[$fieldName] = $userItem["f{$userKey}"];
  1297. }
  1298. return $item;
  1299. }
  1300. public function getFieldsMap() {// [ $userKey => $fieldName ] // TODO: $this->_fieldsMap
  1301. $fieldsMap = [];
  1302. foreach ($this->getFields() as $id => $field) $fieldsMap[ $id ] = $field['name'];
  1303. return $fieldsMap;
  1304. }
  1305. public function validateAndFixField($fieldName, $value) {
  1306. if (empty($value) && 0 === strlen($value)) {// TODO: fixEmptyValueFromUser
  1307. return $this->fixFieldEmptyValue($fieldName);
  1308. }
  1309. $xsdType = $this->getXsdFieldType($fieldName);
  1310. switch ($xsdType) {
  1311. case 'xsd:decimal': {
  1312. return str_replace([',', ' '], ['.', ''], $value);
  1313. } break;
  1314. case 'p5:price': {
  1315. return V::convert($value, 'price');
  1316. } break;
  1317. }
  1318. return $value;
  1319. }
  1320. public function fixFieldEmptyValue($fieldName) {// TODO: legacy
  1321. $value = '';
  1322. $type = $this->getFieldType($fieldName);
  1323. if (!$type) return '';
  1324. if ('date' == $type['type']) {
  1325. $value = $type['default'];
  1326. }
  1327. if (substr($type['type'], 0, 3) == 'int'
  1328. || substr($type['type'], 0, 7) == 'tinyint'
  1329. || substr($type['type'], 0, 8) == 'smallint'
  1330. || substr($type['type'], 0, 6) == 'bigint'
  1331. ) {
  1332. $value = intval($type['default']);
  1333. }
  1334. // fix bug when field is unique and is null allowed: change empty string to null
  1335. if ($type['null']) {
  1336. $value = 'NULL';
  1337. }
  1338. // fix bug when field is enum and is set to '0': for php '0' is empty
  1339. if (substr($type['type'], 0, 4) == 'enum') {// && $args["f{$fieldID}"] === '0') {
  1340. // if (false !== strpos($type['type'], "''")) {
  1341. // // enum('', '1','2')
  1342. // $value = '';
  1343. // } else if (false !== strpos($type['type'], "'0'")) {
  1344. // // enum('0', '1','2')
  1345. // $value = '0';
  1346. // } else {
  1347. $value = $type['default'];
  1348. // }
  1349. }
  1350. return $value;
  1351. }
  1352. public function getItem($primaryKey, $params = []) {
  1353. $ds = $this->getDataSource();
  1354. return $ds->getItem($primaryKey);
  1355. }
  1356. public function getItems($params = array()) {// TODO: use ParseOgcQuery
  1357. $ds = $this->getDataSource();
  1358. return $ds->getItems($params);
  1359. }
  1360. public function getTotal($params = array()) {// TODO: use ParseOgcQuery
  1361. $ds = $this->getDataSource();
  1362. return $ds->getTotal($params);
  1363. }
  1364. public function getColDefault($fieldName) {
  1365. $ds = $this->getDataSource();
  1366. return $ds->getColDefault($fieldName);
  1367. }
  1368. public function getSpecialFilters() {
  1369. $ds = $this->getDataSource();
  1370. return $ds->getSpecialFilters();
  1371. }
  1372. public function getGeomFields() {
  1373. $ds = $this->getDataSource();
  1374. return $ds->getGeomFields();
  1375. }
  1376. public function isGeomField($fldName) {
  1377. $ds = $this->getDataSource();
  1378. return $ds->isGeomField($fldName);
  1379. }
  1380. public function getGeomFieldType($fieldName) {
  1381. $dbGeomType = $this->getFieldType($fieldName);
  1382. $dbGeomType = (!empty($dbGeomType['type']))? $dbGeomType['type'] : '';
  1383. $geomType = strtolower($dbGeomType);
  1384. return $geomType;
  1385. }
  1386. public function getHistItems($id) {
  1387. if ($this->_schemaClass && method_exists($this->_schemaClass, 'hasGetHistItems') && $this->_schemaClass->hasGetHistItems()) {
  1388. return $this->_schemaClass->getHistItems($id);
  1389. }
  1390. $ds = $this->getDataSource();
  1391. return $ds->getHistItems($id);
  1392. }
  1393. public function getHistItem($id, $idHist) {
  1394. $ds = $this->getDataSource();
  1395. $histItems = $ds->getHistItems($id, ['ID' => $idHist]);
  1396. if (empty($histItems)) return null;
  1397. return reset($histItems);
  1398. }
  1399. public function addItem($itemTodo) {
  1400. if (is_object($itemTodo)) {
  1401. $itemTodo = (array)$itemTodo;
  1402. } else if (!is_array($itemTodo)) {
  1403. throw new HttpException('Item is not array', 400);
  1404. }
  1405. $ds = $this->getDataSource();
  1406. // from convertObjectFromUserInput - fixEmptyValueFromUser
  1407. $item = array();
  1408. $fields = $this->getFields();
  1409. foreach ($fields as $kID => $vField) {
  1410. $vFieldName = $vField['name'];
  1411. if (!$this->isAllowed($kID, 'C')) {
  1412. continue;
  1413. }
  1414. if (isset($itemTodo[$vFieldName])) {
  1415. $value = $itemTodo[$vFieldName];
  1416. if (empty($value) && strlen($value) == 0) {// fix bug in input type date and value="0000-00-00"
  1417. $value = $this->fixEmptyValueFromUser($kID);
  1418. }
  1419. $item[$vFieldName] = $value;
  1420. }
  1421. }
  1422. // add empty record is allowed - empty($item)
  1423. {// add DefaultAclGroup if no create perms ('C')
  1424. $defaultAclGroup = User::getDefaultAclGroup();
  1425. if ($defaultAclGroup) {
  1426. $permFields = array('A_ADM_COMPANY', 'A_CLASSIFIED');
  1427. foreach ($permFields as $permFldName) {
  1428. if (array_key_exists($permFldName, $this->_types)) {
  1429. $permFldId = $this->getFieldIdByName($permFldName);
  1430. if (0 == $permFldId || !$this->isAllowed($permFldId, 'C')) {
  1431. $item[$permFldName] = $defaultAclGroup;
  1432. }
  1433. }
  1434. }
  1435. }
  1436. }
  1437. DBG::_('DBG_DS', '>2', "addItem", $item, __CLASS__, __FUNCTION__, __LINE__);
  1438. return $ds->addItem($item);
  1439. }
  1440. /**
  1441. * @param array $itemPatch
  1442. */
  1443. public function updateItem($itemPatch) {
  1444. if (is_object($itemPatch)) {
  1445. $itemPatch = (array)$itemPatch;
  1446. } else if (!is_array($itemPatch)) {
  1447. throw new HttpException('Item patch is not array', 400);
  1448. }
  1449. if (empty($itemPatch)) {
  1450. //throw new Exception('Item patch is empty');
  1451. return 0;// nothing to change
  1452. }
  1453. $primaryKeyField = $this->getPrimaryKeyField();
  1454. if (empty($itemPatch[$primaryKeyField])) throw new HttpException("Item Primary Key not set!", 400);
  1455. $primaryKey = $itemPatch[$primaryKeyField];
  1456. $itemOld = $this->getItem($primaryKey);
  1457. if (!$itemOld) throw new HttpException("Item not exists!", 404);
  1458. if (!$this->canWriteRecord($itemOld) && !$this->hasPermSuperWrite()) throw new HttpException("Brak dostępu do rekordu", 403);
  1459. // $itemPatch from user input to $itemPatchChecked
  1460. $itemPatchChecked = array();
  1461. $fields = $this->getFields();
  1462. foreach ($fields as $kID => $vField) {
  1463. $vFieldName = $vField['name'];
  1464. if (!$this->isAllowed($kID, 'W', $itemOld)) {
  1465. continue;
  1466. }
  1467. if (array_key_exists($vFieldName, $itemPatch)) {
  1468. if (!$this->isAllowed($kID, 'R', $itemOld) && '*****' == $itemPatch[$vFieldName]) {
  1469. // default value for perms 'W' without 'R' is '*****'
  1470. }
  1471. else {
  1472. $value = $itemPatch[$vFieldName];
  1473. if (empty($itemPatch[$vFieldName]) && strlen($itemPatch[$vFieldName]) == 0) {// fix bug in input type date and value="0000-00-00"
  1474. $value = $this->fixEmptyValueFromUser($kID);
  1475. }
  1476. if ($value != $itemOld->$vFieldName) {
  1477. $itemPatchChecked[$vFieldName] = $value;
  1478. }
  1479. }
  1480. }
  1481. }
  1482. if (empty($itemPatchChecked)) {
  1483. //throw new HttpException("Item Primary Key not set!", 400);
  1484. return 0;// nothing to change
  1485. }
  1486. $itemPatchChecked[$primaryKeyField] = $primaryKey;
  1487. if ($this->_schemaClass && method_exists($this->_schemaClass, 'hasUpdateItem') && $this->_schemaClass->hasUpdateItem()) {
  1488. $affected = $this->_schemaClass->updateItem($itemPatchChecked);
  1489. } else {
  1490. $ds = $this->getDataSource();
  1491. $affected = $ds->updateItem($itemPatchChecked);
  1492. }
  1493. return $affected;
  1494. }
  1495. public function createItemCopy($item) {
  1496. $ds = $this->getDataSource();
  1497. $types = $this->getTypes();
  1498. $uniqKeys = $ds->getUniqueKeys();// TODO: getUniqueFields
  1499. $primaryKeyField = $ds->getPrimaryKeyField();
  1500. $itemCopy = new stdClass();
  1501. foreach ($types as $kName => $vType) {
  1502. if ($kName == $primaryKeyField) {
  1503. continue;
  1504. } else if (in_array($kName, array('A_RECORD_UPDATE_AUTHOR','A_RECORD_UPDATE_DATE'))) {
  1505. continue;
  1506. }
  1507. $value = V::get($kName, '', $item);
  1508. if (in_array($kName, $uniqKeys)) {
  1509. $value .= '?';
  1510. }
  1511. if ($ds->isGeomField($kName) && !empty($value)) {
  1512. $value = "GeomFromText('{$value}')";
  1513. }
  1514. $itemCopy->{$kName} = $value;
  1515. }
  1516. return $itemCopy;
  1517. }
  1518. public function getDataSource() {
  1519. $realFieldList = $this->getRealFieldList();
  1520. $dataSource = $this->_getDataSource($realFieldList);
  1521. $dataSource->setFieldGroupWrite('A_ADM_COMPANY', $this->hasFieldType('A_ADM_COMPANY'));
  1522. $dataSource->setFieldGroupRead('A_CLASSIFIED', $this->hasFieldType('A_CLASSIFIED'));
  1523. $dataSource->setFieldOwner('L_APPOITMENT_USER', $this->hasFieldType('L_APPOITMENT_USER'));
  1524. $adminFields = array('A_RECORD_CREATE_DATE', 'A_RECORD_CREATE_AUTHOR', 'A_RECORD_UPDATE_DATE', 'A_RECORD_UPDATE_AUTHOR');
  1525. foreach ($adminFields as $vAdmFld) {
  1526. if (!in_array($vAdmFld, $realFieldList) && $this->hasFieldType($vAdmFld)) {
  1527. $dataSource->addCol($vAdmFld);
  1528. }
  1529. }
  1530. return $dataSource;
  1531. }
  1532. private function _getDataSource($cols) {
  1533. $dsConfig = array();
  1534. $dsConfig['source_id'] = $this->getDB();
  1535. $dsConfig['object_name'] = $this->getRootTableName();
  1536. $dsConfig['fields'] = $cols;
  1537. $dsConfig['field_types'] = $this->getTypes();
  1538. $dsConfig['fields_virtual'] = $this->getVirtualFieldListByIdZasob();
  1539. $dsConfig['acl_fltr_allowed'] = !$this->hasSuperAccessPerms();
  1540. return DataSourceFactory::buildFromZasobInfo($dsConfig);
  1541. }
  1542. public function getPrimaryKeyField() {
  1543. if ($this->_schemaClass) {
  1544. $pkField = $this->_schemaClass->getPrimaryKeyField();
  1545. if ($pkField) return $pkField;
  1546. }
  1547. $ds = $this->getDataSource();
  1548. return $ds->getPrimaryKeyField();
  1549. }
  1550. public function isIntegerField($fldName) {
  1551. $type = $this->getFieldType($fldName);
  1552. if (!$type) return false;
  1553. if (substr($type['type'], 0, 3) == 'int'
  1554. || substr($type['type'], 0, 7) == 'tinyint'
  1555. || substr($type['type'], 0, 8) == 'smallint'
  1556. || substr($type['type'], 0, 9) == 'mediumint'
  1557. || substr($type['type'], 0, 6) == 'bigint'
  1558. ) {
  1559. return true;
  1560. }
  1561. return false;
  1562. }
  1563. public function isDecimalField($fldName) {
  1564. $type = $this->getFieldType($fldName);
  1565. if (!$type) return false;
  1566. if (substr($type['type'], 0, 7) == 'decimal'
  1567. || substr($type['type'], 0, 7) == 'numeric'
  1568. || substr($type['type'], 0, 6) == 'double'
  1569. || substr($type['type'], 0, 5) == 'float'
  1570. || substr($type['type'], 0, 4) == 'real'
  1571. ) {
  1572. return true;
  1573. }
  1574. return false;
  1575. }
  1576. public function isDateField($fldName) {
  1577. $type = $this->getFieldType($fldName);
  1578. if (!$type) return false;
  1579. if (substr($type['type'], 0, 4) == 'date' && substr($type['type'], 0, 8) != 'datetime') {
  1580. return true;
  1581. }
  1582. return false;
  1583. }
  1584. public function isDateTimeField($fldName) {
  1585. $type = $this->getFieldType($fldName);
  1586. if (!$type) return false;
  1587. if (substr($type['type'], 0, 8) == 'datetime') {
  1588. return true;
  1589. }
  1590. return false;
  1591. }
  1592. public function isStringField($fldName) {
  1593. $type = $this->getFieldType($fldName);
  1594. if (!$type) return false;
  1595. if (substr($type['type'], 0, 7) == 'varchar'
  1596. || substr($colType['type'], 0, 4) == 'char'
  1597. ) {
  1598. return true;
  1599. }
  1600. return false;
  1601. }
  1602. public function isTextField($fldName) {
  1603. $type = $this->getFieldType($fldName);
  1604. if (!$type) return false;
  1605. if (substr($type['type'], 0, 4) == 'text'
  1606. || substr($type['type'], 0, 8) == 'tinytext'
  1607. || substr($type['type'], 0, 10) == 'mediumtext'
  1608. || substr($type['type'], 0, 8) == 'longtext'
  1609. ) {
  1610. return true;
  1611. }
  1612. return false;
  1613. }
  1614. public function isBinaryField($fldName) {
  1615. $type = $this->getFieldType($fldName);
  1616. if (!$type) return false;
  1617. if (substr($type['type'], 0, 4) == 'blob'
  1618. || substr($type['type'], 0, 8) == 'tinyblob'
  1619. || substr($type['type'], 0, 10) == 'mediumblob'
  1620. || substr($type['type'], 0, 8) == 'longblob'
  1621. ) {
  1622. return true;
  1623. }
  1624. return false;
  1625. }
  1626. public function isEnumerationField($fldName) {
  1627. $type = $this->getFieldType($fldName);
  1628. if (!$type) return false;
  1629. if (substr($type['type'], 0, 4) == 'enum') {
  1630. return true;
  1631. }
  1632. return false;
  1633. }
  1634. public function getEnumerations($fldName) {
  1635. $enum = array();
  1636. $type = $this->getFieldType($fldName);
  1637. if (!$type) return $enum;
  1638. if (!$this->isEnumerationField($fldName)) return $enum;
  1639. $values = explode(',', str_replace(array('(',')',"'",'"'), '', substr($type['type'], 5)));
  1640. foreach ($values as $val) {
  1641. $enum[$val] = $val;
  1642. }
  1643. return $enum;
  1644. }
  1645. public function getAttributesFromZasoby() {
  1646. $attributes = array();
  1647. $db = DB::getDB();
  1648. $sql = "
  1649. select `ID` as `id_zasob`
  1650. , `DESC` as `field_name`
  1651. , `DESC_PL` as `label`
  1652. , `OPIS` as `description`
  1653. from `CRM_LISTA_ZASOBOW`
  1654. where `PARENT_ID`={$this->_zasobID}
  1655. and `TYPE`='KOMORKA'
  1656. ";
  1657. $res = $db->query($sql);
  1658. while ($r = $db->fetch($res)) {
  1659. $fldAttr = array();
  1660. $fldAttr['id_zasob'] = $r->id_zasob;
  1661. if (!empty($r->label)) $fldAttr['label'] = $r->label;
  1662. if (!empty($r->description)) $fldAttr['description'] = $r->description;
  1663. $attributes[$r->field_name] = $fldAttr;
  1664. }
  1665. // fetch field values
  1666. $sql = "
  1667. select z.`ID` as `id_zasob`
  1668. , z.`DESC` as `field_name`
  1669. , v.`DESC` as `value`
  1670. , v.`DESC_PL` as `label`
  1671. -- , v.`OPIS` as `description`
  1672. from `CRM_LISTA_ZASOBOW` z
  1673. join `CRM_LISTA_ZASOBOW` v on(v.`PARENT_ID` = z.`ID`)
  1674. where z.`PARENT_ID`={$this->_zasobID}
  1675. and z.`TYPE`='KOMORKA'
  1676. ";
  1677. $res = $db->query($sql);
  1678. while ($r = $db->fetch($res)) {
  1679. if (!empty($r->value) && !empty($r->label)) {
  1680. $valuesMap = V::get('valuesMap', array(), $attributes[$r->field_name]);
  1681. $valuesMap[$r->value] = $r->label;
  1682. $attributes[$r->field_name]['valuesMap'] = $valuesMap;
  1683. }
  1684. }
  1685. return $attributes;
  1686. }
  1687. public function getXsdFieldType($fieldName) {// @returns string - xsd type, TODO: throw Exception when field not found
  1688. if ($this->_schemaClass) {
  1689. $schemaType = $this->_schemaClass->getType($fieldName);
  1690. if ($schemaType) return $schemaType;
  1691. }
  1692. $fldType = 'xsd:string';
  1693. if ('A_RECORD_UPDATE_DATE' == $fieldName) return 'xsd:string';
  1694. if ('A_RECORD_CREATE_DATE' == $fieldName) return 'xsd:string';
  1695. if ($this->isIntegerField($fieldName)) return 'xsd:integer';
  1696. else if ($this->isDecimalField($fieldName)) return 'xsd:decimal';
  1697. else if ($this->isDateField($fieldName)) return 'xsd:date';
  1698. else if ($this->isDateTimeField($fieldName)) return 'xsd:dateTime';
  1699. else if ($this->isGeomField($fieldName)) {
  1700. //$fldType = 'gml:GeometryPropertyType';
  1701. $geomType = $this->getGeomFieldType($fieldName);
  1702. if ('polygon' == $geomType) return 'gml:PolygonPropertyType';
  1703. else if ('point' == $geomType) return 'gml:PointPropertyType';
  1704. else if ('linestring' == $geomType) return 'gml:LineStringPropertyType';
  1705. else return 'gml:GeometryPropertyType';
  1706. }
  1707. else if ($this->isEnumerationField($fieldName)) return 'xsd:string';
  1708. else if ($this->isBinaryField($fieldName)) return 'xsd:base64Binary';
  1709. return $fldType;
  1710. }
  1711. public function getXsdFieldParam($fieldName, $paramKey) {
  1712. return ($this->_schemaClass)
  1713. ? $this->_schemaClass->getFieldParam($fieldName, $paramKey)
  1714. : null
  1715. ;
  1716. }
  1717. public function getXsdTypes() {
  1718. $xsdTypes = [];
  1719. foreach ($this->getFields() as $idZasob => $field) {
  1720. $xsdTypes[ $field['name'] ] = [
  1721. 'name' => $field['name'],
  1722. 'perms' => $field['perms'],
  1723. 'idZasob' => $idZasob,
  1724. 'xsdType' => $this->getXsdFieldType($field['name']),
  1725. ];
  1726. }
  1727. return $xsdTypes;
  1728. }
  1729. public function getSqlFieldName($childName) {
  1730. return $childName;
  1731. }
  1732. }