export-v2.php 23 KB

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