PageRenderTime 34ms CodeModel.GetById 9ms app.highlight 19ms RepoModel.GetById 2ms app.codeStats 0ms

/PHPExcel/Reader/HTML.php

https://bitbucket.org/nfredricks/wp-employee-time
PHP | 499 lines | 320 code | 41 blank | 138 comment | 34 complexity | eb8dcfc09e11953f8667fd401ab6b8b5 MD5 | raw file
  1<?php
  2/**
  3 * PHPExcel
  4 *
  5 * Copyright (c) 2006 - 2012 PHPExcel
  6 *
  7 * This library is free software; you can redistribute it and/or
  8 * modify it under the terms of the GNU Lesser General Public
  9 * License as published by the Free Software Foundation; either
 10 * version 2.1 of the License, or (at your option) any later version.
 11 *
 12 * This library is distributed in the hope that it will be useful,
 13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 15 * Lesser General Public License for more details.
 16 *
 17 * You should have received a copy of the GNU Lesser General Public
 18 * License along with this library; if not, write to the Free Software
 19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 20 *
 21 * @category   PHPExcel
 22 * @package    PHPExcel_Reader
 23 * @copyright  Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
 24 * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt	LGPL
 25 * @version    1.7.8, 2012-10-12
 26 */
 27
 28
 29/** PHPExcel root directory */
 30if (!defined('PHPEXCEL_ROOT')) {
 31	/**
 32	 * @ignore
 33	 */
 34	define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
 35	require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
 36}
 37
 38/**
 39 * PHPExcel_Reader_HTML
 40 *
 41 * @category   PHPExcel
 42 * @package    PHPExcel_Reader
 43 * @copyright  Copyright (c) 2006 - 2012 PHPExcel (http://www.codeplex.com/PHPExcel)
 44 */
 45class PHPExcel_Reader_HTML implements PHPExcel_Reader_IReader
 46{
 47	/**
 48	 * Input encoding
 49	 *
 50	 * @var string
 51	 */
 52	private $_inputEncoding	= 'ANSI';
 53
 54	/**
 55	 * Sheet index to read
 56	 *
 57	 * @var int
 58	 */
 59	private $_sheetIndex 	= 0;
 60
 61	/**
 62	 * Formats
 63	 *
 64	 * @var array
 65	 */
 66	private $_formats = array( 'h1' => array( 'font' => array( 'bold' => true,
 67															   'size' => 24,
 68															 ),
 69											),	//	Bold, 24pt
 70							   'h2' => array( 'font' => array( 'bold' => true,
 71															   'size' => 18,
 72															 ),
 73											),	//	Bold, 18pt
 74							   'h3' => array( 'font' => array( 'bold' => true,
 75															   'size' => 13.5,
 76															 ),
 77											),	//	Bold, 13.5pt
 78							   'h4' => array( 'font' => array( 'bold' => true,
 79															   'size' => 12,
 80															 ),
 81											),	//	Bold, 12pt
 82							   'h5' => array( 'font' => array( 'bold' => true,
 83															   'size' => 10,
 84															 ),
 85											),	//	Bold, 10pt
 86							   'h6' => array( 'font' => array( 'bold' => true,
 87															   'size' => 7.5,
 88															 ),
 89											),	//	Bold, 7.5pt
 90							   'a'  => array( 'font' => array( 'underline' => true,
 91															   'color' => array( 'argb' => PHPExcel_Style_Color::COLOR_BLUE,
 92															                   ),
 93															 ),
 94											),	//	Blue underlined
 95							   'hr' => array( 'borders' => array( 'bottom' => array( 'style' => PHPExcel_Style_Border::BORDER_THIN,
 96																					 'color' => array( PHPExcel_Style_Color::COLOR_BLACK,
 97																					                 ),
 98																				   ),
 99																),
100											),	//	Bottom border
101							 );
102
103	/**
104	 * PHPExcel_Reader_IReadFilter instance
105	 *
106	 * @var PHPExcel_Reader_IReadFilter
107	 */
108	private $_readFilter = null;
109
110
111	/**
112	 * Create a new PHPExcel_Reader_HTML
113	 */
114	public function __construct() {
115		$this->_readFilter 	= new PHPExcel_Reader_DefaultReadFilter();
116	}
117
118	/**
119	 *	Can the current PHPExcel_Reader_IReader read the file?
120	 *
121	 *	@param 	string 		$pFileName
122	 *	@return 	boolean
123	 *	@throws Exception
124	 */
125	public function canRead($pFilename)
126	{
127		// Check if file exists
128		if (!file_exists($pFilename)) {
129			throw new Exception("Could not open " . $pFilename . " for reading! File does not exist.");
130		}
131
132		// Read sample data (first 2 KB will do)
133		$fh = fopen($pFilename, 'r');
134		$data = fread($fh, 2048);
135		fclose($fh);
136
137		return true;
138	}
139
140	/**
141	 * Loads PHPExcel from file
142	 *
143	 * @param 	string 		$pFilename
144	 * @return 	PHPExcel
145	 * @throws 	Exception
146	 */
147	public function load($pFilename)
148	{
149		// Create new PHPExcel
150		$objPHPExcel = new PHPExcel();
151
152		// Load into this instance
153		return $this->loadIntoExisting($pFilename, $objPHPExcel);
154	}
155
156	/**
157	 * Read filter
158	 *
159	 * @return PHPExcel_Reader_IReadFilter
160	 */
161	public function getReadFilter() {
162		return $this->_readFilter;
163	}
164
165	/**
166	 * Set read filter
167	 *
168	 * @param PHPExcel_Reader_IReadFilter $pValue
169	 */
170	public function setReadFilter(PHPExcel_Reader_IReadFilter $pValue) {
171		$this->_readFilter = $pValue;
172		return $this;
173	}
174
175	/**
176	 * Set input encoding
177	 *
178	 * @param string $pValue Input encoding
179	 */
180	public function setInputEncoding($pValue = 'ANSI')
181	{
182		$this->_inputEncoding = $pValue;
183		return $this;
184	}
185
186	/**
187	 * Get input encoding
188	 *
189	 * @return string
190	 */
191	public function getInputEncoding()
192	{
193		return $this->_inputEncoding;
194	}
195
196	//	Data Array used for testing only, should write to PHPExcel object on completion of tests
197	private $_dataArray = array();
198
199	private $_tableLevel = 0;
200	private $_nestedColumn = array('A');
201
202	private function _setTableStartColumn($column) {
203		if ($this->_tableLevel == 0)
204			$column = 'A';
205		++$this->_tableLevel;
206		$this->_nestedColumn[$this->_tableLevel] = $column;
207
208		return $this->_nestedColumn[$this->_tableLevel];
209	}
210
211	private function _getTableStartColumn() {
212		return $this->_nestedColumn[$this->_tableLevel];
213	}
214
215	private function _releaseTableStartColumn() {
216		--$this->_tableLevel;
217		return array_pop($this->_nestedColumn);
218	}
219
220	private function _flushCell($sheet,$column,$row,&$cellContent) {
221		if (is_string($cellContent)) {
222			//	Simple String content
223			if (trim($cellContent) > '') {
224				//	Only actually write it if there's content in the string
225				echo 'FLUSH CELL: ' , $column , $row , ' => ' , $cellContent , '<br />';
226				//	Write to worksheet to be done here...
227				//	... we return the cell so we can mess about with styles more easily
228				$cell = $sheet->setCellValue($column.$row,$cellContent,true);
229				$this->_dataArray[$row][$column] = $cellContent;
230			}
231		} else {
232			//	We have a Rich Text run
233			//	TODO
234			$this->_dataArray[$row][$column] = 'RICH TEXT: ' . $cellContent;
235		}
236		$cellContent = (string) '';
237	}
238
239	private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, &$cellContent){
240		foreach($element->childNodes as $child){
241			if ($child instanceOf DOMText) {
242				$domText = preg_replace('/\s+/',' ',trim($child->nodeValue));
243				if (is_string($cellContent)) {
244					//	simply append the text if the cell content is a plain text string
245					$cellContent .= $domText;
246				} else {
247					//	but if we have a rich text run instead, we need to append it correctly
248					//	TODO
249				}
250			} elseif($child instanceOf DOMElement) {
251				echo '<b>DOM ELEMENT: </b>' , strtoupper($child->nodeName) , '<br />';
252
253				$attributeArray = array();
254				foreach($child->attributes as $attribute) {
255					echo '<b>ATTRIBUTE: </b>' , $attribute->name , ' => ' , $attribute->value , '<br />';
256					$attributeArray[$attribute->name] = $attribute->value;
257				}
258
259				switch($child->nodeName) {
260					case 'meta' :
261						foreach($attributeArray as $attributeName => $attributeValue) {
262							switch($attributeName) {
263								case 'content':
264									//	TODO
265									//	Extract character set, so we can convert to UTF-8 if required
266									break;
267							}
268						}
269						$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
270						break;
271					case 'title' :
272						$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
273						$sheet->setTitle($cellContent);
274						$cellContent = '';
275						break;
276					case 'span'  :
277					case 'div'   :
278					case 'font'  :
279					case 'i'     :
280					case 'em'    :
281					case 'strong':
282					case 'b'     :
283						echo 'STYLING, SPAN OR DIV<br />';
284						if ($cellContent > '')
285							$cellContent .= ' ';
286						$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
287						if ($cellContent > '')
288							$cellContent .= ' ';
289						echo 'END OF STYLING, SPAN OR DIV<br />';
290						break;
291					case 'hr' :
292						$this->_flushCell($sheet,$column,$row,$cellContent);
293						++$row;
294						if (isset($this->_formats[$child->nodeName])) {
295							$sheet->getStyle($column.$row)->applyFromArray($this->_formats[$child->nodeName]);
296						} else {
297							$cellContent = '----------';
298							$this->_flushCell($sheet,$column,$row,$cellContent);
299						}
300						++$row;
301					case 'br' :
302						if ($this->_tableLevel > 0) {
303							//	If we're inside a table, replace with a \n
304							$cellContent .= "\n";
305						} else {
306							//	Otherwise flush our existing content and move the row cursor on
307							$this->_flushCell($sheet,$column,$row,$cellContent);
308							++$row;
309						}
310						echo 'HARD LINE BREAK: ' , '<br />';
311						break;
312					case 'a'  :
313						echo 'START OF HYPERLINK: ' , '<br />';
314						foreach($attributeArray as $attributeName => $attributeValue) {
315							switch($attributeName) {
316								case 'href':
317									echo 'Link to ' , $attributeValue , '<br />';
318									$sheet->getCell($column.$row)->getHyperlink()->setUrl($attributeValue);
319									if (isset($this->_formats[$child->nodeName])) {
320										$sheet->getStyle($column.$row)->applyFromArray($this->_formats[$child->nodeName]);
321									}
322									break;
323							}
324						}
325						$cellContent .= ' ';
326						$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
327						echo 'END OF HYPERLINK:' , '<br />';
328						break;
329					case 'h1' :
330					case 'h2' :
331					case 'h3' :
332					case 'h4' :
333					case 'h5' :
334					case 'h6' :
335					case 'ol' :
336					case 'ul' :
337					case 'p'  :
338						if ($this->_tableLevel > 0) {
339							//	If we're inside a table, replace with a \n
340							$cellContent .= "\n";
341							echo 'LIST ENTRY: ' , '<br />';
342							$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
343							echo 'END OF LIST ENTRY:' , '<br />';
344						} else {
345							if ($cellContent > '') {
346								$this->_flushCell($sheet,$column,$row,$cellContent);
347								$row += 2;
348							}
349							echo 'START OF PARAGRAPH: ' , '<br />';
350							$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
351							echo 'END OF PARAGRAPH:' , '<br />';
352							$this->_flushCell($sheet,$column,$row,$cellContent);
353
354							if (isset($this->_formats[$child->nodeName])) {
355								$sheet->getStyle($column.$row)->applyFromArray($this->_formats[$child->nodeName]);
356							}
357
358							$row += 2;
359							$column = 'A';
360						}
361						break;
362					case 'li'  :
363						if ($this->_tableLevel > 0) {
364							//	If we're inside a table, replace with a \n
365							$cellContent .= "\n";
366							echo 'LIST ENTRY: ' , '<br />';
367							$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
368							echo 'END OF LIST ENTRY:' , '<br />';
369						} else {
370							if ($cellContent > '') {
371								$this->_flushCell($sheet,$column,$row,$cellContent);
372							}
373							++$row;
374							echo 'LIST ENTRY: ' , '<br />';
375							$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
376							echo 'END OF LIST ENTRY:' , '<br />';
377							$this->_flushCell($sheet,$column,$row,$cellContent);
378							$column = 'A';
379						}
380						break;
381					case 'table' :
382						$this->_flushCell($sheet,$column,$row,$cellContent);
383						$column = $this->_setTableStartColumn($column);
384						echo 'START OF TABLE LEVEL ' , $this->_tableLevel , '<br />';
385						if ($this->_tableLevel > 1)
386							--$row;
387						$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
388						echo 'END OF TABLE LEVEL ' , $this->_tableLevel , '<br />';
389						$column = $this->_releaseTableStartColumn();
390						if ($this->_tableLevel > 1) {
391							++$column;
392						} else {
393							++$row;
394						}
395						break;
396					case 'thead' :
397					case 'tbody' :
398						$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
399						break;
400					case 'tr' :
401						++$row;
402						$column = $this->_getTableStartColumn();
403						$cellContent = '';
404						echo 'START OF TABLE ' , $this->_tableLevel , ' ROW<br />';
405						$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
406						echo 'END OF TABLE ' , $this->_tableLevel , ' ROW<br />';
407						break;
408					case 'th' :
409					case 'td' :
410						echo 'START OF TABLE ' , $this->_tableLevel , ' CELL<br />';
411						$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
412						echo 'END OF TABLE ' , $this->_tableLevel , ' CELL<br />';
413						$this->_flushCell($sheet,$column,$row,$cellContent);
414						++$column;
415						break;
416					case 'body' :
417						$row = 1;
418						$column = 'A';
419						$content = '';
420						$this->_tableLevel = 0;
421						$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
422						break;
423					default:
424						$this->_processDomElement($child,$sheet,$row,$column,$cellContent);
425				}
426			}
427		}
428	}
429
430	/**
431	 * Loads PHPExcel from file into PHPExcel instance
432	 *
433	 * @param 	string 		$pFilename
434	 * @param	PHPExcel	$objPHPExcel
435	 * @return 	PHPExcel
436	 * @throws 	Exception
437	 */
438	public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel)
439	{
440		// Check if file exists
441		if (!file_exists($pFilename)) {
442			throw new Exception("Could not open " . $pFilename . " for reading! File does not exist.");
443		}
444
445		if (!is_file($pFilename)) {
446			throw new Exception("Could not open " . $pFilename . " for reading! The given file is not a regular file.");
447		}
448
449		// Create new PHPExcel
450		while ($objPHPExcel->getSheetCount() <= $this->_sheetIndex) {
451			$objPHPExcel->createSheet();
452		}
453		$objPHPExcel->setActiveSheetIndex( $this->_sheetIndex );
454
455		//	Create a new DOM object
456		$dom = new domDocument;
457		//	Load the HTML file into the DOM object
458		$loaded = $dom->loadHTMLFile($pFilename);
459		if ($loaded === false) {
460			throw new Exception('Failed to load ',$pFilename,' as a DOM Document');
461		}
462
463		//	Discard white space
464		$dom->preserveWhiteSpace = false;
465
466
467		$row = 0;
468		$column = 'A';
469		$content = '';
470		$this->_processDomElement($dom,$objPHPExcel->getActiveSheet(),$row,$column,$content);
471
472		echo '<hr />';
473		var_dump($this->_dataArray);
474
475		// Return
476		return $objPHPExcel;
477	}
478
479	/**
480	 * Get sheet index
481	 *
482	 * @return int
483	 */
484	public function getSheetIndex() {
485		return $this->_sheetIndex;
486	}
487
488	/**
489	 * Set sheet index
490	 *
491	 * @param	int		$pValue		Sheet index
492	 * @return PHPExcel_Reader_HTML
493	 */
494	public function setSheetIndex($pValue = 0) {
495		$this->_sheetIndex = $pValue;
496		return $this;
497	}
498
499}