export.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. if ($oFilter)
  160. {
  161. $oSet = new CMDBObjectSet($oFilter, array(), $aArgs);
  162. $oSet->OptimizeColumnLoad($aAliasToFields);
  163. switch($sFormat)
  164. {
  165. case 'html':
  166. $oP = new NiceWebPage("iTop - Export");
  167. // Integration within MS-Excel web queries + HTTPS + IIS:
  168. // MS-IIS set these header values with no-cache... while Excel fails to do the job if using HTTPS
  169. // Then the fix is to force the reset of header values Pragma and Cache-control
  170. header("Pragma:", true);
  171. header("Cache-control:", true);
  172. // The HTML output is made for pages located in the /pages/ folder
  173. // since this page is in a different folder, let's adjust the HTML 'base' attribute
  174. // to make the relative hyperlinks in the page work
  175. $sUrl = utils::GetAbsoluteUrlAppRoot();
  176. $oP->set_base($sUrl.'pages/');
  177. if(count($aFields) > 0)
  178. {
  179. $iSearch = array_search('id', $aFields);
  180. if ($iSearch !== false)
  181. {
  182. $bViewLink = true;
  183. unset($aFields[$iSearch]);
  184. }
  185. else
  186. {
  187. $bViewLink = false;
  188. }
  189. $sFields = implode(',', $aFields);
  190. $aExtraParams = array('menu' => false, 'toolkit_menu' => false, 'display_limit' => false, 'localize_values' => $bLocalize, 'zlist' => false, 'extra_fields' => $sFields, 'view_link' => $bViewLink);
  191. }
  192. else
  193. {
  194. $aExtraParams = array('menu' => false, 'toolkit_menu' => false, 'display_limit' => false, 'localize_values' => $bLocalize, 'zlist' => 'details');
  195. }
  196. $oResultBlock = new DisplayBlock($oFilter, 'list', false, $aExtraParams);
  197. $oResultBlock->Display($oP, 'expresult');
  198. break;
  199. case 'csv':
  200. $oP = new CSVPage("iTop - Export");
  201. $sFields = implode(',', $aFields);
  202. $sCharset = utils::ReadParam('charset', MetaModel::GetConfig()->Get('csv_file_default_charset'), true /* Allow CLI */, 'raw_data');
  203. $sCSVData = cmdbAbstractObject::GetSetAsCSV($oSet, array('fields' => $sFields, 'fields_advanced' => $bFieldsAdvanced, 'localize_values' => $bLocalize), $sCharset);
  204. if ($sCharset == 'UTF-8')
  205. {
  206. $sOutputData = UTF8_BOM.$sCSVData;
  207. }
  208. else
  209. {
  210. $sOutputData = $sCSVData;
  211. }
  212. if ($sFileName == '')
  213. {
  214. // Plain text => Firefox will NOT propose to download the file
  215. $oP->add_header("Content-type: text/plain; charset=$sCharset");
  216. }
  217. else
  218. {
  219. $oP->add_header("Content-type: text/csv; charset=$sCharset");
  220. }
  221. $oP->add($sOutputData);
  222. break;
  223. case 'spreadsheet':
  224. $oP = new WebPage("iTop - Export for spreadsheet");
  225. // Integration within MS-Excel web queries + HTTPS + IIS:
  226. // MS-IIS set these header values with no-cache... while Excel fails to do the job if using HTTPS
  227. // Then the fix is to force the reset of header values Pragma and Cache-control
  228. header("Pragma:", true);
  229. header("Cache-control:", true);
  230. $sFields = implode(',', $aFields);
  231. $oP->add_style('table br {mso-data-placement:same-cell;}'); // Trick for Excel: keep line breaks inside the same cell !
  232. cmdbAbstractObject::DisplaySetAsHTMLSpreadsheet($oP, $oSet, array('fields' => $sFields, 'fields_advanced' => $bFieldsAdvanced, 'localize_values' => $bLocalize));
  233. break;
  234. case 'xml':
  235. $oP = new XMLPage("iTop - Export", true /* passthrough */);
  236. cmdbAbstractObject::DisplaySetAsXML($oP, $oSet, array('localize_values' => $bLocalize));
  237. break;
  238. case 'xlsx':
  239. $oP = new ajax_page('');
  240. $oExporter = new ExcelExporter();
  241. $oExporter->SetObjectList($oFilter);
  242. // Run the export by chunk of 1000 objects to limit memory usage
  243. $oExporter->SetChunkSize(1000);
  244. do
  245. {
  246. $aStatus = $oExporter->Run(); // process one chunk
  247. }
  248. while( ($aStatus['code'] != 'done') && ($aStatus['code'] != 'error'));
  249. if ($aStatus['code'] == 'done')
  250. {
  251. $oP->SetContentType('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  252. $oP->SetContentDisposition('attachment', $oFilter->GetClass().'.xlsx');
  253. $oP->add(file_get_contents($oExporter->GetExcelFilePath()));
  254. $oExporter->Cleanup();
  255. }
  256. else
  257. {
  258. $oP->add('Error, xlsx export failed: '.$aStatus['message']);
  259. }
  260. break;
  261. default:
  262. $oP = new WebPage("iTop - Export");
  263. $oP->add("Unsupported format '$sFormat'. Possible values are: html, csv, spreadsheet or xml.");
  264. }
  265. }
  266. }
  267. catch(Exception $e)
  268. {
  269. $oP = new WebPage("iTop - Export");
  270. $oP->p("Error the query can not be executed.");
  271. if ($e instanceof CoreException)
  272. {
  273. $oP->p($e->GetHtmlDesc());
  274. }
  275. else
  276. {
  277. $oP->p($e->getMessage());
  278. }
  279. }
  280. }
  281. if (!$oP)
  282. {
  283. // Display a short message about how to use this page
  284. $bModeCLI = utils::IsModeCLI();
  285. if ($bModeCLI)
  286. {
  287. $oP = new CLIPage("iTop - Export");
  288. }
  289. else
  290. {
  291. $oP = new WebPage("iTop - Export");
  292. }
  293. $oP->p("General purpose export page.");
  294. $oP->p("Parameters:");
  295. $oP->p(" * expression: an OQL expression (URL encoded if needed)");
  296. $oP->p(" * query: (alternative to 'expression') the id of an entry from the query phrasebook");
  297. $oP->p(" * arg_xxx: (needed if the query has parameters) the value of the parameter 'xxx'");
  298. $oP->p(" * format: (optional, default is html) the desired output format. Can be one of 'html', 'spreadsheet', 'csv', 'xlsx' or 'xml'");
  299. $oP->p(" * fields: (optional, no effect on XML format) list of fields (attribute codes, or alias.attcode) separated by a coma");
  300. $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");
  301. $oP->p(" * filename: (optional, no effect in CLI mode) if set then the results will be downloaded as a file");
  302. }
  303. if ($sFileName != '')
  304. {
  305. $oP->add_header('Content-Disposition: attachment; filename="'.$sFileName.'"');
  306. }
  307. $oP->TrashUnexpectedOutput();
  308. $oP->output();
  309. ?>