bulkexport.class.inc.php 11 KB

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