export.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. foreach($aFields as $index => $sField)
  111. {
  112. if (preg_match('/^(.*)\.(.*)$/', $sField, $aMatches))
  113. {
  114. $sClassAlias = $aMatches[1];
  115. $sAttCode = $aMatches[2];
  116. }
  117. else
  118. {
  119. $sClassAlias = $oFilter->GetClassAlias();
  120. $sAttCode = $sField;
  121. $aFields[$index] = $sClassAlias.'.'.$sAttCode;
  122. }
  123. $sClass = $oFilter->GetClassName($sClassAlias);
  124. if (!MetaModel::IsValidAttCode($sClass, $sAttCode))
  125. {
  126. throw new CoreException("Invalid field specification $sField: $sAttCode is not a valid attribute for $sClass");
  127. }
  128. }
  129. // Read query parameters
  130. //
  131. $aArgs = array();
  132. foreach($oFilter->GetQueryParams() as $sParam => $foo)
  133. {
  134. $value = utils::ReadParam('arg_'.$sParam, null, true, 'raw_data');
  135. if (!is_null($value))
  136. {
  137. $aArgs[$sParam] = $value;
  138. }
  139. }
  140. $oFilter->SetInternalParams($aArgs);
  141. if ($oFilter)
  142. {
  143. $oSet = new CMDBObjectSet($oFilter, array(), $aArgs);
  144. switch($sFormat)
  145. {
  146. case 'html':
  147. $oP = new NiceWebPage("iTop - Export");
  148. // Integration within MS-Excel web queries + HTTPS + IIS:
  149. // MS-IIS set these header values with no-cache... while Excel fails to do the job if using HTTPS
  150. // Then the fix is to force the reset of header values Pragma and Cache-control
  151. header("Pragma:", true);
  152. header("Cache-control:", true);
  153. // The HTML output is made for pages located in the /pages/ folder
  154. // since this page is in a different folder, let's adjust the HTML 'base' attribute
  155. // to make the relative hyperlinks in the page work
  156. $sUrl = utils::GetAbsoluteUrlAppRoot();
  157. $oP->set_base($sUrl.'pages/');
  158. if(count($aFields) > 0)
  159. {
  160. $iSearch = array_search('id', $aFields);
  161. if ($iSearch !== false)
  162. {
  163. $bViewLink = true;
  164. unset($aFields[$iSearch]);
  165. }
  166. else
  167. {
  168. $bViewLink = false;
  169. }
  170. $sFields = implode(',', $aFields);
  171. $aExtraParams = array('menu' => false, 'toolkit_menu' => false, 'display_limit' => false, 'localize_values' => $bLocalize, 'zlist' => false, 'extra_fields' => $sFields, 'view_link' => $bViewLink);
  172. }
  173. else
  174. {
  175. $aExtraParams = array('menu' => false, 'toolkit_menu' => false, 'display_limit' => false, 'localize_values' => $bLocalize, 'zlist' => 'details');
  176. }
  177. $oResultBlock = new DisplayBlock($oFilter, 'list', false, $aExtraParams);
  178. $oResultBlock->Display($oP, 'expresult');
  179. break;
  180. case 'csv':
  181. $oP = new CSVPage("iTop - Export");
  182. $sFields = implode(',', $aFields);
  183. $sCSVData = cmdbAbstractObject::GetSetAsCSV($oSet, array('fields' => $sFields, 'fields_advanced' => $bFieldsAdvanced, 'localize_values' => $bLocalize));
  184. $sCharset = MetaModel::GetConfig()->Get('csv_file_default_charset');
  185. if ($sCharset == 'UTF-8')
  186. {
  187. $sOutputData = UTF8_BOM.iconv('UTF-8', 'UTF-8//IGNORE//TRANSLIT', $sCSVData);
  188. }
  189. else
  190. {
  191. $sOutputData = iconv('UTF-8', $sCharset.'//IGNORE//TRANSLIT', $sCSVData);
  192. }
  193. if ($sFileName == '')
  194. {
  195. // Plain text => Firefox will NOT propose to download the file
  196. $oP->add_header("Content-type: text/plain; charset=$sCharset");
  197. }
  198. else
  199. {
  200. $oP->add_header("Content-type: text/csv; charset=$sCharset");
  201. }
  202. $oP->add($sOutputData);
  203. break;
  204. case 'spreadsheet':
  205. $oP = new WebPage("iTop - Export for spreadsheet");
  206. // Integration within MS-Excel web queries + HTTPS + IIS:
  207. // MS-IIS set these header values with no-cache... while Excel fails to do the job if using HTTPS
  208. // Then the fix is to force the reset of header values Pragma and Cache-control
  209. header("Pragma:", true);
  210. header("Cache-control:", true);
  211. $sFields = implode(',', $aFields);
  212. cmdbAbstractObject::DisplaySetAsHTMLSpreadsheet($oP, $oSet, array('fields' => $sFields, 'fields_advanced' => $bFieldsAdvanced, 'localize_values' => $bLocalize));
  213. break;
  214. case 'xml':
  215. $oP = new XMLPage("iTop - Export", true /* passthrough */);
  216. cmdbAbstractObject::DisplaySetAsXML($oP, $oSet, array('localize_values' => $bLocalize));
  217. break;
  218. default:
  219. $oP = new WebPage("iTop - Export");
  220. $oP->add("Unsupported format '$sFormat'. Possible values are: html, csv, spreadsheet or xml.");
  221. }
  222. }
  223. }
  224. catch(Exception $e)
  225. {
  226. $oP = new WebPage("iTop - Export");
  227. $oP->p("Error the query can not be executed.");
  228. if ($e instanceof CoreException)
  229. {
  230. $oP->p($e->GetHtmlDesc());
  231. }
  232. else
  233. {
  234. $oP->p($e->getMessage());
  235. }
  236. }
  237. }
  238. if (!$oP)
  239. {
  240. // Display a short message about how to use this page
  241. $bModeCLI = utils::IsModeCLI();
  242. if ($bModeCLI)
  243. {
  244. $oP = new CLIPage("iTop - Export");
  245. }
  246. else
  247. {
  248. $oP = new WebPage("iTop - Export");
  249. }
  250. $oP->p("General purpose export page.");
  251. $oP->p("Parameters:");
  252. $oP->p(" * expression: an OQL expression (URL encoded if needed)");
  253. $oP->p(" * query: (alternative to 'expression') the id of an entry from the query phrasebook");
  254. $oP->p(" * arg_xxx: (needed if the query has parameters) the value of the parameter 'xxx'");
  255. $oP->p(" * format: (optional, default is html) the desired output format. Can be one of 'html', 'spreadsheet', 'csv' or 'xml'");
  256. $oP->p(" * fields: (optional, no effect on XML format) list of fields (attribute codes, or alias.attcode) separated by a coma");
  257. $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");
  258. $oP->p(" * filename: (optional, no effect in CLI mode) if set then the results will be downloaded as a file");
  259. }
  260. if ($sFileName != '')
  261. {
  262. $oP->add_header('Content-Disposition: attachment; filename="'.$sFileName.'"');
  263. }
  264. $oP->TrashUnexpectedOutput();
  265. $oP->output();
  266. ?>