]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/HtmlParser.php
Reformat code
[SourceForge/phpwiki.git] / lib / HtmlParser.php
1 <?php
2
3 /**
4  * HtmlParser Class: Conversion HTML => wikimarkup
5  * Requires XmlParser, XmlElement and the expat (or now the libxml) library. This is all in core.
6  */
7
8 /*
9  * Copyright (C) 2004 Reini Urban
10  *
11  * This file is part of PhpWiki.
12  *
13  * PhpWiki is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * PhpWiki is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License along
24  * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
25  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26  */
27
28 /**
29  * Base class to implement html => wikitext converters,
30  * extendable for various wiki syntax versions.
31  * This is needed to be able to use htmlarea-alike editors,
32  * and to import XML or HTML documents.
33  *
34  * See also php-html.sf.net for a php-only version, if
35  * you don't have the expat/libxml extension included.
36  * See also http://search.cpan.org/~diberri/HTML-WikiConverter/
37  *
38  */
39
40 // RssParser contains the XML (expat) and url-grabber methods
41 require_once 'lib/XmlParser.php';
42
43 class HtmlParser
44     extends XmlParser
45 {
46     var $dialect, $_handlers, $root;
47
48     /**
49      *  dialect: "PhpWiki2", "PhpWiki"
50      *  possible more dialects: MediaWiki, kwiki, c2
51      */
52     function HtmlParser($dialect = "PhpWiki2", $encoding = '')
53     {
54         $classname = "HtmlParser_" . $dialect;
55         if (class_exists($classname))
56             $this->dialect = new $classname;
57         else {
58             trigger_error(sprintf("unknown HtmlParser dialect %s", $dialect), E_USER_ERROR);
59         }
60         $this->_handlers =& $this->dialect->_handlers;
61         $this->XmlParser($encoding);
62         xml_parser_set_option($this->_parser, XML_OPTION_CASE_FOLDING, 0);
63         xml_parser_set_option($this->_parser, XML_OPTION_SKIP_WHITE, 1);
64     }
65
66     // The three callbacks, called on walking through the HTML tree.
67     // No extensions needed from XmlParser.
68     /*
69     function tag_open($parser, $name, $attrs='') {
70     }
71     function tag_close($parser, $name, $attrs='') {
72     }
73     function cdata($parser, $data) {
74     }
75     function parse_url($file, $debug=false)
76     */
77
78     function output()
79     {
80         if (is_null($this->root))
81             $this->root = $GLOBALS['xml_parser_root'];
82         $output = $this->wikify($this->root);
83         return $output;
84     }
85
86     function wikify($node, $parent = null)
87     {
88         $output = '';
89         if (isa($node, 'XmlElement')) {
90             $dialect =& $this->dialect;
91             $conv = $dialect->_handlers[$node->_tag];
92             if (is_string($conv) and method_exists($dialect, $conv)) {
93                 $output = $dialect->$conv($node);
94             } elseif (is_array($conv)) {
95                 foreach ($node->getContent() as $n) {
96                     $output .= $this->wikify($n, $node);
97                 }
98                 $output = $conv[0] . $output . $conv[count($conv) - 1];
99             } elseif (!empty($conv)) {
100                 $output = $conv;
101                 foreach ($node->getContent() as $n) {
102                     $output .= $this->wikify($n, $node);
103                 }
104             } else {
105                 foreach ($node->getContent() as $n) {
106                     $output .= $this->wikify($n, $node);
107                 }
108             }
109         } else {
110             $output = $node;
111             if ($parent and $parent->_tag != 'pre')
112                 preg_replace("/ {2,}/", " ", $output);
113             if (trim($output) == '')
114                 $output = '';
115         }
116         return $output;
117     }
118
119     /** elem_contents()
120      *  $output = $parser->elem_contents( $elem );
121      * Returns a wikified version of the contents of the specified
122      * HTML element. This is done by passing each element of this
123      * element's content list through the C<wikify()> method, and
124      * returning the concatenated result.
125      */
126     function elem_contents($node)
127     {
128         $output = '';
129         if (isa($node, 'XmlElement')) {
130             foreach ($node->getContent() as $child) {
131                 $output .= $this->wikify($child, isset($node->parent) ? $node->parent : null);
132             }
133         } else {
134             $output = $this->wikify($content);
135         }
136         return $output;
137     }
138
139     //
140     // Private function: _elem_attr_str( $elem, @attrs )
141     //
142     // Returns a string containing a list of attribute names and
143     // values associated with the specified HTML element. Only
144     // attribute names included in @attrs will be added to the
145     // string of attributes that is returned. The return value
146     // is suitable for inserting into an HTML document, as
147     // attribute name/value pairs are specified in attr="value"
148     // format.
149     //
150     function _elem_attr_str($node, $attrs)
151     {
152         $s = '';
153         foreach ($node->_attr as $attr => $val) {
154             $attr = strtolower($attr);
155             if (in_array($attr, $attrs))
156                 $s .= " $attr=\"$val\"";
157         }
158         return $s;
159     }
160
161     //
162     // Private function: _elem_has_ancestor( $elem, $tagname )
163     //
164     // Returns true if the specified HtmlElement has an ancestor element
165     // whose element tag equals $tag. This is useful for determining if
166     // an element belongs to the specified tag.
167     //
168     function _elem_has_ancestor($node, $tag)
169     {
170         if (isset($node->parent)) {
171             if ($node->parent->_tag == $tag) return true;
172             return $this->_elem_has_ancestor($node->parent, $tag);
173         }
174         return false;
175     }
176
177     //
178     // Private function: _elem_is_image_div( $elem )
179     //
180     // Returns true $elem is a container element (P or DIV) meant only to
181     // lay out an IMG.
182     //
183     // More specifically, returns true if the given element is a DIV or P
184     // element and the only child it contains is an IMG tag or an IMG tag
185     // contained within a sole A tag (not counting child elements with
186     // whitespace text only).
187     //
188     function _elem_is_image_div($node)
189     {
190         // Return false if node is undefined or isn't a DIV at all
191         if (!$node or !in_array($node->_tag, array("div", "p")))
192             return false;
193         $contents = $node->getContent();
194         // Returns true if sole child is an IMG tag
195         if (count($contents) == 1 and isset($contents[0]) and $contents[0]->_tag == 'img')
196             return true;
197         // Check if child is a sole A tag that contains an IMG tag
198         if (count($contents) == 1 and isset($contents[0]) and $contents[0]->_tag == 'a') {
199             $children = $contents[0]->getContent();
200             if (count($children) == 1 and isset($children[0]) and $children[0]->_tag == 'img')
201                 return true;
202         }
203         return false;
204     }
205
206     /** preserves tags and content
207      */
208     function wikify_default($node)
209     {
210         return $this->wikify_preserve($node);
211     }
212
213     /** preserves tags and content
214      */
215     function wikify_preserve($node)
216     {
217         return $node->asXML();
218     }
219
220     function log($dummy)
221     {
222     }
223 }
224
225
226 class HtmlParser_PhpWiki2
227     extends HtmlParser
228 {
229     function HtmlParser_PhpWiki2()
230     {
231         $this->_handlers =
232             array('html' => '',
233                 'head' => '',
234                 'title' => '',
235                 'meta' => '',
236                 'link' => '',
237                 'script' => '',
238                 'body' => '',
239
240                 'br' => "<br>",
241                 'b' => array("*"),
242                 'strong' => array("*"),
243                 'i' => array("_"),
244                 'em' => array("_"),
245                 'hr' => "----\n\n",
246
247                 // PRE blocks are handled specially (see tidy_whitespace and
248                 // wikify methods)
249                 'pre' => array("<pre>", "</pre>"),
250
251                 'dl' => array('', "\n\n"),
252                 'dt' => array(';', ''),
253                 'dd' => array(':', ''),
254
255                 'p' => array("\n\n", "\n\n"),
256                 'ul' => array('', "\n"),
257                 'ol' => array('', "\n"),
258
259                 'li' => "wikify_list_item",
260                 'table' => "wikify_table",
261                 'tr' => "wikify_tr",
262                 'td' => "wikify_td",
263                 'th' => "wikify_td",
264                 'div' => array('', "\n\n"),
265                 'img' => "wikify_img",
266                 'a' => "wikify_link",
267                 'span' => array('', ''),
268
269                 'h1' => "wikify_h",
270                 'h2' => "wikify_h",
271                 'h3' => "wikify_h",
272                 'h4' => "wikify_h",
273                 'h5' => "wikify_h",
274                 'h6' => "wikify_h",
275
276                 'font' => array('', ''),
277                 'sup' => "wikify_default",
278                 'sub' => "wikify_default",
279                 'nowiki' => "wikify_verbatim",
280                 'verbatim' => "wikify_default",
281                 'noinclude' => "wikify_noinclude",
282             );
283     }
284
285     function wikify_table($node)
286     {
287         $this->ident = '';
288         return "| \n" . $this->elem_contents($node) . "|\n\n";
289     }
290
291     function wikify_tr($node)
292     {
293         return "\n| " . $this->elem_contents($node);
294     }
295
296     function wikify_th($node)
297     {
298         $ident = empty($this->ident) ? '' : $this->ident;
299         $output = "$ident| ";
300         $content = $this->elem_contents($node);
301         preg_replace("s/^\s+/", "", $content);
302         $output .= $content;
303         $this->ident .= '  ';
304         return "$output |\n";
305     }
306
307     function wikify_list_item($node)
308     {
309         return ($this->_elem_has_ancestor($node, 'ol') ? '*' : '#') . " " . trim($this->elem_contents($node)) . "\n";
310     }
311
312     function wikify_link($node)
313     {
314         $url = $this->absolute_url($node->getAttr('href'));
315         $title = $this->elem_contents($node);
316         if (empty($url))
317             $title = trim($title);
318
319         // Just return the link title if this tag is contained
320         // within an header tag
321         if (isset($node->parent) and preg_match('/^h\d$/', $node->parent->_tag))
322             return $title;
323
324         // Return if this is a link to an image contained within
325         if (isset($node->parent) and $this->_elem_is_image_div($node->parent))
326             return $title;
327
328         // If HREF is the same as the link title, then
329         // just return the URL (it'll be converted into
330         // a clickable link by the wiki engine)
331         if ($url == $title) return $url;
332         return "[ $url | $title ]";
333     }
334
335     function wikify_h($node)
336     {
337         $level = substr($node->_tag, 1);
338         if ($level < 4) {
339             $markup = str_repeat('!', 4 - $level);
340         } else {
341             $markup = '!';
342         }
343         return $markup . ' ' . trim($this->elem_contents($node)) . "\n\n";
344     }
345
346     function wikify_verbatim($node)
347     {
348         $contents = $this->elem_contents($node);
349         return "\n<verbatim>\n$contents\n</verbatim>";
350     }
351
352     function wikify_noinclude($node)
353     {
354         return $this->elem_contents($node);
355     }
356
357     function wikify_img($node)
358     {
359         $image_url = $this->absolute_url($node->getAttr('src'));
360         $file = basename($image_url);
361         $alignment = $node->getAttr('align');
362         $this->log("Processing IMG tag for SRC: " . $image_url . "...");
363         //
364         // Grab attributes to be added to the [ Image ] markup (since 1.3.10)
365         //
366         if (!$alignment) {
367             if ($this->_elem_is_image_div($node->parent))
368                 $image_div = $node->parent;
369             elseif (isset($node->parent) and $this->_elem_is_image_div($node->parent->parent))
370                 $image_div = $node->parent->parent;
371         }
372         if (!$alignment and $image_div) {
373             $css_style = $image_div->getAttr('style');
374             $css_class = $image_div->getAttr('class');
375
376             // float => align: Check for float attribute; if it's there,
377             //                 then we'll add it to the [Image] syntax
378             if (!$alignment and preg_match("/float\:\s*(right|left)/i", $css_style, $m))
379                 $alignment = $m[1];
380             if (!$alignment and preg_match("/float(right|left)/i", $css_class, $m)) ;
381             $alignment = $m[1];
382             if ($alignment) {
383                 $attrs[] = "align=$alignment";
384                 $this->log("  Image is contained within a DIV that specifies $alignment alignment");
385                 $this->log("  Adding '$alignment' to [Image] markup attributes");
386             } else {
387                 $this->log("  Image is not contained within a DIV for alignment");
388             }
389         } else {
390             $this->log("  Image is not contained within a DIV");
391         }
392         if ($alignment)
393             $attrs[] = "align=$alignment";
394         //
395         // Check if we need to request a thumbnail of this
396         // image; it's needed if the specified width attribute
397         // differs from the default size of the image
398         //
399         if ($width = $node->getAttr('width')) {
400             $this->log("  Image has WIDTH attribute of $width");
401             $this->log("  Checking whether resulting [Image] markup should specify a thumbnail...");
402
403             // Download the image from the network and store
404             $abs_url = $this->absolute_url($node->getAttr('src'));
405             $this->log("    Fetching image '$abs_url' from the network");
406             list($actual_w, $actual_h, $flag, $attr_str) = getimagesize($abs_url);
407
408             // If the WIDTH attribute of the IMG tag is not equal
409             // to the actual width of the image, then we need to
410             // create a thumbnail
411             if (preg_match("/^\d+$/", $width) and $width != $actual_w) {
412                 $this->log("    IMG tag's WIDTH attribute ($width) differs from actual width of image ($actual_w)");
413                 $this->log("      -- that means we're going to need a thumbnail");
414                 $this->log("    Adding 'width' to list of attributes for [Image] markup");
415                 $attrs[] = "width=$width";
416                 $width_added = true;
417             }
418             $height = $node->getAttr('height');
419             if (preg_match("/^\d+$/", $height) and $height != $height_h) {
420                 $this->log("    IMG tag's HEIGHT attribute ($height) differs from actual height of image ($actual_h)");
421                 $this->log("      -- that means we're going to need a thumbnail");
422                 $this->log("    Adding 'height' to list of attributes for [Image] markup");
423                 if (isset($width_added))
424                     $attrs[count($attr) - 1] = "size=" . $width . "x" . $height;
425                 else
426                     $attrs[] = "height=$height";
427             }
428         }
429         if ($alt = $node->getAttr('alt')) {
430             $this->log("  Adding alternate text '$alt' to [Image] markup");
431             $attrs[] = "alt=$alt";
432         }
433         $attr_str = join(' ', $attrs);
434         $this->log("...done processing IMG tag\n");
435         return "[ $file $attr_str ]";
436     }
437 }
438
439 // Local Variables:
440 // mode: php
441 // tab-width: 8
442 // c-basic-offset: 4
443 // c-hanging-comment-ender-p: nil
444 // indent-tabs-mode: nil
445 // End: