export-v2.php 20 KB

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