export-v2.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. <?php
  2. // Copyright (C) 2015-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 or a query phrasebook entry
  20. *
  21. * @copyright Copyright (C) 2015-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/itopwebpage.class.inc.php');
  31. require_once(APPROOT.'/application/xmlpage.class.inc.php');
  32. require_once(APPROOT.'/application/clipage.class.inc.php');
  33. require_once(APPROOT.'/application/excelexporter.class.inc.php');
  34. require_once(APPROOT.'/core/bulkexport.class.inc.php');
  35. require_once(APPROOT.'/application/startup.inc.php');
  36. function ReportErrorAndExit($sErrorMessage)
  37. {
  38. if (utils::IsModeCLI())
  39. {
  40. $oP = new CLIPage("iTop - Export");
  41. $oP->p('ERROR: '.$sErrorMessage);
  42. $oP->output();
  43. exit -1;
  44. }
  45. else
  46. {
  47. $oP = new WebPage("iTop - Export");
  48. $oP->p('ERROR: '.$sErrorMessage);
  49. $oP->output();
  50. exit -1;
  51. }
  52. }
  53. function ReportErrorAndUsage($sErrorMessage)
  54. {
  55. if (utils::IsModeCLI())
  56. {
  57. $oP = new CLIPage("iTop - Export");
  58. $oP->p('ERROR: '.$sErrorMessage);
  59. Usage($oP);
  60. $oP->output();
  61. exit -1;
  62. }
  63. else
  64. {
  65. $oP = new WebPage("iTop - Export");
  66. $oP->p('ERROR: '.$sErrorMessage);
  67. Usage($oP);
  68. $oP->output();
  69. exit -1;
  70. }
  71. }
  72. function Usage(Page $oP)
  73. {
  74. if (Utils::IsModeCLI())
  75. {
  76. $oP->p('Usage: php '.basename(__FILE__).' --auth_user=<user> --auth_pwd=<password> --expression=<OQL Query> --query=<phrasebook_id> [--arg_xxx=<query_arguments>] [--no_localize=0|1] [--format=<format>] [--format-options...]');
  77. $oP->p("Parameters:");
  78. $oP->p(" * auth_user: the iTop user account for authentication");
  79. $oP->p(" * auth_pwd: the password of the iTop user account");
  80. }
  81. else
  82. {
  83. $oP->p("Parameters:");
  84. }
  85. $oP->p(" * expression: an OQL expression (e.g. SELECT Contact WHERE name LIKE 'm%')");
  86. $oP->p(" * query: (alternative to 'expression') the id of an entry from the query phrasebook");
  87. if (Utils::IsModeCLI())
  88. {
  89. $oP->p(" * with_archive: (optional, defaults to 0) if set to 1 then the result set will include archived objects");
  90. }
  91. else
  92. {
  93. $oP->p(" * with_archive: (optional, defaults to the current mode) if set to 1 then the result set will include archived objects");
  94. }
  95. $oP->p(" * arg_xxx: (needed if the query has parameters) the value of the parameter 'xxx'");
  96. $aSupportedFormats = BulkExport::FindSupportedFormats();
  97. $oP->p(" * format: (optional, default is html) the desired output format. Can be one of '".implode("', '", array_keys($aSupportedFormats))."'");
  98. foreach($aSupportedFormats as $sFormatCode => $sLabel)
  99. {
  100. $oExporter = BulkExport::FindExporter($sFormatCode);
  101. if ($oExporter !== null)
  102. {
  103. if (!Utils::IsModeCLI())
  104. {
  105. $oP->add('<hr/>');
  106. }
  107. $oExporter->DisplayUsage($oP);
  108. if (!Utils::IsModeCLI())
  109. {
  110. $oP->add('</div>');
  111. }
  112. }
  113. }
  114. if (!Utils::IsModeCLI())
  115. {
  116. //$oP->add('</pre>');
  117. }
  118. }
  119. function DisplayExpressionForm(WebPage $oP, $sAction, $sExpression = '', $sExceptionMessage = '')
  120. {
  121. $oP->add('<fieldset><legend>'.Dict::S('Core:BulkExport:ScopeDefinition').'</legend>');
  122. $oP->add('<form id="export-form" action="'.$sAction.'" method="post">');
  123. $oP->add('<input type="hidden" name="interactive" value="1">');
  124. $oP->add('<table style="width:100%" class="export_parameters">');
  125. $sExpressionHint = empty($sExceptionMessage) ? '' : '<tr><td colspan="2">'.htmlentities($sExceptionMessage, ENT_QUOTES, 'UTF-8').'</td></tr>';
  126. $oP->add('<tr><td class="column-label"><span style="white-space: nowrap;"><input type="radio" name="query_mode" value="oql" id="radio_oql" checked><label for="radio_oql">'.Dict::S('Core:BulkExportLabelOQLExpression').'</label></span></td>');
  127. $oP->add('<td><textarea style="width:100%" cols="70" rows="8" name="expression" id="textarea_oql" placeholder="'.Dict::S('Core:BulkExportQueryPlaceholder').'">'.htmlentities($sExpression, ENT_QUOTES, 'UTF-8').'</textarea></td></tr>');
  128. $oP->add($sExpressionHint);
  129. $oP->add('<tr><td class="column-label"><span style="white-space: nowrap;"><input type="radio" name="query_mode" value="phrasebook" id="radio_phrasebook"><label for="radio_phrasebook">'.Dict::S('Core:BulkExportLabelPhrasebookEntry').'</label></span></td>');
  130. $oP->add('<td><select name="query" id="select_phrasebook">');
  131. $oP->add('<option value="">'.Dict::S('UI:SelectOne').'</option>');
  132. $oSearch = DBObjectSearch::FromOQL('SELECT QueryOQL');
  133. $oQueries = new DBObjectSet($oSearch);
  134. while ($oQuery = $oQueries->Fetch())
  135. {
  136. $oP->add('<option value="'.$oQuery->GetKey().'">'.htmlentities($oQuery->Get('name'), ENT_QUOTES, 'UTF-8').'</option>');
  137. }
  138. $oP->add('</select></td></tr>');
  139. $oP->add('<tr><td colspan="2" style="text-align:right"><button type="submit" id="next-btn">'.Dict::S('UI:Button:Next').'</button></td></tr>');
  140. $oP->add('</table>');
  141. $oP->add('</form>');
  142. $oP->add('</fieldset>');
  143. $oP->p('<a target="_blank" href="'.utils::GetAbsoluteUrlAppRoot().'webservices/export-v2.php">'.Dict::S('Core:BulkExportCanRunNonInteractive').'</a>');
  144. $oP->p('<a target="_blank" href="'.utils::GetAbsoluteUrlAppRoot().'webservices/export.php">'.Dict::S('Core:BulkExportLegacyExport').'</a>');
  145. $sJSEmptyOQL = json_encode(Dict::S('Core:BulkExportMessageEmptyOQL'));
  146. $sJSEmptyQueryId = json_encode(Dict::S('Core:BulkExportMessageEmptyPhrasebookEntry'));
  147. $oP->add_ready_script(
  148. <<<EOF
  149. var colWidth = 0;
  150. $('td.column-label').each(function() {
  151. var jLabel = $(this).find('span');
  152. colWidth = Math.max(colWidth, jLabel.width());
  153. });
  154. $('td.column-label').each(function() {
  155. var jLabel = $(this).width(colWidth);
  156. });
  157. $('#textarea_oql').on('change keyup', function() {
  158. $('#radio_oql').prop('checked', true);
  159. });
  160. $('#select_phrasebook').on('change', function() {
  161. $('#radio_phrasebook').prop('checked', true);
  162. });
  163. $('#export-form').on('submit', function() {
  164. if ($('#radio_oql').prop('checked'))
  165. {
  166. var sOQL = $('#textarea_oql').val();
  167. if (sOQL == '')
  168. {
  169. alert($sJSEmptyOQL);
  170. return false;
  171. }
  172. }
  173. else
  174. {
  175. var sQueryId = $('#select_phrasebook').val();
  176. if (sQueryId == '')
  177. {
  178. alert($sJSEmptyQueryId);
  179. return false;
  180. }
  181. }
  182. return true;
  183. });
  184. EOF
  185. );
  186. }
  187. function DisplayForm(WebPage $oP, $sAction = '', $sExpression = '', $sQueryId = '', $sFormat = null)
  188. {
  189. $oExportSearch = null;
  190. $oP->add_script(DateTimeFormat::GetJSSQLToCustomFormat());
  191. $sJSDefaultDateTimeFormat = json_encode((string)AttributeDateTime::GetFormat());
  192. $oP->add_script(
  193. <<<EOF
  194. function FormatDatesInPreview(sRadioSelector, sPreviewSelector)
  195. {
  196. if ($('#'+sRadioSelector+'_date_time_format_default').prop('checked'))
  197. {
  198. sPHPFormat = $sJSDefaultDateTimeFormat;
  199. }
  200. else
  201. {
  202. sPHPFormat = $('#'+sRadioSelector+'_custom_date_time_format').val();
  203. }
  204. $('#interactive_fields_'+sPreviewSelector+' .user-formatted-date-time').each(function() {
  205. var val = $(this).attr('data-date');
  206. var sDisplay = DateTimeFormatFromPHP(val, sPHPFormat);
  207. $(this).html(sDisplay);
  208. });
  209. $('#interactive_fields_'+sPreviewSelector+' .user-formatted-date').each(function() {
  210. var val = $(this).attr('data-date');
  211. var sDisplay = DateFormatFromPHP(val, sPHPFormat);
  212. $(this).html(sDisplay);
  213. });
  214. }
  215. EOF
  216. );
  217. $oP->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/tabularfieldsselector.js');
  218. $oP->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/jquery.dragtable.js');
  219. $oP->add_linked_stylesheet(utils::GetAbsoluteUrlAppRoot().'css/dragtable.css');
  220. $oP->add('<form id="export-form" action="'.$sAction.'" method="post" data-state="not-yet-started">');
  221. $bExpressionIsValid = true;
  222. $sExpressionError = '';
  223. if (($sExpression === null) && ($sQueryId === null))
  224. {
  225. $bExpressionIsValid = false;
  226. }
  227. else if ($sExpression !== '')
  228. {
  229. try
  230. {
  231. $oExportSearch = DBObjectSearch::FromOQL($sExpression);
  232. }
  233. catch(OQLException $e)
  234. {
  235. $bExpressionIsValid = false;
  236. $sExpressionError = $e->getMessage();
  237. }
  238. }
  239. if (!$bExpressionIsValid)
  240. {
  241. DisplayExpressionForm($oP, $sAction, $sExpression, $sExpressionError);
  242. return;
  243. }
  244. if ($sExpression !== '')
  245. {
  246. $oP->add('<input type="hidden" name="expression" value="'.htmlentities($sExpression, ENT_QUOTES, 'UTF-8').'">');
  247. $oExportSearch = DBObjectSearch::FromOQL($sExpression);
  248. }
  249. else
  250. {
  251. $oQuery = MetaModel::GetObject('QueryOQL', $sQueryId);
  252. $oExportSearch = DBObjectSearch::FromOQL($oQuery->Get('oql'));
  253. $oP->add('<input type="hidden" name="query" value="'.htmlentities($sQueryId, ENT_QUOTES, 'UTF-8').'">');
  254. }
  255. $aFormPartsByFormat = array();
  256. $aAllFormParts = array();
  257. if ($sFormat == null)
  258. {
  259. // No specific format chosen
  260. $sDefaultFormat = utils::ReadParam('format', 'xlsx');
  261. $oP->add('<p>'.Dict::S('Core:BulkExport:ExportFormatPrompt').' <select name="format" id="format_selector">');
  262. $aSupportedFormats = BulkExport::FindSupportedFormats();
  263. asort($aSupportedFormats);
  264. foreach($aSupportedFormats as $sFormatCode => $sLabel)
  265. {
  266. $sSelected = ($sFormatCode == $sDefaultFormat) ? 'selected' : '';
  267. $oP->add('<option value="'.$sFormatCode.'" '.$sSelected.'>'.htmlentities($sLabel, ENT_QUOTES, 'UTF-8').'</option>');
  268. $oExporter = BulkExport::FindExporter($sFormatCode);
  269. $oExporter->SetObjectList($oExportSearch);
  270. $aParts = $oExporter->EnumFormParts();
  271. foreach($aParts as $sPartId => $void)
  272. {
  273. $aAllFormParts[$sPartId] = $oExporter;
  274. }
  275. $aFormPartsByFormat[$sFormatCode] = array_keys($aParts);
  276. }
  277. $oP->add('</select></p>');
  278. }
  279. else
  280. {
  281. // One specific format was chosen
  282. $oP->add('<input type="hidden" name="format" value="'.htmlentities($sFormat, ENT_QUOTES, 'UTF-8').'">');
  283. $oExporter = BulkExport::FindExporter($sFormat, $oExportSearch);
  284. $aParts = $oExporter->EnumFormParts();
  285. foreach($aParts as $sPartId => $void)
  286. {
  287. $aAllFormParts[$sPartId] = $oExporter;
  288. }
  289. $aFormPartsByFormat[$sFormat] = array_keys($aAllFormParts);
  290. }
  291. foreach($aAllFormParts as $sPartId => $oExport)
  292. {
  293. $oP->add('<div class="form_part" id="form_part_'.$sPartId.'">');
  294. $oExport->DisplayFormPart($oP, $sPartId);
  295. $oP->add('</div>');
  296. }
  297. $oP->add('</form>');
  298. $oP->add('<div id="export-feedback" style="display:none;"><p class="export-message" style="text-align:center;">'.Dict::S('ExcelExport:PreparingExport').'</p><div class="export-progress-bar" style="max-width:30em; margin-left:auto;margin-right:auto;"><div class="export-progress-message" style="text-align:center;"></div></div></div>');
  299. $oP->add('<button type="button" id="export-btn">'.Dict::S('UI:Button:Export').'</button>');
  300. $oP->add('<div id="export_text_result" style="display:none;">');
  301. $oP->add('<div>'.Dict::S('Core:BulkExport:ExportResult').'</div>');
  302. $oP->add('<textarea id="export_content" style="width:100%;min-height:15em;"></textarea>');
  303. $oP->add('</div>');
  304. $sJSParts = json_encode($aFormPartsByFormat);
  305. $sJSCancel = json_encode(Dict::S('UI:Button:Cancel'));
  306. $sJSClose = json_encode(Dict::S('UI:Button:Done'));
  307. $oP->add_ready_script(
  308. <<<EOF
  309. window.aFormParts = $sJSParts;
  310. $('#format_selector').on('change init', function() {
  311. ExportToggleFormat($(this).val());
  312. }).trigger('init');
  313. $('.export-progress-bar').progressbar({
  314. value: 0,
  315. change: function() {
  316. $('.export-progress-message').text( $(this).progressbar( "value" ) + "%" );
  317. },
  318. complete: function() {
  319. $('.export-progress-message').text( '100 %' );
  320. }
  321. });
  322. ExportInitButton('#export-btn');
  323. EOF
  324. );
  325. }
  326. function InteractiveShell($sExpression, $sQueryId, $sFormat, $sFileName, $sMode)
  327. {
  328. if ($sMode == 'dialog')
  329. {
  330. $oP = new ajax_page('');
  331. $oP->add('<div id="interactive_export_dlg">');
  332. $sExportBtnLabel = json_encode(Dict::S('UI:Button:Export'));
  333. $sJSTitle = json_encode(htmlentities(utils::ReadParam('dialog_title', '', false, 'raw_data'), ENT_QUOTES, 'UTF-8'));
  334. $oP->add_ready_script(
  335. <<<EOF
  336. $('#interactive_export_dlg').dialog({
  337. autoOpen: true,
  338. modal: true,
  339. width: '80%',
  340. title: $sJSTitle,
  341. close: function() { $('#export-form').attr('data-state', 'cancelled'); $(this).remove(); },
  342. buttons: [
  343. {text: $sExportBtnLabel, id: 'export-dlg-submit', click: function() {} }
  344. ]
  345. });
  346. setTimeout(function() { $('#interactive_export_dlg').dialog('option', { position: { my: "center", at: "center", of: window }}); $('#export-btn').hide(); ExportInitButton('#export-dlg-submit'); }, 100);
  347. EOF
  348. );
  349. }
  350. else
  351. {
  352. $oP = new iTopWebPage('iTop Export');
  353. $oP->SetBreadCrumbEntry('ui-tool-export', Dict::S('Menu:ExportMenu'), Dict::S('Menu:ExportMenu+'), '', utils::GetAbsoluteUrlAppRoot().'images/wrench.png');
  354. }
  355. if ($sExpression === null)
  356. {
  357. // No expression supplied, let's check if phrasebook entry is given
  358. if ($sQueryId !== null)
  359. {
  360. $oSearch = DBObjectSearch::FromOQL('SELECT QueryOQL WHERE id = :query_id', array('query_id' => $sQueryId));
  361. $oQueries = new DBObjectSet($oSearch);
  362. if ($oQueries->Count() > 0)
  363. {
  364. $oQuery = $oQueries->Fetch();
  365. $sExpression = $oQuery->Get('oql');
  366. $sFields = trim($oQuery->Get('fields'));
  367. }
  368. else
  369. {
  370. ReportErrorAndExit("Invalid query phrasebook identifier: '$sQueryId'");
  371. }
  372. }
  373. else
  374. {
  375. if (utils::IsModeCLI())
  376. {
  377. Usage();
  378. ReportErrorAndExit("No expression or query phrasebook identifier supplied.");
  379. }
  380. else
  381. {
  382. // form to enter an OQL query or pick a query phrasebook identifier
  383. DisplayForm($oP, utils::GetAbsoluteUrlAppRoot().'webservices/export-v2.php', $sExpression, $sQueryId, $sFormat);
  384. $oP->output();
  385. exit;
  386. }
  387. }
  388. }
  389. if ($sFormat !== null)
  390. {
  391. $oExporter = BulkExport::FindExporter($sFormat);
  392. if ($oExporter === null)
  393. {
  394. $aSupportedFormats = BulkExport::FindSupportedFormats();
  395. ReportErrorAndExit("Invalid output format: '$sFormat'. The supported formats are: ".implode(', ', array_keys($aSupportedFormats)));
  396. }
  397. else
  398. {
  399. DisplayForm($oP, utils::GetAbsoluteUrlAppRoot().'webservices/export-v2.php', $sExpression, $sQueryId, $sFormat);
  400. }
  401. }
  402. else
  403. {
  404. DisplayForm($oP, utils::GetAbsoluteUrlAppRoot().'webservices/export-v2.php', $sExpression, $sQueryId, $sFormat);
  405. }
  406. if ($sMode == 'dialog')
  407. {
  408. $oP->add('</div>');
  409. }
  410. $oP->output();
  411. }
  412. /**
  413. * Checks the parameters and returns the appropriate exporter (if any)
  414. * @param string $sExpression The OQL query to export or null
  415. * @param string $sQueryId The entry in the query phrasebook if $sExpression is null
  416. * @param string $sFormat The code of export format: csv, pdf, html, xlsx
  417. * @param boolean $bWithArchive
  418. * @throws MissingQueryArgument
  419. * @return Ambigous <iBulkExport, NULL>
  420. */
  421. function CheckParameters($sExpression, $sQueryId, $sFormat)
  422. {
  423. $oExporter = null;
  424. if (utils::IsArchiveMode() && !UserRights::CanBrowseArchive())
  425. {
  426. ReportErrorAndExit("The user account is not authorized to access the archives");
  427. }
  428. if (($sExpression === null) && ($sQueryId === null))
  429. {
  430. ReportErrorAndUsage("Missing parameter. The parameter 'expression' or 'query' must be specified.");
  431. }
  432. // Either $sExpression or $sQueryId must be specified
  433. if ($sExpression === null)
  434. {
  435. $oSearch = DBObjectSearch::FromOQL('SELECT QueryOQL WHERE id = :query_id', array('query_id' => $sQueryId));
  436. $oQueries = new DBObjectSet($oSearch);
  437. if ($oQueries->Count() > 0)
  438. {
  439. $oQuery = $oQueries->Fetch();
  440. $sExpression = $oQuery->Get('oql');
  441. $sFields = $oQuery->Get('fields');
  442. if (strlen($sFields) == 0)
  443. {
  444. $sFields = trim($oQuery->Get('fields'));
  445. }
  446. }
  447. else
  448. {
  449. ReportErrorAndExit("Invalid query phrasebook identifier: '$sQueryId'");
  450. }
  451. }
  452. if ($sFormat === null)
  453. {
  454. ReportErrorAndUsage("Missing parameter 'format'.");
  455. }
  456. // Check if the supplied query is valid (and all the parameters are supplied
  457. try
  458. {
  459. $oSearch = DBObjectSearch::FromOQL($sExpression);
  460. $aArgs = array();
  461. foreach($oSearch->GetQueryParams() as $sParam => $foo)
  462. {
  463. $value = utils::ReadParam('arg_'.$sParam, null, true, 'raw_data');
  464. if (!is_null($value))
  465. {
  466. $aArgs[$sParam] = $value;
  467. }
  468. else
  469. {
  470. throw new MissingQueryArgument("Missing parameter '--arg_$sParam'");
  471. }
  472. }
  473. $oSearch->SetInternalParams($aArgs);
  474. $sFormat = utils::ReadParam('format', 'html', true /* Allow CLI */, 'raw_data');
  475. $oExporter = BulkExport::FindExporter($sFormat, $oSearch);
  476. if ($oExporter == null)
  477. {
  478. $aSupportedFormats = BulkExport::FindSupportedFormats();
  479. ReportErrorAndExit("Invalid output format: '$sFormat'. The supported formats are: ".implode(', ', array_keys($aSupportedFormats)));
  480. }
  481. }
  482. catch(MissingQueryArgument $e)
  483. {
  484. ReportErrorAndUsage("Invalid OQL query: '$sExpression'.\n".$e->getMessage());
  485. }
  486. catch(OQLException $e)
  487. {
  488. ReportErrorAndExit("Invalid OQL query: '$sExpression'.\n".$e->getMessage());
  489. }
  490. catch(Exception $e)
  491. {
  492. ReportErrorAndExit($e->getMessage());
  493. }
  494. $oExporter->SetFormat($sFormat);
  495. $oExporter->SetChunkSize(EXPORTER_DEFAULT_CHUNK_SIZE);
  496. $oExporter->SetObjectList($oSearch);
  497. $oExporter->ReadParameters();
  498. return $oExporter;
  499. }
  500. function DoExport(WebPage $oP, BulkExport $oExporter, $bInteractive = false)
  501. {
  502. $oExporter->SetHttpHeaders($oP);
  503. $exportResult = $oExporter->GetHeader();
  504. $aStatus = array();
  505. do
  506. {
  507. $exportResult .= $oExporter->GetNextChunk($aStatus);
  508. }
  509. while (($aStatus['code'] != 'done') && ($aStatus['code'] != 'error'));
  510. if ($aStatus['code'] == 'error')
  511. {
  512. $oExporter->Cleanup();
  513. ReportErrorAndExit("Export failed: '{$aStatus['message']}'");
  514. }
  515. else
  516. {
  517. $exportResult .= $oExporter->GetFooter();
  518. $sMimeType = $oExporter->GetMimeType();
  519. if (substr($sMimeType, 0, 5) == 'text/')
  520. {
  521. $sMimeType .= ';charset='.strtolower($oExporter->GetCharacterSet());
  522. }
  523. $oP->SetContentType($sMimeType);
  524. $oP->SetContentDisposition('attachment', $oExporter->GetDownloadFileName());
  525. $oP->add($exportResult);
  526. $oExporter->Cleanup();
  527. }
  528. }
  529. /////////////////////////////////////////////////////////////////////////////
  530. //
  531. // Command Line mode
  532. //
  533. /////////////////////////////////////////////////////////////////////////////
  534. if (utils::IsModeCLI())
  535. {
  536. try
  537. {
  538. // Do this before loging, in order to allow setting user credentials from within the file
  539. utils::UseParamFile();
  540. }
  541. catch(Exception $e)
  542. {
  543. echo "Error: ".$e->GetMessage()."<br/>\n";
  544. exit -2;
  545. }
  546. $sAuthUser = utils::ReadParam('auth_user', null, true /* Allow CLI */, 'raw_data');
  547. $sAuthPwd = utils::ReadParam('auth_pwd', null, true /* Allow CLI */, 'raw_data');
  548. if ($sAuthUser == null)
  549. {
  550. ReportErrorAndUsage("Missing parameter '--auth_user'");
  551. }
  552. if ($sAuthPwd == null)
  553. {
  554. ReportErrorAndUsage("Missing parameter '--auth_pwd'");
  555. }
  556. if (UserRights::CheckCredentials($sAuthUser, $sAuthPwd))
  557. {
  558. UserRights::Login($sAuthUser); // Login & set the user's language
  559. }
  560. else
  561. {
  562. ReportErrorAndExit("Access restricted or wrong credentials for user '$sAuthUser'");
  563. }
  564. $sExpression = utils::ReadParam('expression', null, true /* Allow CLI */, 'raw_data');
  565. $sQueryId = utils::ReadParam('query', null, true /* Allow CLI */, 'raw_data');
  566. $bLocalize = (utils::ReadParam('no_localize', 0) != 1);
  567. if (utils::IsArchiveMode() && !UserRights::CanBrowseArchive())
  568. {
  569. ReportErrorAndExit("The user account is not authorized to access the archives");
  570. }
  571. if (($sExpression == null) && ($sQueryId == null))
  572. {
  573. ReportErrorAndUsage("Missing parameter. At least one of '--expression' or '--query' must be specified.");
  574. }
  575. if ($sExpression === null)
  576. {
  577. $oSearch = DBObjectSearch::FromOQL('SELECT QueryOQL WHERE id = :query_id', array('query_id' => $sQueryId));
  578. $oQueries = new DBObjectSet($oSearch);
  579. if ($oQueries->Count() > 0)
  580. {
  581. $oQuery = $oQueries->Fetch();
  582. $sExpression = $oQuery->Get('oql');
  583. }
  584. else
  585. {
  586. ReportErrorAndExit("Invalid query phrasebook identifier: '$sQueryId'");
  587. }
  588. }
  589. try
  590. {
  591. $oSearch = DBObjectSearch::FromOQL($sExpression);
  592. $aArgs = array();
  593. foreach($oSearch->GetQueryParams() as $sParam => $foo)
  594. {
  595. $value = utils::ReadParam('arg_'.$sParam, null, true, 'raw_data');
  596. if (!is_null($value))
  597. {
  598. $aArgs[$sParam] = $value;
  599. }
  600. else
  601. {
  602. throw new MissingQueryArgument("Missing parameter '--arg_$sParam'");
  603. }
  604. }
  605. $oSearch->SetInternalParams($aArgs);
  606. $sFormat = utils::ReadParam('format', 'html', true /* Allow CLI */, 'raw_data');
  607. $oExporter = BulkExport::FindExporter($sFormat);
  608. if ($oExporter == null)
  609. {
  610. $aSupportedFormats = BulkExport::FindSupportedFormats();
  611. ReportErrorAndExit("Invalid output format: '$sFormat'. The supported formats are: ".implode(', ', array_keys($aSupportedFormats)));
  612. }
  613. $oExporter->SetFormat($sFormat);
  614. $oExporter->SetChunkSize(EXPORTER_DEFAULT_CHUNK_SIZE);
  615. $oExporter->SetObjectList($oSearch);
  616. $oExporter->ReadParameters();
  617. $exportResult = $oExporter->GetHeader();
  618. $aStatus = array();
  619. do
  620. {
  621. $exportResult .= $oExporter->GetNextChunk($aStatus);
  622. }
  623. while (($aStatus['code'] != 'done') && ($aStatus['code'] != 'error'));
  624. if ($aStatus['code'] == 'error')
  625. {
  626. ReportErrorAndExit("Export failed: '{$aStatus['message']}'");
  627. }
  628. else
  629. {
  630. $exportResult .= $oExporter->GetFooter();
  631. echo $exportResult;
  632. }
  633. $oExporter->Cleanup();
  634. }
  635. catch(MissingQueryArgument $e)
  636. {
  637. ReportErrorAndUsage("Invalid OQL query: '$sExpression'.\n".$e->getMessage());
  638. }
  639. catch(OQLException $e)
  640. {
  641. ReportErrorAndExit("Invalid OQL query: '$sExpression'.\n".$e->getMessage());
  642. }
  643. catch(Exception $e)
  644. {
  645. ReportErrorAndExit($e->getMessage());
  646. }
  647. exit;
  648. }
  649. /////////////////////////////////////////////////////////////////////////////
  650. //
  651. // Web Server mode
  652. //
  653. /////////////////////////////////////////////////////////////////////////////
  654. try
  655. {
  656. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  657. // Main parameters
  658. $sExpression = utils::ReadParam('expression', null, true /* Allow CLI */, 'raw_data');
  659. $sQueryId = utils::ReadParam('query', null, true /* Allow CLI */, 'raw_data');
  660. $sFormat = utils::ReadParam('format', null, true /* Allow CLI */);
  661. $sFileName = utils::ReadParam('filename', '', true, 'string');
  662. $bInteractive = utils::ReadParam('interactive', false);
  663. $sMode = utils::ReadParam('mode', '');
  664. LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  665. ApplicationContext::SetUrlMakerClass('iTopStandardURLMaker');
  666. if ($bInteractive)
  667. {
  668. InteractiveShell($sExpression, $sQueryId, $sFormat, $sFileName, $sMode);
  669. }
  670. else
  671. {
  672. $oExporter = CheckParameters($sExpression, $sQueryId, $sFormat);
  673. $sMimeType = $oExporter->GetMimeType();
  674. if ($sMimeType == 'text/html')
  675. {
  676. $oP = new NiceWebPage('iTop export');
  677. $oP->add_style("body { overflow: auto; }");
  678. $oP->add_ready_script("$('table.listResults').tablesorter({widgets: ['MyZebra']});");
  679. }
  680. else
  681. {
  682. $oP = new ajax_page('iTop export');
  683. $oP->SetContentType($oExporter->GetMimeType());
  684. }
  685. DoExport($oP, $oExporter, false);
  686. $oP->output();
  687. }
  688. }
  689. catch (BulkExportMissingParameterException $e)
  690. {
  691. $oP = new ajax_page('iTop Export');
  692. $oP->add($e->getMessage());
  693. Usage($oP);
  694. $oP->output();
  695. }
  696. catch (Exception $e)
  697. {
  698. $oP = new WebPage('iTop Export');
  699. $oP->add('Error: '.$e->getMessage());
  700. IssueLog::Error($e->getMessage()."\n".$e->getTraceAsString());
  701. $oP->output();
  702. }