TableAcl.php 59 KB

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