diff --git a/lib/phpword/h2d_htmlconverter.php b/lib/phpword/h2d_htmlconverter.php
new file mode 100755
index 0000000000..8a6ea9e76b
--- /dev/null
+++ b/lib/phpword/h2d_htmlconverter.php
@@ -0,0 +1,783 @@
+ array('p', 'ul', 'ol', 'table', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'),
+ 'h1' => array('a', 'em', 'i', 'strong', 'b', 'br', 'span', 'code', 'u', 'sup', 'text'),
+ 'h2' => array('a', 'em', 'i', 'strong', 'b', 'br', 'span', 'code', 'u', 'sup', 'text'),
+ 'h3' => array('a', 'em', 'i', 'strong', 'b', 'br', 'span', 'code', 'u', 'sup', 'text'),
+ 'h4' => array('a', 'em', 'i', 'strong', 'b', 'br', 'span', 'code', 'u', 'sup', 'text'),
+ 'h5' => array('a', 'em', 'i', 'strong', 'b', 'br', 'span', 'code', 'u', 'sup', 'text'),
+ 'h6' => array('a', 'em', 'i', 'strong', 'b', 'br', 'span', 'code', 'u', 'sup', 'text'),
+ 'p' => array('a', 'em', 'i', 'strong', 'b', 'ul', 'ol', 'img', 'table', 'br', 'span', 'code', 'u', 'sup', 'text', 'div', 'p', 'strike', 'del', 's'), // p does not nest - simple_html_dom will create a flat set of paragraphs if it finds nested ones.
+ 'div' => array('a', 'em', 'i', 'strong', 'b', 'ul', 'ol', 'img', 'table', 'br', 'span', 'code', 'u', 'sup', 'text', 'div', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'strike', 'del'),
+ 'a' => array('text'), // PHPWord doesn't allow elements to be placed in link elements
+ 'em' => array('a', 'strong', 'b', 'br', 'span', 'code', 'u', 'sup', 'text'), // Italic
+ 'i' => array('a', 'strong', 'b', 'br', 'span', 'code', 'u', 'sup', 'text'), // Italic
+ 'strong' => array('a', 'em', 'i', 'br', 'span', 'code', 'u', 'sup', 'text'), // Bold
+ 'b' => array('a', 'em', 'i', 'br', 'span', 'code', 'u', 'sup', 'text'), // Bold
+ 'sup' => array('a', 'em', 'i', 'br', 'span', 'code', 'u', 'text'), // Superscript
+ 'u' => array('a', 'em', 'strong', 'b', 'i', 'br', 'span', 'code', 'sup', 'text'), // Underline - deprecated - but could be encountered.
+ 'ul' => array('li'),
+ 'ol' => array('li'),
+ 'li' => array('a', 'em', 'i', 'strong', 'b', 'ul', 'ol', 'img', 'br', 'span', 'code', 'u', 'sup', 'text'),
+ 'img' => array(),
+ 'table' => array('tbody', 'tr'),
+ 'tbody' => array('tr'),
+ 'tr' => array('td', 'th'),
+ 'td' => array('p', 'a', 'em', 'i', 'strong', 'b', 'ul', 'ol', 'img', 'br', 'span', 'code', 'u', 'sup', 'text', 'table'), // PHPWord does not allow you to insert a table into a table cell
+ 'th' => array('p', 'a', 'em', 'i', 'strong', 'b', 'ul', 'ol', 'img', 'br', 'span', 'code', 'u', 'sup', 'text', 'table'), // PHPWord does not allow you to insert a table into a table cell
+ 'br' => array(),
+ 'code' => array(), // Note, elements nested inside the code element do not work! (Perhaps simpleHTMLDom isn't recognising them).
+ 'span' => array('a', 'em', 'i', 'strong', 'b', 'img', 'br', 'span', 'code', 'sup', 'text', 'del', 'strike', 's'), // Used for styles - underline
+ 'strike' => array('a', 'em', 'i', 'strong', 'b', 'img', 'br', 'span', 'code', 'sup', 'text'),
+ 'del' => array('a', 'em', 'i', 'strong', 'b', 'img', 'br', 'span', 'code', 'sup', 'text'),
+ 's' => array('a', 'em', 'i', 'strong', 'b', 'img', 'br', 'span', 'code', 'sup', 'text'),
+ 'text' => array(), // The tag name used for elements containing just text in SimpleHtmlDom.
+ );
+
+ if (!$tag) {
+ return $allowed_children;
+ }
+ elseif (isset($allowed_children[$tag])) {
+ return $allowed_children[$tag];
+ }
+ else {
+ return array();
+ }
+}
+
+/**
+ * Clean up text:
+ *
+ * @param string $text
+ *
+ */
+function htmltodocx_clean_text($text) {
+
+ // Replace each with a single space:
+ $text = str_replace(' ', ' ', $text);
+ if (strpos($text, '<') !== FALSE) {
+ // We only run strip_tags if it looks like there might be some tags in the text
+ // as strip_tags is expensive:
+ $text = strip_tags($text);
+ }
+
+ // Strip out extra spaces:
+ $text = preg_replace('/\s+/u', ' ', $text);
+
+ // Convert entities:
+ $text = html_entity_decode($text, ENT_COMPAT, 'UTF-8');
+ return $text;
+}
+
+/**
+ * Compute the styles that should be applied for the
+ * current element.
+ * We start with the default style, and successively override
+ * this with the current style, style set for the tag, classes
+ * and inline styles.
+ *
+ */
+function _htmltodocx_get_style($element, $state) {
+
+ $style_sheet = $state['style_sheet'];
+
+ // Get the default styles
+ $phpword_style = $style_sheet['default'];
+
+ // Update with the current style
+ $current_style = $state['current_style'];
+
+ // Remove uninheritable items:
+ $inheritable_props = htmltodocx_inheritable_props();
+ foreach ($current_style as $property => $value) {
+ if (!in_array($property, $inheritable_props)) {
+ unset($current_style[$property]);
+ }
+ }
+
+ $phpword_style = array_merge($phpword_style, $current_style);
+
+ // Update with any styles defined by the element tag
+ $tag_style = isset($style_sheet['elements'][$element->tag]) ? $style_sheet['elements'][$element->tag] : array();
+ $phpword_style = array_merge($phpword_style, $tag_style);
+
+ // Find any classes defined for this element:
+ $class_list = array();
+ if (!empty($element->class)) {
+ $classes = explode(' ', $element->class);
+ foreach ($classes as $class) {
+ $class_list[] = trim($class);
+ }
+ }
+
+ // Look for any style definitions for these classes:
+ $classes_style = array();
+ if (!empty($class_list) && !empty($style_sheet['classes'])) {
+ foreach ($style_sheet['classes'] as $class => $attributes) {
+ if (in_array($class, $class_list)) {
+ $classes_style = array_merge($classes_style, $attributes);
+ }
+ }
+ }
+
+ $phpword_style = array_merge($phpword_style, $classes_style);
+
+ // Find any inline styles:
+ $inline_style_list = array();
+ if (!empty($element->attr['style'])) {
+ $inline_styles = explode(';', rtrim(rtrim($element->attr['style']), ';'));
+ foreach ($inline_styles as $inline_style) {
+ $style_pair = explode(':', $inline_style);
+ $inline_style_list[] = trim($style_pair[0]) . ': ' . trim($style_pair[1]);
+ }
+ }
+
+ // Look for style definitions of these inline styles:
+ $inline_styles = array();
+ if (!empty($inline_style_list) && !empty($style_sheet['inline'])) {
+ foreach ($style_sheet['inline'] as $inline_style => $attributes) {
+ if (in_array($inline_style, $inline_style_list)) {
+ $inline_styles = array_merge($inline_styles, $attributes);
+ }
+ }
+ }
+
+ $phpword_style = array_merge($phpword_style, $inline_styles);
+
+ return $phpword_style;
+}
+
+/**
+ * PHPWord style properties which are inheritable for the purposes of our
+ * conversion:
+ *
+ */
+function htmltodocx_inheritable_props() {
+ return array(
+ 'size',
+ 'name',
+ 'bold',
+ 'italic',
+ 'superScript',
+ 'subScript',
+ 'underline',
+ 'strike',
+ 'strikethrough',
+ 'color',
+ 'fgColor',
+ 'align',
+ 'spacing',
+ 'listType',
+ 'spaceAfter'
+ );
+}
+
+
+/**
+ * Wrapper for htmltodocx_insert_html_recursive()
+ * - inserts the initial defaults.
+ *
+ * @param $phpword_element
+ * PHPWord object
+ * @param mixed $html_dom_array
+ * SimpleHTMLDom object
+ * @param mixed $state
+ * State
+ */
+function htmltodocx_insert_html(&$phpword_element, $html_dom_array, &$state = array()) {
+
+ // Set up initial defaults:
+
+ // Lists:
+ $state['pseudo_list'] = TRUE;
+ // This converter only supports "pseudo" lists at present.
+
+ $state['pseudo_list_indicator_font_name'] = isset($state['pseudo_list_indicator_font_name']) ? $state['pseudo_list_indicator_font_name'] : 'Wingdings'; // Bullet indicator font
+ $state['pseudo_list_indicator_font_size'] = isset($state['pseudo_list_indicator_font_size']) ? $state['pseudo_list_indicator_font_size'] : '7'; // Bullet indicator size
+ $state['pseudo_list_indicator_character'] = isset($state['pseudo_list_indicator_character']) ? $state['pseudo_list_indicator_character'] : 'l '; // Gives a circle bullet point with wingdings
+
+ // "Style sheet":
+ $state['style_sheet'] = isset($state['style_sheet']) ? $state['style_sheet'] : array();
+ $state['style_sheet']['default'] = isset($state['style_sheet']['default']) ? $state['style_sheet']['default'] : array();
+
+ // Current style:
+ $state['current_style'] = isset($state['current_style']) ? $state['current_style'] : array('size' => '11');
+
+ // Parents:
+ $state['parents'] = isset($state['parents']) ? $state['parents'] : array(0 => 'body');
+ $state['list_depth'] = isset($state['list_depth']) ? $state['list_depth'] : 0;
+ $state['context'] = isset($state['context']) ? $state['context'] : 'section';
+ // Possible values - section, footer or header.
+
+ // Tables:
+ if (in_array('td', $state['parents']) || in_array('th', $state['parents']) || (isset($state['table_allowed']) && !$state['table_allowed'])) {
+ $state['table_allowed'] = FALSE;
+ }
+ else {
+ $state['table_allowed'] = TRUE;
+ }
+
+ // Headings option:
+ $state['structure_document'] = isset($state['structure_document']) ? $state['structure_document'] : FALSE;
+
+ if ($state['structure_document']) {
+ $state['structure_headings'] = array('h1' => 1, 'h2' => 2, 'h3' => 3, 'h4' => 4, 'h5' => 5, 'h6' => 6);
+ }
+ if (!$state['structure_document'] || !isset($state['table_of_contents_id'])) {
+ $state['table_of_contents_id'] = FALSE;
+ }
+
+ // Treatment of divs:
+ // The default is to treat a div like a paragraph - that is we insert a new
+ // line each time we encounter a new div.
+ $state['treat_div_as_paragraph'] = isset($state['treat_div_as_paragraph']) ? $state['treat_div_as_paragraph'] : TRUE;
+
+ // Recurse through the HTML Dom inserting elements into the phpword object as
+ // we go:
+ htmltodocx_insert_html_recursive($phpword_element, $html_dom_array, $state);
+}
+
+/**
+ * Populate PHPWord element
+ * This recursive function processes all the elements and child elements
+ * from the DOM array of objects created by SimpleHTMLDom.
+ *
+ * @param object phpword_element
+ * PHPWord object to add in the converted html
+ * @param array $html_dom_array
+ * Array of nodes generated by simple HTML dom
+ * @param array $state
+ * Parameters for the current run
+ */
+function htmltodocx_insert_html_recursive(&$phpword_element, $html_dom_array, &$state = array()) {
+
+ // Go through the html_dom_array, adding bits to go in the PHPWord element
+ $allowed_children = htmltodocx_html_allowed_children($state['parents'][0]);
+
+ // Go through each element:
+ foreach ($html_dom_array as $element) {
+
+ $old_style = $state['current_style'];
+
+ $state['current_style'] = _htmltodocx_get_style($element, $state);
+ if(in_array($element->tag, ['del', 's', 'strike'])) $state['current_style']['strikethrough'] = true;
+
+ switch ($element->tag) {
+
+ case 'p':
+ case 'div': // Treat a div as a paragraph
+ case 'h1':
+ case 'h2':
+ case 'h3':
+ case 'h4':
+ case 'h5':
+ case 'h6':
+
+ if ($state['structure_document'] && in_array($element->tag, array('h1', 'h2', 'h3', 'h4', 'h5', 'h6')) && is_object($state['phpword_object'])) {
+ // If the structure_document option has been enabled, then headings
+ // are used to create Word heading styles. Note, in this case, any
+ // nested elements within the heading are displayed as text only.
+ // Additionally we don't now add a text break after a heading where
+ // sizeAfter has not been set.
+ $state['phpword_object']->addTitleStyle($state['structure_headings'][$element->tag], $state['current_style']);
+ $phpword_element->addTitle(htmltodocx_clean_text($element->innertext), $state['structure_headings'][$element->tag]);
+ break;
+ }
+
+ if ($element->tag == 'div' && $state['table_of_contents_id'] && $element->id == $state['table_of_contents_id']) {
+ // Replace this div with a table of contents:
+ $phpword_element->addTOC($state['current_style'], $state['current_style']);
+ break;
+ }
+
+ // Everything in this element should be in the same text run
+ // we need to initiate a text run here and pass it on. Starting one of
+ // these elements will cause a new line to be added in the Word
+ // document. In the case of divs this might not always be what is
+ // wanted the setting 'treat_div_as_paragraph' determines whether or
+ // not to add new lines for divs.
+ if ($element->tag != 'div' || $state['treat_div_as_paragraph'] || !isset($state['textrun'])) {
+ $state['textrun'] = $phpword_element->createTextRun($state['current_style']);
+ }
+
+ // For better usability for the end user of the Word document, we
+ // separate paragraphs and headings with an empty line. You can
+ // override this behaviour by setting the spaceAfter parameter for
+ // the current element.
+
+ // If the spaceAfter parameter is not set, we set it temporarily to 0
+ // here and record that it wasn't set in the style. Later we will add
+ // an empty line. Word 2007 and later have a non-zero default for
+ // paragraph separation, so without setting that spacing to 0 here we
+ // would end up with a large gap between paragraphs (the document
+ // template default plus the extra line).
+ $space_after_set = TRUE;
+ if (!isset($state['current_style']['spaceAfter'])) {
+ $state['current_style']['spaceAfter'] = 0;
+ $space_after_set = FALSE;
+ }
+
+ if (in_array($element->tag, $allowed_children)) {
+ array_unshift($state['parents'], $element->tag);
+ htmltodocx_insert_html_recursive($phpword_element, $element->nodes, $state);
+ array_shift($state['parents']);
+ }
+ else {
+ $state['textrun']->addText(htmltodocx_clean_text($element->innertext), $state['current_style']);
+ }
+ unset($state['textrun']);
+ if (!$space_after_set) {
+ // Add the text break here - where the spaceAfter parameter hadn't
+ // been set initially - also unset the spaceAfter parameter we just
+ // set:
+ $phpword_element->addTextBreak();
+ unset($state['current_style']['spaceAfter']);
+ }
+ break;
+
+ case 'table':
+ if (in_array('table', $allowed_children)) {
+ $old_table_state = $state['table_allowed'];
+ if (!$state['table_allowed'] || in_array('td', $state['parents']) || in_array('th', $state['parents'])) {
+ $state['table_allowed'] = FALSE; // This is a PHPWord constraint
+ }
+ else {
+ $state['table_allowed'] = TRUE;
+ // PHPWord allows table_styles to be passed in a couple of
+ // different ways either using an array of properties, or by
+ // defining a full table style on the PHPWord object:
+ if (is_object($state['phpword_object']) && method_exists($state['phpword_object'], 'addTableStyle')) {
+ $state['phpword_object']->addTableStyle('temp_table_style', $state['current_style']);
+ $table_style = 'temp_table_style';
+ }
+ else {
+ $table_style = $state['current_style'];
+ }
+ $table_style['unit'] = \PhpOffice\PhpWord\Style\Table::WIDTH_PERCENT;
+ $table_style['width'] = 5000;
+ $state['table'] = $phpword_element->addTable($table_style);
+ }
+ array_unshift($state['parents'], 'table');
+ htmltodocx_insert_html_recursive($phpword_element, $element->nodes, $state);
+ array_shift($state['parents']);
+ // Reset table state to what it was before a table was added:
+ $state['table_allowed'] = $old_table_state;
+ $phpword_element->addTextBreak();
+ }
+ else {
+ $state['textrun'] = $phpword_element->createTextRun();
+ $state['textrun']->addText(htmltodocx_clean_text($element->innertext), $state['current_style']);
+ }
+ break;
+
+ case 'tbody':
+ if (in_array('tbody', $allowed_children)) {
+ array_unshift($state['parents'], 'tbody');
+ htmltodocx_insert_html_recursive($phpword_element, $element->nodes, $state);
+ array_shift($state['parents']);
+ }
+ else {
+ $state['textrun'] = $phpword_element->createTextRun();
+ $state['textrun']->addText(htmltodocx_clean_text($element->innertext), $state['current_style']);
+ }
+ break;
+
+ case 'tr':
+ if (in_array('tr', $allowed_children)) {
+ if ($state['table_allowed']) {
+ $state['table']->addRow();
+ }
+ else {
+ // Simply add a new line if a table is not possible in this
+ // context:
+ $state['textrun'] = $phpword_element->createTextRun();
+ }
+ array_unshift($state['parents'], 'tr');
+ htmltodocx_insert_html_recursive($phpword_element, $element->nodes, $state);
+ array_shift($state['parents']);
+ }
+ else {
+ $state['textrun'] = $phpword_element->createTextRun();
+ $state['textrun']->addText(htmltodocx_clean_text($element->innertext), $state['current_style']);
+ }
+ break;
+
+ case 'td':
+ case 'th':
+ if (in_array($element->tag, $allowed_children) && $state['table_allowed']) {
+ unset($state['textrun']);
+ if (isset($state['current_style']['width'])) {
+ $cell_width = $state['current_style']['width'];
+ }
+ elseif (isset($element->width) and is_numeric($element->width)) {
+ $cell_width = $element->width * 15;
+ // Converting at 15 TWIPS per pixel.
+ }
+ else {
+ $cell_width = 800;
+ }
+ $colspan = $element->getAttribute('colspan');
+ if(is_numeric($colspan) && $colspan > 1) $state['current_style']['gridSpan'] = $colspan;
+ $state['table_cell'] = $state['table']->addCell($cell_width, $state['current_style']);
+ array_unshift($state['parents'], $element->tag);
+ htmltodocx_insert_html_recursive($state['table_cell'], $element->nodes, $state);
+ array_shift($state['parents']);
+ }
+ else {
+ if (!isset($state['textrun'])) {
+ $state['textrun'] = $phpword_element->createTextRun();
+ }
+ $state['textrun']->addText(htmltodocx_clean_text($element->innertext), $state['current_style']);
+ }
+ break;
+
+ case 'a':
+ // Create a new text run if we aren't in one already:
+ if (!isset($state['textrun'])) {
+ $state['textrun'] = $phpword_element->createTextRun();
+ }
+ if ($state['context'] == 'section') {
+
+ if (strpos($element->href, 'http://') === 0) {
+ $href = $element->href;
+ }
+ elseif (strpos($element->href, '/') === 0) {
+ $href = $state['base_root'] . $element->href;
+ }
+ else {
+ $href = $state['base_root'] . $state['base_path'] . $element->href;
+ }
+ // Replace any spaces in url with %20 - to prevent errors in the Word
+ // document:
+ $state['textrun']->addLink(htmltodocx_url_encode_chars($href), htmltodocx_clean_text($element->innertext), $state['current_style']);
+ }
+ else {
+ // Links can't seem to be included in headers or footers with
+ // PHPWord: trying to include them causes an error which stops Word
+ // from opening the file - in Word 2003 with the converter at least.
+ // So add the link styled as a link only.
+ $state['textrun']->addText(htmltodocx_clean_text($element->innertext), $state['current_style']);
+ }
+ break;
+
+ case 'ul':
+ $state['list_total_count'] = count($element->children);
+ // We use this to be able to add the ordered list spaceAfter onto the
+ // last list element. All ol children should be li elements.
+ _htmltodocx_add_list_start_end_spacing_style($state);
+ $state['list_number'] = 0; // Reset list number.
+ if (in_array('ul', $allowed_children)) {
+ if (!isset($state['pseudo_list'])) {
+ // Unset any existing text run:
+ unset($state['textrun']);
+ // PHPWord lists cannot appear in a text run. If we leave a text
+ // run active then subsequent text will go in that text run (if it
+ // isn't re-initialised), which would mean that text after this
+ // list would appear before it in the Word document.
+ }
+ array_unshift($state['parents'], 'ul');
+ htmltodocx_insert_html_recursive($phpword_element, $element->nodes, $state);
+ array_shift($state['parents']);
+ }
+ else {
+ $state['textrun'] = $phpword_element->createTextRun();
+ $state['textrun']->addText(htmltodocx_clean_text($element->innertext), $state['current_style']);
+ }
+ break;
+
+ case 'ol':
+ $state['list_total_count'] = count($element->children);
+ // We use this to be able to add the ordered list spaceAfter onto the
+ // last list element. All ol children should be li elements.
+ _htmltodocx_add_list_start_end_spacing_style($state);
+ $state['list_number'] = 0; // Reset list number.
+ if (in_array('ol', $allowed_children)) {
+ if (!isset($state['pseudo_list'])) {
+ // Unset any existing text run:
+ unset($state['textrun']);
+ // Lists cannot appear in a text run. If we leave a text run active
+ // then subsequent text will go in that text run (if it isn't
+ // re-initialised), which would mean that text after this list
+ // would appear before it in the Word document.
+ }
+ array_unshift($state['parents'], 'ol');
+ htmltodocx_insert_html_recursive($phpword_element, $element->nodes, $state);
+ array_shift($state['parents']);
+ }
+ else {
+ $state['textrun'] = $phpword_element->createTextRun();
+ $state['textrun']->addText(htmltodocx_clean_text($element->innertext), $state['current_style']);
+ }
+ break;
+
+ case 'li':
+ // You cannot style individual pieces of text in a list element so we do it
+ // with text runs instead. This does not allow us to indent lists at all, so
+ // we can't show nesting.
+
+ // Before and after spacings:
+ if ($state['list_number'] === 0) {
+ $state['current_style'] = array_merge($state['current_style'], $state['list_style_before']);
+ }
+ $last_item = FALSE;
+ if ($state['list_number'] == $state['list_total_count'] - 1) {
+ $last_item = TRUE;
+ if (empty($state['list_style_after'])) {
+ $state['current_style']['spaceAfter'] = 0;
+ // Set to 0 if not defined so we can add a text break without
+ // ending up within too much space in Word2007+.
+ // *Needs further testing on Word 2007+*
+ }
+ $state['current_style'] = array_merge($state['current_style'], $state['list_style_after']);
+ }
+
+ // We create a new text run for each element:
+ $state['textrun'] = $phpword_element->createTextRun($state['current_style']);
+
+ if (in_array('li', $allowed_children)) {
+ $state['list_number']++;
+ if ($state['parents'][0] == 'ol') {
+ $item_indicator = $state['list_number'] . '. ';
+ $style = $state['current_style'];
+ }
+ else {
+ $style = $state['current_style'];
+ $style['name'] = $state['pseudo_list_indicator_font_name'];
+ $style['size'] = $state['pseudo_list_indicator_font_size'];
+ $item_indicator = $state['pseudo_list_indicator_character'];
+ }
+ array_unshift($state['parents'], 'li');
+ $state['textrun']->addText($item_indicator, $style);
+ htmltodocx_insert_html_recursive($phpword_element, $element->nodes, $state);
+ array_shift($state['parents']);
+ }
+ else {
+ $state['textrun']->addText(htmltodocx_clean_text($element->innertext), $state['current_style']);
+ }
+ if ($last_item && empty($state['list_style_after'])) {
+ $phpword_element->addTextBreak();
+ // Add an empty line after the list if no spacing after has been
+ // defined.
+ }
+ unset($state['textrun']);
+ break;
+
+ case 'text':
+ // We may get some empty text nodes - containing just a space - in
+ // simple HTML dom - we want to exclude those, as these can cause extra
+ // line returns. However we don't want to exclude spaces between styling
+ // elements (these will be within a text run).
+ if (!isset($state['textrun'])) {
+ $text = htmltodocx_clean_text(trim($element->innertext));
+ }
+ else {
+ $text = htmltodocx_clean_text($element->innertext);
+ }
+ if (!empty($text)) {
+ if (!isset($state['textrun'])) {
+ $state['textrun'] = $phpword_element->createTextRun();
+ }
+ $state['textrun']->addText($text, $state['current_style']);
+ }
+ break;
+
+ // Style tags:
+ case 'strong':
+ case 'b':
+ case 'sup': // Not working in PHPWord
+ case 'em':
+ case 'i':
+ case 'u':
+ case 'span':
+ case 'strike':
+ case 's':
+ case 'del':
+ case 'code':
+ // Create a new text run if we aren't in one already:
+ if (!isset($state['textrun'])) {
+ $state['textrun'] = $phpword_element->createTextRun();
+ }
+ if (in_array($element->tag, $allowed_children)) {
+ array_unshift($state['parents'], $element->tag);
+ htmltodocx_insert_html_recursive($phpword_element, $element->nodes, $state);
+ array_shift($state['parents']);
+ }
+ else {
+ $state['textrun']->addText(htmltodocx_clean_text($element->innertext), $state['current_style']);
+ }
+
+ break;
+ case 'pre':
+ $codeFontStyle = array('name' => 'Courier New', 'size' => 10, 'color' => '000000');
+ $codeParagraphStyle = array('align' => 'left', 'spaceAfter' => 0, 'spaceBefore' => 0, 'spacing' => 120);
+
+ if(strpos($element->innertext, '') !== false)
+ {
+ $element->innertext = str_replace('', '', $element->innertext);
+ $element->innertext = str_replace('', '', $element->innertext);
+ }
+
+ /* 使用普通段落处理 pre 标签,保留换行和空格。 */
+ /* Use normal paragraph to handle pre tag, keep line breaks and spaces. */
+ $lines = explode("\n", $element->innertext);
+
+ foreach($lines as $line)
+ {
+ /* 为每一行创建一个新的段落 */
+ /* Create a new paragraph for each line */
+ $textrun = $phpword_element->createTextRun($codeParagraphStyle);
+ $textrun->addText($line, $codeFontStyle);
+ }
+
+ break;
+ // NB, Simple HTML Dom might not be picking up
tags.
+ case 'br':
+ // Simply create a new text run:
+ $state['textrun'] = $phpword_element->createTextRun();
+ break;
+
+ case 'img':
+ $image_style = array();
+ if ($element->height && $element->width) {
+ $state['current_style']['height'] = $element->height;
+ $state['current_style']['width'] = $element->width;
+ }
+
+ if (strpos($element->src, $state['base_root']) === 0) {
+ // The image source is a full url, but nevertheless it is on this
+ // server.
+ $element_src = substr($element->src, strlen($state['base_root']));
+ }
+ else {
+ $element_src = $element->src;
+ }
+
+ if(strpos($element_src, 'http://') === 0 or is_file($element_src)) {
+ // The image url is from another site. Most probably the image won't
+ // appear in the Word document.
+ $src = $element_src;
+ }
+ elseif (strpos($element_src, '/') === 0) {
+ $src = htmltodocx_doc_root() . $element_src;
+ }
+ else {
+ $src = htmltodocx_doc_root() . $state['base_path'] . $element_src;
+ }
+
+ $phpword_element->addImage($src, $state['current_style']);
+
+ break;
+
+ default:
+ $state['textrun'] = $phpword_element->createTextRun();
+ $state['textrun']->addText(htmltodocx_clean_text($element->innertext), $state['current_style']);
+ break;
+ }
+
+ // Reset the style back to what it was:
+ $state['current_style'] = $old_style;
+ }
+}
+
+/**
+ * Before/after styles for list elements - recorded
+ * for use by the first or last item in a list.
+ *
+ */
+function _htmltodocx_add_list_start_end_spacing_style(&$state) {
+
+ $state['list_style_after'] = isset($state['current_style']['spaceAfter']) ? array('spaceAfter' => $state['current_style']['spaceAfter']) : array();
+
+ $state['list_style_before'] = isset($state['current_style']['spaceBefore']) ? array('spaceBefore' => $state['current_style']['spaceBefore']) : array();
+
+}
+
+/**
+ * Get the document root.
+ *
+ */
+function htmltodocx_doc_root() {
+
+ $local_path = getenv("SCRIPT_NAME");
+
+ // Should be available on both Apache and non Apache servers.
+ $local_dir = substr($local_path, 0, strrpos($local_path, '/'));
+
+ if (empty($local_dir)) {
+ return $_SERVER['DOCUMENT_ROOT'];
+ }
+ else {
+ return dirname($_SERVER['SCRIPT_FILENAME']);
+ //return substr(realpath(''), 0, -1 * strlen($local_dir));
+ }
+}
+
+/**
+ * Encodes selected characters in a url to prevent errors in the created Word
+ * document. Note: if there is a space in the url and there isn't a forward
+ * slash preceding it at some point, the resulting Word document will be
+ * corrupted (even where the space has been urlencoded). We convert spaces to
+ * %20 which stops this corruption in circumstances where a forward slash is
+ * present.
+ *
+ */
+function htmltodocx_url_encode_chars($url) {
+
+ // List the characters in this array to be encoded:
+ $encode_chars = array(' ');
+
+ foreach ($encode_chars as $char) {
+ $encoded_chars[] = rawurlencode($char);
+ }
+
+ $encoded_url = str_replace($encode_chars, $encoded_chars, $url);
+
+ return $encoded_url;
+}
diff --git a/lib/phpword/phpword.class.php b/lib/phpword/phpword.class.php
new file mode 100644
index 0000000000..968d4b8c9c
--- /dev/null
+++ b/lib/phpword/phpword.class.php
@@ -0,0 +1,15 @@
+instance = new self::$className();
+ }
+}
diff --git a/lib/phpword/simple_html_dom.php b/lib/phpword/simple_html_dom.php
new file mode 100755
index 0000000000..b1a8da3901
--- /dev/null
+++ b/lib/phpword/simple_html_dom.php
@@ -0,0 +1,1393 @@
+size is the "real" number of bytes the dom was created from.
+ * but for most purposes, it's a really good estimation.
+ * Paperg - Added the forceTagsClosed to the dom constructor. Forcing tags closed is great for malformed html, but it CAN lead to parsing errors.
+ * Allow the user to tell us how much they trust the html.
+ * Paperg add the text and plaintext to the selectors for the find syntax. plaintext implies text in the innertext of a node. text implies that the tag is a text node.
+ * This allows for us to find tags based on the text they contain.
+ * Create find_ancestor_tag to see if a tag is - at any level - inside of another specific tag.
+ * Paperg: added parse_charset so that we know about the character set of the source document.
+ * NOTE: If the user's system has a routine called get_last_retrieve_url_contents_content_type availalbe, we will assume it's returning the content-type header from the
+ * last transfer or curl_exec, and we will parse that and use it in preference to any other method of charset detection.
+ *
+ * Licensed under The MIT License
+ * Redistributions of files must retain the above copyright notice.
+ *
+ * @author S.C. Chen
+ * @author John Schlick
+ * @author Rus Carroll
+ * @version 1.11 ($Rev: 184 $)
+ * @package PlaceLocalInclude
+ * @subpackage simple_html_dom
+ */
+
+/**
+ * All of the Defines for the classes below.
+ * @author S.C. Chen
+ */
+define('HDOM_TYPE_ELEMENT', 1);
+define('HDOM_TYPE_COMMENT', 2);
+define('HDOM_TYPE_TEXT', 3);
+define('HDOM_TYPE_ENDTAG', 4);
+define('HDOM_TYPE_ROOT', 5);
+define('HDOM_TYPE_UNKNOWN', 6);
+define('HDOM_QUOTE_DOUBLE', 0);
+define('HDOM_QUOTE_SINGLE', 1);
+define('HDOM_QUOTE_NO', 3);
+define('HDOM_INFO_BEGIN', 0);
+define('HDOM_INFO_END', 1);
+define('HDOM_INFO_QUOTE', 2);
+define('HDOM_INFO_SPACE', 3);
+define('HDOM_INFO_TEXT', 4);
+define('HDOM_INFO_INNER', 5);
+define('HDOM_INFO_OUTER', 6);
+define('HDOM_INFO_ENDSPACE',7);
+define('DEFAULT_TARGET_CHARSET', 'UTF-8');
+define('DEFAULT_BR_TEXT', "\r\n");
+// helper functions
+// -----------------------------------------------------------------------------
+// get html dom from file
+// $maxlen is defined in the code as PHP_STREAM_COPY_ALL which is defined as -1.
+function file_get_html($url, $use_include_path = false, $context=null, $offset = -1, $maxLen=-1, $lowercase = true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT)
+{
+ // We DO force the tags to be terminated.
+ $dom = new simple_html_dom(null, $lowercase, $forceTagsClosed, $target_charset, $defaultBRText);
+ // For sourceforge users: uncomment the next line and comment the retreive_url_contents line 2 lines down if it is not already done.
+ $contents = file_get_contents($url, $use_include_path, $context, $offset);
+ // Paperg - use our own mechanism for getting the contents as we want to control the timeout.
+// $contents = retrieve_url_contents($url);
+ if (empty($contents))
+ {
+ return false;
+ }
+ // The second parameter can force the selectors to all be lowercase.
+ $dom->load($contents, $lowercase, $stripRN);
+ return $dom;
+}
+
+// get html dom from string
+function str_get_html($str, $lowercase=true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT)
+{
+ $dom = new simple_html_dom(null, $lowercase, $forceTagsClosed, $target_charset, $defaultBRText);
+ if (empty($str))
+ {
+ $dom->clear();
+ return false;
+ }
+ $dom->load($str, $lowercase, $stripRN);
+ return $dom;
+}
+
+// dump html dom tree
+function dump_html_tree($node, $show_attr=true, $deep=0)
+{
+ $node->dump($node);
+}
+
+/**
+ * simple html dom node
+ * PaperG - added ability for "find" routine to lowercase the value of the selector.
+ * PaperG - added $tag_start to track the start position of the tag in the total byte index
+ *
+ * @package PlaceLocalInclude
+ */
+class simple_html_dom_node {
+ public $nodetype = HDOM_TYPE_TEXT;
+ public $tag = 'text';
+ public $attr = array();
+ public $children = array();
+ public $nodes = array();
+ public $parent = null;
+ public $_ = array();
+ public $tag_start = 0;
+ private $dom = null;
+
+ function __construct($dom)
+ {
+ $this->dom = $dom;
+ $dom->nodes[] = $this;
+ }
+
+ function __destruct()
+ {
+ $this->clear();
+ }
+
+ function __toString()
+ {
+ return $this->outertext();
+ }
+
+ // clean up memory due to php5 circular references memory leak...
+ function clear()
+ {
+ $this->dom = null;
+ $this->nodes = null;
+ $this->parent = null;
+ $this->children = null;
+ }
+
+ // dump node's tree
+ function dump($show_attr=true, $deep=0)
+ {
+ $lead = str_repeat(' ', $deep);
+
+ echo $lead.$this->tag;
+ if ($show_attr && count($this->attr)>0)
+ {
+ echo '(';
+ foreach ($this->attr as $k=>$v)
+ echo "[$k]=>\"".$this->$k.'", ';
+ echo ')';
+ }
+ echo "\n";
+
+ foreach ($this->nodes as $c)
+ $c->dump($show_attr, $deep+1);
+ }
+
+
+ // Debugging function to dump a single dom node with a bunch of information about it.
+ function dump_node()
+ {
+ echo $this->tag;
+ if (count($this->attr)>0)
+ {
+ echo '(';
+ foreach ($this->attr as $k=>$v)
+ {
+ echo "[$k]=>\"".$this->$k.'", ';
+ }
+ echo ')';
+ }
+ if (count($this->attr)>0)
+ {
+ echo ' $_ (';
+ foreach ($this->_ as $k=>$v)
+ {
+ if (is_array($v))
+ {
+ echo "[$k]=>(";
+ foreach ($v as $k2=>$v2)
+ {
+ echo "[$k2]=>\"".$v2.'", ';
+ }
+ echo ")";
+ } else {
+ echo "[$k]=>\"".$v.'", ';
+ }
+ }
+ echo ")";
+ }
+
+ if (isset($this->text))
+ {
+ echo " text: (" . $this->text . ")";
+ }
+
+ echo " children: " . count($this->children);
+ echo " nodes: " . count($this->nodes);
+ echo " tag_start: " . $this->tag_start;
+ echo "\n";
+
+ }
+
+ // returns the parent of node
+ function parent()
+ {
+ return $this->parent;
+ }
+
+ // returns children of node
+ function children($idx=-1)
+ {
+ if ($idx===-1) return $this->children;
+ if (isset($this->children[$idx])) return $this->children[$idx];
+ return null;
+ }
+
+ // returns the first child of node
+ function first_child()
+ {
+ if (count($this->children)>0) return $this->children[0];
+ return null;
+ }
+
+ // returns the last child of node
+ function last_child()
+ {
+ if (($count=count($this->children))>0) return $this->children[$count-1];
+ return null;
+ }
+
+ // returns the next sibling of node
+ function next_sibling()
+ {
+ if ($this->parent===null) return null;
+ $idx = 0;
+ $count = count($this->parent->children);
+ while ($idx<$count && $this!==$this->parent->children[$idx])
+ ++$idx;
+ if (++$idx>=$count) return null;
+ return $this->parent->children[$idx];
+ }
+
+ // returns the previous sibling of node
+ function prev_sibling()
+ {
+ if ($this->parent===null) return null;
+ $idx = 0;
+ $count = count($this->parent->children);
+ while ($idx<$count && $this!==$this->parent->children[$idx])
+ ++$idx;
+ if (--$idx<0) return null;
+ return $this->parent->children[$idx];
+ }
+
+ // function to locate a specific ancestor tag in the path to the root.
+ function find_ancestor_tag($tag)
+ {
+ global $debugObject;
+ if (is_object($debugObject))
+ {
+ $debugObject->debugLogEntry(1);
+ }
+
+ // Start by including ourselves in the comparison.
+ $returnDom = $this;
+
+ while (!is_null($returnDom))
+ {
+ if (is_object($debugObject))
+ {
+ $debugObject->debugLog(2, "Current tag is: " . $returnDom->tag);
+ }
+
+ if ($returnDom->tag == $tag)
+ {
+ break;
+ }
+ $returnDom = $returnDom->parent;
+ }
+ return $returnDom;
+ }
+
+ // get dom node's inner html
+ function innertext()
+ {
+ if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER];
+ if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
+
+ $ret = '';
+ foreach ($this->nodes as $n)
+ $ret .= $n->outertext();
+ return $ret;
+ }
+
+ // get dom node's outer text (with tag)
+ function outertext()
+ {
+ global $debugObject;
+ if (is_object($debugObject))
+ {
+ $text = '';
+ if ($this->tag == 'text')
+ {
+ if (!empty($this->text))
+ {
+ $text = " with text: " . $this->text;
+ }
+ }
+ $debugObject->debugLog(1, 'Innertext of tag: ' . $this->tag . $text);
+ }
+
+ if ($this->tag==='root') return $this->innertext();
+
+ // trigger callback
+ if ($this->dom && $this->dom->callback!==null)
+ {
+ call_user_func_array($this->dom->callback, array($this));
+ }
+
+ if (isset($this->_[HDOM_INFO_OUTER])) return $this->_[HDOM_INFO_OUTER];
+ if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
+
+ // render begin tag
+ if ($this->dom && $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]])
+ {
+ $ret = $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]]->makeup();
+ } else {
+ $ret = "";
+ }
+
+ // render inner text
+ if (isset($this->_[HDOM_INFO_INNER]))
+ {
+ // If it's a br tag... don't return the HDOM_INNER_INFO that we may or may not have added.
+ if ($this->tag != "br")
+ {
+ $ret .= $this->_[HDOM_INFO_INNER];
+ }
+ } else {
+ if ($this->nodes)
+ {
+ foreach ($this->nodes as $n)
+ {
+ $ret .= $this->convert_text($n->outertext());
+ }
+ }
+ }
+
+ // render end tag
+ if (isset($this->_[HDOM_INFO_END]) && $this->_[HDOM_INFO_END]!=0)
+ $ret .= ''.$this->tag.'>';
+ return $ret;
+ }
+
+ // get dom node's plain text
+ function text()
+ {
+ if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER];
+ switch ($this->nodetype)
+ {
+ case HDOM_TYPE_TEXT: return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
+ case HDOM_TYPE_COMMENT: return '';
+ case HDOM_TYPE_UNKNOWN: return '';
+ }
+ if (strcasecmp($this->tag, 'script')===0) return '';
+ if (strcasecmp($this->tag, 'style')===0) return '';
+
+ $ret = '';
+ // In rare cases, (always node type 1 or HDOM_TYPE_ELEMENT - observed for some span tags, and some p tags) $this->nodes is set to NULL.
+ // NOTE: This indicates that there is a problem where it's set to NULL without a clear happening.
+ // WHY is this happening?
+ if (!is_null($this->nodes))
+ {
+ foreach ($this->nodes as $n)
+ {
+ $ret .= $this->convert_text($n->text());
+ }
+ }
+ return $ret;
+ }
+
+ function xmltext()
+ {
+ $ret = $this->innertext();
+ $ret = str_ireplace('', '', $ret);
+ return $ret;
+ }
+
+ // build node's text with tag
+ function makeup()
+ {
+ // text, comment, unknown
+ if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
+
+ $ret = '<'.$this->tag;
+ $i = -1;
+
+ foreach ($this->attr as $key=>$val)
+ {
+ ++$i;
+
+ // skip removed attribute
+ if ($val===null || $val===false)
+ continue;
+
+ $ret .= $this->_[HDOM_INFO_SPACE][$i][0];
+ //no value attr: nowrap, checked selected...
+ if ($val===true)
+ $ret .= $key;
+ else {
+ switch ($this->_[HDOM_INFO_QUOTE][$i])
+ {
+ case HDOM_QUOTE_DOUBLE: $quote = '"'; break;
+ case HDOM_QUOTE_SINGLE: $quote = '\''; break;
+ default: $quote = '';
+ }
+ $ret .= $key.$this->_[HDOM_INFO_SPACE][$i][1].'='.$this->_[HDOM_INFO_SPACE][$i][2].$quote.$val.$quote;
+ }
+ }
+ $ret = $this->dom->restore_noise($ret);
+ return $ret . $this->_[HDOM_INFO_ENDSPACE] . '>';
+ }
+
+ // find elements by css selector
+ //PaperG - added ability for find to lowercase the value of the selector.
+ function find($selector, $idx=null, $lowercase=false)
+ {
+ $selectors = $this->parse_selector($selector);
+ if (($count=count($selectors))===0) return array();
+ $found_keys = array();
+
+ // find each selector
+ for ($c=0; $c<$count; ++$c)
+ {
+ // The change on the below line was documented on the sourceforge code tracker id 2788009
+ // used to be: if (($levle=count($selectors[0]))===0) return array();
+ if (($levle=count($selectors[$c]))===0) return array();
+ if (!isset($this->_[HDOM_INFO_BEGIN])) return array();
+
+ $head = array($this->_[HDOM_INFO_BEGIN]=>1);
+
+ // handle descendant selectors, no recursive!
+ for ($l=0; $l<$levle; ++$l)
+ {
+ $ret = array();
+ foreach ($head as $k=>$v)
+ {
+ $n = ($k===-1) ? $this->dom->root : $this->dom->nodes[$k];
+ //PaperG - Pass this optional parameter on to the seek function.
+ $n->seek($selectors[$c][$l], $ret, $lowercase);
+ }
+ $head = $ret;
+ }
+
+ foreach ($head as $k=>$v)
+ {
+ if (!isset($found_keys[$k]))
+ $found_keys[$k] = 1;
+ }
+ }
+
+ // sort keys
+ ksort($found_keys);
+
+ $found = array();
+ foreach ($found_keys as $k=>$v)
+ $found[] = $this->dom->nodes[$k];
+
+ // return nth-element or array
+ if (is_null($idx)) return $found;
+ else if ($idx<0) $idx = count($found) + $idx;
+ return (isset($found[$idx])) ? $found[$idx] : null;
+ }
+
+ // seek for given conditions
+ // PaperG - added parameter to allow for case insensitive testing of the value of a selector.
+ protected function seek($selector, &$ret, $lowercase=false)
+ {
+ global $debugObject;
+ if (is_object($debugObject))
+ {
+ $debugObject->debugLogEntry(1);
+ }
+
+ list($tag, $key, $val, $exp, $no_key) = $selector;
+
+ // xpath index
+ if ($tag && $key && is_numeric($key))
+ {
+ $count = 0;
+ foreach ($this->children as $c)
+ {
+ if ($tag==='*' || $tag===$c->tag) {
+ if (++$count==$key) {
+ $ret[$c->_[HDOM_INFO_BEGIN]] = 1;
+ return;
+ }
+ }
+ }
+ return;
+ }
+
+ $end = (!empty($this->_[HDOM_INFO_END])) ? $this->_[HDOM_INFO_END] : 0;
+ if ($end==0) {
+ $parent = $this->parent;
+ while (!isset($parent->_[HDOM_INFO_END]) && $parent!==null) {
+ $end -= 1;
+ $parent = $parent->parent;
+ }
+ $end += $parent->_[HDOM_INFO_END];
+ }
+
+ for ($i=$this->_[HDOM_INFO_BEGIN]+1; $i<$end; ++$i) {
+ $node = $this->dom->nodes[$i];
+
+ $pass = true;
+
+ if ($tag==='*' && !$key) {
+ if (in_array($node, $this->children, true))
+ $ret[$i] = 1;
+ continue;
+ }
+
+ // compare tag
+ if ($tag && $tag!=$node->tag && $tag!=='*') {$pass=false;}
+ // compare key
+ if ($pass && $key) {
+ if ($no_key) {
+ if (isset($node->attr[$key])) $pass=false;
+ } else {
+ if (($key != "plaintext") && !isset($node->attr[$key])) $pass=false;
+ }
+ }
+ // compare value
+ if ($pass && $key && $val && $val!=='*') {
+ // If they have told us that this is a "plaintext" search then we want the plaintext of the node - right?
+ if ($key == "plaintext") {
+ // $node->plaintext actually returns $node->text();
+ $nodeKeyValue = $node->text();
+ } else {
+ // this is a normal search, we want the value of that attribute of the tag.
+ $nodeKeyValue = $node->attr[$key];
+ }
+ if (is_object($debugObject)) {$debugObject->debugLog(2, "testing node: " . $node->tag . " for attribute: " . $key . $exp . $val . " where nodes value is: " . $nodeKeyValue);}
+
+ //PaperG - If lowercase is set, do a case insensitive test of the value of the selector.
+ if ($lowercase) {
+ $check = $this->match($exp, strtolower($val), strtolower($nodeKeyValue));
+ } else {
+ $check = $this->match($exp, $val, $nodeKeyValue);
+ }
+ if (is_object($debugObject)) {$debugObject->debugLog(2, "after match: " . ($check ? "true" : "false"));}
+
+ // handle multiple class
+ if (!$check && strcasecmp($key, 'class')===0) {
+ foreach (explode(' ',$node->attr[$key]) as $k) {
+ // Without this, there were cases where leading, trailing, or double spaces lead to our comparing blanks - bad form.
+ if (!empty($k)) {
+ if ($lowercase) {
+ $check = $this->match($exp, strtolower($val), strtolower($k));
+ } else {
+ $check = $this->match($exp, $val, $k);
+ }
+ if ($check) break;
+ }
+ }
+ }
+ if (!$check) $pass = false;
+ }
+ if ($pass) $ret[$i] = 1;
+ unset($node);
+ }
+ // It's passed by reference so this is actually what this function returns.
+ if (is_object($debugObject)) {$debugObject->debugLog(1, "EXIT - ret: ", $ret);}
+ }
+
+ protected function match($exp, $pattern, $value) {
+ global $debugObject;
+ if (is_object($debugObject)) {$debugObject->debugLogEntry(1);}
+
+ switch ($exp) {
+ case '=':
+ return ($value===$pattern);
+ case '!=':
+ return ($value!==$pattern);
+ case '^=':
+ return preg_match("/^".preg_quote($pattern,'/')."/", $value);
+ case '$=':
+ return preg_match("/".preg_quote($pattern,'/')."$/", $value);
+ case '*=':
+ if ($pattern[0]=='/') {
+ return preg_match($pattern, $value);
+ }
+ return preg_match("/".$pattern."/i", $value);
+ }
+ return false;
+ }
+
+ protected function parse_selector($selector_string) {
+ global $debugObject;
+ if (is_object($debugObject)) {$debugObject->debugLogEntry(1);}
+
+ // pattern of CSS selectors, modified from mootools
+ // Paperg: Add the colon to the attrbute, so that it properly finds like google does.
+ // Note: if you try to look at this attribute, yo MUST use getAttribute since $dom->x:y will fail the php syntax check.
+// Notice the \[ starting the attbute? and the @? following? This implies that an attribute can begin with an @ sign that is not captured.
+// This implies that an html attribute specifier may start with an @ sign that is NOT captured by the expression.
+// farther study is required to determine of this should be documented or removed.
+// $pattern = "/([\w-:\*]*)(?:\#([\w-]+)|\.([\w-]+))?(?:\[@?(!?[\w-]+)(?:([!*^$]?=)[\"']?(.*?)[\"']?)?\])?([\/, ]+)/is";
+ $pattern = "/([\w\-:\*]*)(?:\#([\w\-]+)|\.([\w\-]+))?(?:\[@?(!?[\w\-:]+)(?:([!*^$]?=)[\"']?(.*?)[\"']?)?\])?([\/, ]+)/is";
+ preg_match_all($pattern, trim($selector_string).' ', $matches, PREG_SET_ORDER);
+ if (is_object($debugObject)) {$debugObject->debugLog(2, "Matches Array: ", $matches);}
+
+ $selectors = array();
+ $result = array();
+ //print_r($matches);
+
+ foreach ($matches as $m) {
+ $m[0] = trim($m[0]);
+ if ($m[0]==='' || $m[0]==='/' || $m[0]==='//') continue;
+ // for browser generated xpath
+ if ($m[1]==='tbody') continue;
+
+ list($tag, $key, $val, $exp, $no_key) = array($m[1], null, null, '=', false);
+ if (!empty($m[2])) {$key='id'; $val=$m[2];}
+ if (!empty($m[3])) {$key='class'; $val=$m[3];}
+ if (!empty($m[4])) {$key=$m[4];}
+ if (!empty($m[5])) {$exp=$m[5];}
+ if (!empty($m[6])) {$val=$m[6];}
+
+ // convert to lowercase
+ if ($this->dom->lowercase) {$tag = empty($tag) ? '' : strtolower($tag); $key = empty($key) ? '' : strtolower($key);}
+ //elements that do NOT have the specified attribute
+ if (isset($key[0]) && $key[0]==='!') {$key=substr($key, 1); $no_key=true;}
+
+ $result[] = array($tag, $key, $val, $exp, $no_key);
+ if (trim($m[7])===',') {
+ $selectors[] = $result;
+ $result = array();
+ }
+ }
+ if (count($result)>0)
+ $selectors[] = $result;
+ return $selectors;
+ }
+
+ function __get($name) {
+ if (isset($this->attr[$name]))
+ {
+ return $this->convert_text($this->attr[$name]);
+ }
+ switch ($name) {
+ case 'outertext': return $this->outertext();
+ case 'innertext': return $this->innertext();
+ case 'plaintext': return $this->text();
+ case 'xmltext': return $this->xmltext();
+ default: return array_key_exists($name, $this->attr);
+ }
+ }
+
+ function __set($name, $value) {
+ switch ($name) {
+ case 'outertext': return $this->_[HDOM_INFO_OUTER] = $value;
+ case 'innertext':
+ if (isset($this->_[HDOM_INFO_TEXT])) return $this->_[HDOM_INFO_TEXT] = $value;
+ return $this->_[HDOM_INFO_INNER] = $value;
+ }
+ if (!isset($this->attr[$name])) {
+ $this->_[HDOM_INFO_SPACE][] = array(' ', '', '');
+ $this->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_DOUBLE;
+ }
+ $this->attr[$name] = $value;
+ }
+
+ function __isset($name) {
+ switch ($name) {
+ case 'outertext': return true;
+ case 'innertext': return true;
+ case 'plaintext': return true;
+ }
+ //no value attr: nowrap, checked selected...
+ return (array_key_exists($name, $this->attr)) ? true : isset($this->attr[$name]);
+ }
+
+ function __unset($name) {
+ if (isset($this->attr[$name]))
+ unset($this->attr[$name]);
+ }
+
+ // PaperG - Function to convert the text from one character set to another if the two sets are not the same.
+ function convert_text($text) {
+ global $debugObject;
+ if (is_object($debugObject)) {$debugObject->debugLogEntry(1);}
+
+ $converted_text = $text;
+
+ $sourceCharset = "";
+ $targetCharset = "";
+ if ($this->dom) {
+ $sourceCharset = empty($this->dom->_charset) ? '' : strtoupper($this->dom->_charset);
+ $targetCharset = empty($this->dom->_target_charset) ? '' : strtoupper($this->dom->_target_charset);
+ }
+ if (is_object($debugObject)) {$debugObject->debugLog(3, "source charset: " . $sourceCharset . " target charaset: " . $targetCharset);}
+
+ if (!empty($sourceCharset) && !empty($targetCharset) && (strcasecmp($sourceCharset, $targetCharset) != 0))
+ {
+ // Check if the reported encoding could have been incorrect and the text is actually already UTF-8
+ if ((strcasecmp($targetCharset, 'UTF-8') == 0) && ($this->is_utf8($text)))
+ {
+ $converted_text = $text;
+ }
+ else
+ {
+ $converted_text = iconv($sourceCharset, $targetCharset, $text);
+ }
+ }
+
+ return $converted_text;
+ }
+
+ function is_utf8($string)
+ {
+ return (utf8_encode(utf8_decode($string)) == $string);
+ }
+
+ // camel naming conventions
+ function getAllAttributes() {return $this->attr;}
+ function getAttribute($name) {return $this->__get($name);}
+ function setAttribute($name, $value) {$this->__set($name, $value);}
+ function hasAttribute($name) {return $this->__isset($name);}
+ function removeAttribute($name) {$this->__set($name, null);}
+ function getElementById($id) {return $this->find("#$id", 0);}
+ function getElementsById($id, $idx=null) {return $this->find("#$id", $idx);}
+ function getElementByTagName($name) {return $this->find($name, 0);}
+ function getElementsByTagName($name, $idx=null) {return $this->find($name, $idx);}
+ function parentNode() {return $this->parent();}
+ function childNodes($idx=-1) {return $this->children($idx);}
+ function firstChild() {return $this->first_child();}
+ function lastChild() {return $this->last_child();}
+ function nextSibling() {return $this->next_sibling();}
+ function previousSibling() {return $this->prev_sibling();}
+}
+
+/**
+ * simple html dom parser
+ * Paperg - in the find routine: allow us to specify that we want case insensitive testing of the value of the selector.
+ * Paperg - change $size from protected to public so we can easily access it
+ * Paperg - added ForceTagsClosed in the constructor which tells us whether we trust the html or not. Default is to NOT trust it.
+ *
+ * @package PlaceLocalInclude
+ */
+class simple_html_dom {
+ public $root = null;
+ public $nodes = array();
+ public $callback = null;
+ public $lowercase = false;
+ public $size;
+ protected $pos;
+ protected $doc;
+ protected $char;
+ protected $cursor;
+ protected $parent;
+ protected $noise = array();
+ protected $token_blank = " \t\r\n";
+ protected $token_equal = ' =/>';
+ protected $token_slash = " />\r\n\t";
+ protected $token_attr = ' >';
+ protected $_charset = '';
+ protected $_target_charset = '';
+ protected $default_br_text = "";
+
+ // use isset instead of in_array, performance boost about 30%...
+ protected $self_closing_tags = array('img'=>1, 'br'=>1, 'input'=>1, 'meta'=>1, 'link'=>1, 'hr'=>1, 'base'=>1, 'embed'=>1, 'spacer'=>1);
+ protected $block_tags = array('root'=>1, 'body'=>1, 'form'=>1, 'div'=>1, 'span'=>1, 'table'=>1);
+ // Known sourceforge issue #2977341
+ // B tags that are not closed cause us to return everything to the end of the document.
+ protected $optional_closing_tags = array(
+ 'tr'=>array('tr'=>1, 'td'=>1, 'th'=>1),
+ 'th'=>array('th'=>1),
+ 'td'=>array('td'=>1),
+ 'li'=>array('li'=>1),
+ 'dt'=>array('dt'=>1, 'dd'=>1),
+ 'dd'=>array('dd'=>1, 'dt'=>1),
+ 'dl'=>array('dd'=>1, 'dt'=>1),
+ 'p'=>array('p'=>1),
+ 'nobr'=>array('nobr'=>1),
+ 'b'=>array('b'=>1),
+ );
+
+ function __construct($str=null, $lowercase=true, $forceTagsClosed=true, $target_charset=DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT) {
+ if ($str) {
+ if (preg_match("/^http:\/\//i",$str) || is_file($str))
+ $this->load_file($str);
+ else
+ $this->load($str, $lowercase, $stripRN, $defaultBRText);
+ }
+ // Forcing tags to be closed implies that we don't trust the html, but it can lead to parsing errors if we SHOULD trust the html.
+ if (!$forceTagsClosed) {
+ $this->optional_closing_array=array();
+ }
+ $this->_target_charset = $target_charset;
+ }
+
+ function __destruct() {
+ $this->clear();
+ }
+
+ // load html from string
+ function load($str, $lowercase=true, $stripRN=false, $defaultBRText=DEFAULT_BR_TEXT) {
+ global $debugObject;
+
+ // prepare
+ $this->prepare($str, $lowercase, $stripRN, $defaultBRText);
+ // strip out comments
+ $this->remove_noise("''is");
+ // strip out cdata
+ $this->remove_noise("''is", true);
+ // Per sourceforge http://sourceforge.net/tracker/?func=detail&aid=2949097&group_id=218559&atid=1044037
+ // Script tags removal now preceeds style tag removal.
+ // strip out