export.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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/csvpage.class.inc.php');
  29. require_once(APPROOT.'/application/xmlpage.class.inc.php');
  30. require_once(APPROOT.'/application/clipage.class.inc.php');
  31. require_once(APPROOT.'/application/startup.inc.php');
  32. try
  33. {
  34. // Do this before loging, in order to allow setting user credentials from within the file
  35. utils::UseParamFile();
  36. }
  37. catch(Exception $e)
  38. {
  39. echo "Error: ".$e->GetMessage()."<br/>\n";
  40. exit -2;
  41. }
  42. if (utils::IsModeCLI())
  43. {
  44. $sAuthUser = utils::ReadParam('auth_user', null, true /* Allow CLI */, 'raw_data');
  45. $sAuthPwd = utils::ReadParam('auth_pwd', null, true /* Allow CLI */, 'raw_data');
  46. if (UserRights::CheckCredentials($sAuthUser, $sAuthPwd))
  47. {
  48. UserRights::Login($sAuthUser); // Login & set the user's language
  49. }
  50. else
  51. {
  52. $oP = new CLIPage("iTop - Export");
  53. $oP->p("Access restricted or wrong credentials ('$sAuthUser')");
  54. $oP->output();
  55. exit -1;
  56. }
  57. }
  58. else
  59. {
  60. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  61. LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  62. }
  63. ApplicationContext::SetUrlMakerClass('iTopStandardURLMaker');
  64. $oAppContext = new ApplicationContext();
  65. $iActiveNodeId = utils::ReadParam('menu', -1);
  66. $currentOrganization = utils::ReadParam('org_id', '');
  67. $bLocalize = (utils::ReadParam('no_localize', 0) != 1);
  68. $sFileName = utils::ReadParam('filename', '', true, 'string');
  69. // Main program
  70. $sExpression = utils::ReadParam('expression', '', true /* Allow CLI */, 'raw_data');
  71. $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)
  72. $bFieldsAdvanced = utils::ReadParam('fields_advanced', 0);
  73. if (strlen($sExpression) == 0)
  74. {
  75. $sQueryId = trim(utils::ReadParam('query', '', true /* Allow CLI */, 'raw_data'));
  76. if (strlen($sQueryId) > 0)
  77. {
  78. $oSearch = DBObjectSearch::FromOQL('SELECT QueryOQL WHERE id = :query_id', array('query_id' => $sQueryId));
  79. $oQueries = new DBObjectSet($oSearch);
  80. if ($oQueries->Count() > 0)
  81. {
  82. $oQuery = $oQueries->Fetch();
  83. $sExpression = $oQuery->Get('oql');
  84. if (strlen($sFields) == 0)
  85. {
  86. $sFields = trim($oQuery->Get('fields'));
  87. }
  88. }
  89. }
  90. }
  91. $sFormat = strtolower(utils::ReadParam('format', 'html', true /* Allow CLI */));
  92. $aFields = explode(',', $sFields);
  93. // Clean the list of columns (empty it if every string is empty)
  94. foreach($aFields as $index => $sField)
  95. {
  96. $aFields[$index] = trim($sField);
  97. if(strlen($aFields[$index]) == 0)
  98. {
  99. unset($aFields[$index]);
  100. }
  101. }
  102. $oP = null;
  103. if (!empty($sExpression))
  104. {
  105. try
  106. {
  107. $oFilter = DBObjectSearch::FromOQL($sExpression);
  108. // Check and adjust column names
  109. //
  110. $aAliasToFields = array();
  111. foreach($aFields as $index => $sField)
  112. {
  113. if (preg_match('/^(.*)\.(.*)$/', $sField, $aMatches))
  114. {
  115. $sClassAlias = $aMatches[1];
  116. $sAttCode = $aMatches[2];
  117. }
  118. else
  119. {
  120. $sClassAlias = $oFilter->GetClassAlias();
  121. $sAttCode = $sField;
  122. // Disambiguate the class alias
  123. $aFields[$index] = $sClassAlias.'.'.$sAttCode;
  124. }
  125. $aAliasToFields[$sClassAlias][] = $sAttCode;
  126. $sClass = $oFilter->GetClassName($sClassAlias);
  127. if (!MetaModel::IsValidAttCode($sClass, $sAttCode))
  128. {
  129. throw new CoreException("Invalid field specification $sField: $sAttCode is not a valid attribute for $sClass");
  130. }
  131. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  132. if ($oAttDef instanceof AttributeSubItem)
  133. {
  134. $aAliasToFields[$sClassAlias][] = $oAttDef->GetParentAttCode();
  135. }
  136. }
  137. // Read query parameters
  138. //
  139. $aArgs = array();
  140. foreach($oFilter->GetQueryParams() as $sParam => $foo)
  141. {
  142. $value = utils::ReadParam('arg_'.$sParam, null, true, 'raw_data');
  143. if (!is_null($value))
  144. {
  145. $aArgs[$sParam] = $value;
  146. }
  147. }
  148. $oFilter->SetInternalParams($aArgs);
  149. if ($oFilter)
  150. {
  151. $oSet = new CMDBObjectSet($oFilter, array(), $aArgs);
  152. $oSet->OptimizeColumnLoad($aAliasToFields);
  153. switch($sFormat)
  154. {
  155. case 'html':
  156. $oP = new NiceWebPage("iTop - Export");
  157. // Integration within MS-Excel web queries + HTTPS + IIS:
  158. // MS-IIS set these header values with no-cache... while Excel fails to do the job if using HTTPS
  159. // Then the fix is to force the reset of header values Pragma and Cache-control
  160. header("Pragma:", true);
  161. header("Cache-control:", true);
  162. // The HTML output is made for pages located in the /pages/ folder
  163. // since this page is in a different folder, let's adjust the HTML 'base' attribute
  164. // to make the relative hyperlinks in the page work
  165. $sUrl = utils::GetAbsoluteUrlAppRoot();
  166. $oP->set_base($sUrl.'pages/');
  167. if(count($aFields) > 0)
  168. {
  169. $iSearch = array_search('id', $aFields);
  170. if ($iSearch !== false)
  171. {
  172. $bViewLink = true;
  173. unset($aFields[$iSearch]);
  174. }
  175. else
  176. {
  177. $bViewLink = false;
  178. }
  179. $sFields = implode(',', $aFields);
  180. $aExtraParams = array('menu' => false, 'toolkit_menu' => false, 'display_limit' => false, 'localize_values' => $bLocalize, 'zlist' => false, 'extra_fields' => $sFields, 'view_link' => $bViewLink);
  181. }
  182. else
  183. {
  184. $aExtraParams = array('menu' => false, 'toolkit_menu' => false, 'display_limit' => false, 'localize_values' => $bLocalize, 'zlist' => 'details');
  185. }
  186. $oResultBlock = new DisplayBlock($oFilter, 'list', false, $aExtraParams);
  187. $oResultBlock->Display($oP, 'expresult');
  188. break;
  189. case 'csv':
  190. $oP = new CSVPage("iTop - Export");
  191. $sFields = implode(',', $aFields);
  192. $sCSVData = cmdbAbstractObject::GetSetAsCSV($oSet, array('fields' => $sFields, 'fields_advanced' => $bFieldsAdvanced, 'localize_values' => $bLocalize));
  193. $sCharset = MetaModel::GetConfig()->Get('csv_file_default_charset');
  194. if ($sCharset == 'UTF-8')
  195. {
  196. $sOutputData = UTF8_BOM.iconv('UTF-8', 'UTF-8//IGNORE//TRANSLIT', $sCSVData);
  197. }
  198. else
  199. {
  200. $sOutputData = iconv('UTF-8', $sCharset.'//IGNORE//TRANSLIT', $sCSVData);
  201. }
  202. if ($sFileName == '')
  203. {
  204. // Plain text => Firefox will NOT propose to download the file
  205. $oP->add_header("Content-type: text/plain; charset=$sCharset");
  206. }
  207. else
  208. {
  209. $oP->add_header("Content-type: text/csv; charset=$sCharset");
  210. }
  211. $oP->add($sOutputData);
  212. break;
  213. case 'spreadsheet':
  214. $oP = new WebPage("iTop - Export for spreadsheet");
  215. // Integration within MS-Excel web queries + HTTPS + IIS:
  216. // MS-IIS set these header values with no-cache... while Excel fails to do the job if using HTTPS
  217. // Then the fix is to force the reset of header values Pragma and Cache-control
  218. header("Pragma:", true);
  219. header("Cache-control:", true);
  220. $sFields = implode(',', $aFields);
  221. $oP->add_style('table br {mso-data-placement:same-cell;}'); // Trick for Excel: keep line breaks inside the same cell !
  222. cmdbAbstractObject::DisplaySetAsHTMLSpreadsheet($oP, $oSet, array('fields' => $sFields, 'fields_advanced' => $bFieldsAdvanced, 'localize_values' => $bLocalize));
  223. break;
  224. case 'xml':
  225. $oP = new XMLPage("iTop - Export", true /* passthrough */);
  226. cmdbAbstractObject::DisplaySetAsXML($oP, $oSet, array('localize_values' => $bLocalize));
  227. break;
  228. default:
  229. $oP = new WebPage("iTop - Export");
  230. $oP->add("Unsupported format '$sFormat'. Possible values are: html, csv, spreadsheet or xml.");
  231. }
  232. }
  233. }
  234. catch(Exception $e)
  235. {
  236. $oP = new WebPage("iTop - Export");
  237. $oP->p("Error the query can not be executed.");
  238. if ($e instanceof CoreException)
  239. {
  240. $oP->p($e->GetHtmlDesc());
  241. }
  242. else
  243. {
  244. $oP->p($e->getMessage());
  245. }
  246. }
  247. }
  248. if (!$oP)
  249. {
  250. // Display a short message about how to use this page
  251. $bModeCLI = utils::IsModeCLI();
  252. if ($bModeCLI)
  253. {
  254. $oP = new CLIPage("iTop - Export");
  255. }
  256. else
  257. {
  258. $oP = new WebPage("iTop - Export");
  259. }
  260. $oP->p("General purpose export page.");
  261. $oP->p("Parameters:");
  262. $oP->p(" * expression: an OQL expression (URL encoded if needed)");
  263. $oP->p(" * query: (alternative to 'expression') the id of an entry from the query phrasebook");
  264. $oP->p(" * arg_xxx: (needed if the query has parameters) the value of the parameter 'xxx'");
  265. $oP->p(" * format: (optional, default is html) the desired output format. Can be one of 'html', 'spreadsheet', 'csv' or 'xml'");
  266. $oP->p(" * fields: (optional, no effect on XML format) list of fields (attribute codes, or alias.attcode) separated by a coma");
  267. $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");
  268. $oP->p(" * filename: (optional, no effect in CLI mode) if set then the results will be downloaded as a file");
  269. }
  270. if ($sFileName != '')
  271. {
  272. $oP->add_header('Content-Disposition: attachment; filename="'.$sFileName.'"');
  273. }
  274. $oP->TrashUnexpectedOutput();
  275. $oP->output();
  276. ?>