TableAcl.php 68 KB

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