export.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. <?php
  2. // Copyright (C) 2010-2017 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. * Export data specified by an OQL
  20. *
  21. * @copyright Copyright (C) 2010-2017 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. if (!defined('__DIR__')) define('__DIR__', dirname(__FILE__));
  25. require_once(__DIR__.'/../approot.inc.php');
  26. require_once(APPROOT.'/application/application.inc.php');
  27. require_once(APPROOT.'/application/nicewebpage.class.inc.php');
  28. require_once(APPROOT.'/application/ajaxwebpage.class.inc.php');
  29. require_once(APPROOT.'/application/csvpage.class.inc.php');
  30. require_once(APPROOT.'/application/xmlpage.class.inc.php');
  31. require_once(APPROOT.'/application/clipage.class.inc.php');
  32. require_once(APPROOT.'/application/excelexporter.class.inc.php');
  33. require_once(APPROOT.'/application/startup.inc.php');
  34. try
  35. {
  36. // Do this before loging, in order to allow setting user credentials from within the file
  37. utils::UseParamFile();
  38. }
  39. catch(Exception $e)
  40. {
  41. echo "Error: ".$e->GetMessage()."<br/>\n";
  42. exit -2;
  43. }
  44. if (utils::IsModeCLI())
  45. {
  46. $sAuthUser = utils::ReadParam('auth_user', null, true /* Allow CLI */, 'raw_data');
  47. $sAuthPwd = utils::ReadParam('auth_pwd', null, true /* Allow CLI */, 'raw_data');
  48. if (UserRights::CheckCredentials($sAuthUser, $sAuthPwd))
  49. {
  50. UserRights::Login($sAuthUser); // Login & set the user's language
  51. }
  52. else
  53. {
  54. $oP = new CLIPage("iTop - Export");
  55. $oP->p("Access restricted or wrong credentials ('$sAuthUser')");
  56. $oP->output();
  57. exit -1;
  58. }
  59. }
  60. else
  61. {
  62. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  63. LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  64. }
  65. ApplicationContext::SetUrlMakerClass('iTopStandardURLMaker');
  66. $oAppContext = new ApplicationContext();
  67. $iActiveNodeId = utils::ReadParam('menu', -1);
  68. $currentOrganization = utils::ReadParam('org_id', '');
  69. if (utils::IsArchiveMode() && !UserRights::CanBrowseArchive())
  70. {
  71. $oP = new CLIPage("iTop - Export");
  72. $oP->p("The user account is not authorized to access the archives");
  73. $oP->output();
  74. exit -1;
  75. }
  76. $bLocalize = (utils::ReadParam('no_localize', 0) != 1);
  77. $sFileName = utils::ReadParam('filename', '', true, 'string');
  78. // Main program
  79. $sExpression = utils::ReadParam('expression', '', true /* Allow CLI */, 'raw_data');
  80. $sFields = trim(utils::ReadParam('fields', '', true, 'raw_data')); // CSV field list (allows to specify link set attributes, still not taken into account for XML export)
  81. $bFieldsAdvanced = utils::ReadParam('fields_advanced', 0);
  82. if (strlen($sExpression) == 0)
  83. {
  84. $sQueryId = trim(utils::ReadParam('query', '', true /* Allow CLI */, 'raw_data'));
  85. if (strlen($sQueryId) > 0)
  86. {
  87. $oSearch = DBObjectSearch::FromOQL('SELECT QueryOQL WHERE id = :query_id', array('query_id' => $sQueryId));
  88. $oQueries = new DBObjectSet($oSearch);
  89. if ($oQueries->Count() > 0)
  90. {
  91. $oQuery = $oQueries->Fetch();
  92. $sExpression = $oQuery->Get('oql');
  93. if (strlen($sFields) == 0)
  94. {
  95. $sFields = trim($oQuery->Get('fields'));
  96. }
  97. }
  98. }
  99. }
  100. $sFormat = strtolower(utils::ReadParam('format', 'html', true /* Allow CLI */));
  101. $aFields = explode(',', $sFields);
  102. // Clean the list of columns (empty it if every string is empty)
  103. foreach($aFields as $index => $sField)
  104. {
  105. $aFields[$index] = trim($sField);
  106. if(strlen($aFields[$index]) == 0)
  107. {
  108. unset($aFields[$index]);
  109. }
  110. }
  111. $oP = null;
  112. if (!empty($sExpression))
  113. {
  114. try
  115. {
  116. $oFilter = DBObjectSearch::FromOQL($sExpression);
  117. // Check and adjust column names
  118. //
  119. $aAliasToFields = array();
  120. foreach($aFields as $index => $sField)
  121. {
  122. if (preg_match('/^(.*)\.(.*)$/', $sField, $aMatches))
  123. {
  124. $sClassAlias = $aMatches[1];
  125. $sAttCode = $aMatches[2];
  126. }
  127. else
  128. {
  129. $sClassAlias = $oFilter->GetClassAlias();
  130. $sAttCode = $sField;
  131. // Disambiguate the class alias
  132. $aFields[$index] = $sClassAlias.'.'.$sAttCode;
  133. }
  134. $aAliasToFields[$sClassAlias][] = $sAttCode;
  135. $sClass = $oFilter->GetClassName($sClassAlias);
  136. if (!MetaModel::IsValidAttCode($sClass, $sAttCode))
  137. {
  138. throw new CoreException("Invalid field specification $sField: $sAttCode is not a valid attribute for $sClass");
  139. }
  140. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  141. if ($oAttDef instanceof AttributeSubItem)
  142. {
  143. $aAliasToFields[$sClassAlias][] = $oAttDef->GetParentAttCode();
  144. }
  145. else if($oAttDef instanceof AttributeExternalField && $oAttDef->IsFriendlyName())
  146. {
  147. $aAliasToFields[$sClassAlias][] = $sKeyAttCode;
  148. }
  149. }
  150. // Read query parameters
  151. //
  152. $aArgs = array();
  153. foreach($oFilter->GetQueryParams() as $sParam => $foo)
  154. {
  155. $value = utils::ReadParam('arg_'.$sParam, null, true, 'raw_data');
  156. if (!is_null($value))
  157. {
  158. $aArgs[$sParam] = $value;
  159. }
  160. }
  161. $oFilter->SetInternalParams($aArgs);
  162. foreach ($oFilter->GetSelectedClasses() as $sAlias => $sClass)
  163. {
  164. if ((UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_READ) && UR_ALLOWED_YES) == 0)
  165. {
  166. throw new Exception("The current user does not have permission for exporting data of class $sClass");
  167. }
  168. }
  169. if ($oFilter)
  170. {
  171. $oSet = new CMDBObjectSet($oFilter, array(), $aArgs);
  172. $oSet->OptimizeColumnLoad($aAliasToFields);
  173. switch($sFormat)
  174. {
  175. case 'html':
  176. $oP = new NiceWebPage("iTop - Export");
  177. $oP->add_style('body { overflow: auto; }'); // Show scroll bars if needed
  178. // Integration within MS-Excel web queries + HTTPS + IIS:
  179. // MS-IIS set these header values with no-cache... while Excel fails to do the job if using HTTPS
  180. // Then the fix is to force the reset of header values Pragma and Cache-control
  181. header("Pragma:", true);
  182. header("Cache-control:", true);
  183. // The HTML output is made for pages located in the /pages/ folder
  184. // since this page is in a different folder, let's adjust the HTML 'base' attribute
  185. // to make the relative hyperlinks in the page work
  186. $sUrl = utils::GetAbsoluteUrlAppRoot();
  187. $oP->set_base($sUrl.'pages/');
  188. if(count($aFields) > 0)
  189. {
  190. $iSearch = array_search('id', $aFields);
  191. if ($iSearch !== false)
  192. {
  193. $bViewLink = true;
  194. unset($aFields[$iSearch]);
  195. }
  196. else
  197. {
  198. $bViewLink = false;
  199. }
  200. $sFields = implode(',', $aFields);
  201. $aExtraParams = array('menu' => false, 'toolkit_menu' => false, 'display_limit' => false, 'localize_values' => $bLocalize, 'zlist' => false, 'extra_fields' => $sFields, 'view_link' => $bViewLink);
  202. }
  203. else
  204. {
  205. $aExtraParams = array('menu' => false, 'toolkit_menu' => false, 'display_limit' => false, 'localize_values' => $bLocalize, 'zlist' => 'details');
  206. }
  207. $oResultBlock = new DisplayBlock($oFilter, 'list', false, $aExtraParams);
  208. $oResultBlock->Display($oP, 'expresult');
  209. break;
  210. case 'csv':
  211. $oP = new CSVPage("iTop - Export");
  212. $sFields = implode(',', $aFields);
  213. $sCharset = utils::ReadParam('charset', MetaModel::GetConfig()->Get('csv_file_default_charset'), true /* Allow CLI */, 'raw_data');
  214. $sCSVData = cmdbAbstractObject::GetSetAsCSV($oSet, array('fields' => $sFields, 'fields_advanced' => $bFieldsAdvanced, 'localize_values' => $bLocalize), $sCharset);
  215. if ($sCharset == 'UTF-8')
  216. {
  217. $sOutputData = UTF8_BOM.$sCSVData;
  218. }
  219. else
  220. {
  221. $sOutputData = $sCSVData;
  222. }
  223. if ($sFileName == '')
  224. {
  225. // Plain text => Firefox will NOT propose to download the file
  226. $oP->add_header("Content-type: text/plain; charset=$sCharset");
  227. }
  228. else
  229. {
  230. $oP->add_header("Content-type: text/csv; charset=$sCharset");
  231. }
  232. $oP->add($sOutputData);
  233. break;
  234. case 'spreadsheet':
  235. $oP = new WebPage("iTop - Export for spreadsheet");
  236. // Integration within MS-Excel web queries + HTTPS + IIS:
  237. // MS-IIS set these header values with no-cache... while Excel fails to do the job if using HTTPS
  238. // Then the fix is to force the reset of header values Pragma and Cache-control
  239. header("Pragma:", true);
  240. header("Cache-control:", true);
  241. $sFields = implode(',', $aFields);
  242. $oP->add_style('table br {mso-data-placement:same-cell;}'); // Trick for Excel: keep line breaks inside the same cell !
  243. cmdbAbstractObject::DisplaySetAsHTMLSpreadsheet($oP, $oSet, array('fields' => $sFields, 'fields_advanced' => $bFieldsAdvanced, 'localize_values' => $bLocalize));
  244. break;
  245. case 'xml':
  246. $oP = new XMLPage("iTop - Export", true /* passthrough */);
  247. cmdbAbstractObject::DisplaySetAsXML($oP, $oSet, array('localize_values' => $bLocalize));
  248. break;
  249. case 'xlsx':
  250. $oP = new ajax_page('');
  251. $oExporter = new ExcelExporter();
  252. $oExporter->SetObjectList($oFilter);
  253. // Run the export by chunk of 1000 objects to limit memory usage
  254. $oExporter->SetChunkSize(1000);
  255. do
  256. {
  257. $aStatus = $oExporter->Run(); // process one chunk
  258. }
  259. while( ($aStatus['code'] != 'done') && ($aStatus['code'] != 'error'));
  260. if ($aStatus['code'] == 'done')
  261. {
  262. $oP->SetContentType('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  263. $oP->SetContentDisposition('attachment', $oFilter->GetClass().'.xlsx');
  264. $oP->add(file_get_contents($oExporter->GetExcelFilePath()));
  265. $oExporter->Cleanup();
  266. }
  267. else
  268. {
  269. $oP->add('Error, xlsx export failed: '.$aStatus['message']);
  270. }
  271. break;
  272. default:
  273. $oP = new WebPage("iTop - Export");
  274. $oP->add("Unsupported format '$sFormat'. Possible values are: html, csv, spreadsheet or xml.");
  275. }
  276. }
  277. }
  278. catch(Exception $e)
  279. {
  280. $oP = new WebPage("iTop - Export");
  281. $oP->p("Error the query can not be executed.");
  282. if ($e instanceof CoreException)
  283. {
  284. $oP->p($e->GetHtmlDesc());
  285. }
  286. else
  287. {
  288. $oP->p($e->getMessage());
  289. }
  290. }
  291. }
  292. if (!$oP)
  293. {
  294. // Display a short message about how to use this page
  295. $bModeCLI = utils::IsModeCLI();
  296. if ($bModeCLI)
  297. {
  298. $oP = new CLIPage("iTop - Export");
  299. }
  300. else
  301. {
  302. $oP = new WebPage("iTop - Export");
  303. }
  304. $oP->p("General purpose export page.");
  305. $oP->p("Parameters:");
  306. $oP->p(" * expression: an OQL expression (URL encoded if needed)");
  307. $oP->p(" * query: (alternative to 'expression') the id of an entry from the query phrasebook");
  308. if (Utils::IsModeCLI())
  309. {
  310. $oP->p(" * with_archive: (optional, defaults to 0) if set to 1 then the result set will include archived objects");
  311. }
  312. else
  313. {
  314. $oP->p(" * with_archive: (optional, defaults to the current mode) if set to 1 then the result set will include archived objects");
  315. }
  316. $oP->p(" * arg_xxx: (needed if the query has parameters) the value of the parameter 'xxx'");
  317. $oP->p(" * format: (optional, default is html) the desired output format. Can be one of 'html', 'spreadsheet', 'csv', 'xlsx' or 'xml'");
  318. $oP->p(" * fields: (optional, no effect on XML format) list of fields (attribute codes, or alias.attcode) separated by a coma");
  319. $oP->p(" * fields_advanced: (optional, no effect on XML/HTML formats ; ignored is fields is specified) If set to 1, the default list of fields will include the external keys and their reconciliation keys");
  320. $oP->p(" * filename: (optional, no effect in CLI mode) if set then the results will be downloaded as a file");
  321. }
  322. if ($sFileName != '')
  323. {
  324. $oP->add_header('Content-Disposition: attachment; filename="'.$sFileName.'"');
  325. }
  326. $oP->TrashUnexpectedOutput();
  327. $oP->output();
  328. ?>