PageRenderTime 54ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/cubi/modules/service/excelService.php

http://openbiz-cubi.googlecode.com/
PHP | 293 lines | 169 code | 28 blank | 96 comment | 28 complexity | 1111341c2f73c9e0a55cdf49a14d45bd MD5 | raw file
Possible License(s): GPL-2.0, LGPL-3.0
  1. <?php
  2. /**
  3. * Openbiz Cubi Application Platform
  4. *
  5. * LICENSE http://code.google.com/p/openbiz-cubi/wiki/CubiLicense
  6. *
  7. * @package cubi.service
  8. * @copyright Copyright (c) 2005-2011, Openbiz Technology LLC
  9. * @license http://code.google.com/p/openbiz-cubi/wiki/CubiLicense
  10. * @link http://code.google.com/p/openbiz-cubi/
  11. * @version $Id: excelService.php 3371 2012-05-31 06:17:21Z rockyswen@gmail.com $
  12. */
  13. /**
  14. * PHPOpenBiz Framework
  15. *
  16. * LICENSE
  17. *
  18. * This source file is subject to the BSD license that is bundled
  19. * with this package in the file LICENSE.txt.
  20. *
  21. * @package openbiz.bin.service
  22. * @copyright Copyright &copy; 2005-2012, Rocky Swen
  23. * @license http://www.opensource.org/licenses/bsd-license.php
  24. * @link http://www.phpopenbiz.org/
  25. * @version $Id: excelService.php 3371 2012-05-31 06:17:21Z rockyswen@gmail.com $
  26. */
  27. include_once (OPENBIZ_HOME."/messages/excelService.msg");
  28. /**
  29. * excelService -
  30. * class excelService is the plug-in service of printing {@link EasyForm} to excel
  31. *
  32. * @package openbiz.bin.service
  33. * @author Rocky Swen
  34. * @copyright Copyright (c) 2005-2009, Rocky Swen
  35. * @access public
  36. */
  37. class excelService
  38. {
  39. /**
  40. * Initialize excelService with xml array metadata
  41. *
  42. * @param array $xmlArr
  43. * @return void
  44. */
  45. function __construct(&$xmlArr)
  46. {
  47. }
  48. /**
  49. * Render the excel output with CSV format
  50. *
  51. * @param string $objName object name which is the bizform name
  52. * @return void
  53. */
  54. function renderCSV ($objName)
  55. {
  56. $this->render($objName, ",", "csv");
  57. //Log This Export
  58. BizSystem::log(LOG_INFO, "ExcelService", "Export CSV file.");
  59. }
  60. /**
  61. * Render the excel output with TSV format
  62. *
  63. * @param string $objName object name which is the bizform name
  64. * @return void
  65. */
  66. function renderTSV ($objName)
  67. {
  68. $this->render($objName, "\t", "tsv");
  69. //Log This Export
  70. BizSystem::log(LOG_INFO, "ExcelService", "Export TSV file.");
  71. }
  72. /**
  73. * Import from CSV file
  74. * NOTE: This method must be called from a popup form where a file is uploaded.
  75. * The parent form of the popup form is the target to import.
  76. *
  77. * @param string $objName
  78. * @return void
  79. */
  80. public function importCSV ($objName)
  81. {
  82. // read in file from $_FILE
  83. foreach ($_FILES as $file)
  84. {
  85. $error = $file['error'];
  86. if ($error != 0)
  87. {
  88. $this->reportError($error);
  89. return;
  90. }
  91. $tmpFileName = $file['tmp_name'];
  92. break;
  93. }
  94. //echo "upload file name = $tmpFileName";
  95. $filename = $file['name'];
  96. if (strpos($filename,".csv")===false)
  97. {
  98. $errorMsg = BizSystem::getMessage("EXCELSVC_INVALID_FILE",array($filename));
  99. BizSystem::log(LOG_ERR, "EXCEL SERVICE", "Import error = ".$errorMsg);
  100. BizSystem::clientProxy()->showClientAlert($errorMsg);
  101. return;
  102. }
  103. /* @var $formObj EasyForm */
  104. $formObj = BizSystem::objectFactory()->getObject($objName); // get the existing EasyForm object
  105. $parentFormObj = BizSystem::objectFactory()->getObject($formObj->m_ParentFormName);
  106. $dataObj = $parentFormObj->getDataObj();
  107. $handle = fopen($tmpFileName, "r");
  108. $fields = fgetcsv($handle, 2000, ",");
  109. if (!$fields || count($fields)<2)
  110. {
  111. $errorMsg = BizSystem::getMessage("EXCELSVC_INVALID_FILE",array($filename));
  112. BizSystem::log(LOG_ERR, "EXCEL SERVICE", "Import error = ".$errorMsg);
  113. BizSystem::clientProxy()->showClientAlert($errorMsg);
  114. return;
  115. }
  116. // convert form element names to DO field names
  117. foreach ($parentFormObj->m_DataPanel as $element)
  118. {
  119. $elem_fields[$element->m_Label] = $element->m_FieldName;
  120. }
  121. // validate with dataobj fields
  122. for ($i=0; $i<count($fields); $i++)
  123. {
  124. $fields[$i] = $elem_fields[$fields[$i]];
  125. $field = $fields[$i];
  126. if (!$dataObj->getField($field))
  127. {
  128. $errorMsg = BizSystem::getMessage("EXCELSVC_INVALID_COLUMN",array($field, $dataObj->m_Name));
  129. BizSystem::log(LOG_ERR, "EXCEL SERVICE", "Import error = ".$errorMsg);
  130. BizSystem::clientProxy()->showClientAlert($errorMsg);
  131. return;
  132. }
  133. }
  134. while (($arr = fgetcsv($handle, 2000, ",")) !== FALSE)
  135. {
  136. if (count($arr) != count($fields))
  137. continue;
  138. unset($recArr);
  139. $i = 0;
  140. for ($i=0; $i<count($arr); $i++)
  141. {
  142. $recArr[$fields[$i]] = $arr[$i];
  143. }
  144. //print_r($recArr); echo "<hr>";
  145. $dataRec = new DataRecord(null, $dataObj);
  146. foreach ($recArr as $k => $v)
  147. $dataRec[$k] = $v;
  148. $ok = $dataRec->save();
  149. if (! $ok)
  150. {
  151. // NOTE: EasyForm::processDataObjError() not return any value (void)
  152. return $formObj->processDataObjError($ok);
  153. }
  154. }
  155. fclose($handle);
  156. // in case of popup form, close it, then rerender the parent form
  157. if ($formObj->m_ParentFormName)
  158. {
  159. $formObj->close();
  160. $formObj->renderParent();
  161. }
  162. }
  163. /**
  164. * Render excel data
  165. *
  166. * @param string $objName object form name
  167. * @param string $separator sparator between column
  168. * @param string $ext file extension
  169. * @return void
  170. */
  171. protected function render($objName, $separator=",", $ext="csv")
  172. {
  173. ob_end_clean();
  174. header("Pragma: public");
  175. header("Expires: 0");
  176. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  177. header("Cache-Control: public");
  178. header("Content-Description: File Transfer");
  179. header("Content-Type: application/vnd.ms-excel");
  180. header("Content-Disposition: filename=" . $objName."_".date('Y-m-d') . "." . $ext);
  181. header("Content-Transfer-Encoding: binary");
  182. $dataTable = $this->getDataTable($objName);
  183. foreach ($dataTable as $row)
  184. {
  185. $line = "";
  186. foreach ($row as $cell) {
  187. $txt = $this->strip_cell($cell);
  188. if (!is_null($txt))
  189. $line .= "\"" . $txt . "\"$separator";
  190. }
  191. $line = rtrim($line, $separator);
  192. $line = iconv("UTF-8","GB2312//IGNORE",$line);
  193. echo rtrim($line) . "\n";
  194. }
  195. }
  196. protected function strip_cell($str){
  197. $str = strip_tags($str);
  198. $str = str_replace("\n",'',$str);
  199. $str = str_replace("\r",'',$str);
  200. return $str;
  201. }
  202. /**
  203. * Get raw data to display in the spreadsheet. header and data table
  204. *
  205. * @param string $objName
  206. * @return array
  207. */
  208. protected function getDataTable($objName)
  209. {
  210. /* @var $formObj EasyForm */
  211. $formObj = BizSystem::objectFactory()->getObject($objName); // get the existing EasyForm|BizForm object
  212. // if BizForm, call BizForm::renderTable
  213. if ($formObj instanceof BizForm)
  214. {
  215. $dataTable = $formObj->renderTable();
  216. }
  217. // if EasyForm, call EasyForm->DataPanel::renderTable
  218. if ($formObj instanceof EasyForm)
  219. {
  220. $recordSet = $formObj->fetchDataSet();
  221. $dataSet = $formObj->m_DataPanel->renderTable($recordSet);
  222. foreach ($dataSet['elems'] as $elem)
  223. {
  224. $labelRow[] = $elem['label'];
  225. }
  226. //If no datasets, return only labelrow to enable gracful export
  227. //to avoid error message as a result of trying to apply array_merge
  228. //on a null variable
  229. //Cyril Ogana 2012-01-28 23:30
  230. if (count($dataSet['data']))
  231. {
  232. $dataTable = array_merge(array($labelRow), $dataSet['data']);
  233. }
  234. else
  235. {
  236. $dataTable = array($labelRow);
  237. }
  238. }
  239. return $dataTable;
  240. }
  241. /**
  242. * Show error message
  243. *
  244. * @param int $error error number
  245. */
  246. protected function reportError($error)
  247. {
  248. if ($error==1)
  249. $errorStr = "The uploaded file exceeds the upload_max_filesize directive in php.ini";
  250. else if ($error==2)
  251. $errorStr = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
  252. else if ($error==3)
  253. $errorStr = "The uploaded file was only partially uploaded";
  254. else if ($error==4)
  255. $errorStr = "No file was uploaded";
  256. else if ($error==6)
  257. $errorStr = "Missing a temporary folder";
  258. else if ($error==7)
  259. $errorStr = "Failed to write file to disk";
  260. else
  261. $errorStr = "Error in file upload";
  262. BizSystem::clientProxy()->showErrorMessage($errorStr);
  263. }
  264. }
  265. ?>