TableAcl.php 64 KB

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