bulkexport.class.inc.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. define('EXPORTER_DEFAULT_CHUNK_SIZE', 1000);
  19. class BulkExportException extends Exception
  20. {
  21. protected $sLocalizedMessage;
  22. public function __construct($message, $sLocalizedMessage, $code = null, $previous = null)
  23. {
  24. parent::__construct($message, $code, $previous);
  25. $this->sLocalizedMessage = $sLocalizedMessage;
  26. }
  27. public function GetLocalizedMessage()
  28. {
  29. return $this->sLocalizedMessage;
  30. }
  31. }
  32. class BulkExportMissingParameterException extends BulkExportException
  33. {
  34. public function __construct($sFieldCode)
  35. {
  36. parent::__construct('Missing parameter: '.$sFieldCode, Dict::Format('Core:BulkExport:MissingParameter_Param', $sFieldCode));
  37. }
  38. }
  39. /**
  40. * Class BulkExport
  41. *
  42. * @copyright Copyright (C) 2015 Combodo SARL
  43. * @license http://opensource.org/licenses/AGPL-3.0
  44. */
  45. class BulkExportResult extends DBObject
  46. {
  47. public static function Init()
  48. {
  49. $aParams = array
  50. (
  51. "category" => 'core/cmdb',
  52. "key_type" => 'autoincrement',
  53. "name_attcode" => array('created'),
  54. "state_attcode" => '',
  55. "reconc_keys" => array(),
  56. "db_table" => 'priv_bulk_export_result',
  57. "db_key_field" => 'id',
  58. "db_finalclass_field" => '',
  59. "display_template" => '',
  60. );
  61. MetaModel::Init_Params($aParams);
  62. MetaModel::Init_AddAttribute(new AttributeDateTime("created", array("allowed_values"=>null, "sql"=>"created", "default_value"=>"", "is_null_allowed"=>false, "depends_on"=>array())));
  63. MetaModel::Init_AddAttribute(new AttributeInteger("user_id", array("allowed_values"=>null, "sql"=>"user_id", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  64. MetaModel::Init_AddAttribute(new AttributeInteger("chunk_size", array("allowed_values"=>null, "sql"=>"chunk_size", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
  65. MetaModel::Init_AddAttribute(new AttributeString("format", array("allowed_values"=>null, "sql"=>"format", "default_value"=>'', "is_null_allowed"=>false, "depends_on"=>array())));
  66. MetaModel::Init_AddAttribute(new AttributeString("temp_file_path", array("allowed_values"=>null, "sql"=>"temp_file_path", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
  67. MetaModel::Init_AddAttribute(new AttributeLongText("search", array("allowed_values"=>null, "sql"=>"search", "default_value"=>'', "is_null_allowed"=>false, "depends_on"=>array())));
  68. MetaModel::Init_AddAttribute(new AttributeLongText("status_info", array("allowed_values"=>null, "sql"=>"status_info", "default_value"=>'', "is_null_allowed"=>false, "depends_on"=>array())));
  69. }
  70. public function ComputeValues()
  71. {
  72. $this->Set('user_id', UserRights::GetUserId());
  73. }
  74. }
  75. /**
  76. * Garbage collector for cleaning "old" export results from the database and the disk.
  77. * This background process runs once per day and deletes the results of all exports which
  78. * are older than one day.
  79. */
  80. class BulkExportResultGC implements iBackgroundProcess
  81. {
  82. public function GetPeriodicity()
  83. {
  84. return 24*3600; // seconds
  85. }
  86. public function Process($iTimeLimit)
  87. {
  88. $sDateLimit = date(AttributeDateTime::GetSQLFormat(), time() - 24*3600); // Every BulkExportResult older than one day will be deleted
  89. $sOQL = "SELECT BulkExportResult WHERE created < '$sDateLimit'";
  90. $iProcessed = 0;
  91. while (time() < $iTimeLimit)
  92. {
  93. // Next one ?
  94. $oSet = new CMDBObjectSet(DBObjectSearch::FromOQL($sOQL), array('created' => true) /* order by*/, array(), null, 1 /* limit count */);
  95. $oSet->OptimizeColumnLoad(array('temp_file_path'));
  96. $oResult = $oSet->Fetch();
  97. if (is_null($oResult))
  98. {
  99. // Nothing to be done
  100. break;
  101. }
  102. $iProcessed++;
  103. @unlink($oResult->Get('temp_file_path'));
  104. utils::PushArchiveMode(false);
  105. $oResult->DBDelete();
  106. utils::PopArchiveMode();
  107. }
  108. return "Cleaned $iProcessed old export results(s).";
  109. }
  110. }
  111. /**
  112. * Class BulkExport
  113. *
  114. * @copyright Copyright (C) 2015 Combodo SARL
  115. * @license http://opensource.org/licenses/AGPL-3.0
  116. */
  117. abstract class BulkExport
  118. {
  119. protected $oSearch;
  120. protected $iChunkSize;
  121. protected $sFormatCode;
  122. protected $aStatusInfo;
  123. protected $oBulkExportResult;
  124. protected $sTmpFile;
  125. protected $bLocalizeOutput;
  126. public function __construct()
  127. {
  128. $this->oSearch = null;
  129. $this->iChunkSize = 0;
  130. $this->sFormatCode = null;
  131. $this->aStatusInfo = array();
  132. $this->oBulkExportResult = null;
  133. $this->sTmpFile = '';
  134. $this->bLocalizeOutput = false;
  135. }
  136. /**
  137. * Find the first class capable of exporting the data in the given format
  138. * @param string $sFormat The lowercase format (e.g. html, csv, spreadsheet, xlsx, xml, json, pdf...)
  139. * @param DBSearch $oSearch The search/filter defining the set of objects to export or null when listing the supported formats
  140. * @return iBulkExport|NULL
  141. */
  142. static public function FindExporter($sFormatCode, $oSearch = null)
  143. {
  144. foreach(get_declared_classes() as $sPHPClass)
  145. {
  146. $oRefClass = new ReflectionClass($sPHPClass);
  147. if ($oRefClass->isSubclassOf('BulkExport') && !$oRefClass->isAbstract())
  148. {
  149. $oBulkExporter = new $sPHPClass();
  150. if ($oBulkExporter->IsFormatSupported($sFormatCode, $oSearch))
  151. {
  152. if ($oSearch)
  153. {
  154. $oBulkExporter->SetObjectList($oSearch);
  155. }
  156. return $oBulkExporter;
  157. }
  158. }
  159. }
  160. return null;
  161. }
  162. /**
  163. * Find the exporter corresponding to the given persistent token
  164. * @param int $iPersistentToken The identifier of the BulkExportResult object storing the information
  165. * @return iBulkExport|NULL
  166. */
  167. static public function FindExporterFromToken($iPersistentToken = null)
  168. {
  169. $oBulkExporter = null;
  170. $oInfo = MetaModel::GetObject('BulkExportResult', $iPersistentToken, false);
  171. if ($oInfo && ($oInfo->Get('user_id') == UserRights::GetUserId()))
  172. {
  173. $sFormatCode = $oInfo->Get('format');
  174. $oSearch = DBObjectSearch::unserialize($oInfo->Get('search'));
  175. $oBulkExporter = self::FindExporter($sFormatCode, $oSearch);
  176. if ($oBulkExporter)
  177. {
  178. $oBulkExporter->SetFormat($sFormatCode);
  179. $oBulkExporter->SetObjectList($oSearch);
  180. $oBulkExporter->SetChunkSize($oInfo->Get('chunk_size'));
  181. $oBulkExporter->SetStatusInfo(json_decode($oInfo->Get('status_info'), true));
  182. $oBulkExporter->sTmpFile = $oInfo->Get('temp_file_path');
  183. $oBulkExporter->oBulkExportResult = $oInfo;
  184. }
  185. }
  186. return $oBulkExporter;
  187. }
  188. public function AppendToTmpFile($data)
  189. {
  190. if ($this->sTmpFile == '')
  191. {
  192. $this->sTmpFile = $this->MakeTmpFile($this->GetFileExtension());
  193. }
  194. $hFile = fopen($this->sTmpFile, 'ab');
  195. if ($hFile !== false)
  196. {
  197. fwrite($hFile, $data);
  198. fclose($hFile);
  199. }
  200. }
  201. public function GetTmpFilePath()
  202. {
  203. return $this->sTmpFile;
  204. }
  205. /**
  206. * Lists all possible export formats. The output is a hash array in the form: 'format_code' => 'localized format label'
  207. * @return multitype:string
  208. */
  209. static public function FindSupportedFormats()
  210. {
  211. $aSupportedFormats = array();
  212. foreach(get_declared_classes() as $sPHPClass)
  213. {
  214. $oRefClass = new ReflectionClass($sPHPClass);
  215. if ($oRefClass->isSubClassOf('BulkExport') && !$oRefClass->isAbstract())
  216. {
  217. $oBulkExporter = new $sPHPClass;
  218. $aFormats = $oBulkExporter->GetSupportedFormats();
  219. $aSupportedFormats = array_merge($aSupportedFormats, $aFormats);
  220. }
  221. }
  222. return $aSupportedFormats;
  223. }
  224. /**
  225. * (non-PHPdoc)
  226. * @see iBulkExport::SetChunkSize()
  227. */
  228. public function SetChunkSize($iChunkSize)
  229. {
  230. $this->iChunkSize = $iChunkSize;
  231. }
  232. /**
  233. * (non-PHPdoc)
  234. * @see iBulkExport::SetObjectList()
  235. */
  236. public function SetObjectList(DBSearch $oSearch)
  237. {
  238. $this->oSearch = $oSearch;
  239. }
  240. public function SetFormat($sFormatCode)
  241. {
  242. $this->sFormatCode = $sFormatCode;
  243. }
  244. /**
  245. * (non-PHPdoc)
  246. * @see iBulkExport::IsFormatSupported()
  247. */
  248. public function IsFormatSupported($sFormatCode, $oSearch = null)
  249. {
  250. return array_key_exists($sFormatCode, $this->GetSupportedFormats());
  251. }
  252. /**
  253. * (non-PHPdoc)
  254. * @see iBulkExport::GetSupportedFormats()
  255. */
  256. public function GetSupportedFormats()
  257. {
  258. return array(); // return array('csv' => Dict::S('UI:ExportFormatCSV'));
  259. }
  260. public function SetHttpHeaders(WebPage $oPage)
  261. {
  262. }
  263. public function GetHeader()
  264. {
  265. }
  266. abstract public function GetNextChunk(&$aStatus);
  267. public function GetFooter()
  268. {
  269. }
  270. public function SaveState()
  271. {
  272. if ($this->oBulkExportResult === null)
  273. {
  274. $this->oBulkExportResult = new BulkExportResult();
  275. $this->oBulkExportResult->Set('format', $this->sFormatCode);
  276. $this->oBulkExportResult->Set('search', $this->oSearch->serialize());
  277. $this->oBulkExportResult->Set('chunk_size', $this->iChunkSize);
  278. $this->oBulkExportResult->Set('temp_file_path', $this->sTmpFile);
  279. }
  280. $this->oBulkExportResult->Set('status_info', json_encode($this->GetStatusInfo()));
  281. utils::PushArchiveMode(false);
  282. $ret = $this->oBulkExportResult->DBWrite();
  283. utils::PopArchiveMode();
  284. return $ret;
  285. }
  286. public function Cleanup()
  287. {
  288. if (($this->oBulkExportResult && (!$this->oBulkExportResult->IsNew())))
  289. {
  290. $sFilename = $this->oBulkExportResult->Get('temp_file_path');
  291. if ($sFilename != '')
  292. {
  293. @unlink($sFilename);
  294. }
  295. utils::PushArchiveMode(false);
  296. $this->oBulkExportResult->DBDelete();
  297. utils::PopArchiveMode();
  298. }
  299. }
  300. public function EnumFormParts()
  301. {
  302. return array();
  303. }
  304. public function DisplayFormPart(WebPage $oP, $sPartId)
  305. {
  306. }
  307. public function DisplayUsage(Page $oP)
  308. {
  309. }
  310. public function ReadParameters()
  311. {
  312. $this->bLocalizeOutput = !((bool)utils::ReadParam('no_localize', 0, true, 'integer'));
  313. }
  314. public function GetResultAsHtml()
  315. {
  316. }
  317. public function GetRawResult()
  318. {
  319. }
  320. public function GetMimeType()
  321. {
  322. }
  323. public function GetFileExtension()
  324. {
  325. }
  326. public function GetCharacterSet()
  327. {
  328. return 'UTF-8';
  329. }
  330. public function GetStatistics()
  331. {
  332. }
  333. public function GetDownloadFileName()
  334. {
  335. return Dict::Format('Core:BulkExportOf_Class', MetaModel::GetName($this->oSearch->GetClass())).'.'.$this->GetFileExtension();
  336. }
  337. public function SetStatusInfo($aStatusInfo)
  338. {
  339. $this->aStatusInfo = $aStatusInfo;
  340. }
  341. public function GetStatusInfo()
  342. {
  343. return $this->aStatusInfo;
  344. }
  345. protected function MakeTmpFile($sExtension)
  346. {
  347. if(!is_dir(APPROOT."data/bulk_export"))
  348. {
  349. @mkdir(APPROOT."data/bulk_export", 0777, true /* recursive */);
  350. clearstatcache();
  351. }
  352. if (!is_writable(APPROOT."data/bulk_export"))
  353. {
  354. throw new Exception('Data directory "'.APPROOT.'data/bulk_export" could not be written.');
  355. }
  356. $iNum = rand();
  357. $sFileName = '';
  358. do
  359. {
  360. $iNum++;
  361. $sToken = sprintf("%08x", $iNum);
  362. $sFileName = APPROOT."data/bulk_export/$sToken.".$sExtension;
  363. $hFile = @fopen($sFileName, 'x');
  364. }
  365. while($hFile === false);
  366. fclose($hFile);
  367. return $sFileName;
  368. }
  369. }
  370. // The built-in exports
  371. require_once(APPROOT.'core/tabularbulkexport.class.inc.php');
  372. require_once(APPROOT.'core/htmlbulkexport.class.inc.php');
  373. if (extension_loaded('gd'))
  374. {
  375. // PDF export - via TCPDF - requires GD
  376. require_once(APPROOT.'core/pdfbulkexport.class.inc.php');
  377. }
  378. require_once(APPROOT.'core/csvbulkexport.class.inc.php');
  379. require_once(APPROOT.'core/excelbulkexport.class.inc.php');
  380. require_once(APPROOT.'core/spreadsheetbulkexport.class.inc.php');
  381. require_once(APPROOT.'core/xmlbulkexport.class.inc.php');