source: t29-www/lib/menu.php

Last change on this file was 1491, checked in by sven, 5 years ago

Adding a small blog (incl. first post), fixing english imprint.

  • Property svn:keywords set to Id
File size: 15.9 KB
Line 
1<?php
2/**
3 * Needs conf:
4 *  webroot lang_path lang seiten_id languages
5 *
6 **/
7
8require_once dirname(__FILE__).'/messages.php';
9require_once dirname(__FILE__).'/logging.php';
10 
11class t29Menu {
12        public $conf;
13        public $xml;
14        public $log; // just for convenience
15
16        // Bevor es eine ordentliche Dev-Moeglichkeit gibt: Der magische
17        // Schalter zum Ausblenden der Geraeteseiten im Menue
18        public $hide_geraete_seiten = true;
19
20        // jeweils relativ zum lang_path
21        const navigation_file = 'navigation.xml';
22        const news_file = 'news.php';
23
24        // xpath queries to the navigation elements
25        const horizontal_menu = '/html/nav[@class="horizontal"]';
26        const sidebar_menu = '/html/nav[@class="side"]';
27
28        function __construct($conf_array) {
29                $this->conf = $conf_array;
30                $this->log = t29Log::get(); // just for convenience
31               
32                // create a message object if not given
33                if(!isset($this->conf['msg']))
34                        $this->conf['msg'] = new t29Messages($this->conf['lang']);
35               
36                // libxml: don't raise errors while parsing.
37                // will fetch them with libxml_get_errors later.
38                //libxml_use_internal_errors(true);
39               
40                if(!function_exists("simplexml_load_file")) {
41                        trigger_error("t29Menu: Require SimpleXML PHP extension to load menu.");
42                } else {
43                        // load xml file
44                        $this->xml = simplexml_load_file($this->conf['webroot'].$this->conf['lang_path'] . '/' . self::navigation_file);
45                        if($this->xml_is_defective()) {
46                                trigger_error("Kann Navigationsdatei nicht verwenden, da das XML nicht sauber ist. Bitte reparieren!");
47                        }
48                }
49        }
50
51        function xml_is_defective() {
52                // check if return value of simplexml_load_file was false,
53                // which means parse error.
54                return $this->xml === FALSE;
55        }
56       
57        ///////////////////// NEWS EXTRACTION
58        function load_news_data() {
59                $newsfile = $this->conf['webroot'].$this->conf['lang_path']."/".self::news_file;
60                $newsdir = dirname(realpath($newsfile));
61                // include path wird ignoriert wenn include relativ ist, was in der
62                // eingebundenen Datei der Fall ist
63                // set_include_path( get_include_path(). PATH_SEPARATOR . dirname($newsfile));
64                $pwd = getcwd(); chdir($newsdir);
65                include(self::news_file);
66                chdir($pwd);
67                if(!isset($neues_menu) || empty($neues_menu))
68                        // in self::news_file konnte das neue Menue nicht extrahiert werden oder war leer
69                        $neues_menu = "";
70                return $neues_menu;
71        }
72
73        /**
74         * Liest das YAML-formatierte News-Menue aus der news.php-File der entsprechenden
75         * Sprache aus und erzeugt daraus ein HTML-Menue, welches als String zurueckgegeben
76         * wird.
77         * @param $host Instance of t29Host which can be used for link rewriting if given.
78         **/
79        function convert_news_data($host=null) {
80                require_once $this->conf['lib'].'/spyc.php';
81                $data = Spyc::YAMLLoad($this->load_news_data());
82                $fields = array('datum', 'titel',/* 'untertitel', 'bild'*/);
83
84                $news_ul_content = '';
85                foreach($data as $e) {
86                        if(!array_reduce(array_map(function($x) use ($fields,$e){ return isset($e[$x]); }, $fields),
87                                        function($a,$b){ return $a && $b;}, true)) {
88                                $li = "<li><a href='#'>Fehler in Formatierung!<em>Dieser Menüeintrag ist falsch formatiert</em></a></li>";
89                                $this->log->WARN("<h5>Neuigkeiten-Menü: Fehler in Formatierung</h5><p>Ein Eintrag im Neuigkeiten-Menü ist falsch formatiert. Ich erwarte zu jedem Menüeintrag die Felder ".implode(", ", $fields).". Eine der Angaben fehlt oder ist fehlerhaft formatiert: <pre>".var_export($e, true)."</pre>");
90                        } else {
91                                // Ehemals konnte die URL per "link: #August_2013" angegeben werden oder "link: /de/irgendwohin".
92                                // $url = ($e['link']{0} == '#' ? $this->conf['lang_path'].'/'.self::news_file : '').$e['link'];
93                                // Jetzt wird die URL automatisch aus dem Datum gebaut (slugify-artig)
94                                $url = $this->conf['lang_path'].'/'.self::news_file.'#'.str_replace(' ', '_', $e['datum']);
95                                if($host)
96                                        $url = $host->rewrite_link($url);
97
98                                // optionales Feld: Untertitel
99                                if(!isset($e['untertitel'])) $e['untertitel'] = '';
100
101                                // weiteres optionales Feld: Bildeinbindung
102                                $img = !isset($e['bild']) ? '' : "<img src='$e[bild]' style='max-width:64px; max-height:64px;'>";
103                                $li = "<li><a href='$url'>$img$e[titel]<span class='hidden'>: </span><em>$e[untertitel]</em></a></li>";
104                        }
105                        $news_ul_content .= "\t".$li."\n";
106                }
107
108                return $news_ul_content;
109        }
110       
111        ///////////////////// RETURN INFOS ABOUT SEITEN_ID LINK
112       
113        /**
114         * Find the corresponding XML node in the navigation tree for the link
115         * with given $seiten_id or the current given seiten_id in the configuration
116         * array.
117         * This method is used in get_link_navigation_class, etc. for resolving
118         * the XML element from the string. They can be used with the XML node, too,
119         * and this behaviour is passed throught by this method, so if you call
120         * this with an SimpleXMLElement as argument, it behaves like an identity
121         * function and just does nothing.
122         * (This is used in template.php for caching the found xml element and saving
123         * several xpath querys on get_* calls)
124         *
125         * @param $seiten_id Either a string, or nothing (defaults to conf) or SimpleXMLElement
126         * @returns SimpleXMLElement or null if link not found
127         **/
128        function get_link($seiten_id=false) {
129                if($this->xml_is_defective()) {
130                        return null;
131                }
132                if(!$seiten_id) $seiten_id = $this->conf['seiten_id'];
133                // convenience: If you found your link already.
134                if($seiten_id instanceof SimpleXMLElement) return $seiten_id;
135
136                $matches = $this->xml->xpath("//a[@seiten_id='$seiten_id']");
137                if($matches && count($matches)) {
138                        // strip the first one
139                        return $matches[0];
140                }
141                return null;
142        }
143       
144        /**
145         * Get navigation list membership (horizontal or side) of a link
146         * @see get_link for parameters
147         * @returns String of <nav> class where this link is affiliated to
148         **/
149        function get_link_navigation_class($seiten_id=false) {
150                $link = $this->get_link($seiten_id);
151                if(!$link) return null;
152               
153                // navigation list membership
154                $nav = $link->xpath("ancestor::nav");
155                return strval($nav[0]['class']); // cast SimpleXMLElement
156        }
157
158        /**
159         * Get list of parental ul classes (u2, u3, geraete, ...)
160         * @see get_link for parameters
161         * @returns array with individual class names as strings
162         **/
163        function get_link_ul_classes($seiten_id=false) {
164                $link = $this->get_link($seiten_id);
165                if(!$link) return array();
166               
167                // direct parental ul classes
168                $ul = $link->xpath("ancestor::ul");
169                $parent_ul = array_pop($ul);
170                return explode(' ',$parent_ul['class']);
171        }
172       
173        /**
174         * Extracts a list of (CSS) classes the link has,
175         * e.g. <a class="foo bar"> gives array("foo","basr").
176         *
177         * Caveat: This must be called before this class is destructed
178         * by print_menu! Otherwise it will return an empty array. This is
179         * actually bad design, print_menu destroyes the internal structure
180         * for storage efficiencey.
181         *
182         * @returns array or empty array in case of error
183         **/
184        function get_link_classes($seiten_id=false) {
185                $link = $this->get_link($seiten_id);
186                //print "link:"; var_dump($this->xml);
187                if(!$link) return array();
188                //var_dump($link); exit;
189                return isset($link['class']) ? explode(' ',$link['class']) : array();
190        }
191
192        ///////////////////// INTER LANGUAGE DETECTION
193        /**
194         * @param seiten_id Get interlanguage link for that seiten_id or default.
195         **/
196        function get_interlanguage_link($seiten_id=false) {
197                if(!$seiten_id) $seiten_id = $this->conf['seiten_id'];
198               
199                $interlinks = array(); // using a loop instead of mappings since php is stupid
200                foreach($this->conf['languages'] as $lang => $lconf) {
201                        $foreign_menu = new t29Menu(array(
202                                'webroot' => $this->conf['webroot'],
203                                'seiten_id' => $this->conf['seiten_id'],
204                                'languages' => $this->conf['languages'],
205                                'lang' => $lang,
206                                'lang_path' => $lconf[1],
207                        ));
208
209                        $link = $foreign_menu->get_link($seiten_id);
210                        $interlinks[$lang] = $link;
211                }
212               
213                return $interlinks;
214        }
215
216        // helper methods
217       
218        /** Check if a simplexml element has an attribute. Lightweight operation
219         *  over the DOM.
220         * @returns boolean
221         **/
222        public static function dom_has_attribute($simplexml_element, $attribute_name) {
223                $dom = dom_import_simplexml($simplexml_element); // is a fast operation
224                return $dom->hasAttribute($attribute_name);
225        }
226       
227        public static function dom_prepend_attribute($simplexml_element, $attribute_name, $content, $seperator='') {
228                if(!is_array($simplexml_element)) $simplexml_element = array($simplexml_element);
229                foreach($simplexml_element as $e)
230                        $e[$attribute_name] = $content . (self::dom_has_attribute($e, $attribute_name) ? ($seperator.$e[$attribute_name]) : '');
231        }
232       
233        public static function dom_append_attribute($simplexml_element, $attribute_name, $content, $seperator='') {
234                if(!is_array($simplexml_element)) $simplexml_element = array($simplexml_element);
235                foreach($simplexml_element as $e)
236                        $e[$attribute_name] = (self::dom_has_attribute($e, $attribute_name) ? ($e[$attribute_name].$seperator) : '') . $content;
237        }
238
239        public static function dom_attribute_contains($simplexml_element, $attribute_name, $needle) {
240                if(isset($simplexml_element[$attribute_name])) {
241                        return strpos((string)$simplexml_element[$attribute_name], $needle) !== false;
242                } else
243                        return false;
244        }
245       
246        /**
247         * Appends a (CSS) class to a simplexml element, seperated by whitespace. Just an alias.
248         **/
249        public static function dom_add_class($simplexml_element, $value) {
250                self::dom_append_attribute($simplexml_element, 'class', $value, ' ');
251        }
252       
253        public static function dom_new_link($href, $label) {
254                return new SimpleXMLElement(sprintf('<a href="%s">%s</a>', $href, htmlentities($label)));
255        }
256
257
258        ///////////////////// MENU ACTIVE LINK DETECTION
259        /**
260         * print_menu is the central method in this class. It converts the $this->xml
261         * XML tree to valid HTML with all enrichments for appropriate CSS styling.
262         * It also removes all 'seiten_id' attributes.
263         * This method does *not* clone the structure, so this instance won't produce
264         * the same results any more after print_menu invocation! This especially will
265         * affect get_link().
266         *
267         * @arg $xpath_menu_selection  one of the horizontal_menu / sidebar_menu consts.
268         * @arg $host Instance of t29Host which can be used for link rewriting if given.
269         * @returns nothing, since the output is printed out
270         **/
271        function print_menu($xpath_menu_selection, $host=null) {
272                if($this->xml_is_defective()) {
273                        print "The Menu file is broken.";
274                        return false;
275                }
276                $seiten_id = $this->conf['seiten_id'];
277                $_ = $this->conf['msg']->get_shorthand_returner();
278               
279                // find wanted menu
280                $xml = $this->xml->xpath($xpath_menu_selection);
281                if(!$xml) {
282                        print "Menu <i>$xpath_menu_selection</i> not found!";
283                        return false;
284                }
285                $xml = $xml[0]; // just take the first result (should only one result be present)
286               
287                /*
288                // work on a deep copy of the data. Thus this method won't make the overall
289                // class useless.
290                $dom = dom_import_simplexml($xml);
291                $xml = simplexml_import_dom($dom->cloneNode(true));
292                */
293
294                // aktuelle Seite anmarkern und Hierarchie hochgehen
295                // (<ul><li>bla<ul><li>bla<ul><li>hierbin ich <- hochgehen.)
296                $current_a = $xml->xpath("//a[@seiten_id='$seiten_id']");
297                if(count($current_a)) {
298                        $current_li = $current_a[0]->xpath("parent::li");
299                        self::dom_add_class($current_li[0], 'current');
300                        self::dom_prepend_attribute($current_a, 'title', $_('nav-hierarchy-current'), ': ');
301
302                        $actives = $current_li[0]->xpath("ancestor-or-self::li");
303                        array_walk($actives, function($i) { t29Menu::dom_add_class($i, 'active'); });
304                       
305                        $ancestors = $current_li[0]->xpath("ancestor::li");
306                        foreach($ancestors as $i)
307                                t29Menu::dom_prepend_attribute($i->xpath("./a[1]"), 'title', $_('nav-hierarchy-ancestor'), ': ');
308                }
309
310                // Seiten-IDs (ungueltiges HTML) ummoddeln
311                $all_ids = $xml->xpath("//a[@seiten_id]");
312                foreach($all_ids as $a) {
313                        $a['id'] = "sidebar_link_".$a['seiten_id'];
314                        // umweg ueber DOM um Node zu loeschen
315                        $adom = dom_import_simplexml($a);
316                        $adom->removeAttribute('seiten_id');
317                }
318
319                // Geraete-Seiten entfernen
320                if($this->hide_geraete_seiten) {
321                        $geraete_uls = $xml->xpath("//ul[contains(@class, 'geraete')]");
322                        foreach($geraete_uls as $ul) {
323                                $uld = dom_import_simplexml($ul);
324                                $uld->parentNode->removeChild($uld);
325                        }
326                }
327               
328                // alle Links mittels t29Host umwandeln (idR .php-Endung entfernen),
329                // falls erwuenscht
330                if($host) {
331                        $links = $xml->xpath("//a[@href]");
332                        foreach($links as $a)
333                                $a['href'] = $host->rewrite_link($a['href']);
334                }
335       
336                if($xpath_menu_selection == self::horizontal_menu) {
337                        # inject news
338                        $news_ul_content = $this->convert_news_data($host);
339                        $magic_comment = '<!--# INSERT_NEWS #-->';
340                        $menu = $xml->ul->asXML();
341                        print str_replace($magic_comment, $news_ul_content, $menu);
342                } else {
343                        print $xml->ul->asXML();
344                }
345        }
346
347        ///////////////////// PAGE RELATIONS
348        /**
349         * Usage:
350         * foreach(get_page_relations() as $a) {
351         *    echo "Link $a going to $a[href]";
352         * }
353         *
354         * Hinweis:
355         * Wenn Element (etwa prev) nicht existent, nicht null zurueckgeben,
356         * sondern Element gar nicht zurueckgeben (aus hash loeschen).
357         *
358         * @param $seiten_id A seiten_id string or nothing for taking the current active string
359         * @returns an array(prev=>..., next=>...) or empty array, elements are SimpleXML a links
360         **/
361        function get_page_relations($seiten_id=false) {
362                if($this->xml_is_defective())
363                        return array(); // cannot construct relations due to bad XML file
364                if(!$seiten_id) $seiten_id = $this->conf['seiten_id'];
365               
366                $xml = $this->xml->xpath(self::sidebar_menu);
367                if(!$xml) { print "<i>Sidebar not found</i>"; return; }
368                $sidebar = $xml[0];
369               
370                // nur Sidebar-Links kriegen eine Relation aufgeloest
371                $return = array();
372                $current_a = $sidebar->xpath(".//a[@seiten_id='$seiten_id']");
373                $seiten_id_in_sidebar = count($current_a);
374                // ggf. nochmal global suchen:
375                $current_a = $seiten_id_in_sidebar ? $current_a[0] : $this->get_link($seiten_id);
376                if($current_a) {
377                        // wenn aktuelle seite eine geraeteseite ist
378                        if(in_array('geraete', $this->get_link_ul_classes($seiten_id))) {
379                                //  pfad:                        a ->li->ul.geraete->li->li/a
380                                $geraetelink = $current_a->xpath("../../../a");
381                                if(count($geraetelink))
382                                        $return['prev'] = $geraetelink[0];
383                                $return['next'] = null; // kein Link nach vorne
384                        } else {
385                                $searches = array();
386                                if($seiten_id_in_sidebar || self::dom_attribute_contains($current_a, 'class', 'show-rel-prev'))
387                                        $searches['prev'] = 'preceding::a[@seiten_id]';
388                                if($seiten_id_in_sidebar || self::dom_attribute_contains($current_a, 'class', 'show-rel-next'))
389                                        $searches['next'] = 'following::a[@seiten_id]';
390
391                                foreach($searches as $rel => $xpath) {
392                                        $nodes = $current_a->xpath($xpath);
393                                        foreach($rel == "prev" ? array_reverse($nodes) : $nodes as $link) {
394                                                $is_geraete = count($link->xpath("ancestor::ul[contains(@class, 'geraete')]"));
395                                                if($is_geraete) continue; // skip geraete links
396                                                $return[$rel] = $link;
397                                                break; // just take the first matching element
398                                        }
399                                } // end for prev next
400                        } // end if geraete
401                }
402
403                // Short circuit fuer Links ueberall:
404                // Wenn der aktuelle Link ein "next" oder "prev"-Attribut besitzt, dann ueberschreibt
405                // das alle bisherigen Ergebnisse.
406                // Benutzung: <a seiten_id="a" href="a.html" next="b">foo</a>, <a seiten_id="b">bar</a>
407                //
408                // Funktioniert wahrscheinlich, aber nicht getestet/genutzt, da bislang nur "show-rel-{prev,next}"
409                // genutzt wird (direkte Nachbarn)
410                /*
411                if(!$current_a)
412                        // falls $current_a nicht in der sidebar ist, nochmal global suchen
413                        $current_a = $this->get_link($seiten_id);
414                $short_circuits = array('prev', 'next');
415                foreach($short_circuits as $rel) {
416                        if($current_a[$rel]) {
417                                $target = $this->get_link((string) $current_a[$rel]);
418                                if($target)
419                                        $return[$rel] = $target;
420                        }
421                }
422                */
423               
424                // Linkliste aufarbeiten: Nullen rausschmeissen (nur deko) und
425                // Links *klonen*, denn sie werden durch print_menu sonst veraendert
426                // ("Übergeordnete Kategorie der aktuellen Seite" steht dann drin)
427                // und wir wollen sie unveraendert haben.
428                foreach($return as $key => $node) {
429                        if(!$node) {
430                                unset($return[$key]);
431                                continue;
432                        }
433                        $dn = dom_import_simplexml($node);
434                        $dnc = simplexml_import_dom($dn->cloneNode(true));
435                        $return[$key] = $dnc;
436                }
437               
438                return $return;
439        }
440
441} // class
Note: See TracBrowser for help on using the repository browser.
© 2008 - 2013 technikum29 • Sven Köppel • Some rights reserved
Powered by Trac
Expect where otherwise noted, content on this site is licensed under a Creative Commons 3.0 License