TableAcl.php 61 KB

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