TableAcl.php 68 KB

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