excelexporter.class.inc.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. <?php
  2. require_once('xlsxwriter.class.php');
  3. class ExcelExporter
  4. {
  5. protected $sToken;
  6. protected $aStatistics;
  7. protected $sState;
  8. protected $fStartTime;
  9. protected $oSearch;
  10. protected $aObjectsIDs;
  11. protected $aTableHeaders;
  12. protected $aAuthorizedClasses;
  13. protected $iChunkSize = 1000;
  14. protected $iPosition;
  15. protected $sOutputFilePath;
  16. protected $bAdvancedMode;
  17. public function __construct($sToken = null)
  18. {
  19. $this->aStatistics = array(
  20. 'objects_count' => 0,
  21. 'total_duration' => 0,
  22. 'data_retrieval_duration' => 0,
  23. 'excel_build_duration' => 0,
  24. 'excel_write_duration' => 0,
  25. 'peak_memory_usage' => 0,
  26. );
  27. $this->fStartTime = microtime(true);
  28. $this->oSearch = null;
  29. $this->sState = 'new';
  30. $this->aObjectsIDs = array();
  31. $this->iPosition = 0;
  32. $this->aAuthorizedClasses = null;
  33. $this->aTableHeaders = null;
  34. $this->sOutputFilePath = null;
  35. $this->bAdvancedMode = false;
  36. $this->CheckDataDir();
  37. if ($sToken == null)
  38. {
  39. $this->sToken = $this->GetNewToken();
  40. }
  41. else
  42. {
  43. $this->sToken = $sToken;
  44. $this->ReloadState();
  45. }
  46. }
  47. public function __destruct()
  48. {
  49. if (($this->sState != 'done') && ($this->sState != 'error') && ($this->sToken != null))
  50. {
  51. // Operation in progress, save the state
  52. $this->SaveState();
  53. }
  54. else
  55. {
  56. // Operation completed, cleanup the temp files
  57. @unlink($this->GetStateFile());
  58. @unlink($this->GetDataFile());
  59. }
  60. self::CleanupOldFiles();
  61. }
  62. public function SetChunkSize($iChunkSize)
  63. {
  64. $this->iChunkSize = $iChunkSize;
  65. }
  66. public function SetOutputFilePath($sDestFilePath)
  67. {
  68. $this->sOutputFilePath = $sDestFilePath;
  69. }
  70. public function SetAdvancedMode($bAdvanced)
  71. {
  72. $this->bAdvancedMode = $bAdvanced;
  73. }
  74. public function SaveState()
  75. {
  76. $aState = array(
  77. 'state' => $this->sState,
  78. 'statistics' => $this->aStatistics,
  79. 'filter' => $this->oSearch->serialize(),
  80. 'position' => $this->iPosition,
  81. 'chunk_size' => $this->iChunkSize,
  82. 'object_ids' => $this->aObjectsIDs,
  83. 'output_file_path' => $this->sOutputFilePath,
  84. 'advanced_mode' => $this->bAdvancedMode,
  85. );
  86. file_put_contents($this->GetStateFile(), json_encode($aState));
  87. return $this->sToken;
  88. }
  89. public function ReloadState()
  90. {
  91. if ($this->sToken == null)
  92. {
  93. throw new Exception('ExcelExporter not initialized with a token, cannot reload state');
  94. }
  95. if (!file_exists($this->GetStateFile()))
  96. {
  97. throw new Exception("ExcelExporter: missing status file '".$this->GetStateFile()."', cannot reload state.");
  98. }
  99. $sJson = file_get_contents($this->GetStateFile());
  100. $aState = json_decode($sJson, true);
  101. if ($aState === null)
  102. {
  103. throw new Exception("ExcelExporter:corrupted status file '".$this->GetStateFile()."', not a JSON, cannot reload state.");
  104. }
  105. $this->sState = $aState['state'];
  106. $this->aStatistics = $aState['statistics'];
  107. $this->oSearch = DBObjectSearch::unserialize($aState['filter']);
  108. $this->iPosition = $aState['position'];
  109. $this->iChunkSize = $aState['chunk_size'];
  110. $this->aObjectsIDs = $aState['object_ids'];
  111. $this->sOutputFilePath = $aState['output_file_path'];
  112. $this->bAdvancedMode = $aState['advanced_mode'];
  113. }
  114. public function SetObjectList($oSearch)
  115. {
  116. $this->oSearch = $oSearch;
  117. }
  118. public function Run()
  119. {
  120. $sCode = 'error';
  121. $iPercentage = 100;
  122. $sMessage = Dict::Format('ExcelExporter:ErrorUnexpected_State', $this->sState);
  123. $fTime = microtime(true);
  124. try
  125. {
  126. switch($this->sState)
  127. {
  128. case 'new':
  129. $oIDSet = new DBObjectSet($this->oSearch);
  130. $oIDSet->OptimizeColumnLoad(array('id'));
  131. $this->aObjectsIDs = array();
  132. while($oObj = $oIDSet->Fetch())
  133. {
  134. $this->aObjectsIDs[] = $oObj->GetKey();
  135. }
  136. $sCode = 'retrieving-data';
  137. $iPercentage = 5;
  138. $sMessage = Dict::S('ExcelExporter:RetrievingData');
  139. $this->iPosition = 0;
  140. $this->aStatistics['objects_count'] = count($this->aObjectsIDs);
  141. $this->aStatistics['data_retrieval_duration'] += microtime(true) - $fTime;
  142. // The first line of the file is the "headers" specifying the label and the type of each column
  143. $this->GetFieldsList($oIDSet, $this->bAdvancedMode);
  144. $sRow = json_encode($this->aTableHeaders);
  145. $hFile = @fopen($this->GetDataFile(), 'ab');
  146. if ($hFile === false)
  147. {
  148. throw new Exception('ExcelExporter: Failed to open temporary data file: "'.$this->GetDataFile().'" for writing.');
  149. }
  150. fwrite($hFile, $sRow."\n");
  151. fclose($hFile);
  152. // Next state
  153. $this->sState = 'retrieving-data';
  154. break;
  155. case 'retrieving-data':
  156. $oCurrentSearch = clone $this->oSearch;
  157. $aIDs = array_slice($this->aObjectsIDs, $this->iPosition, $this->iChunkSize);
  158. $oCurrentSearch->AddCondition('id', $aIDs, 'IN');
  159. $hFile = @fopen($this->GetDataFile(), 'ab');
  160. if ($hFile === false)
  161. {
  162. throw new Exception('ExcelExporter: Failed to open temporary data file: "'.$this->GetDataFile().'" for writing.');
  163. }
  164. $oSet = new DBObjectSet($oCurrentSearch);
  165. $this->GetFieldsList($oSet, $this->bAdvancedMode);
  166. while($aObjects = $oSet->FetchAssoc())
  167. {
  168. $aRow = array();
  169. foreach($this->aAuthorizedClasses as $sAlias => $sClassName)
  170. {
  171. $oObj = $aObjects[$sAlias];
  172. if ($this->bAdvancedMode)
  173. {
  174. $aRow[] = $oObj->GetKey();
  175. }
  176. foreach($this->aFieldsList[$sAlias] as $sAttCodeEx => $oAttDef)
  177. {
  178. $value = $oObj->Get($sAttCodeEx);
  179. if ($value instanceOf ormCaseLog)
  180. {
  181. // Extract the case log as text and remove the "===" which make Excel think that the cell contains a formula the next time you edit it!
  182. $sExcelVal = trim(preg_replace('/========== ([^=]+) ============/', '********** $1 ************', $value->GetText()));
  183. }
  184. else
  185. {
  186. $sExcelVal = $oAttDef->GetEditValue($value, $oObj);
  187. }
  188. $aRow[] = $sExcelVal;
  189. }
  190. }
  191. $sRow = json_encode($aRow);
  192. fwrite($hFile, $sRow."\n");
  193. }
  194. fclose($hFile);
  195. if (($this->iPosition + $this->iChunkSize) > count($this->aObjectsIDs))
  196. {
  197. // Next state
  198. $this->sState = 'building-excel';
  199. $sCode = 'building-excel';
  200. $iPercentage = 80;
  201. $sMessage = Dict::S('ExcelExporter:BuildingExcelFile');
  202. }
  203. else
  204. {
  205. $sCode = 'retrieving-data';
  206. $this->iPosition += $this->iChunkSize;
  207. $iPercentage = 5 + round(75 * ($this->iPosition / count($this->aObjectsIDs)));
  208. $sMessage = Dict::S('ExcelExporter:RetrievingData');
  209. }
  210. break;
  211. case 'building-excel':
  212. $hFile = @fopen($this->GetDataFile(), 'rb');
  213. if ($hFile === false)
  214. {
  215. throw new Exception('ExcelExporter: Failed to open temporary data file: "'.$this->GetDataFile().'" for reading.');
  216. }
  217. $sHeaders = fgets($hFile);
  218. $aHeaders = json_decode($sHeaders, true);
  219. $aData = array();
  220. while($sLine = fgets($hFile))
  221. {
  222. $aRow = json_decode($sLine);
  223. $aData[] = $aRow;
  224. }
  225. fclose($hFile);
  226. @unlink($this->GetDataFile());
  227. $fStartExcel = microtime(true);
  228. $writer = new XLSXWriter();
  229. $writer->setAuthor(UserRights::GetUserFriendlyName());
  230. $writer->writeSheet($aData,'Sheet1', $aHeaders);
  231. $fExcelTime = microtime(true) - $fStartExcel;
  232. $this->aStatistics['excel_build_duration'] = $fExcelTime;
  233. $fTime = microtime(true);
  234. $writer->writeToFile($this->GetExcelFilePath());
  235. $fExcelSaveTime = microtime(true) - $fTime;
  236. $this->aStatistics['excel_write_duration'] = $fExcelSaveTime;
  237. // Next state
  238. $this->sState = 'done';
  239. $sCode = 'done';
  240. $iPercentage = 100;
  241. $sMessage = Dict::S('ExcelExporter:Done');
  242. break;
  243. case 'done':
  244. $this->sState = 'done';
  245. $sCode = 'done';
  246. $iPercentage = 100;
  247. $sMessage = Dict::S('ExcelExporter:Done');
  248. break;
  249. }
  250. }
  251. catch(Exception $e)
  252. {
  253. $sCode = 'error';
  254. $sMessage = $e->getMessage();
  255. }
  256. $this->aStatistics['total_duration'] += microtime(true) - $fTime;
  257. $peak_memory = memory_get_peak_usage(true);
  258. if ($peak_memory > $this->aStatistics['peak_memory_usage'])
  259. {
  260. $this->aStatistics['peak_memory_usage'] = $peak_memory;
  261. }
  262. return array(
  263. 'code' => $sCode,
  264. 'message' => $sMessage,
  265. 'percentage' => $iPercentage,
  266. );
  267. }
  268. public function GetExcelFilePath()
  269. {
  270. if ($this->sOutputFilePath == null)
  271. {
  272. return APPROOT.'data/bulk_export/'.$this->sToken.'.xlsx';
  273. }
  274. else
  275. {
  276. return $this->sOutputFilePath;
  277. }
  278. }
  279. public static function GetExcelFileFromToken($sToken)
  280. {
  281. return @file_get_contents(APPROOT.'data/bulk_export/'.$sToken.'.xlsx');
  282. }
  283. public static function CleanupFromToken($sToken)
  284. {
  285. @unlink(APPROOT.'data/bulk_export/'.$sToken.'.status');
  286. @unlink(APPROOT.'data/bulk_export/'.$sToken.'.data');
  287. @unlink(APPROOT.'data/bulk_export/'.$sToken.'.xlsx');
  288. }
  289. public function Cleanup()
  290. {
  291. self::CleanupFromToken($this->sToken);
  292. }
  293. /**
  294. * Delete all files in the data/bulk_export directory which are older than 1 day
  295. * unless a different delay is configured.
  296. */
  297. public static function CleanupOldFiles()
  298. {
  299. $aFiles = glob(APPROOT.'data/bulk_export/*.*');
  300. $iDelay = MetaModel::GetConfig()->Get('xlsx_exporter_cleanup_old_files_delay');
  301. if($iDelay > 0)
  302. {
  303. foreach($aFiles as $sFile)
  304. {
  305. $iModificationTime = filemtime($sFile);
  306. if($iModificationTime < (time() - $iDelay))
  307. {
  308. // Temporary files older than one day are deleted
  309. //echo "Supposed to delete: '".$sFile." (Unix Modification Time: $iModificationTime)'\n";
  310. @unlink($sFile);
  311. }
  312. }
  313. }
  314. }
  315. public function DisplayStatistics(Page $oPage)
  316. {
  317. $aStats = array(
  318. 'Number of objects exported' => $this->aStatistics['objects_count'],
  319. 'Total export duration' => sprintf('%.3f s', $this->aStatistics['total_duration']),
  320. 'Data retrieval duration' => sprintf('%.3f s', $this->aStatistics['data_retrieval_duration']),
  321. 'Excel build duration' => sprintf('%.3f s', $this->aStatistics['excel_build_duration']),
  322. 'Excel write duration' => sprintf('%.3f s', $this->aStatistics['excel_write_duration']),
  323. 'Peak memory usage' => self::HumanDisplay($this->aStatistics['peak_memory_usage']),
  324. );
  325. if ($oPage instanceof CLIPage)
  326. {
  327. $oPage->add($this->GetStatistics('text'));
  328. }
  329. else
  330. {
  331. $oPage->add($this->GetStatistics('html'));
  332. }
  333. }
  334. public function GetStatistics($sFormat = 'html')
  335. {
  336. $sStats = '';
  337. $aStats = array(
  338. 'Number of objects exported' => $this->aStatistics['objects_count'],
  339. 'Total export duration' => sprintf('%.3f s', $this->aStatistics['total_duration']),
  340. 'Data retrieval duration' => sprintf('%.3f s', $this->aStatistics['data_retrieval_duration']),
  341. 'Excel build duration' => sprintf('%.3f s', $this->aStatistics['excel_build_duration']),
  342. 'Excel write duration' => sprintf('%.3f s', $this->aStatistics['excel_write_duration']),
  343. 'Peak memory usage' => self::HumanDisplay($this->aStatistics['peak_memory_usage']),
  344. );
  345. if ($sFormat == 'text')
  346. {
  347. foreach($aStats as $sLabel => $sValue)
  348. {
  349. $sStats .= "+------------------------------+----------+\n";
  350. $sStats .= sprintf("|%-30s|%10s|\n", $sLabel, $sValue);
  351. }
  352. $sStats .= "+------------------------------+----------+";
  353. }
  354. else
  355. {
  356. $sStats .= '<table><tbody>';
  357. foreach($aStats as $sLabel => $sValue)
  358. {
  359. $sStats .= "<tr><td>$sLabel</td><td>$sValue</td></tr>";
  360. }
  361. $sStats .= '</tbody></table>';
  362. }
  363. return $sStats;
  364. }
  365. public static function HumanDisplay($iSize)
  366. {
  367. $aUnits = array('B','KB','MB','GB','TB','PB');
  368. return @round($iSize/pow(1024,($i=floor(log($iSize,1024)))),2).' '.$aUnits[$i];
  369. }
  370. protected function CheckDataDir()
  371. {
  372. if(!is_dir(APPROOT."data/bulk_export"))
  373. {
  374. @mkdir(APPROOT."data/bulk_export", 0777, true /* recursive */);
  375. clearstatcache();
  376. }
  377. if (!is_writable(APPROOT."data/bulk_export"))
  378. {
  379. throw new Exception('Data directory "'.APPROOT.'data/bulk_export" could not be written.');
  380. }
  381. }
  382. protected function GetStateFile($sToken = null)
  383. {
  384. if ($sToken == null)
  385. {
  386. $sToken = $this->sToken;
  387. }
  388. return APPROOT."data/bulk_export/$sToken.status";
  389. }
  390. protected function GetDataFile()
  391. {
  392. return APPROOT.'data/bulk_export/'.$this->sToken.'.data';
  393. }
  394. protected function GetNewToken()
  395. {
  396. $iNum = rand();
  397. do
  398. {
  399. $iNum++;
  400. $sToken = sprintf("%08x", $iNum);
  401. $sFileName = $this->GetStateFile($sToken);
  402. $hFile = @fopen($sFileName, 'x');
  403. }
  404. while($hFile === false);
  405. fclose($hFile);
  406. return $sToken;
  407. }
  408. protected function GetFieldsList($oSet, $bFieldsAdvanced = false, $bLocalize = true, $aFields = null)
  409. {
  410. $this->aFieldsList = array();
  411. $oAppContext = new ApplicationContext();
  412. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  413. $this->aAuthorizedClasses = array();
  414. foreach($aClasses as $sAlias => $sClassName)
  415. {
  416. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  417. {
  418. $this->aAuthorizedClasses[$sAlias] = $sClassName;
  419. }
  420. }
  421. $aAttribs = array();
  422. $this->aTableHeaders = array();
  423. foreach($this->aAuthorizedClasses as $sAlias => $sClassName)
  424. {
  425. $aList[$sAlias] = array();
  426. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef)
  427. {
  428. if (is_null($aFields) || (count($aFields) == 0))
  429. {
  430. // Standard list of attributes (no link sets)
  431. if ($oAttDef->IsScalar() && ($oAttDef->IsWritable() || $oAttDef->IsExternalField()))
  432. {
  433. $sAttCodeEx = $oAttDef->IsExternalField() ? $oAttDef->GetKeyAttCode().'->'.$oAttDef->GetExtAttCode() : $sAttCode;
  434. if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
  435. {
  436. if ($bFieldsAdvanced)
  437. {
  438. $aList[$sAlias][$sAttCodeEx] = $oAttDef;
  439. if ($oAttDef->IsExternalKey(EXTKEY_RELATIVE))
  440. {
  441. $sRemoteClass = $oAttDef->GetTargetClass();
  442. foreach(MetaModel::GetReconcKeys($sRemoteClass) as $sRemoteAttCode)
  443. {
  444. $this->aFieldsList[$sAlias][$sAttCode.'->'.$sRemoteAttCode] = MetaModel::GetAttributeDef($sRemoteClass, $sRemoteAttCode);
  445. }
  446. }
  447. }
  448. }
  449. else
  450. {
  451. // Any other attribute
  452. $this->aFieldsList[$sAlias][$sAttCodeEx] = $oAttDef;
  453. }
  454. }
  455. }
  456. else
  457. {
  458. // User defined list of attributes
  459. if (in_array($sAttCode, $aFields) || in_array($sAlias.'.'.$sAttCode, $aFields))
  460. {
  461. $this->aFieldsList[$sAlias][$sAttCode] = $oAttDef;
  462. }
  463. }
  464. }
  465. if ($bFieldsAdvanced)
  466. {
  467. $this->aTableHeaders['id'] = '0';
  468. }
  469. foreach($this->aFieldsList[$sAlias] as $sAttCodeEx => $oAttDef)
  470. {
  471. $sLabel = $bLocalize ? MetaModel::GetLabel($sClassName, $sAttCodeEx, isset($aParams['showMandatoryFields'])) : $sAttCodeEx;
  472. if($oAttDef instanceof AttributeDateTime)
  473. {
  474. $this->aTableHeaders[$sLabel] = 'datetime';
  475. }
  476. else
  477. {
  478. $this->aTableHeaders[$sLabel] = 'string';
  479. }
  480. }
  481. }
  482. }
  483. }