AclHelper.php 26 KB

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