AclHelper.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. <?php
  2. Lib::loadClass('Api_WfsNs');
  3. Lib::loadClass('ProcesHelper');
  4. Lib::loadClass('Router');
  5. Lib::loadClass('Route_UrlAction');
  6. class Core_AclHelper {// Helper class for Acl
  7. public static function hasCreatePerms($acl) {
  8. foreach ($acl->getFieldListByIdZasob() as $fieldName) {// TODO: use getFieldList
  9. // echo"<p>\$acl->canCreateField({$fieldName}): (".$acl->canCreateField($fieldName).")</p>";
  10. if ($acl->canCreateField($fieldName)) return true;
  11. }
  12. return false;
  13. }
  14. public static function hasGeomFields($acl) {
  15. foreach ($acl->getFieldListByIdZasob() as $fieldName) {
  16. // echo"<p>\$acl->isGeomField({$fieldName}): (".$acl->isGeomField($fieldName).") \$acl->canReadField({$fieldName}): (".$acl->canReadField($fieldName).")</p>";
  17. if ($acl->isGeomField($fieldName) && $acl->canReadField($fieldName)) return true;
  18. }
  19. return false;
  20. }
  21. // @returns array [ field => string(perms like 'RWX') ]
  22. public static function getFieldPerms($acl) {// TODO: fetch perms for given Acl by namespace
  23. // TODO:? cache session or only current request (static)
  24. $fieldPerms = array();
  25. foreach ($acl->getFields() as $idField => $field) {
  26. $fieldPerms[ $field['name'] ] = $field['perms'];
  27. }
  28. return $fieldPerms;
  29. }
  30. public static function getExportFieldList($acl) {
  31. $exportFields = array();
  32. foreach (self::getFieldPerms($acl) as $fieldName => $perms) {
  33. if (false !== strpos($perms, 'E')) {
  34. $exportFields[] = $fieldName;
  35. }
  36. }
  37. return $exportFields;
  38. }
  39. public static function getAclByTypeName($typeName, $forceTblAclInit = false) {// TODO: replace getAclFromTypeName in WFS
  40. return self::getAclByNamespace(str_replace(':', '/', $typeName), $forceTblAclInit);
  41. }
  42. public static function getAclByNamespace($namespace, $forceTblAclInit = false) { // TODO: mv to ACL
  43. try {
  44. Lib::loadClass('SchemaFactory');
  45. $objItem = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, ['propertyName'=>"*,field"]);
  46. DBG::log($objItem, 'array', "DBG objItem({$namespace})");
  47. if (!$objItem['idZasob']) throw new Exception("Missing idZasob for namespace '{$namespace}'");
  48. if (!in_array($objItem['_type'], [
  49. // 'TableAcl', // TODO: TEST - to replace TableAcl by AntAcl
  50. 'AntAcl',
  51. ])) throw new Exception("Not Implemented acl type '{$objItem['_type']}'");
  52. // TODO: check if isActive and isStructInstalled // TODO: modify Acl.isActive to admin settings
  53. Lib::loadClass('AntAclBase');
  54. $acl = AntAclBase::buildInstance($objItem['idZasob'], $objItem);
  55. return $acl;
  56. } catch (Exception $e) {
  57. DBG::log($e);
  58. }
  59. $ns = self::parseNamespaceUrl($namespace);
  60. DBG::log($ns, 'array', "parseNamespaceUrl({$namespace})");
  61. $acl = User::getAcl()->getObjectAcl($ns['prefix'], $ns['name']);
  62. $acl->init($forceTblAclInit);
  63. return $acl;
  64. }
  65. public static function getMoreFunctionsCell($acl, $args) {
  66. $id = V::get('primary_key', 0, $args, 'int');
  67. if ($id <= 0) throw new HttpException("404", 404);
  68. $record = V::get('record', null, $args);
  69. $rowFunList = array();
  70. $tableName = $acl->getName();
  71. $record = ($record)? $record : $acl->getItem($id);
  72. if(1){// TODO: fetch $totalMsgs from TableMsgs
  73. $msgs = Router::getRoute('Msgs');
  74. $msgsList = $msgs->getActiveMessagesForTableRecord($tableName, $id);
  75. $totalMsgs = count($msgsList);
  76. $rowFunc = new stdClass();
  77. $rowFunc->id = 'msgs';
  78. $rowFunc->ico = 'glyphicon glyphicon-envelope';
  79. $rowFunc->href = 'index.php?_route=TableMsgs&_task=tableRow&idTable=' . $acl->getID() . '&idRow=' . $id;
  80. $rowFunc->title = "Wiadomości ({$totalMsgs})";
  81. $rowFunc->label = "Wiadomości <span class=\"badge\">{$totalMsgs}</span>";
  82. $rowFunList[] = $rowFunc;
  83. }
  84. if ('CRM_PROCES' == $acl->getName()) {// TODO: mv to table gui xml or php class
  85. // procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id=22001
  86. $rowFunc = new stdClass();
  87. $rowFunc->ico = 'glyphicon glyphicon-eye-open';
  88. $rowFunc->href = "procesy5.php?task=CRM_PROCES&filtr_id={$id}";
  89. $rowFunc->title = "Zobacz na drzewie procesów {{$id}}";
  90. $rowFunList[] = $rowFunc;
  91. $wskazniki = ProcesHelper::get_wskazniki($id);
  92. $connectedZasobyTotal = count($wskazniki);
  93. $rowFunc = new stdClass();
  94. $rowFunc->ico = 'glyphicon glyphicon-random';
  95. $rowFunc->href = "index.php?MENU_INIT=PROCES_ADD_ZASOB&procesID={$id}";
  96. $rowFunc->title = "Powiązane zasoby <span class=\"badge\">{$connectedZasobyTotal}</span>";
  97. $rowFunList[] = $rowFunc;
  98. }
  99. if ('CRM_LISTA_ZASOBOW' == $acl->getName()) {// TODO: mv to table gui xml or php class
  100. // procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id=22001
  101. $rowFunc = new stdClass();
  102. $rowFunc->ico = 'glyphicon glyphicon-eye-open';
  103. $rowFunc->href = "procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id={$id}";
  104. $rowFunc->title = "Zobacz na drzewie zasobów [{$id}]";
  105. $rowFunList[] = $rowFunc;
  106. // index.php?MENU_INIT=ZASOB_OBOWIAZKI&id_zasob=22001
  107. $rowFunc = new stdClass();
  108. $rowFunc->ico = 'glyphicon glyphicon-random';
  109. $rowFunc->href = "index.php?MENU_INIT=ZASOB_OBOWIAZKI&id_zasob={$id}";
  110. $rowFunc->title = "Powiązane procesy (OB)";
  111. $rowFunList[] = $rowFunc;
  112. // index.php?MENU_INIT=ZASOB_EXTERNAL_IDS&id_zasob=22001
  113. $rowFunc = new stdClass();
  114. $rowFunc->ico = 'glyphicon glyphicon-random';
  115. $rowFunc->href = "index.php?MENU_INIT=ZASOB_EXTERNAL_IDS&id_zasob={$id}";
  116. $rowFunc->title = "Powiązane dane (IDS)";
  117. $rowFunList[] = $rowFunc;
  118. $groupTypeList = array();
  119. $groupTypeList[] = 'STANOWISKO';
  120. $groupTypeList[] = 'PODMIOT';
  121. $groupTypeList[] = 'DZIAL';
  122. if (in_array($record->TYPE, $groupTypeList)) {
  123. $rowFunc = new stdClass();
  124. $rowFunc->ico = 'glyphicon glyphicon-retweet';
  125. $rowFunc->href = "index.php?_route=Users&_task=syncGroup&idGroup={$id}";
  126. $rowFunc->title = "Synchronizuj do LDAP";
  127. $rowFunList[] = $rowFunc;
  128. }
  129. }
  130. if ('ADMIN_USERS' == $acl->getName()) {// TODO: mv to table gui xml
  131. if ($acl->canReadRecord($record) && $acl->canReadObjectField('ADM_ACCOUNT', $record)) {
  132. $rowFunc = new stdClass();
  133. $rowFunc->ico = 'glyphicon glyphicon-user';
  134. $rowFunc->href = 'index.php?_route=Users&_task=userGroups&usrLogin=' . $record->ADM_ACCOUNT;
  135. $rowFunc->title = "Ustal stanowisko";
  136. $rowFunList[] = $rowFunc;
  137. $rowFunc = new stdClass();
  138. $rowFunc->ico = 'glyphicon glyphicon-retweet';
  139. $rowFunc->href = 'index.php?_route=Users&_task=syncUser&usrLogin=' . $record->ADM_ACCOUNT;
  140. $rowFunc->title = "Synchronizuj do LDAP";
  141. $rowFunList[] = $rowFunc;
  142. $rowFunc = new stdClass();
  143. $rowFunc->ico = 'glyphicon glyphicon-minus';
  144. $rowFunc->href = 'index.php?MENU_INIT=USER_OCENA_PRACOWNIKA&usrLogin=' . $record->ADM_ACCOUNT;
  145. $rowFunc->title = "Ocena pracownika";
  146. $rowFunList[] = $rowFunc;
  147. }
  148. }
  149. if ($urlFunctions = Route_UrlAction::getTableFunctions($acl->getID(), $id, $acl->getName(), User::getLogin())) {
  150. foreach ($urlFunctions as $urlFunction) {
  151. // TODO: is allowed to view - test by Router::getRoute('UrlAction')->isFunctionAllowedForRecord($routeName = $urlFunction['name'], $acl->getID(), $id);
  152. $rowFunction = array();
  153. $rowFunction['href'] = $urlFunction['baseLink'];
  154. $rowFunction['ico'] = V::get('ico', 'glyphicon glyphicon-share', $urlFunction);
  155. $rowFunction['label'] = $urlFunction['label'];
  156. $rowFunction['title'] = V::get('title', $urlFunction['label'], $urlFunction);
  157. if (!empty($urlFunction['link_target'])) $rowFunction['target'] = $urlFunction['link_target'];
  158. if (!empty($urlFunction['cell_id_params'])) {
  159. $urlParams = array();// [ "{$urlParamName}={$paramValue}" ]
  160. foreach ($urlFunction['cell_id_params'] as $idField => $urlParamName) {
  161. $paramValue = '';
  162. $fld = $acl->getField($idField);
  163. if ($fld) {
  164. $fldName = $fld['name'];
  165. $paramValue = V::get($fldName, '', $record);
  166. $urlParams[] = "{$urlParamName}={$paramValue}";
  167. }
  168. }
  169. if (!empty($urlParams)) $rowFunction['href'] .= "&" . implode("&", $urlParams);
  170. }
  171. $rowFunList[] = $rowFunction;
  172. }
  173. }
  174. if (1) {// Druki
  175. $parsedNs = self::parseNamespaceUrl($acl->getNamespace());
  176. // array (
  177. // 'name' => 'TEST_PERMS',
  178. // 'prefix' => 'default_db',
  179. // 'url' => 'https://biuro.biall-net.pl/wfs/default_db',
  180. // 'sourceName' => 'default_db',
  181. // ),
  182. $typeName = "{$parsedNs['prefix']}:{$parsedNs['name']}";
  183. DBG::log([
  184. 'msg' => "getMoreFunctionsCell Druki",
  185. 'namespace' => $acl->getNamespace(),
  186. 'typeName' => $typeName,
  187. 'primaryKey' => $id,
  188. 'parseNamespace' => $parsedNs,
  189. ]);
  190. $rowFunList[] = [
  191. 'href' => Request::getPathUri() . "index.php?_route=UrlAction_Ant&typeName={$typeName}&primaryKey={$id}",
  192. 'ico' => 'glyphicon glyphicon-file',
  193. 'label' => "Druki",
  194. 'title' => "Druki"
  195. ];
  196. }
  197. DBG::log(['msg'=>"\$rowFunList", '$rowFunList'=>$rowFunList]);
  198. return $rowFunList;
  199. }
  200. public static function getAclList() {// @usage Core_AclHelper::getAclList();// @returns array [ $typeName , ... ]
  201. $aclList = array();
  202. // Schema_AccessGroupStorageAcl, load by User::getAcl()->getObjectAcl('default_objects', $objName);
  203. // $objClassName = "Schema_{$objName}StorageAcl";
  204. // if (!Lib::tryLoadClass($objClassName)) throw new HttpException("Not implemented", 501);
  205. // $ grep -r 'class ' SE/se-lib/Schema/*Acl.php
  206. // SE/se-lib/Schema/AccessGroupStorageAcl.php:class Schema_AccessGroupStorageAcl extends Core_AclBase
  207. // SE/se-lib/Schema/AccessOwnerStorageAcl.php:class Schema_AccessOwnerStorageAcl extends Core_AclBase
  208. // SE/se-lib/Schema/FileStorageAcl.php:class Schema_FileStorageAcl extends Core_AclBase
  209. // SE/se-lib/Schema/KorespondencjaStorageAcl.php:class Schema_KorespondencjaStorageAcl extends Core_AclBase
  210. // SE/se-lib/Schema/TestPermsStorageAcl.php:class Schema_TestPermsStorageAcl extends Core_AclBase
  211. $aclList[] = 'default_objects:AccessGroupRead';
  212. $aclList[] = 'default_objects:AccessGroupWrite';
  213. $aclList[] = 'default_objects:AccessOwner';
  214. $aclList[] = 'default_objects:SystemObject';// tabele i obiekty możliwe do podłączenia do procesu (default_db/*, default_objects/*)
  215. $aclList[] = 'default_objects:SystemFunction';// funkcje możliwe do podłączenia do procesu UrlAction
  216. // $aclList[] = 'default_objects:UserFunction';// TODO: funkcje możliwe do uruchomienia przez usera
  217. // $aclList[] = 'default_objects:UserObject';// TODO: tabele i obiekty widoczne dla aktualnego usera
  218. $aclList[] = 'default_objects:SystemProcess';// wszystkie proces init
  219. $aclList[] = 'default_objects:UserProcess';// proces init przypisane do aktualnego usera
  220. $aclList[] = 'default_objects:UserTestStats';// TODO: testy stats by user proces init
  221. $aclList[] = 'default_objects:File';
  222. $aclList[] = 'default_objects:Korespondencja';
  223. $aclList[] = 'default_objects:TestPerms';
  224. // TODO: read from Database
  225. // $aclList[] = 'default_db__x3A__TEST_PERMS:TEST_PERMS';// uproszczona wersja: default_db:TEST_PERMS
  226. $cleanHostName = str_replace(array(".", "-"), '_', $_SERVER['SERVER_NAME']);
  227. if (file_exists(APP_PATH_SCHEMA . "/gui/company/{$cleanHostName}/get_object_list.php")) {
  228. $objList = include APP_PATH_SCHEMA . "/gui/company/{$cleanHostName}/get_object_list.php";
  229. if (!empty($objList) && is_array($objList)) {
  230. foreach ($objList as $objectName) {
  231. if (!in_array($objectName, $aclList)) $aclList[] = $objectName;
  232. }
  233. }
  234. }
  235. return $aclList;
  236. }
  237. public static function parseTypeName($typeName) {
  238. return self::parseNamespaceUrl(str_replace(':', '/', $typeName));
  239. }
  240. /**
  241. * Parse namespace url into parts.
  242. *
  243. * @param $namespace - absolute or relative url
  244. * @return array:
  245. * name: element name
  246. * url: url wihtout name
  247. * prefix: xml prefix
  248. * sourceName: used by engine - maybe to remove (used by Core_AclHelper::getAclByNamespace($namespace))
  249. *
  250. * @example - create xmlns attribute:
  251. * xmlns:{$ns['prefix']}="{$ns['url']}"
  252. *
  253. * @example - wfs typeName:
  254. * typeName = "{$ns['prefix']}:{$ns['name']}"
  255. *
  256. * @example 'default_db/TEST_PERMS' => Array:
  257. * [name] => TEST_PERMS
  258. * [prefix] => default_db
  259. * [url] => https://biuro.biall-net.pl/wfs/default_db
  260. * [sourceName] => default_db
  261. *
  262. * @example 'default_objects/AccessOwner' => Array:
  263. * [name] => AccessOwner
  264. * [prefix] => default_objects
  265. * [url] => https://biuro.biall-net.pl/wfs/default_objects
  266. * [sourceName] => default_objects
  267. *
  268. * @example 'default_db/ZALICZKA/Zaliczka' => Array:
  269. * [name] => Zaliczka
  270. * [prefix] => default_db__x3A__Zaliczka
  271. * [url] => https://biuro.biall-net.pl/wfs/default_db/ZALICZKA
  272. * [sourceName] => table_objects
  273. *
  274. */
  275. public static function parseNamespaceUrl($namespace) {// returns assoc array: [ 'name', 'url', 'prefix', 'sourceName' ]
  276. // TODO: the same algo like getAclByNamespace($namespace)
  277. $baseNsUri = Api_WfsNs::getBaseWfsUri();
  278. if ('http' != substr($namespace, 0, 4)) $namespace = "{$baseNsUri}/{$namespace}";//Request::getHostUri() . '/' . $namespace;
  279. $nsUrl = $baseNsUri . '/' . '';
  280. if ("{$baseNsUri}/" != substr($namespace, 0, strlen($baseNsUri) + 1)) throw new HttpException("Zasoby zewnętrzenj systemu nie są jeszcze zaimplementowane", 501);
  281. $relativeNsUrl = substr($namespace, strlen($baseNsUri) + 1);
  282. // convert '__x3A__' to '/' in url
  283. $nsEx = explode('/', str_replace('__x3A__', '/', $relativeNsUrl));// "http://biuro.biall-net.pl/wfs/ default_db/{$nazwa_tabeli}/{$nazwa_obj}
  284. // default_db__x3A__ZALICZKA/Zaliczka => default_db/ZALICZKA/Zaliczka
  285. $sourceName = array_shift($nsEx);// remove first element - source name
  286. $objName = array_pop($nsEx);// name is always last part from url
  287. if ('default_db' == $sourceName || 'p5_default_db' == $sourceName) {
  288. if (count($nsEx) > 1) throw new Exception("Nieznany namespace default_db: '{$relativeNsUrl}'", 501);
  289. $sourceName = 'default_db';
  290. $nsPrefix = $sourceName;
  291. if (1 == count($nsEx)) {
  292. $sourceName = 'table_objects';// TODO: another source name to read from simpleSchema @see Core_AclSimpleSchemaBase
  293. $nsPrefix = 'default_db__x3A__' . $nsEx[0];
  294. }
  295. // $objName = $nsEx[1];// 'default_db/ZALICZKA:Zaliczka' => ('objects', 'Zaliczka') - possible name conflicts
  296. $nsUrl = trim($baseNsUri . '/default_db/' . implode("/", $nsEx), '/');
  297. return [ 'name' => $objName, 'prefix' => $nsPrefix, 'url' => $nsUrl, 'sourceName' => $sourceName ];
  298. }
  299. else if ('default_objects' == $sourceName || 'SystemObjects' == $sourceName) {
  300. if (count($nsEx) > 1) throw new Exception("Nieznany namespace SystemObjects: '{$relativeNsUrl}'", 501);
  301. $sourceName = 'default_objects';
  302. $nsUrl = trim($baseNsUri . '/default_objects/' . implode("/", $nsEx), '/');
  303. $nsPrefix = 'default_objects';
  304. return [ 'name' => $objName, 'prefix' => $nsPrefix, 'url' => $nsUrl, 'sourceName' => $sourceName ];
  305. }
  306. else if ('p5_objects' == $sourceName || 'objects' == $sourceName) {
  307. if (count($nsEx) > 1) throw new Exception("Nieznany namespace SystemObjects: '{$relativeNsUrl}'", 501);
  308. $sourceName = 'default_objects';
  309. $nsUrl = trim($baseNsUri . '/default_objects/' . implode("/", $nsEx), '/');
  310. $nsPrefix = 'default_objects';
  311. return [ 'name' => $objName, 'prefix' => $nsPrefix, 'url' => $nsUrl, 'sourceName' => $sourceName ];
  312. }
  313. else if ('zasob_' == substr($sourceName, 0, 6)) {
  314. $dbName = substr($sourceName, 6);// database id
  315. $remotePdo = DB::getPDO($dbName);
  316. DBG::log($remotePdo, 'array', '$remotePdo');
  317. if (!$remotePdo || $remotePdo->getZasobId() <= 0) throw new Exception("Database [{$dbName}] not exists - namespace '{$relativeNsUrl}'", 501);
  318. if (count($nsEx) > 0) throw new Exception("Nieznany namespace {$sourceName}: '{$relativeNsUrl}'", 501);
  319. return [ 'name' => $objName, 'prefix' => $sourceName, 'url' => implode('/', [$baseNsUri, $sourceName, $objName]), 'sourceName' => $sourceName ];
  320. }
  321. else throw new Exception("Nieznany namespace '{$relativeNsUrl}'", 501);
  322. }
  323. public static function getIdDatabaseFromNamespace($namespace) {
  324. $ns = self::parseNamespaceUrl($namespace);
  325. if ('default_db' == substr($ns['sourceName'], 0, strlen('default_db'))) {
  326. return DB::getPDO()->getZasobId();
  327. } else if ('default_objects' == substr($ns['sourceName'], 0, strlen('default_objects'))) {
  328. return DB::getPDO()->getZasobId();
  329. } else if ('table_objects' == $ns['sourceName']) {
  330. if ('default_db' == substr($ns['prefix'], 0, strlen('default_db'))) {
  331. return DB::getPDO()->getZasobId();
  332. }
  333. } else if ('zasob_' == substr($ns['sourceName'], 0, strlen('zasob_'))) {
  334. // 'zasob_931', 'zasob_931__x3A__...'
  335. $idDatabase = substr($ns['sourceName'], strlen('zasob_'));
  336. if (false !== strpos($idDatabase, '_')) $idDatabase = substr($idDatabase, 0, strpos($idDatabase, '_'));
  337. if (!$idDatabase || !is_numeric($idDatabase)) throw new Exception("Not implemented idDatabase({$idDatabase})");
  338. return $idDatabase;
  339. }
  340. throw new Exception("Not implemented idDatabase for namespace({$namespace})");
  341. }
  342. public static function insertRef($objectName, $pk, $childName, $childPk) {// TODO: $idTransaction
  343. $refTable = self::getRefTable($objectName, $childName);
  344. $sqlPk = DB::getPDO()->quote($pk, PDO::PARAM_STR);
  345. $sqlChildPk = DB::getPDO()->quote($childPk, PDO::PARAM_STR);
  346. DB::getPDO()->exec("
  347. insert into `{$refTable}` (`PRIMARY_KEY`, `REMOTE_PRIMARY_KEY`)
  348. values ({$sqlPk}, {$sqlChildPk})
  349. ");
  350. }
  351. public static function cleanRefs($objectName, $pk, $childName) {// TODO: $idTransaction
  352. $refTable = self::getRefTable($objectName, $childName);
  353. $sqlPk = DB::getPDO()->quote($pk, PDO::PARAM_STR);
  354. DB::getPDO()->exec("
  355. update `{$refTable}` set `A_STATUS` = 'DELETED'
  356. where `PRIMARY_KEY` = {$sqlPk}
  357. ");
  358. }
  359. public static function getRefTable($objectName, $childName) {// TODO: wrong - add prefix to avoid name collisions or generate unique hash
  360. static $cacheRefTables = array();
  361. $refTable = "{$objectName}__#REF__{$childName}";
  362. if (in_array($refTable, $cacheRefTables)) return $refTable;
  363. DB::getPDO()->exec("
  364. CREATE TABLE IF NOT EXISTS `{$refTable}` (
  365. `PRIMARY_KEY` int(11) NOT NULL,
  366. `REMOTE_PRIMARY_KEY` int(11) NOT NULL,
  367. `REMOTE_TYPENAME` varchar(255) NOT NULL DEFAULT '',
  368. `A_STATUS` enum('WAITING', 'NORMAL', 'DELETED') NOT NULL DEFAULT 'WAITING',
  369. `A_RECORD_UPDATE_DATE` timestamp ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  370. -- TODO `TRANACTION_ID` int(11) NOT NULL
  371. KEY `PRIMARY_KEY` (`PRIMARY_KEY`),
  372. KEY `REMOTE_PRIMARY_KEY` (`REMOTE_PRIMARY_KEY`)
  373. ) ENGINE=MyISAM DEFAULT CHARSET=latin2;
  374. ");
  375. try {
  376. DB::getPDO()->exec(" ALTER TABLE `{$refTable}` ADD `A_STATUS` enum('WAITING', 'NORMAL', 'DELETED') NOT NULL DEFAULT 'WAITING' ");
  377. } catch (Exception $e) {
  378. // echo 'C.'.get_class($this).' L.' . __LINE__ . " Error:";print_r($e->getMessage());echo "\n";
  379. }
  380. try {
  381. DB::getPDO()->exec(" ALTER TABLE `{$refTable}` ADD `A_RECORD_UPDATE_DATE` timestamp ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ");
  382. } catch (Exception $e) {
  383. // echo 'C.'.get_class($this).' L.' . __LINE__ . " Error:";print_r($e->getMessage());echo "\n";
  384. }
  385. try {
  386. DB::getPDO()->exec(" ALTER TABLE `{$refTable}` ADD `REMOTE_TYPENAME` varchar(255) NOT NULL DEFAULT '' ");
  387. } catch (Exception $e) {
  388. // echo 'C.'.get_class($this).' L.' . __LINE__ . " Error:";print_r($e->getMessage());echo "\n";
  389. }
  390. $cacheRefTables[] = $refTable;
  391. return $refTable;
  392. }
  393. public static function getInstanceTable($rootTableName) {
  394. static $cacheInstanceTables = array();
  395. $instanceTable = "{$rootTableName}__#INSTANCE";
  396. if (in_array($instanceTable, $cacheInstanceTables)) return $instanceTable;
  397. DB::getPDO()->execSql("
  398. CREATE TABLE IF NOT EXISTS `{$instanceTable}` (
  399. `PRIMARY_KEY` int(11) NOT NULL,
  400. `A_RECORD_UPDATE_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  401. `INSTANCE_NAME` varchar(255) NOT NULL,
  402. UNIQUE KEY `PRIMARY_KEY` (`PRIMARY_KEY`),
  403. KEY `INSTANCE_NAME` (`INSTANCE_NAME`)
  404. -- TODO `A_TRANACTION_ID` int(11) NOT NULL DEFAULT 0
  405. ) ENGINE=MyISAM DEFAULT CHARSET=latin2;
  406. ");
  407. DB::getPDO()->execSql("
  408. CREATE TABLE IF NOT EXISTS `{$instanceTable}_HIST` (
  409. `ID` int(11) NOT NULL AUTO_INCREMENT,
  410. `PRIMARY_KEY` int(11) NOT NULL,
  411. `A_TRANACTION_ID` int(11) NOT NULL DEFAULT 0,
  412. `A_RECORD_UPDATE_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  413. `INSTANCE_NAME` varchar(255) NOT NULL,
  414. PRIMARY KEY (`ID`),
  415. KEY `PRIMARY_KEY` (`PRIMARY_KEY`)
  416. ) ENGINE=MyISAM DEFAULT CHARSET=latin2;
  417. ");
  418. $cacheInstanceTables[] = $instanceTable;
  419. return $instanceTable;
  420. }
  421. public static function setInstance($rootTableName, $pk, $instanceName, $idTransaction = 0) {
  422. $instanceTable = self::getInstanceTable($rootTableName);
  423. $pk = intval($pk);
  424. // TODO: if $pk < 0 throw new Exception("...");
  425. $sql = [
  426. 'instanceName' => DB::getPDO()->quote($instanceName, PDO::PARAM_STR),
  427. 'idTransaction' => intval($idTransaction)
  428. ];
  429. DB::getPDO()->exec("
  430. insert into `{$instanceTable}_HIST` (`PRIMARY_KEY`, `INSTANCE_NAME`, `A_TRANACTION_ID`)
  431. values({$pk}, {$sql['instanceName']}, {$idTransaction})
  432. ");
  433. }
  434. public static function getChildHistTable($rootTableName, $childName, $schema) {
  435. // $childName(id) => Array:
  436. // [@type] => xsd:integer
  437. // $childName(created) => Array:
  438. // [@type] => xsd:date
  439. // $childName(worker) => Array:
  440. // [@ref] => default_objects/AccessOwner
  441. // $childName(kwota) => Array:
  442. // [@type] => xsd:decimal
  443. // [@totalDigits] => 16
  444. // [@fractionDigits] => 2
  445. // $childName(nierozliczona_kwota) => Array:
  446. // [@type] => xsd:decimal
  447. // [@totalDigits] => 16
  448. // [@fractionDigits] => 2
  449. // $childName(pozycja) => Array:
  450. // [@ref] => ZaliczkaPozycja
  451. // [@maxOccurs] => unbounded
  452. static $cacheHistTables = array();
  453. $histTable = "{$rootTableName}__#HIST__{$childName}";
  454. if (in_array($histTable, $cacheHistTables)) return $histTable;
  455. $sqlType = '';
  456. switch ($schema['@type']) {
  457. case 'xsd:integer': $sqlType = "int(11) NOT NULL DEFAULT 0"; break;
  458. case 'xsd:date': $sqlType = "date DEFAULT NULL"; break;
  459. case 'xsd:decimal': $sqlType = "decimal(" . V::get('@totalDigits', 16, $schema) . ", " . V::get('@fractionDigits', 2, $schema) . ") NOT NULL DEFAULT 0"; break;
  460. case 'xsd:string': $sqlType = "varchar(255) NOT NULL DEFAULT ''"; break;
  461. // TODO: type alias like enum fields: @type => "{$prefix}:{$field_name}Type"
  462. }
  463. if (!$sqlType && !empty($schema['@ref'])) $sqlType = "int(11) NOT NULL DEFAULT 0";// TODO: type from ref instance @primaryKey - mostly int
  464. if (!$sqlType) throw new Exception("Unimplemented schema to sql for '{$rootTableName}/{$childName}' schema(".json_encode($schema).")");
  465. DB::getPDO()->exec("
  466. CREATE TABLE IF NOT EXISTS `{$histTable}` (
  467. `ID` int(11) NOT NULL AUTO_INCREMENT,
  468. `VALUE` {$sqlType},
  469. `A_TRANSACTION_ID` int(11) NOT NULL DEFAULT 0,
  470. PRIMARY KEY (`ID`)
  471. ) ENGINE=MyISAM DEFAULT CHARSET=latin2;
  472. ");
  473. $cacheHistTables[] = $histTable;
  474. return $histTable;
  475. }
  476. public static function getTransactionTable($rootTableName) {
  477. static $cacheTransactionTables = array();
  478. $transactionTable = "{$rootTableName}__#TRANSACTION";
  479. if (in_array($transactionTable, $cacheTransactionTables)) return $transactionTable;
  480. DB::getPDO()->exec("
  481. CREATE TABLE IF NOT EXISTS `{$transactionTable}` (
  482. `ID` int(11) NOT NULL AUTO_INCREMENT,
  483. `A_ACTION_ID_USER` int(11) DEFAULT NULL, -- NULL for scripts
  484. `A_ACTION_AUTHOR` varchar(255) NOT NULL DEFAULT '',
  485. `A_ACTION_DATE` timestamp ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  486. `A_STATUS` enum('WAITING', 'NORMAL', 'DELETED') NOT NULL DEFAULT 'WAITING',
  487. `A_CONTEXT_TRANSACTION` varchar(255) NOT NULL DEFAULT '',
  488. PRIMARY KEY (`ID`)
  489. ) ENGINE=MyISAM DEFAULT CHARSET=latin2;
  490. ");
  491. $cacheTransactionTables[] = $transactionTable;
  492. return $transactionTable;
  493. }
  494. public static function startTransaction($rootTableName, $idUser, $author = '') {
  495. $refTable = self::getTransactionTable($rootTableName);
  496. $sqlIdUser = ((int)$idUser > 0) ? DB::getPDO()->quote($idUser, PDO::PARAM_INT) : 'NULL';
  497. $sqlAuthor = DB::getPDO()->quote($author, PDO::PARAM_STR);
  498. DB::getPDO()->exec("
  499. insert into `{$refTable}` (`A_ACTION_ID_USER`, `A_ACTION_AUTHOR`)
  500. values ({$sqlIdUser}, {$sqlAuthor})
  501. ");
  502. return DB::getPDO()->lastInsertId();
  503. }
  504. public static function rollbackTransaction($rootTableName, $idTransaction) {
  505. // TODO: ROLLBACK - do nothing
  506. }
  507. public static function commitTransaction($idTransaction, $simpleSchema_or_acl) {
  508. // TODO: COMMIT
  509. // TODO: save changes to rootTableName and every childrens - recurence
  510. }
  511. public static function commitContextTransaction($rootTableName, $rootIdTransaction, $simpleSchema_or_acl_for_child) {
  512. // TODO: COMMIT - changes for childrens
  513. // TODO: find transaction with context transaction like "{$rootTableName}.{$rootIdTransaction}" = A_CONTEXT_TRANSACTION
  514. // TODO: save changes to rootTableName and every childrens - recurence
  515. }
  516. }