AclHelper.php 26 KB

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