TableAcl.php 59 KB

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