TableAcl.php 62 KB

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