source: t29-www/lib/menu.php @ 1320

Last change on this file since 1320 was 1074, checked in by sven, 7 years ago

Die beiden "Kurs"-Seiten Physical-Computing und Robotik vom Design verähnlicht. Irregeführte "Trenn-Binde-Striche" entfernt, da es keine Silbentrennung auf Webseiten gibt.

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