bulkexport.class.inc.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. $oResult->DBDelete();
  105. }
  106. return "Cleaned $iProcessed old export results(s).";
  107. }
  108. }
  109. /**
  110. * Class BulkExport
  111. *
  112. * @copyright Copyright (C) 2015 Combodo SARL
  113. * @license http://opensource.org/licenses/AGPL-3.0
  114. */
  115. abstract class BulkExport
  116. {
  117. protected $oSearch;
  118. protected $iChunkSize;
  119. protected $sFormatCode;
  120. protected $aStatusInfo;
  121. protected $oBulkExportResult;
  122. protected $sTmpFile;
  123. protected $bLocalizeOutput;
  124. public function __construct()
  125. {
  126. $this->oSearch = null;
  127. $this->iChunkSize = 0;
  128. $this->sFormatCode = null;
  129. $this->aStatusInfo = array();
  130. $this->oBulkExportResult = null;
  131. $this->sTmpFile = '';
  132. $this->bLocalizeOutput = false;
  133. }
  134. /**
  135. * Find the first class capable of exporting the data in the given format
  136. * @param string $sFormat The lowercase format (e.g. html, csv, spreadsheet, xlsx, xml, json, pdf...)
  137. * @param DBSearch $oSearch The search/filter defining the set of objects to export or null when listing the supported formats
  138. * @return iBulkExport|NULL
  139. */
  140. static public function FindExporter($sFormatCode, $oSearch = null)
  141. {
  142. foreach(get_declared_classes() as $sPHPClass)
  143. {
  144. $oRefClass = new ReflectionClass($sPHPClass);
  145. if ($oRefClass->isSubclassOf('BulkExport') && !$oRefClass->isAbstract())
  146. {
  147. $oBulkExporter = new $sPHPClass();
  148. if ($oBulkExporter->IsFormatSupported($sFormatCode, $oSearch))
  149. {
  150. if ($oSearch)
  151. {
  152. $oBulkExporter->SetObjectList($oSearch);
  153. }
  154. return $oBulkExporter;
  155. }
  156. }
  157. }
  158. return null;
  159. }
  160. /**
  161. * Find the exporter corresponding to the given persistent token
  162. * @param int $iPersistentToken The identifier of the BulkExportResult object storing the information
  163. * @return iBulkExport|NULL
  164. */
  165. static public function FindExporterFromToken($iPersistentToken = null)
  166. {
  167. $oBulkExporter = null;
  168. $oInfo = MetaModel::GetObject('BulkExportResult', $iPersistentToken, false);
  169. if ($oInfo && ($oInfo->Get('user_id') == UserRights::GetUserId()))
  170. {
  171. $sFormatCode = $oInfo->Get('format');
  172. $oSearch = DBObjectSearch::unserialize($oInfo->Get('search'));
  173. $oBulkExporter = self::FindExporter($sFormatCode, $oSearch);
  174. if ($oBulkExporter)
  175. {
  176. $oBulkExporter->SetFormat($sFormatCode);
  177. $oBulkExporter->SetObjectList($oSearch);
  178. $oBulkExporter->SetChunkSize($oInfo->Get('chunk_size'));
  179. $oBulkExporter->SetStatusInfo(json_decode($oInfo->Get('status_info'), true));
  180. $oBulkExporter->sTmpFile = $oInfo->Get('temp_file_path');
  181. $oBulkExporter->oBulkExportResult = $oInfo;
  182. }
  183. }
  184. return $oBulkExporter;
  185. }
  186. public function AppendToTmpFile($data)
  187. {
  188. if ($this->sTmpFile == '')
  189. {
  190. $this->sTmpFile = $this->MakeTmpFile($this->GetFileExtension());
  191. }
  192. $hFile = fopen($this->sTmpFile, 'ab');
  193. if ($hFile !== false)
  194. {
  195. fwrite($hFile, $data);
  196. fclose($hFile);
  197. }
  198. }
  199. public function GetTmpFilePath()
  200. {
  201. return $this->sTmpFile;
  202. }
  203. /**
  204. * Lists all possible export formats. The output is a hash array in the form: 'format_code' => 'localized format label'
  205. * @return multitype:string
  206. */
  207. static public function FindSupportedFormats()
  208. {
  209. $aSupportedFormats = array();
  210. foreach(get_declared_classes() as $sPHPClass)
  211. {
  212. $oRefClass = new ReflectionClass($sPHPClass);
  213. if ($oRefClass->isSubClassOf('BulkExport') && !$oRefClass->isAbstract())
  214. {
  215. $oBulkExporter = new $sPHPClass;
  216. $aFormats = $oBulkExporter->GetSupportedFormats();
  217. $aSupportedFormats = array_merge($aSupportedFormats, $aFormats);
  218. }
  219. }
  220. return $aSupportedFormats;
  221. }
  222. /**
  223. * (non-PHPdoc)
  224. * @see iBulkExport::SetChunkSize()
  225. */
  226. public function SetChunkSize($iChunkSize)
  227. {
  228. $this->iChunkSize = $iChunkSize;
  229. }
  230. /**
  231. * (non-PHPdoc)
  232. * @see iBulkExport::SetObjectList()
  233. */
  234. public function SetObjectList(DBSearch $oSearch)
  235. {
  236. $this->oSearch = $oSearch;
  237. }
  238. public function SetFormat($sFormatCode)
  239. {
  240. $this->sFormatCode = $sFormatCode;
  241. }
  242. /**
  243. * (non-PHPdoc)
  244. * @see iBulkExport::IsFormatSupported()
  245. */
  246. public function IsFormatSupported($sFormatCode, $oSearch = null)
  247. {
  248. return array_key_exists($sFormatCode, $this->GetSupportedFormats());
  249. }
  250. /**
  251. * (non-PHPdoc)
  252. * @see iBulkExport::GetSupportedFormats()
  253. */
  254. public function GetSupportedFormats()
  255. {
  256. return array(); // return array('csv' => Dict::S('UI:ExportFormatCSV'));
  257. }
  258. public function SetHttpHeaders(WebPage $oPage)
  259. {
  260. }
  261. public function GetHeader()
  262. {
  263. }
  264. abstract public function GetNextChunk(&$aStatus);
  265. public function GetFooter()
  266. {
  267. }
  268. public function SaveState()
  269. {
  270. if ($this->oBulkExportResult === null)
  271. {
  272. $this->oBulkExportResult = new BulkExportResult();
  273. $this->oBulkExportResult->Set('format', $this->sFormatCode);
  274. $this->oBulkExportResult->Set('search', $this->oSearch->serialize());
  275. $this->oBulkExportResult->Set('chunk_size', $this->iChunkSize);
  276. $this->oBulkExportResult->Set('temp_file_path', $this->sTmpFile);
  277. }
  278. $this->oBulkExportResult->Set('status_info', json_encode($this->GetStatusInfo()));
  279. return $this->oBulkExportResult->DBWrite();
  280. }
  281. public function Cleanup()
  282. {
  283. if (($this->oBulkExportResult && (!$this->oBulkExportResult->IsNew())))
  284. {
  285. $sFilename = $this->oBulkExportResult->Get('temp_file_path');
  286. if ($sFilename != '')
  287. {
  288. @unlink($sFilename);
  289. }
  290. $this->oBulkExportResult->DBDelete();
  291. }
  292. }
  293. public function EnumFormParts()
  294. {
  295. return array();
  296. }
  297. public function DisplayFormPart(WebPage $oP, $sPartId)
  298. {
  299. }
  300. public function DisplayUsage(Page $oP)
  301. {
  302. }
  303. public function ReadParameters()
  304. {
  305. $this->bLocalizeOutput = !((bool)utils::ReadParam('no_localize', 0, true, 'integer'));
  306. }
  307. public function GetResultAsHtml()
  308. {
  309. }
  310. public function GetRawResult()
  311. {
  312. }
  313. public function GetMimeType()
  314. {
  315. }
  316. public function GetFileExtension()
  317. {
  318. }
  319. public function GetCharacterSet()
  320. {
  321. return 'UTF-8';
  322. }
  323. public function GetStatistics()
  324. {
  325. }
  326. public function GetDownloadFileName()
  327. {
  328. return Dict::Format('Core:BulkExportOf_Class', MetaModel::GetName($this->oSearch->GetClass())).'.'.$this->GetFileExtension();
  329. }
  330. public function SetStatusInfo($aStatusInfo)
  331. {
  332. $this->aStatusInfo = $aStatusInfo;
  333. }
  334. public function GetStatusInfo()
  335. {
  336. return $this->aStatusInfo;
  337. }
  338. protected function MakeTmpFile($sExtension)
  339. {
  340. if(!is_dir(APPROOT."data/bulk_export"))
  341. {
  342. @mkdir(APPROOT."data/bulk_export", 0777, true /* recursive */);
  343. clearstatcache();
  344. }
  345. if (!is_writable(APPROOT."data/bulk_export"))
  346. {
  347. throw new Exception('Data directory "'.APPROOT.'data/bulk_export" could not be written.');
  348. }
  349. $iNum = rand();
  350. $sFileName = '';
  351. do
  352. {
  353. $iNum++;
  354. $sToken = sprintf("%08x", $iNum);
  355. $sFileName = APPROOT."data/bulk_export/$sToken.".$sExtension;
  356. $hFile = @fopen($sFileName, 'x');
  357. }
  358. while($hFile === false);
  359. fclose($hFile);
  360. return $sFileName;
  361. }
  362. }
  363. // The built-in exports
  364. require_once(APPROOT.'core/tabularbulkexport.class.inc.php');
  365. require_once(APPROOT.'core/htmlbulkexport.class.inc.php');
  366. require_once(APPROOT.'core/pdfbulkexport.class.inc.php');
  367. require_once(APPROOT.'core/csvbulkexport.class.inc.php');
  368. require_once(APPROOT.'core/excelbulkexport.class.inc.php');
  369. require_once(APPROOT.'core/spreadsheetbulkexport.class.inc.php');
  370. require_once(APPROOT.'core/xmlbulkexport.class.inc.php');