TableAcl.php 63 KB

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