TableAcl.php 66 KB

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