TableAcl.php 63 KB

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