PageRenderTime 50ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/output/include/import_functions_excel.php

https://gitlab.com/Lidbary/PHPRunner
PHP | 319 lines | 186 code | 55 blank | 78 comment | 30 complexity | 55fa39caeebe27dc2d634689ad082ebb MD5 | raw file
  1. <?php
  2. require_once getabspath("plugins/PHPExcel/IOFactory.php");
  3. /**
  4. * Open an Excel file
  5. * It requires the PHPExcel plugin
  6. * @param String uploadfile
  7. * @param String ext
  8. * @return PHPExcel The file resource
  9. */
  10. function openImportExcelFile($uploadfile, $ext)
  11. {
  12. if( strtoupper($ext) == "XLSX" )
  13. {
  14. $objPHPExcel = PHPExcel_IOFactory::load($uploadfile);
  15. }
  16. else
  17. {
  18. $objPHPExcel = new PHPExcel();
  19. $objReader = PHPExcel_IOFactory::createReader("Excel5");
  20. $objPHPExcel = $objReader->load($uploadfile);
  21. }
  22. return $objPHPExcel;
  23. }
  24. /**
  25. * Get the filed names from the first row of the current work sheet
  26. * @param PHPExcel data
  27. * @return Array
  28. */
  29. function getImportExcelFields($data)
  30. {
  31. $fields = array();
  32. $worksheet = $data->getSheet();
  33. $highestColumn = $worksheet->getHighestColumn();
  34. $highestColumnIndex = PHPExcel_Cell::columnIndexFromString( $highestColumn );
  35. for($col = 0; $col < $highestColumnIndex; ++$col)
  36. {
  37. $fieldName = $worksheet->getCellByColumnAndRow($col, 1)->getValue();
  38. if( !strlen($fieldName) )
  39. break;
  40. $fields[] = $fieldName;
  41. }
  42. return $fields;
  43. }
  44. /**
  45. * Import data from an Excel file
  46. * @param PHPExcel fileHandle
  47. * @param Array fieldsData
  48. * @param Array keys
  49. * @param ImportPage importPageObject
  50. * @param Boolean autoinc
  51. * @param Boolean useFirstLine
  52. * @param String dateFormat
  53. * @return Array
  54. */
  55. function ImportDataFromExcel( $fileHandle, $fieldsData, $keys, $importPageObject, $autoinc, $useFirstLine, $dateFormat )
  56. {
  57. global $cCharset;
  58. $metaData = array();
  59. $metaData["totalRecords"] = 0;
  60. $errorMessages = array();
  61. $unprocessedData = array();
  62. $updatedRecords = 0;
  63. $addedRecords = 0;
  64. $startRow = $useFirstLine ? 1 : 2;
  65. foreach($fileHandle->getWorksheetIterator() as $worksheet)
  66. {
  67. $highestRow = $worksheet->getHighestRow();
  68. // get a litteral index of the 'highest' column (e.g. 'K')
  69. $highestColumn = $worksheet->getHighestColumn();
  70. // get an index number of the 'highest' column (e.g. 11)
  71. $highestColumnIndex = PHPExcel_Cell::columnIndexFromString( $highestColumn );
  72. for($row = $startRow; $row <= $highestRow; $row++)
  73. {
  74. $fieldValuesData = array();
  75. for($col = 0; $col < $highestColumnIndex; $col++)
  76. {
  77. if( !isset( $fieldsData[ $col ] ) )
  78. continue;
  79. $importFieldName = $fieldsData[ $col ]["fName"];
  80. $cell = $worksheet->getCellByColumnAndRow($col, $row);
  81. $cellValue = $cell->getValue();
  82. if( PHPExcel_Shared_Date::isDateTime($cell) )
  83. {
  84. $cellDateFormat = $fileHandle->getCellXfByIndex( $cell->getXfIndex() )->getNumberFormat()->getFormatCode();
  85. $cellTextValue = PHPExcel_Style_NumberFormat::ToFormattedString($cellValue, $cellDateFormat);
  86. $cellValue = getDBDateValue( $cellTextValue, $cellDateFormat );
  87. }
  88. else
  89. {
  90. if( is_a($cellValue, 'PHPExcel_RichText') )
  91. $cellValue = $cellValue->getPlainText();
  92. if( IsDateFieldType( $fieldsData[ $col ]["type"] ) )
  93. $cellValue = getDBDateValue( $cellValue, $dateFormat );
  94. $error_handler = set_error_handler("empty_error_handler");
  95. $cellValue = PHPExcel_Shared_String::ConvertEncoding($cellValue, $cCharset, 'UTF-8');
  96. if( $error_handler )
  97. set_error_handler($error_handler);
  98. $matches = array();
  99. preg_match('/^="(=.*)"$/i', $cellValue, $matches);
  100. if( array_key_exists(1, $matches) )
  101. $cellValue = $matches[1];
  102. }
  103. $fieldValuesData[ $importFieldName ] = $cellValue;
  104. }
  105. $importPageObject->importRecord( $fieldValuesData, $keys, $autoinc, $addedRecords, $updatedRecords, $errorMessages, $unprocessedData );
  106. $metaData["totalRecords"] = $metaData["totalRecords"] + 1;
  107. }
  108. }
  109. $metaData["addedRecords"] = $addedRecords;
  110. $metaData["updatedRecords"] = $updatedRecords;
  111. $metaData["errorMessages"] = $errorMessages;
  112. $metaData["unprocessedData"] = $unprocessedData;
  113. return $metaData;
  114. }
  115. /**
  116. * Get no more the 100 rows of the file's data to display the file's preview.
  117. * It could augment the fieldsData array
  118. * It requires the PHPExcel plugin
  119. * @param PHPExcel fileHandle
  120. * @param &Array fieldsData The corresponding import fields data
  121. * @return Array
  122. */
  123. function getPreviewDataFromExcel( $fileHandle, &$fieldsData )
  124. {
  125. global $locale_info;
  126. $previewData = array();
  127. $remainNumOfPreviewRows = 100;
  128. foreach($fileHandle->getWorksheetIterator() as $worksheet)
  129. {
  130. if( $remainNumOfPreviewRows <= 0 )
  131. break;
  132. // get the number of rows for the current worksheet
  133. $highestRow = $worksheet->getHighestRow();
  134. if( $highestRow > $remainNumOfPreviewRows )
  135. $highestRow = $remainNumOfPreviewRows;
  136. $remainNumOfPreviewRows -= $highestRow;
  137. // get a litteral index of the 'highest' column (e.g. 'K')
  138. $highestColumn = $worksheet->getHighestColumn();
  139. // get an index number of the 'highest' column (e.g. 11)
  140. $highestColumnIndex = PHPExcel_Cell::columnIndexFromString( $highestColumn );
  141. // start traversing rows from the first one that contains columns' names
  142. for($row = 1; $row <= $highestRow; $row++)
  143. {
  144. $rowData = array();
  145. for($col = 0; $col < $highestColumnIndex; $col++)
  146. {
  147. $cell = $worksheet->getCellByColumnAndRow($col, $row);
  148. $cellValue = $cell->getValue();
  149. if( $row > 1 )
  150. {
  151. $columnMatched = isset( $fieldsData[ $col ] );
  152. if( PHPExcel_Shared_Date::isDateTime($cell) )
  153. {
  154. $cellDateFormat = $fileHandle->getCellXfByIndex( $cell->getXfIndex() )->getNumberFormat()->getFormatCode();
  155. $cellTextValue = PHPExcel_Style_NumberFormat::ToFormattedString($cellValue, $cellDateFormat);
  156. $cellValue = getTimeStamp($cellTextValue, $cellDateFormat);
  157. if( !$columnMatched )
  158. $fieldsData[ $col ] = array();
  159. $fieldsData[ $col ]["dateTimeType"] = true;
  160. $fieldsData[ $col ]["requireFormatting"] = true;
  161. }
  162. else if( $columnMatched && $fieldsData[ $col ]["dateTimeType"] && !strlen($dateFormat) )
  163. $dateFormat = ImportPage::extractDateFormat( $cellValue );
  164. }
  165. $rowData[] = $cellValue;
  166. }
  167. if( $rowData && ( count($rowData) >1 || $rowData[0] != null ) )
  168. $tableData[] = $rowData;
  169. }
  170. }
  171. $previewData["tableData"] = $tableData;
  172. if( ImportPage::hasDateTimeFields( $fieldsData ) )
  173. $previewData["dateFormat"] = !strlen($dateFormat) ? $locale_info["LOCALE_SSHORTDATE"] : $dateFormat;
  174. return $previewData;
  175. }
  176. /**
  177. * Get the uploded file's data from superglobals
  178. * @param String fileName
  179. * @return Mixed
  180. */
  181. function getImportFileData( $fileName )
  182. {
  183. return $_FILES[ $fileName ];
  184. }
  185. /**
  186. * @param String fname
  187. * @return String
  188. */
  189. function getImportFileExtension($fname)
  190. {
  191. return getFileExtension( $_FILES[$fname]['name'] );
  192. }
  193. /**
  194. * @param String fname
  195. * @return String
  196. */
  197. function getTempImportFileName($fname)
  198. {
  199. return $_FILES[$fname]['tmp_name'];
  200. }
  201. /**
  202. * Delete am import temp file
  203. * @param String filePath
  204. */
  205. function deleteImportTempFile( $filePath )
  206. {
  207. $error_handler = set_error_handler("empty_error_handler");
  208. runner_delete_file( $filePath );
  209. if( $error_handler )
  210. set_error_handler($error_handler);
  211. }
  212. /**
  213. * Do not touch $table and $isIdentityOffNeeded - they needed for ASP.Net MVC version
  214. * @param String sql
  215. * @param Connection connection
  216. * @param String table
  217. * @param Boolean isIdentityOffNeeded
  218. * @return Mixed
  219. */
  220. function db_exec_import($sql, $connection, $table = "", $isIdentityOffNeeded = false)
  221. {
  222. set_error_handler("import_error_handler");
  223. return $connection->exec( $sql );
  224. }
  225. /**
  226. * A PHP rewind function wrapper
  227. * @param Mixed handle
  228. * @param $filePath added for ASP
  229. * @return Boolean (TRUE | FALSE)
  230. */
  231. function rewindFilePointerPosition($handle,$filePath)
  232. {
  233. rewind( $handle );
  234. return $handle;
  235. }
  236. /**
  237. * Get the list of file names from a particular directory
  238. * @param String dirPath
  239. * @return Array
  240. */
  241. function getFileNamesFromDir( $dirPath )
  242. {
  243. $fileNames = array();
  244. $dirHandle = opendir( $dirPath );
  245. if( $dirHandle )
  246. {
  247. while( false !== ($fileName = readdir($dirHandle)) )
  248. {
  249. $fileNames[] = $fileName;
  250. }
  251. closedir( $dirHandle );
  252. }
  253. return $fileNames;
  254. }
  255. /**
  256. * A PHP fgets function wrapper
  257. * @param Mixed handle
  258. * @param Number length
  259. */
  260. function getLineFromFile($handle, $length)
  261. {
  262. return fgets($handle, $length);
  263. }
  264. ?>