tabularbulkexport.class.inc.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. <?php
  2. // Copyright (C) 2015 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Bulk export: Tabular export: abstract base class for all "tabular" exports.
  20. * Provides the user interface for selecting the column to be exported
  21. *
  22. * @copyright Copyright (C) 2015 Combodo SARL
  23. * @license http://opensource.org/licenses/AGPL-3.0
  24. */
  25. abstract class TabularBulkExport extends BulkExport
  26. {
  27. public function EnumFormParts()
  28. {
  29. return array_merge(parent::EnumFormParts(), array('tabular_fields' => array('fields')));
  30. }
  31. public function DisplayFormPart(WebPage $oP, $sPartId)
  32. {
  33. switch($sPartId)
  34. {
  35. case 'tabular_fields':
  36. $sFields = utils::ReadParam('fields', '', true, 'raw_data');
  37. $sSuggestedFields = utils::ReadParam('suggested_fields', null, true, 'raw_data');
  38. if (($sSuggestedFields !== null) && ($sSuggestedFields !== ''))
  39. {
  40. $aSuggestedFields = explode(',', $sSuggestedFields);
  41. $sFields = implode(',', $this->SuggestFields($aSuggestedFields));
  42. }
  43. $oP->add('<input id="tabular_fields" type="hidden" size="50" name="fields" value="'.htmlentities($sFields, ENT_QUOTES, 'UTF-8').'"></input>');
  44. break;
  45. default:
  46. return parent::DisplayFormPart($oP, $sPartId);
  47. }
  48. }
  49. protected function SuggestFields($aSuggestedFields)
  50. {
  51. $aRet = array();
  52. // By defaults all fields are Ok, nothing gets translated but
  53. // you can overload this method if some fields are better exported
  54. // (in a given format) by using an alternate field, for example id => friendlyname
  55. $aAliases = $this->oSearch->GetSelectedClasses();
  56. foreach($aSuggestedFields as $idx => $sField)
  57. {
  58. if (preg_match('/^([^\\.]+)\\.(.+)$/', $sField, $aMatches))
  59. {
  60. $sAlias = $aMatches[1];
  61. $sAttCode = $aMatches[2];
  62. $sClass = $aAliases[$sAlias];
  63. }
  64. else
  65. {
  66. $sAlias = '';
  67. $sAttCode = $sField;
  68. $sClass = reset($aAliases);
  69. }
  70. $sMostRelevantField = $this->SuggestField($sClass, $sAttCode);
  71. $sAttCodeEx = MetaModel::NormalizeFieldSpec($sClass, $sMostRelevantField);
  72. // Remove the aliases (if any) from the field names to make them compatible
  73. // with the 'short' notation used in this case by the widget
  74. if (count($aAliases) > 1)
  75. {
  76. $sAttCodeEx = $sAlias.'.'.$sAttCodeEx;
  77. }
  78. $aRet[] = $sAttCodeEx;
  79. }
  80. return $aRet;
  81. }
  82. protected function SuggestField($sClass, $sAttCode)
  83. {
  84. return $sAttCode;
  85. }
  86. protected function IsSubAttribute($sClass, $sAttCode, $oAttDef)
  87. {
  88. return (($oAttDef instanceof AttributeFriendlyName) || ($oAttDef instanceof AttributeExternalField) || ($oAttDef instanceof AttributeSubItem));
  89. }
  90. protected function GetSubAttributes($sClass, $sAttCode, $oAttDef)
  91. {
  92. $aResult = array();
  93. switch(get_class($oAttDef))
  94. {
  95. case 'AttributeExternalKey':
  96. case 'AttributeHierarchicalKey':
  97. $bAddFriendlyName = true;
  98. $oKeyAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  99. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  100. $sFriendlyNameAttCode = MetaModel::GetFriendlyNameAttributeCode($sRemoteClass);
  101. if (!is_null($sFriendlyNameAttCode))
  102. {
  103. // The friendly name is made of a single attribute, check if that attribute is present as an external field
  104. foreach(MetaModel::ListAttributeDefs($sClass) as $sSubAttCode => $oSubAttDef)
  105. {
  106. if ($oSubAttDef instanceof AttributeExternalField)
  107. {
  108. if (($oSubAttDef->GetKeyAttCode() == $sAttCode) && ($oSubAttDef->GetExtAttCode() == $sFriendlyNameAttCode))
  109. {
  110. $bAddFriendlyName = false;
  111. }
  112. }
  113. }
  114. }
  115. $aResult[$sAttCode] = array('code' => $sAttCode, 'unique_label' => $oAttDef->GetLabel(), 'label' => Dict::S('UI:CSVImport:idField'), 'attdef' => $oAttDef);
  116. if ($bAddFriendlyName)
  117. {
  118. if ($this->IsExportableField($sClass, $sAttCode.'->friendlyname'))
  119. {
  120. $aResult[$sAttCode.'->friendlyname'] = array('code' => $sAttCode.'->friendlyname', 'unique_label' => $oAttDef->GetLabel().'->'.Dict::S('Core:FriendlyName-Label'), 'label' => Dict::S('Core:FriendlyName-Label'), 'attdef' => MetaModel::GetAttributeDef($sClass, $sAttCode.'_friendlyname'));
  121. }
  122. }
  123. foreach(MetaModel::ListAttributeDefs($sClass) as $sSubAttCode => $oSubAttDef)
  124. {
  125. if ($oSubAttDef instanceof AttributeExternalField)
  126. {
  127. if ($this->IsExportableField($sClass, $sSubAttCode, $oSubAttDef))
  128. {
  129. if ($oSubAttDef->GetKeyAttCode() == $sAttCode)
  130. {
  131. $sAttCodeEx = $sAttCode.'->'.$oSubAttDef->GetExtAttCode();
  132. $aResult[$sAttCodeEx] = array('code' => $sAttCodeEx, 'unique_label' => $oAttDef->GetLabel().'->'.$oSubAttDef->GetExtAttDef()->GetLabel(), 'label' => MetaModel::GetLabel($sRemoteClass, $oSubAttDef->GetExtAttCode()), 'attdef' => $oSubAttDef);
  133. }
  134. }
  135. }
  136. }
  137. // Add the reconciliation keys
  138. foreach(MetaModel::GetReconcKeys($sRemoteClass) as $sRemoteAttCode)
  139. {
  140. $sAttCodeEx = $sAttCode.'->'.$sRemoteAttCode;
  141. if (!array_key_exists($sAttCodeEx, $aResult))
  142. {
  143. $oRemoteAttDef = MetaModel::GetAttributeDef($sRemoteClass, $sRemoteAttCode);
  144. if ($this->IsExportableField($sRemoteClass, $sRemoteAttCode, $oRemoteAttDef))
  145. {
  146. $aResult[$sAttCodeEx] = array('code' => $sAttCodeEx, 'unique_label' => $oAttDef->GetLabel().'->'.$oRemoteAttDef->GetLabel(), 'label' => MetaModel::GetLabel($sRemoteClass, $sRemoteAttCode), 'attdef' => $oRemoteAttDef);
  147. }
  148. }
  149. }
  150. break;
  151. case 'AttributeStopWatch':
  152. foreach(MetaModel::ListAttributeDefs($sClass) as $sSubAttCode => $oSubAttDef)
  153. {
  154. if ($oSubAttDef instanceof AttributeSubItem)
  155. {
  156. if ($oSubAttDef->GetParentAttCode() == $sAttCode)
  157. {
  158. if ($this->IsExportableField($sClass, $sSubAttCode, $oSubAttDef))
  159. {
  160. $aResult[$sSubAttCode] = array('code' => $sSubAttCode, 'unique_label' => $oSubAttDef->GetLabel(), 'label' => $oSubAttDef->GetLabel(), 'attdef' => $oSubAttDef);
  161. }
  162. }
  163. }
  164. }
  165. break;
  166. }
  167. return $aResult;
  168. }
  169. protected function GetInteractiveFieldsWidget(WebPage $oP, $sWidgetId)
  170. {
  171. $oSet = new DBObjectSet($this->oSearch);
  172. $aSelectedClasses = $this->oSearch->GetSelectedClasses();
  173. $aAuthorizedClasses = array();
  174. foreach($aSelectedClasses as $sAlias => $sClassName)
  175. {
  176. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_BULK_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  177. {
  178. $aAuthorizedClasses[$sAlias] = $sClassName;
  179. }
  180. }
  181. $aAllFieldsByAlias = array();
  182. $aAllAttCodes = array();
  183. foreach($aAuthorizedClasses as $sAlias => $sClass)
  184. {
  185. $aAllFields = array();
  186. if (count($aAuthorizedClasses) > 1 )
  187. {
  188. $sShortAlias = $sAlias.'.';
  189. }
  190. else
  191. {
  192. $sShortAlias = '';
  193. }
  194. if ($this->IsExportableField($sClass, 'id'))
  195. {
  196. $sFriendlyNameAttCode = MetaModel::GetFriendlyNameAttributeCode($sClass);
  197. if (is_null($sFriendlyNameAttCode))
  198. {
  199. // The friendly name is made of several attribute
  200. $aSubAttr = array(
  201. array('attcodeex' => 'id', 'code' => $sShortAlias.'id', 'unique_label' => $sShortAlias.Dict::S('UI:CSVImport:idField'), 'label' => $sShortAlias.'id'),
  202. array('attcodeex' => 'friendlyname', 'code' => $sShortAlias.'friendlyname', 'unique_label' => $sShortAlias.Dict::S('Core:FriendlyName-Label'), 'label' => $sShortAlias.Dict::S('Core:FriendlyName-Label')),
  203. );
  204. }
  205. else
  206. {
  207. // The friendly name has no added value
  208. $aSubAttr = array();
  209. }
  210. $aAllFields[] = array('attcodeex' => 'id', 'code' => $sShortAlias.'id', 'unique_label' => $sShortAlias.Dict::S('UI:CSVImport:idField'), 'label' => Dict::S('UI:CSVImport:idField'), 'subattr' => $aSubAttr);
  211. }
  212. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  213. {
  214. if($this->IsSubAttribute($sClass, $sAttCode, $oAttDef)) continue;
  215. if ($this->IsExportableField($sClass, $sAttCode, $oAttDef))
  216. {
  217. $sShortLabel = $oAttDef->GetLabel();
  218. $sLabel = $sShortAlias.$oAttDef->GetLabel();
  219. $aSubAttr = $this->GetSubAttributes($sClass, $sAttCode, $oAttDef);
  220. $aValidSubAttr = array();
  221. foreach($aSubAttr as $aSubAttDef)
  222. {
  223. $aValidSubAttr[] = array('attcodeex' => $aSubAttDef['code'], 'code' => $sShortAlias.$aSubAttDef['code'], 'label' => $aSubAttDef['label'], 'unique_label' => $sShortAlias.$aSubAttDef['unique_label']);
  224. }
  225. $aAllFields[] = array('attcodeex' => $sAttCode, 'code' => $sShortAlias.$sAttCode, 'label' => $sShortLabel, 'unique_label' => $sLabel, 'subattr' => $aValidSubAttr);
  226. }
  227. }
  228. usort($aAllFields, array(get_class($this), 'SortOnLabel'));
  229. if (count($aAuthorizedClasses) > 1)
  230. {
  231. $sKey = MetaModel::GetName($sClass).' ('.$sAlias.')';
  232. }
  233. else
  234. {
  235. $sKey = MetaModel::GetName($sClass);
  236. }
  237. $aAllFieldsByAlias[$sKey] = $aAllFields;
  238. foreach ($aAllFields as $aFieldSpec)
  239. {
  240. $sAttCode = $aFieldSpec['attcodeex'];
  241. if (count($aFieldSpec['subattr']) > 0)
  242. {
  243. foreach ($aFieldSpec['subattr'] as $aSubFieldSpec)
  244. {
  245. $aAllAttCodes[$sAlias][] = $aSubFieldSpec['attcodeex'];
  246. }
  247. }
  248. else
  249. {
  250. $aAllAttCodes[$sAlias][] = $sAttCode;
  251. }
  252. }
  253. }
  254. $oP->add('<div id="'.$sWidgetId.'"></div>');
  255. $JSAllFields = json_encode($aAllFieldsByAlias);
  256. // First, fetch only the ids - the rest will be fetched by an object reload
  257. $oSet = new DBObjectSet($this->oSearch);
  258. $iCount = $oSet->Count();
  259. foreach ($this->oSearch->GetSelectedClasses() as $sAlias => $sClass)
  260. {
  261. $aColumns[$sAlias] = array();
  262. }
  263. $oSet->OptimizeColumnLoad($aColumns);
  264. $iPreviewLimit = 3;
  265. $oSet->SetLimit($iPreviewLimit);
  266. $aSampleData = array();
  267. while($aRow = $oSet->FetchAssoc())
  268. {
  269. $aSampleRow = array();
  270. foreach($aAuthorizedClasses as $sAlias => $sClass)
  271. {
  272. if (count($aAuthorizedClasses) > 1 )
  273. {
  274. $sShortAlias = $sAlias.'.';
  275. }
  276. else
  277. {
  278. $sShortAlias = '';
  279. }
  280. foreach ($aAllAttCodes[$sAlias] as $sAttCodeEx)
  281. {
  282. $oObj = $aRow[$sAlias];
  283. $aSampleRow[$sShortAlias.$sAttCodeEx] = $oObj ? $this->GetSampleData($oObj, $sAttCodeEx) : '';
  284. }
  285. }
  286. $aSampleData[] = $aSampleRow;
  287. }
  288. $sJSSampleData = json_encode($aSampleData);
  289. $aLabels = array(
  290. 'preview_header' => Dict::S('Core:BulkExport:DragAndDropHelp'),
  291. 'empty_preview' => Dict::S('Core:BulkExport:EmptyPreview'),
  292. 'columns_order' => Dict::S('Core:BulkExport:ColumnsOrder'),
  293. 'columns_selection' => Dict::S('Core:BulkExport:AvailableColumnsFrom_Class'),
  294. 'check_all' => Dict::S('Core:BulkExport:CheckAll'),
  295. 'uncheck_all' => Dict::S('Core:BulkExport:UncheckAll'),
  296. 'no_field_selected' => Dict::S('Core:BulkExport:NoFieldSelected'),
  297. );
  298. $sJSLabels = json_encode($aLabels);
  299. $oP->add_ready_script(
  300. <<<EOF
  301. $('#$sWidgetId').tabularfieldsselector({fields: $JSAllFields, value_holder: '#tabular_fields', advanced_holder: '#tabular_advanced', sample_data: $sJSSampleData, total_count: $iCount, preview_limit: $iPreviewLimit, labels: $sJSLabels });
  302. EOF
  303. );
  304. }
  305. static public function SortOnLabel($aItem1, $aItem2)
  306. {
  307. return strcmp($aItem1['label'], $aItem2['label']);
  308. }
  309. /**
  310. * Tells if the specified field can be exported
  311. * @param unknown $sClass
  312. * @param unknown $sAttCode
  313. * @param AttributeDefinition $oAttDef Can be null in case the attribute definition has not been fetched by the caller
  314. * @return boolean
  315. */
  316. protected function IsExportableField($sClass, $sAttCode, $oAttDef = null)
  317. {
  318. if ($sAttCode == 'id') return true;
  319. if (is_null($oAttDef))
  320. {
  321. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  322. }
  323. if ($oAttDef instanceof AttributeLinkedSet) return false;
  324. return true; //$oAttDef->IsScalar();
  325. }
  326. protected function GetSampleData($oObj, $sAttCode)
  327. {
  328. if ($sAttCode == 'id') return $oObj->GetKey();
  329. return $oObj->GetEditValue($sAttCode);
  330. }
  331. public function ReadParameters()
  332. {
  333. parent::ReadParameters();
  334. $sQueryId = utils::ReadParam('query', null, true);
  335. $sFields = utils::ReadParam('fields', null, true, 'raw_data');
  336. if ((($sFields === null) || ($sFields === '')) && ($sQueryId === null))
  337. {
  338. throw new BulkExportMissingParameterException('fields');
  339. }
  340. else if(($sQueryId !== null) && ($sQueryId !== null))
  341. {
  342. $oSearch = DBObjectSearch::FromOQL('SELECT QueryOQL WHERE id = :query_id', array('query_id' => $sQueryId));
  343. $oQueries = new DBObjectSet($oSearch);
  344. if ($oQueries->Count() > 0)
  345. {
  346. $oQuery = $oQueries->Fetch();
  347. if (($sFields === null) || ($sFields === ''))
  348. {
  349. // No 'fields' parameter supplied, take the fields from the query phrasebook definition
  350. $sFields = trim($oQuery->Get('fields'));
  351. if ($sFields === '')
  352. {
  353. throw new BulkExportMissingParameterException('fields');
  354. }
  355. }
  356. }
  357. else
  358. {
  359. throw BulkExportException('Invalid value for the parameter: query. There is no Query Phrasebook with id = '.$sQueryId, Dict::Format('Core:BulkExport:InvalidParameter_Query', $sQueryId));
  360. }
  361. }
  362. // Interpret (and check) the list of fields
  363. //
  364. $aSelectedClasses = $this->oSearch->GetSelectedClasses();
  365. $aAliases = array_keys($aSelectedClasses);
  366. $aAuthorizedClasses = array();
  367. foreach($aSelectedClasses as $sAlias => $sClassName)
  368. {
  369. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_BULK_READ) == UR_ALLOWED_YES)
  370. {
  371. $aAuthorizedClasses[$sAlias] = $sClassName;
  372. }
  373. }
  374. $aFields = explode(',', $sFields);
  375. $this->aStatusInfo['fields'] = array();
  376. foreach($aFields as $sFieldSpec)
  377. {
  378. // Trim the values since it's natural to write: fields=name, first_name, org_name instead of fields=name,first_name,org_name
  379. $sExtendedAttCode = trim($sFieldSpec);
  380. if (preg_match('/^([^\.]+)\.(.+)$/', $sExtendedAttCode, $aMatches))
  381. {
  382. $sAlias = $aMatches[1];
  383. $sAttCode = $aMatches[2];
  384. }
  385. else
  386. {
  387. $sAlias = reset($aAliases);
  388. $sAttCode = $sExtendedAttCode;
  389. }
  390. if (!array_key_exists($sAlias, $aSelectedClasses))
  391. {
  392. throw new Exception("Invalid alias '$sAlias' for the column '$sExtendedAttCode'. Availables aliases: '".implode("', '", $aAliases)."'");
  393. }
  394. $sClass = $aSelectedClasses[$sAlias];
  395. if (!array_key_exists($sAlias, $aAuthorizedClasses))
  396. {
  397. throw new Exception("You do not have enough permissions to bulk read data of class '$sClass' (alias: $sAlias)");
  398. }
  399. if ($this->bLocalizeOutput)
  400. {
  401. try
  402. {
  403. $sLabel = MetaModel::GetLabel($sClass, $sAttCode);
  404. }
  405. catch (Exception $e)
  406. {
  407. throw new Exception("Wrong field specification '$sFieldSpec': ".$e->getMessage());
  408. }
  409. }
  410. else
  411. {
  412. $sLabel = $sAttCode;
  413. }
  414. if (count($aAuthorizedClasses) > 1)
  415. {
  416. $sColLabel = $sAlias.'.'.$sLabel;
  417. }
  418. else
  419. {
  420. $sColLabel = $sLabel;
  421. }
  422. $this->aStatusInfo['fields'][] = array(
  423. 'sFieldSpec' => $sExtendedAttCode,
  424. 'sAlias' => $sAlias,
  425. 'sClass' => $sClass,
  426. 'sAttCode' => $sAttCode,
  427. 'sLabel' => $sLabel,
  428. 'sColLabel' => $sColLabel
  429. );
  430. }
  431. }
  432. /**
  433. * Prepare the given object set with the list of fields as read into $this->aStatusInfo['fields']
  434. */
  435. protected function OptimizeColumnLoad(DBObjectSet $oSet)
  436. {
  437. $aColumnsToLoad = array();
  438. foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
  439. {
  440. $sClass = $aFieldSpec['sClass'];
  441. $sAlias = $aFieldSpec['sAlias'];
  442. $sAttCode = $aFieldSpec['sAttCode'];
  443. if (!array_key_exists($sAlias, $aColumnsToLoad))
  444. {
  445. $aColumnsToLoad[$sAlias] = array();
  446. }
  447. // id is not a real attribute code and, moreover, is always loaded
  448. if ($sAttCode != 'id')
  449. {
  450. // Extended attributes are not recognized by DBObjectSet::OptimizeColumnLoad
  451. if (($iPos = strpos($sAttCode, '->')) === false)
  452. {
  453. $aColumnsToLoad[$sAlias][] = $sAttCode;
  454. $sClass = '???';
  455. }
  456. else
  457. {
  458. $sExtKeyAttCode = substr($sAttCode, 0, $iPos);
  459. $sRemoteAttCode = substr($sAttCode, $iPos + 2);
  460. // Load the external key to avoid an object reload!
  461. $aColumnsToLoad[$sAlias][] = $sExtKeyAttCode;
  462. // Load the external field (if any) to avoid getting the remote object (see DBObject::Get that does the same)
  463. $oExtFieldAtt = MetaModel::FindExternalField($sClass, $sExtKeyAttCode, $sRemoteAttCode);
  464. if (!is_null($oExtFieldAtt))
  465. {
  466. $aColumnsToLoad[$sAlias][] = $oExtFieldAtt->GetCode();
  467. }
  468. }
  469. }
  470. }
  471. // Add "always loaded attributes"
  472. //
  473. $aSelectedClasses = $this->oSearch->GetSelectedClasses();
  474. foreach ($aSelectedClasses as $sAlias => $sClass)
  475. {
  476. foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  477. {
  478. if ($oAttDef->AlwaysLoadInTables())
  479. {
  480. $aColumnsToLoad[$sAlias][] = $sAttCode;
  481. }
  482. }
  483. }
  484. $oSet->OptimizeColumnLoad($aColumnsToLoad);
  485. }
  486. }