TableAcl.php 68 KB

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