TableAcl.php 66 KB

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