TableAcl.php 61 KB

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