AclReinstall.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. <?php
  2. Lib::loadClass('RouteBase');
  3. Lib::loadClass('Router');
  4. Lib::loadClass('Response');
  5. Lib::loadClass('UI');
  6. Lib::loadClass('SchemaFactory');
  7. Lib::loadClass('RefConfig');
  8. Lib::loadClass('Type_Field');
  9. Lib::loadClass('Schema_SystemObjectFieldStorageAcl');
  10. class Route_Storage_AclReinstall extends RouteBase {
  11. public function handleAuth() {
  12. if (!User::logged()) {
  13. User::authByRequest();
  14. }
  15. }
  16. public function defaultAction() {
  17. UI::gora();
  18. UI::startContainer();
  19. try {
  20. $namespace = V::get('namespace', '', $_GET);
  21. if (empty($namespace)) throw new Exception("Missing param namespace");
  22. echo UI::h('h3', [], $namespace);
  23. echo UI::h('p', [], [
  24. UI::h('a', [
  25. 'href' => Router::getRoute('Storage_AclStruct')->getLink('', [ 'namespace' => $namespace ]),
  26. 'class' => "btn btn-md btn-link",
  27. ], "<i class=\"glyphicon glyphicon-arrow-left\"></i> Wróć do struktury"),
  28. " | ",
  29. UI::h('a', [
  30. 'href' => $this->getLink('viewXsdSource', [ 'namespace' => $namespace ]),
  31. 'class' => "btn btn-md btn-link",
  32. 'target' => "_blank",
  33. ], "Otwórz plik xsd (źródłowy)"),
  34. ]);
  35. if ('reinstall' == V::get('_postTask', '', $_POST)) {
  36. $this->reinstallAcl($namespace);
  37. return;
  38. }
  39. echo UI::hButtonPost("Reinstall", [
  40. 'data' => [
  41. '_postTask' => 'reinstall'
  42. ],
  43. 'class' => 'btn btn-md btn-danger',
  44. 'title' => "Reinstall structure"
  45. ]);
  46. echo '<hr>';
  47. try {
  48. $this->printReinstallPreview($namespace);
  49. } catch (Exception $e) {
  50. DBG::log($e);
  51. UI::alert('danger', $e->getMessage());
  52. }
  53. } catch (Exception $e) {
  54. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  55. DBG::log($e);
  56. }
  57. UI::endContainer();
  58. UI::dol();
  59. }
  60. public function printReinstallPreview($namespace) {
  61. $objectItem = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => "*,field" ]);
  62. DBG::log($objectItem, 'array', '$objectItem preview');
  63. switch ($objectItem['_type']) {
  64. case 'AntAcl': $this->printReinstallAntAclPreview($objectItem); break;
  65. case 'TableAcl': $this->printReinstallTableAclPreview($objectItem); break;
  66. case 'StorageAcl': $this->printReinstallStorageAclPreview($objectItem); break;
  67. default: throw new Exception("TODO: Not Implemented type '{$objectItem['_type']}'");
  68. }
  69. }
  70. public function printReinstallAntAclPreview($item) {
  71. $antAclPath = Schema_SystemObjectFieldStorageAcl::getAntAclXsdBasePath($item['typeName']);
  72. if (!file_exists("{$antAclPath}/build.xml")) throw new Exception("Ant build file not exists " . str_replace(APP_PATH_ROOT, 'SE', $antAclPath));
  73. Lib::loadClass('XML');
  74. $xsdType = XML::getXsdTypeFromXsdSchema("{$antAclPath}/{$item['name']}.xsd", $namespace = $item['namespace'], $name = $item['name']);
  75. DBG::nicePrint($item, '$item');
  76. $sortPrio = 0;
  77. foreach ($xsdType['struct'] as $fieldName => $fieldItem) {
  78. $xsdType['struct'][$fieldName]['sortPrio'] = $sortPrio++;
  79. }
  80. DBG::nicePrint($xsdType, '$xsdType');
  81. // TODO: fix sortPrio for all fields if not set = 0
  82. echo '<hr>';
  83. echo UI::h('h3', [], "Lista zmian:");
  84. echo ($item['primaryKey'] != $xsdType['primaryKey'])
  85. ? UI::h('p', [ 'style' => "" ], "@primaryKey - zmiana z '{$item['primaryKey']}' na '{$xsdType['primaryKey']}'")
  86. : UI::h('p', [ 'style' => "font-style:italic; color:silver" ], "@primaryKey - bez zmian");
  87. if (empty($xsdType['struct'])) throw new Exception("Field list not found for '{$item['namespace']}'");
  88. foreach ($xsdType['struct'] as $fieldName => $x) {
  89. $listEnum = [];
  90. if (!empty($x['restrictions']['enumeration'])) {
  91. $listEnum = $x['restrictions']['enumeration'];
  92. unset($x['restrictions']['enumeration']);
  93. }
  94. if (!empty($listEnum)) {
  95. DBG::log($listEnum, 'array', "\$listEnum for field '{$fieldName}'");
  96. }
  97. }
  98. $old = [
  99. 'fields' => array_map(function ($field) { return $field['fieldNamespace']; }, $item['field']),
  100. ];
  101. $new = [
  102. 'fields' => array_keys($xsdType['struct']),
  103. ];
  104. sort($old['fields']);
  105. sort($new['fields']);
  106. $diffFieldsToCreate = array_diff($new['fields'], $old['fields']);
  107. $diffFieldsToRemove = array_diff($old['fields'], $new['fields']);
  108. $sameFields = array_intersect($new['fields'], $old['fields']);
  109. echo (!empty($diffFieldsToCreate))
  110. ? UI::h('details', [ 'open' => "open" ], [
  111. UI::h('summary', [], "Pola do dodania (".count($diffFieldsToCreate)."):"),
  112. UI::h('ul', [], array_map(function ($fieldName) {
  113. return UI::h('li', [], $fieldName);
  114. }, $diffFieldsToCreate)),
  115. ])
  116. : UI::h('p', [ 'style' => "font-style:italic; color:silver" ], "Brak pól do dodania");
  117. echo (!empty($diffFieldsToRemove))
  118. ? UI::h('details', [ 'open' => "open", 'style' => "margin:4px 0; color:#8a6d3b; background-color:#fcf8e3; border:1px solid #faebcc;" ], [
  119. UI::h('summary', [ 'style' => "padding:4px; outline:none; cursor:pointer" ], "Pola do usunięcia (".count($diffFieldsToRemove)."):"),
  120. UI::h('ul', [], array_map(function ($fieldName) {
  121. return UI::h('li', [], $fieldName);
  122. }, $diffFieldsToRemove)),
  123. ])
  124. : UI::h('p', [ 'style' => "font-style:italic; color:silver" ], "Brak pól do usunięcia");
  125. foreach ($sameFields as $fieldName) {
  126. // UI::alert('warning', "TODO: is field changed? '{$fieldName}'");
  127. $oldField = array_filter($item['field'], function ($field) use ($fieldName) { return ( $fieldName === $field['fieldNamespace'] ); });
  128. $oldField = ($oldField) ? reset($oldField) : null;
  129. // DBG::nicePrint($oldField, "\$oldField '$fieldName'");
  130. $newField = $xsdType['struct'][$fieldName];
  131. // DBG::nicePrint($newField, "\$newField '$fieldName'");
  132. $fieldDiff = [];
  133. if ($newField['type'] !== $oldField['xsdType']) $fieldDiff[] = 'xsdType';
  134. if ($newField['minOccurs'] != $oldField['minOccurs']) $fieldDiff[] = 'minOccurs';
  135. if ($newField['maxOccurs'] != $oldField['maxOccurs']) $fieldDiff[] = 'maxOccurs';
  136. if (json_encode($newField['restrictions']) !== $oldField['xsdRestrictions']) $fieldDiff[] = 'xsdRestrictions';
  137. if (json_encode($newField['appInfo']) !== $oldField['appInfo']) $fieldDiff[] = 'appInfo';
  138. if (RefConfig::isRefField($item['namespace'], $fieldName)) {
  139. $typeNewField = Type_Field::build($newField);
  140. $typeOldField = Type_Field::build($oldField);
  141. if (RefConfig::needUpdate($item['namespace'], $oldField['fieldNamespace'], $typeNewField, $typeOldField)) {
  142. $fieldDiff[] = 'RefConfig';
  143. }
  144. }
  145. echo (!empty($fieldDiff))
  146. ? UI::h('p', [ 'style' => "" ], "Pole '{$fieldName}' - zmiany: " . implode(", ", $fieldDiff))
  147. : UI::h('p', [ 'style' => "font-style:italic; color:silver" ], "Pole '{$fieldName}' - bez zmian");
  148. }
  149. }
  150. public function printReinstallTableAclPreview($item) {
  151. throw new Exception("TODO: Podgląd zmian dla tabeli {$item['namespace']} ...");
  152. }
  153. public function printReinstallStorageAclPreview($item) {
  154. DBG::nicePrint($item, '$item');
  155. $acl = SchemaFactory::loadDefaultObject($item['name']);
  156. DBG::nicePrint($acl, '$acl');
  157. $xsdType = [
  158. 'primaryKey' => $acl->getPrimaryKeyField(),
  159. 'struct' => $acl->getFieldsWithXsdTypes()
  160. ];
  161. DBG::nicePrint($xsdType, '$xsdType');
  162. echo '<hr>';
  163. echo UI::h('h3', [], "Lista zmian:");
  164. echo ($item['primaryKey'] != $xsdType['primaryKey'])
  165. ? UI::h('p', [ 'style' => "" ], "@primaryKey - zmiana z '{$item['primaryKey']}' na '{$xsdType['primaryKey']}'")
  166. : UI::h('p', [ 'style' => "font-style:italic; color:silver" ], "@primaryKey - bez zmian");
  167. if (empty($xsdType['struct'])) throw new Exception("Field list not found for '{$item['namespace']}'");
  168. foreach ($xsdType['struct'] as $fieldName => $x) {
  169. $listEnum = [];
  170. if (!empty($x['restrictions']['enumeration'])) {
  171. $listEnum = $x['restrictions']['enumeration'];
  172. unset($x['restrictions']['enumeration']);
  173. }
  174. if (!empty($listEnum)) {
  175. DBG::log($listEnum, 'array', "\$listEnum for field '{$fieldName}'");
  176. }
  177. }
  178. $old = [
  179. 'fields' => array_map(function ($field) { return $field['fieldNamespace']; }, $item['field']),
  180. ];
  181. $new = [
  182. 'fields' => array_keys($xsdType['struct']),
  183. ];
  184. sort($old['fields']);
  185. sort($new['fields']);
  186. $diffFieldsToCreate = array_diff($new['fields'], $old['fields']);
  187. $diffFieldsToRemove = array_diff($old['fields'], $new['fields']);
  188. $sameFields = array_intersect($new['fields'], $old['fields']);
  189. echo (!empty($diffFieldsToCreate))
  190. ? UI::h('details', [ 'open' => "open" ], [
  191. UI::h('summary', [], "Pola do dodania (".count($diffFieldsToCreate)."):"),
  192. UI::h('ul', [], array_map(function ($fieldName) {
  193. return UI::h('li', [], $fieldName);
  194. }, $diffFieldsToCreate)),
  195. ])
  196. : UI::h('p', [ 'style' => "font-style:italic; color:silver" ], "Brak pól do dodania");
  197. echo (!empty($diffFieldsToRemove))
  198. ? UI::h('details', [ 'open' => "open", 'style' => "margin:4px 0; color:#8a6d3b; background-color:#fcf8e3; border:1px solid #faebcc;" ], [
  199. UI::h('summary', [ 'style' => "padding:4px; outline:none; cursor:pointer" ], "Pola do usunięcia (".count($diffFieldsToRemove)."):"),
  200. UI::h('ul', [], array_map(function ($fieldName) {
  201. return UI::h('li', [], $fieldName);
  202. }, $diffFieldsToRemove)),
  203. ])
  204. : UI::h('p', [ 'style' => "font-style:italic; color:silver" ], "Brak pól do usunięcia");
  205. foreach ($sameFields as $fieldName) {
  206. // UI::alert('warning', "TODO: is field changed? '{$fieldName}'");
  207. $oldField = array_filter($item['field'], function ($field) use ($fieldName) { return ( $fieldName === $field['fieldNamespace'] ); });
  208. $oldField = ($oldField) ? reset($oldField) : null;
  209. // DBG::nicePrint($oldField, "\$oldField '$fieldName'");
  210. $newField = $xsdType['struct'][$fieldName];
  211. // DBG::nicePrint($newField, "\$newField '$fieldName'");
  212. $fieldDiff = [];
  213. if ($newField['type'] !== $oldField['xsdType']) $fieldDiff[] = 'xsdType';
  214. if ($newField['minOccurs'] != $oldField['minOccurs']) $fieldDiff[] = 'minOccurs';
  215. if ($newField['maxOccurs'] != $oldField['maxOccurs']) $fieldDiff[] = 'maxOccurs';
  216. if (json_encode($newField['restrictions']) !== $oldField['xsdRestrictions']) $fieldDiff[] = 'xsdRestrictions';
  217. if (json_encode($newField['appInfo']) !== $oldField['appInfo']) $fieldDiff[] = 'appInfo';
  218. echo (!empty($fieldDiff))
  219. ? UI::h('p', [ 'style' => "" ], "Pole '{$fieldName}' - zmiany: " . implode(", ", $fieldDiff))
  220. : UI::h('p', [ 'style' => "font-style:italic; color:silver" ], "Pole '{$fieldName}' - bez zmian");
  221. }
  222. }
  223. public function viewXsdSourceAction() {
  224. try {
  225. $namespace = V::get('namespace', '', $_GET);
  226. if (empty($namespace)) throw new Exception("Missing param namespace");
  227. $objectItem = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => "*,field" ]);
  228. switch ($objectItem['_type']) {
  229. case 'AntAcl': $this->viewXsdSource($objectItem); break;
  230. // case 'TableAcl': $this->viewXsdSource($objectItem); break;
  231. default: throw new Exception("TODO: Not Implemented type '{$objectItem['_type']}'");
  232. }
  233. } catch (Exception $e) {
  234. DBG::log($e);
  235. echo "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage();
  236. }
  237. }
  238. function viewXsdSource($objectItem) {
  239. if (empty($objectItem)) throw new Exception("Missing objectItem in viewXsdSource");
  240. DBG::log($objectItem, "viewXsdSource \$objectItem");
  241. $antAclPath = Schema_SystemObjectFieldStorageAcl::getAntAclXsdBasePath($objectItem['typeName']);
  242. if (!file_exists("{$antAclPath}/build.xml")) throw new Exception("Ant build file not exists");
  243. DBG::log(str_replace(APP_PATH_ROOT, '~', $antAclPath), "viewXsdSource \$antAclPath");
  244. $xsdFile = "{$antAclPath}/{$objectItem['name']}.xsd";
  245. if (!file_exists($xsdFile)) throw new Exception("Xsd file not exists");
  246. DBG::log(str_replace(APP_PATH_ROOT, '~', $xsdFile), "viewXsdSource \$xsdFile");
  247. header('Content-Type: application/xml; charset=utf-8');
  248. $fd = fopen($xsdFile, 'r');
  249. fpassthru($fd);
  250. exit;
  251. }
  252. function reinstallAcl($namespace) {
  253. try {
  254. $this->_createOrUpdateTableStructure($namespace);
  255. } catch (Exception $e) {
  256. DBG::log($e);
  257. UI::alert('danger', $e->getMessage());
  258. }
  259. $objFieldAcl = new Schema_SystemObjectFieldStorageAcl();
  260. $objFieldAcl->updateCache($namespace);
  261. try {
  262. $dbgInfo = [
  263. 'idInstance' => ACL::getInstanceId($namespace),
  264. // 'rootInstance' => InstanceConfig::getRootNamespace($namespace),
  265. // 'conf' => InstanceConfig::fetchInstanceConfig($namespace),
  266. ];
  267. DBG::nicePrint($dbgInfo, "dbg");
  268. } catch (Exception $e) {
  269. DBG::log($e);
  270. UI::alert('warning', $e->getMessage());
  271. }
  272. $childRefList = RefConfig::getChildRefFullList($namespace);
  273. DBG::nicePrint($childRefList, '$childRefList');
  274. DBG::nicePrint($item, '$item');
  275. $activeFields = array_filter($item['field'], function ($field) {
  276. return ($field['isActive'] > 0);
  277. });
  278. $fieldNsList = array_map(function ($field) {
  279. return $field['fieldNamespace'];
  280. }, $activeFields);
  281. DBG::nicePrint($fieldNsList, '$fieldNsList');
  282. if ('AntAcl' === $item['_type']) { // fix ref config status (turn on/off)
  283. foreach ($childRefList as $refConfig) { // [ namespace, A_STATUS ]
  284. if ($refConfig->status !== 'DELETED' && !in_array($refConfig->childName, $fieldNsList)) {
  285. UI::alert('danger', "remove ref config for '{$refConfig->childName}' ...");
  286. if (!$refConfig->id) throw new Exception("Missing ref config ID");
  287. RefConfig::remove($refConfig);
  288. }
  289. else if ($refConfig->status !== 'DELETED' && in_array($refConfig->childName, $fieldNsList)) {
  290. UI::alert('info', "ref config for '{$refConfig->childName}' active - OK");
  291. }
  292. else if ($refConfig->status === 'DELETED' && in_array($refConfig->childName, $fieldNsList)) {
  293. UI::alert('warning', "activate ref config for '{$refConfig->childName}' ...");
  294. if (!$refConfig->id) throw new Exception("Missing ref config ID");
  295. RefConfig::reactivate($refConfig);
  296. }
  297. else if ($refConfig->status === 'DELETED' && !in_array($refConfig->childName, $fieldNsList)) {
  298. UI::alert('info', "ref config for '{$refConfig->childName}' removed - OK");
  299. }
  300. else {
  301. UI::alert('danger', "Not implemented action for '{$refConfig->childName}'");
  302. }
  303. }
  304. // TODO: create missing refConfig - field is not in $childRefList
  305. }
  306. if ('AntAcl' === $item['_type']) { // fix ref tables by appInfo
  307. $activeRefFields = array_filter($item['field'], function ($field) {
  308. return ($field['isActive'] && 'ref:' === substr($field['xsdType'], 0, 4));
  309. });
  310. DBG::log($activeRefFields, 'array', "DBG \$activeRefFields");
  311. foreach ($activeRefFields as $field) {
  312. $typeNewField = Type_Field::build($field);
  313. // if (RefConfig::needUpdate($item['namespace'], $oldField['fieldNamespace'], $typeNewField, $typeOldField))
  314. try {
  315. RefConfig::update($item['namespace'], $field['fieldNamespace'], $typeNewField);
  316. } catch (Exception $e) {
  317. // TODO: deactivate RefConfig if error
  318. DBG::log($e);
  319. UI::alert('danger', $e->getMessage());
  320. }
  321. }
  322. }
  323. { // TODO: RMME? function is too slow for join query
  324. if ('AntAcl' === $item['_type']) {
  325. $idInstance = ACL::getInstanceId($namespace);
  326. $dbName = DB::getPDO()->getDatabaseName();
  327. DB::getPDO()->execSql(" DROP FUNCTION IF EXISTS `{$dbName}`.`isInstance_{$idInstance}` ");
  328. }
  329. }
  330. { // TODO: mv to updateCache
  331. if ('AntAcl' === $item['_type']) {
  332. $instConf = InstanceConfig::getInstanceConfig($namespace);
  333. InstanceConfig::createInstanceTable($instConf, $item); // force create instance table event if A_STATUS is NORMAL
  334. }
  335. }
  336. }
  337. function _createOrUpdateTableStructure($namespace) {
  338. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  339. DBG::log($item, 'array', 'DBG:_createOrUpdateTableStructure:$item');
  340. $currentStruct = [];
  341. try {
  342. $currentStruct = DB::getStorage($item['idDatabase'])->getTableStruct($item['_rootTableName']);
  343. } catch (Exception $e) {
  344. DBG::log($e);
  345. }
  346. DBG::log($currentStruct, 'array', 'DBG:_createOrUpdateTableStructure:$currentStruct');
  347. if (DB::getPDO()->getZasobId() != $item['idDatabase']) throw new Exception("Not imeplemented Create/Update table structure in non default database");
  348. if (empty($currentStruct)) $this->_createTableStructure($item);
  349. else $this->_updateTableStructure($item, $currentStruct);
  350. }
  351. // $item['idDatabase'] => int idDatabase
  352. // $item['_rootTableName'] => string tableName
  353. // $item['primaryKey'] => string primaryKey fieldName
  354. // $item['field'] => []
  355. // $item['field']['fieldNamespace'] => fieldName,
  356. // $item['field']['xsdRestrictions'] => [] // TODO: handle restrictions like maxLength, etc.
  357. // $item['field']['xsdType'] `select distinct xsdType from `CRM_#CACHE_ACL_OBJECT_FIELD` where xsdType not like 'ref:%'`: [
  358. // default_db__x3A__BADANIA_W_TERENIE:A_STATUS_Type
  359. // default_db__x3A__CRM_PROCES:TYPE_Simple
  360. // gml:AbstractFeatureType
  361. // gml:PolygonPropertyType
  362. // p5:enum
  363. // p5:price
  364. // p5:www_link
  365. // p5Type:date
  366. // p5Type:dateTime
  367. // p5Type:decimal
  368. // p5Type:integer
  369. // p5Type:lineString
  370. // p5Type:point
  371. // p5Type:polygon
  372. // p5Type:string
  373. // p5Type:text
  374. // xsd:date
  375. // xsd:dateTime
  376. // xsd:decimal
  377. // xsd:double
  378. // xsd:float
  379. // xsd:gYear
  380. // xsd:hexBinary
  381. // xsd:int
  382. // xsd:integer
  383. // xsd:long
  384. // xsd:positiveInteger
  385. // xsd:short
  386. // xsd:string
  387. // xsd:time
  388. // xsd:token
  389. // ]
  390. function _createTableStructure($item) {
  391. $expectedStruct = $this->_makeTableStructure($item);
  392. DB::getStorage($item['idDatabase'])->createTableStructure([
  393. 'tableName' => $item['_rootTableName'],
  394. 'fields' => $expectedStruct,
  395. 'primaryKey' => $item['primaryKey'],
  396. 'keys' => [],
  397. ]);
  398. }
  399. function _updateTableStructure($item, $currentStruct) {
  400. DBG::log($item, 'array', "DBG:update table struct:\$item");
  401. DBG::log($currentStruct, 'array', "DBG:update table struct:\$currentStruct");
  402. $expectedStruct = $this->_makeTableStructure($item);
  403. DBG::log($expectedStruct, 'array', "DBG:update table struct:\$expectedStruct");
  404. // $expectedStruct: [ fieldName => shortStruct ]
  405. // shortStruct:
  406. // 'name' => 'ID',
  407. // 'raw_storage_type' => 'int(11)',
  408. // 'extra' => 'auto_increment',
  409. // $currentStruct: [ fieldName => fullStruct ]
  410. // fullStruct:
  411. // 'name' => 'ID',
  412. // 'type' => 'int',
  413. // 'is_nullable' => '0',
  414. // 'default_value' => NULL,
  415. // 'default_is_null' => '1',
  416. // 'max_length' => NULL,
  417. // 'num_precision' => '10',
  418. // 'num_scale' => '0',
  419. // 'char_encoding' => NULL,
  420. // 'char_collation' => NULL,
  421. // 'extra' => 'auto_increment',
  422. // 'raw_storage_type' => 'int(11)',
  423. $expectedFieldList = array_keys($expectedStruct);
  424. $currentFieldList = array_keys($currentStruct);
  425. // array_diff([ 'a', 'b', 'c' ], [ 'b', 'c', 'd' ]) => [ 'a' ]
  426. // array_diff([ 'b', 'c', 'd' ], [ 'a', 'b', 'c' ]) => [ 'd' ]
  427. // $toRemoveFieldFromStruct = array_diff($currentFieldList, $expectedFieldList); // TODO: not used, fields defined in base object
  428. $toAddFieldToStruct = array_diff($expectedFieldList, $currentFieldList);
  429. DBG::log($toRemoveFieldFromStruct, 'array', "DBG:update table struct:\$toRemoveFieldFromStruct");
  430. DBG::log($toAddFieldToStruct, 'array', "DBG:update table struct:\$toAddFieldToStruct");
  431. if (!empty($toAddFieldToStruct)) {
  432. $rootTableName = $item['_rootTableName'];
  433. array_map(function ($fieldName) use ($rootTableName, $expectedStruct) {
  434. $expectedField = $expectedStruct[$fieldName];
  435. $sqlNotNull = ""; // TODO: "NOT NULL" if field can not be null
  436. $sqlDefault = ""; // TODO: "DEFAULT {$value}"
  437. DB::getPDO()->execSql(" ALTER TABLE {$rootTableName} ADD {$fieldName} {$expectedField['raw_storage_type']} {$sqlNotNull} {$sqlDefault}");
  438. }, $toAddFieldToStruct);
  439. }
  440. $maybeToUpdateFields = array_intersect($currentFieldList, $expectedFieldList);
  441. DBG::log($maybeToUpdateFields, 'array', "DBG:update table struct:\$maybeToUpdateFields");
  442. if (empty($maybeToUpdateFields)) {
  443. UI::alert('info', "No fields to compare");
  444. return;
  445. }
  446. $diffNotes = array_map(function ($fieldName) use ($currentStruct, $expectedStruct) {
  447. $currentField = $currentStruct[$fieldName];
  448. $expectedField = $expectedStruct[$fieldName];
  449. return [
  450. 'fieldName' => $fieldName,
  451. 'current_raw_type' => $currentField['raw_storage_type'],
  452. 'expected_raw_type' => $expectedField['raw_storage_type'],
  453. 'diff' => ($currentField['raw_storage_type'] === $expectedField['raw_storage_type']) ? "same" : "diff",
  454. ];
  455. }, $maybeToUpdateFields);
  456. UI::table([ 'caption' => "Fields types diff:", 'rows' => $diffNotes ]);
  457. $diffFields = array_filter($diffNotes, function ($item) { return ("diff" === $item['diff']); });
  458. if (empty($diffFields)) {
  459. UI::alert('info', "Struct is ok");
  460. return;
  461. }
  462. DBG::log($diffFields, 'array', "TODO: update table struct by \$diffFields");
  463. throw new Exception("TODO: Not imeplemented Update table structure (Update existing fields)");
  464. }
  465. function _makeTableStructure($item) {
  466. $tryConvertFields = array_map([ $this, '_makeFieldStructure' ], $item['field']);
  467. DBG::log($tryConvertFields, 'array', "DBG:make table struct:\$tryConvertFields");
  468. $toCreateFields = array_filter($tryConvertFields, function ($fieldInfo) { return null !== $fieldInfo; });
  469. DBG::log($toCreateFields, 'array', "DBG:make table struct:\$toCreateFields");
  470. $tblStruct = array_combine(
  471. array_map(V::makePick('name'), $toCreateFields),
  472. array_values($toCreateFields)
  473. );
  474. DBG::log($tblStruct, 'array', "DBG:make table struct:\$tblStruct");
  475. if (!array_key_exists($item['primaryKey'], $tblStruct)) throw new Exception("BUG: primaryKey field definition not exists");
  476. $tblStruct[$item['primaryKey']]['extra'] = "auto_increment";
  477. return $tblStruct;
  478. }
  479. function _makeFieldStructure($fieldInfo) {
  480. // select distinct xsdType from `CRM_#CACHE_ACL_OBJECT_FIELD` where xsdType not like 'ref:%' order by xsdType;
  481. if ('ref:' === substr($fieldInfo['xsdType'], 0, 4)) {
  482. DBG::log("Skipped create ref field '{$fieldInfo['xsdType']}'");
  483. return null;
  484. }
  485. $fieldName = $fieldInfo['fieldNamespace'];
  486. if (!preg_match('/^[a-z_]+$/i', $fieldName)) {
  487. DBG::log("Skipped create: not allowed field name '{$fieldName}'");
  488. return null;
  489. }
  490. switch ($fieldInfo['xsdType']) {
  491. // number
  492. case 'xsd:integer':
  493. case 'p5Type:integer':
  494. case 'xsd:int': return [ 'name' => $fieldInfo['fieldNamespace'], 'raw_storage_type' => "int(11)" ];
  495. case 'xsd:positiveInteger': return [ 'name' => $fieldInfo['fieldNamespace'], 'raw_storage_type' => "int(11) unsigned" ];
  496. case 'xsd:short': return [ 'name' => $fieldInfo['fieldNamespace'], 'raw_storage_type' => "int(11)" ];
  497. case 'xsd:long': return [ 'name' => $fieldInfo['fieldNamespace'], 'raw_storage_type' => "int(11)" ];
  498. case 'xsd:float': return [ 'name' => $fieldInfo['fieldNamespace'], 'raw_storage_type' => "float" ];
  499. case 'xsd:double': return [ 'name' => $fieldInfo['fieldNamespace'], 'raw_storage_type' => "double" ];
  500. case 'xsd:decimal': return [ 'name' => $fieldInfo['fieldNamespace'], 'raw_storage_type' => "decimal(12,2)" ];
  501. case 'p5Type:decimal':
  502. case 'p5:price': return [ 'name' => $fieldInfo['fieldNamespace'], 'raw_storage_type' => "decimal(12,2)" ];
  503. // time
  504. case 'p5Type:date':
  505. case 'xsd:date': return [ 'name' => $fieldInfo['fieldNamespace'], 'raw_storage_type' => "date" ];
  506. case 'p5Type:dateTime':
  507. case 'xsd:dateTime': return [ 'name' => $fieldInfo['fieldNamespace'], 'raw_storage_type' => "datetime" ];
  508. case 'xsd:time': return [ 'name' => $fieldInfo['fieldNamespace'], 'raw_storage_type' => "time" ];
  509. // string
  510. case 'xsd:string':
  511. case 'p5Type:string': return [ 'name' => $fieldInfo['fieldNamespace'], 'raw_storage_type' => "varchar(255)" ];
  512. case 'xsd:token': return [ 'name' => $fieldInfo['fieldNamespace'], 'raw_storage_type' => "varchar(255)" ];
  513. case 'p5Type:text': return [ 'name' => $fieldInfo['fieldNamespace'], 'raw_storage_type' => "text" ];
  514. // geom
  515. case 'p5Type:polygon': return [ 'name' => $fieldInfo['fieldNamespace'], 'raw_storage_type' => "polygon", 'default' => "NULL" ];
  516. case 'p5Type:lineString': return [ 'name' => $fieldInfo['fieldNamespace'], 'raw_storage_type' => "linestring", 'default' => "NULL" ];
  517. case 'p5Type:point': return [ 'name' => $fieldInfo['fieldNamespace'], 'raw_storage_type' => "point", 'default' => "NULL" ];
  518. case 'gml:AbstractFeatureType': return [ 'name' => $fieldInfo['fieldNamespace'], 'raw_storage_type' => "polygon", 'default' => "NULL" ];
  519. // TODO: ???: 'gml:PolygonPropertyType'
  520. case 'p5:enum': {
  521. // [A_STATUS] => Array:
  522. // [type] => p5:enum
  523. // [minOccurs] => 0
  524. // [maxOccurs] => 1
  525. // [restrictions] => Array:
  526. // [enumeration] => Array:
  527. // [NORMAL] => NORMAL
  528. // [WAITING] => WAITING
  529. // [MONITOR] => MONITOR
  530. // [DELETED] => DELETED
  531. // [WARNING] => WARNING
  532. // [OFF_SOFT] => OFF_SOFT
  533. // [OFF_HARD] => OFF_HARD
  534. $xsdRestrictions = Schema_SystemObjectFieldStorageAcl::getXsdRestrictionsValue($fieldInfo);
  535. DBG::log($xsdRestrictions, 'array', "DBG: p5:enum xsdRestrictions for field('{$fieldInfo['fieldNamespace']}')");
  536. return [ 'name' => $fieldInfo['fieldNamespace'], 'raw_storage_type' => "enum(" .
  537. implode(",", array_map(function ($value) { return "'{$value}'"; }, array_keys($xsdRestrictions['enumeration']))) .
  538. ")" ];
  539. }
  540. // TODO: implement more xsd types:
  541. // case 'default_db__x3A__BADANIA_W_TERENIE:A_STATUS_Type':
  542. // case 'default_db__x3A__CRM_PROCES:TYPE_Simple':
  543. // case 'p5:www_link':
  544. // case 'xsd:gYear':
  545. // case 'xsd:hexBinary':
  546. default: {
  547. DBG::log($fieldInfo, 'array', "TODO: _makeFieldStructure '{$fieldInfo['xsdType']}' (SystemObject/fieldInfo)"); // $fieldInfo = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ])['field'];
  548. throw new Exception("Not implemented type '{$fieldInfo['xsdType']}'");
  549. }
  550. }
  551. }
  552. }