export.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. <?php
  2. // Copyright (C) 2010-2012 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-2012 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. $bLocalize = (utils::ReadParam('no_localize', 0) != 1);
  70. $sFileName = utils::ReadParam('filename', '', true, 'string');
  71. // Main program
  72. $sExpression = utils::ReadParam('expression', '', true /* Allow CLI */, 'raw_data');
  73. $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)
  74. $bFieldsAdvanced = utils::ReadParam('fields_advanced', 0);
  75. if (strlen($sExpression) == 0)
  76. {
  77. $sQueryId = trim(utils::ReadParam('query', '', true /* Allow CLI */, 'raw_data'));
  78. if (strlen($sQueryId) > 0)
  79. {
  80. $oSearch = DBObjectSearch::FromOQL('SELECT QueryOQL WHERE id = :query_id', array('query_id' => $sQueryId));
  81. $oQueries = new DBObjectSet($oSearch);
  82. if ($oQueries->Count() > 0)
  83. {
  84. $oQuery = $oQueries->Fetch();
  85. $sExpression = $oQuery->Get('oql');
  86. if (strlen($sFields) == 0)
  87. {
  88. $sFields = trim($oQuery->Get('fields'));
  89. }
  90. }
  91. }
  92. }
  93. $sFormat = strtolower(utils::ReadParam('format', 'html', true /* Allow CLI */));
  94. $aFields = explode(',', $sFields);
  95. // Clean the list of columns (empty it if every string is empty)
  96. foreach($aFields as $index => $sField)
  97. {
  98. $aFields[$index] = trim($sField);
  99. if(strlen($aFields[$index]) == 0)
  100. {
  101. unset($aFields[$index]);
  102. }
  103. }
  104. $oP = null;
  105. if (!empty($sExpression))
  106. {
  107. try
  108. {
  109. $oFilter = DBObjectSearch::FromOQL($sExpression);
  110. // Check and adjust column names
  111. //
  112. $aAliasToFields = array();
  113. foreach($aFields as $index => $sField)
  114. {
  115. if (preg_match('/^(.*)\.(.*)$/', $sField, $aMatches))
  116. {
  117. $sClassAlias = $aMatches[1];
  118. $sAttCode = $aMatches[2];
  119. }
  120. else
  121. {
  122. $sClassAlias = $oFilter->GetClassAlias();
  123. $sAttCode = $sField;
  124. // Disambiguate the class alias
  125. $aFields[$index] = $sClassAlias.'.'.$sAttCode;
  126. }
  127. $aAliasToFields[$sClassAlias][] = $sAttCode;
  128. $sClass = $oFilter->GetClassName($sClassAlias);
  129. if (!MetaModel::IsValidAttCode($sClass, $sAttCode))
  130. {
  131. throw new CoreException("Invalid field specification $sField: $sAttCode is not a valid attribute for $sClass");
  132. }
  133. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  134. if ($oAttDef instanceof AttributeSubItem)
  135. {
  136. $aAliasToFields[$sClassAlias][] = $oAttDef->GetParentAttCode();
  137. }
  138. else if($oAttDef instanceof AttributeFriendlyname)
  139. {
  140. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  141. if ($sKeyAttCode != 'id')
  142. {
  143. $aAliasToFields[$sClassAlias][] = $sKeyAttCode;
  144. }
  145. }
  146. }
  147. // Read query parameters
  148. //
  149. $aArgs = array();
  150. foreach($oFilter->GetQueryParams() as $sParam => $foo)
  151. {
  152. $value = utils::ReadParam('arg_'.$sParam, null, true, 'raw_data');
  153. if (!is_null($value))
  154. {
  155. $aArgs[$sParam] = $value;
  156. }
  157. }
  158. $oFilter->SetInternalParams($aArgs);
  159. foreach ($oFilter->GetSelectedClasses() as $sAlias => $sClass)
  160. {
  161. if ((UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_READ) && UR_ALLOWED_YES) == 0)
  162. {
  163. throw new Exception("The current user does not have permission for exporting data of class $sClass");
  164. }
  165. }
  166. if ($oFilter)
  167. {
  168. $oSet = new CMDBObjectSet($oFilter, array(), $aArgs);
  169. $oSet->OptimizeColumnLoad($aAliasToFields);
  170. switch($sFormat)
  171. {
  172. case 'html':
  173. $oP = new NiceWebPage("iTop - Export");
  174. $oP->add_style('body { overflow: auto; }'); // Show scroll bars if needed
  175. // Integration within MS-Excel web queries + HTTPS + IIS:
  176. // MS-IIS set these header values with no-cache... while Excel fails to do the job if using HTTPS
  177. // Then the fix is to force the reset of header values Pragma and Cache-control
  178. header("Pragma:", true);
  179. header("Cache-control:", true);
  180. // The HTML output is made for pages located in the /pages/ folder
  181. // since this page is in a different folder, let's adjust the HTML 'base' attribute
  182. // to make the relative hyperlinks in the page work
  183. $sUrl = utils::GetAbsoluteUrlAppRoot();
  184. $oP->set_base($sUrl.'pages/');
  185. if(count($aFields) > 0)
  186. {
  187. $iSearch = array_search('id', $aFields);
  188. if ($iSearch !== false)
  189. {
  190. $bViewLink = true;
  191. unset($aFields[$iSearch]);
  192. }
  193. else
  194. {
  195. $bViewLink = false;
  196. }
  197. $sFields = implode(',', $aFields);
  198. $aExtraParams = array('menu' => false, 'toolkit_menu' => false, 'display_limit' => false, 'localize_values' => $bLocalize, 'zlist' => false, 'extra_fields' => $sFields, 'view_link' => $bViewLink);
  199. }
  200. else
  201. {
  202. $aExtraParams = array('menu' => false, 'toolkit_menu' => false, 'display_limit' => false, 'localize_values' => $bLocalize, 'zlist' => 'details');
  203. }
  204. $oResultBlock = new DisplayBlock($oFilter, 'list', false, $aExtraParams);
  205. $oResultBlock->Display($oP, 'expresult');
  206. break;
  207. case 'csv':
  208. $oP = new CSVPage("iTop - Export");
  209. $sFields = implode(',', $aFields);
  210. $sCharset = utils::ReadParam('charset', MetaModel::GetConfig()->Get('csv_file_default_charset'), true /* Allow CLI */, 'raw_data');
  211. $sCSVData = cmdbAbstractObject::GetSetAsCSV($oSet, array('fields' => $sFields, 'fields_advanced' => $bFieldsAdvanced, 'localize_values' => $bLocalize), $sCharset);
  212. if ($sCharset == 'UTF-8')
  213. {
  214. $sOutputData = UTF8_BOM.$sCSVData;
  215. }
  216. else
  217. {
  218. $sOutputData = $sCSVData;
  219. }
  220. if ($sFileName == '')
  221. {
  222. // Plain text => Firefox will NOT propose to download the file
  223. $oP->add_header("Content-type: text/plain; charset=$sCharset");
  224. }
  225. else
  226. {
  227. $oP->add_header("Content-type: text/csv; charset=$sCharset");
  228. }
  229. $oP->add($sOutputData);
  230. break;
  231. case 'spreadsheet':
  232. $oP = new WebPage("iTop - Export for spreadsheet");
  233. // Integration within MS-Excel web queries + HTTPS + IIS:
  234. // MS-IIS set these header values with no-cache... while Excel fails to do the job if using HTTPS
  235. // Then the fix is to force the reset of header values Pragma and Cache-control
  236. header("Pragma:", true);
  237. header("Cache-control:", true);
  238. $sFields = implode(',', $aFields);
  239. $oP->add_style('table br {mso-data-placement:same-cell;}'); // Trick for Excel: keep line breaks inside the same cell !
  240. cmdbAbstractObject::DisplaySetAsHTMLSpreadsheet($oP, $oSet, array('fields' => $sFields, 'fields_advanced' => $bFieldsAdvanced, 'localize_values' => $bLocalize));
  241. break;
  242. case 'xml':
  243. $oP = new XMLPage("iTop - Export", true /* passthrough */);
  244. cmdbAbstractObject::DisplaySetAsXML($oP, $oSet, array('localize_values' => $bLocalize));
  245. break;
  246. case 'xlsx':
  247. $oP = new ajax_page('');
  248. $oExporter = new ExcelExporter();
  249. $oExporter->SetObjectList($oFilter);
  250. // Run the export by chunk of 1000 objects to limit memory usage
  251. $oExporter->SetChunkSize(1000);
  252. do
  253. {
  254. $aStatus = $oExporter->Run(); // process one chunk
  255. }
  256. while( ($aStatus['code'] != 'done') && ($aStatus['code'] != 'error'));
  257. if ($aStatus['code'] == 'done')
  258. {
  259. $oP->SetContentType('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  260. $oP->SetContentDisposition('attachment', $oFilter->GetClass().'.xlsx');
  261. $oP->add(file_get_contents($oExporter->GetExcelFilePath()));
  262. $oExporter->Cleanup();
  263. }
  264. else
  265. {
  266. $oP->add('Error, xlsx export failed: '.$aStatus['message']);
  267. }
  268. break;
  269. default:
  270. $oP = new WebPage("iTop - Export");
  271. $oP->add("Unsupported format '$sFormat'. Possible values are: html, csv, spreadsheet or xml.");
  272. }
  273. }
  274. }
  275. catch(Exception $e)
  276. {
  277. $oP = new WebPage("iTop - Export");
  278. $oP->p("Error the query can not be executed.");
  279. if ($e instanceof CoreException)
  280. {
  281. $oP->p($e->GetHtmlDesc());
  282. }
  283. else
  284. {
  285. $oP->p($e->getMessage());
  286. }
  287. }
  288. }
  289. if (!$oP)
  290. {
  291. // Display a short message about how to use this page
  292. $bModeCLI = utils::IsModeCLI();
  293. if ($bModeCLI)
  294. {
  295. $oP = new CLIPage("iTop - Export");
  296. }
  297. else
  298. {
  299. $oP = new WebPage("iTop - Export");
  300. }
  301. $oP->p("General purpose export page.");
  302. $oP->p("Parameters:");
  303. $oP->p(" * expression: an OQL expression (URL encoded if needed)");
  304. $oP->p(" * query: (alternative to 'expression') the id of an entry from the query phrasebook");
  305. $oP->p(" * arg_xxx: (needed if the query has parameters) the value of the parameter 'xxx'");
  306. $oP->p(" * format: (optional, default is html) the desired output format. Can be one of 'html', 'spreadsheet', 'csv', 'xlsx' or 'xml'");
  307. $oP->p(" * fields: (optional, no effect on XML format) list of fields (attribute codes, or alias.attcode) separated by a coma");
  308. $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");
  309. $oP->p(" * filename: (optional, no effect in CLI mode) if set then the results will be downloaded as a file");
  310. }
  311. if ($sFileName != '')
  312. {
  313. $oP->add_header('Content-Disposition: attachment; filename="'.$sFileName.'"');
  314. }
  315. $oP->TrashUnexpectedOutput();
  316. $oP->output();
  317. ?>