TableAcl.php 63 KB

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