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

Last change on this file since 560 was 390, checked in by sven, 11 years ago
  • Vor/Zurück-Link bei Lernprojekten aktiviert
  • Anzeige fehlender englischer Übersetzungen wieder aktiviert (aufgehübscht; mit Infobox)
  • Property svn:keywords set to Id
File size: 13.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        const 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                return $neues_menu;
64        }
65
66        /**
67         * Liest das YAML-formatierte News-Menue aus der news.php-File der entsprechenden
68         * Sprache aus und erzeugt daraus ein HTML-Menue, welches als String zurueckgegeben
69         * wird.
70         * @param $host Instance of t29Host which can be used for link rewriting if given.
71         **/
72        function convert_news_data($host=null) {
73                require $this->conf['lib'].'/spyc.php';
74                $data = Spyc::YAMLLoad($this->load_news_data());
75                $fields = array('titel', 'text', 'link', /*'bild'*/);
76
77                $news_ul_content = '';
78                foreach($data as $e) {
79                        if(!array_reduce(array_map(function($x) use ($fields,$e){ return isset($e[$x]); }, $fields),
80                                        function($a,$b){ return $a && $b;}, true)) {
81                                $li = "<li><a href='#'>Fehler in Formatierung!<em>Dieser Menüeintrag ist falsch formatiert</em></a></li>";
82                                $this->log->WARN("<h5>Neuigkeiten-Menü: Fehler in Formatierung</h5><p>Ein Eintrag im Neuigkeiten-Menü ist falsch formatiert.");
83                        } else {
84                                $url = ($e['link']{0} == '#' ? $this->conf['lang_path'].'/'.self::news_file : '').$e['link'];
85                                if($host)
86                                        $url = $host->rewrite_link($url);
87                                $li = "<li><a href='$url'>$e[titel]<span class='hidden'>: </span><em>$e[text]</em></a></li>";
88                        }
89                        $news_ul_content .= "\t".$li."\n";
90                }
91
92                return $news_ul_content;
93        }
94       
95        ///////////////////// RETURN INFOS ABOUT SEITEN_ID LINK
96       
97        /**
98         * Find the corresponding XML node in the navigation tree for the link
99         * with given $seiten_id or the current given seiten_id in the configuration
100         * array.
101         * This method is used in get_link_navigation_class, etc. for resolving
102         * the XML element from the string. They can be used with the XML node, too,
103         * and this behaviour is passed throught by this method, so if you call
104         * this with an SimpleXMLElement as argument, it behaves like an identity
105         * function and just does nothing.
106         * (This is used in template.php for caching the found xml element and saving
107         * several xpath querys on get_* calls)
108         *
109         * @param $seiten_id Either a string, or nothing (defaults to conf) or SimpleXMLElement
110         * @returns SimpleXMLElement or null if link not found
111         **/
112        function get_link($seiten_id=false) {
113                if($this->xml_is_defective()) {
114                        return null;
115                }
116                if(!$seiten_id) $seiten_id = $this->conf['seiten_id'];
117                // convenience: If you found your link already.
118                if($seiten_id instanceof SimpleXMLElement) return $seiten_id;
119
120                $matches = $this->xml->xpath("//a[@seiten_id='$seiten_id']");
121                if($matches && count($matches)) {
122                        // strip the first one
123                        return $matches[0];
124                }
125                return null;
126        }
127       
128        /**
129         * Get navigation list membership (horizontal or side) of a link
130         * @see get_link for parameters
131         * @returns String of <nav> class where this link is affiliated to
132         **/
133        function get_link_navigation_class($seiten_id=false) {
134                $link = $this->get_link($seiten_id);
135                if(!$link) return null;
136               
137                // navigation list membership
138                $nav = $link->xpath("ancestor::nav");
139                return strval($nav[0]['class']); // cast SimpleXMLElement
140        }
141
142        /**
143         * Get list of parental ul classes (u2, u3, geraete, ...)
144         * @see get_link for parameters
145         * @returns array with individual class names as strings
146         **/
147        function get_link_ul_classes($seiten_id=false) {
148                $link = $this->get_link($seiten_id);
149                if(!$link) return array();
150               
151                // direct parental ul classes
152                $ul = $link->xpath("ancestor::ul");
153                $parent_ul = array_pop($ul);
154                return explode(' ',$parent_ul['class']);
155        }
156       
157        /**
158         * Extracts a list of (CSS) classes the link has,
159         * e.g. <a class="foo bar"> gives array("foo","basr").
160         *
161         * Caveat: This must be called before this class is destructed
162         * by print_menu! Otherwise it will return an empty array. This is
163         * actually bad design, print_menu destroyes the internal structure
164         * for storage efficiencey.
165         *
166         * @returns array or empty array in case of error
167         **/
168        function get_link_classes($seiten_id=false) {
169                $link = $this->get_link($seiten_id);
170                //print "link:"; var_dump($this->xml);
171                if(!$link) return array();
172                //var_dump($link); exit;
173                return isset($link['class']) ? explode(' ',$link['class']) : array();
174        }
175
176        ///////////////////// INTER LANGUAGE DETECTION
177        /**
178         * @param seiten_id Get interlanguage link for that seiten_id or default.
179         **/
180        function get_interlanguage_link($seiten_id=false) {
181                if(!$seiten_id) $seiten_id = $this->conf['seiten_id'];
182               
183                $interlinks = array(); // using a loop instead of mappings since php is stupid
184                foreach($this->conf['languages'] as $lang => $lconf) {
185                        $foreign_menu = new t29Menu(array(
186                                'webroot' => $this->conf['webroot'],
187                                'seiten_id' => $this->conf['seiten_id'],
188                                'languages' => $this->conf['languages'],
189                                'lang' => $lang,
190                                'lang_path' => $lconf[1],
191                        ));
192
193                        $link = $foreign_menu->get_link($seiten_id);
194                        $interlinks[$lang] = $link;
195                }
196               
197                return $interlinks;
198        }
199
200        // helper methods
201       
202        /** Check if a simplexml element has an attribute. Lightweight operation
203         *  over the DOM.
204         * @returns boolean
205         **/
206        public static function dom_has_attribute($simplexml_element, $attribute_name) {
207                $dom = dom_import_simplexml($simplexml_element); // is a fast operation
208                return $dom->hasAttribute($attribute_name);
209        }
210       
211        public static function dom_prepend_attribute($simplexml_element, $attribute_name, $content, $seperator='') {
212                if(!is_array($simplexml_element)) $simplexml_element = array($simplexml_element);
213                foreach($simplexml_element as $e)
214                        $e[$attribute_name] = $content . (self::dom_has_attribute($e, $attribute_name) ? ($seperator.$e[$attribute_name]) : '');
215        }
216       
217        public static function dom_append_attribute($simplexml_element, $attribute_name, $content, $seperator='') {
218                if(!is_array($simplexml_element)) $simplexml_element = array($simplexml_element);
219                foreach($simplexml_element as $e)
220                        $e[$attribute_name] = (self::dom_has_attribute($e, $attribute_name) ? ($e[$attribute_name].$seperator) : '') . $content;
221        }
222       
223        /**
224         * Appends a (CSS) class to a simplexml element, seperated by whitespace. Just an alias.
225         **/
226        public static function dom_add_class($simplexml_element, $value) {
227                self::dom_append_attribute($simplexml_element, 'class', $value, ' ');
228        }
229       
230        public static function dom_new_link($href, $label) {
231                return new SimpleXMLElement(sprintf('<a href="%s">%s</a>', $href, $label));
232        }
233
234
235        ///////////////////// MENU ACTIVE LINK DETECTION
236        /**
237         * print_menu is the central method in this class. It converts the $this->xml
238         * XML tree to valid HTML with all enrichments for appropriate CSS styling.
239         * It also removes all 'seiten_id' attributes.
240         * This method does *not* clone the structure, so this instance won't produce
241         * the same results any more after print_menu invocation! This especially will
242         * affect get_link().
243         *
244         * @arg $xpath_menu_selection  one of the horizontal_menu / sidebar_menu consts.
245         * @arg $host Instance of t29Host which can be used for link rewriting if given.
246         * @returns nothing, since the output is printed out
247         **/
248        function print_menu($xpath_menu_selection, $host=null) {
249                if($this->xml_is_defective()) {
250                        print "The Menu file is broken.";
251                        return false;
252                }
253                $seiten_id = $this->conf['seiten_id'];
254                $_ = $this->conf['msg']->get_shorthand_returner();
255               
256                // find wanted menu
257                $xml = $this->xml->xpath($xpath_menu_selection);
258                if(!$xml) {
259                        print "Menu <i>$xpath_menu_selection</i> not found!";
260                        return false;
261                }
262                $xml = $xml[0]; // just take the first result (should only one result be present)
263               
264                /*
265                // work on a deep copy of the data. Thus this method won't make the overall
266                // class useless.
267                $dom = dom_import_simplexml($xml);
268                $xml = simplexml_import_dom($dom->cloneNode(true));
269                */
270
271                // aktuelle Seite anmarkern und Hierarchie hochgehen
272                // (<ul><li>bla<ul><li>bla<ul><li>hierbin ich <- hochgehen.)
273                $current_a = $xml->xpath("//a[@seiten_id='$seiten_id']");
274                if(count($current_a)) {
275                        $current_li = $current_a[0]->xpath("parent::li");
276                        self::dom_add_class($current_li[0], 'current');
277                        self::dom_prepend_attribute($current_a, 'title', $_('nav-hierarchy-current'), ': ');
278
279                        $actives = $current_li[0]->xpath("ancestor-or-self::li");
280                        array_walk($actives, function($i) { t29Menu::dom_add_class($i, 'active'); });
281                       
282                        $ancestors = $current_li[0]->xpath("ancestor::li");
283                        foreach($ancestors as $i)
284                                t29Menu::dom_prepend_attribute($i->xpath("./a[1]"), 'title', $_('nav-hierarchy-ancestor'), ': ');
285                }
286
287                // Seiten-IDs (ungueltiges HTML) ummoddeln
288                $all_ids = $xml->xpath("//a[@seiten_id]");
289                foreach($all_ids as $a) {
290                        $a['id'] = "sidebar_link_".$a['seiten_id'];
291                        // umweg ueber DOM um Node zu loeschen
292                        $adom = dom_import_simplexml($a);
293                        $adom->removeAttribute('seiten_id');
294                }
295
296                // Geraete-Seiten entfernen
297                if(self::hide_geraete_seiten) {
298                        $geraete_uls = $xml->xpath("//ul[contains(@class, 'geraete')]");
299                        foreach($geraete_uls as $ul) {
300                                $uld = dom_import_simplexml($ul);
301                                $uld->parentNode->removeChild($uld);
302                        }
303                }
304               
305                // alle Links mittels t29Host umwandeln (idR .php-Endung entfernen),
306                // falls erwuenscht
307                if($host) {
308                        $links = $xml->xpath("//a[@href]");
309                        foreach($links as $a)
310                                $a['href'] = $host->rewrite_link($a['href']);
311                }
312       
313                if($xpath_menu_selection == self::horizontal_menu) {
314                        # inject news
315                        $news_ul_content = $this->convert_news_data($host);
316                        $magic_comment = '<!--# INSERT_NEWS #-->';
317                        $menu = $xml->ul->asXML();
318                        print str_replace($magic_comment, $news_ul_content, $menu);
319                } else {
320                        print $xml->ul->asXML();
321                }
322        }
323
324        ///////////////////// PAGE RELATIONS
325        /**
326         * Usage:
327         * foreach(get_page_relations() as $a) {
328         *    echo "Link $a going to $a[href]";
329         * }
330         *
331         * Hinweis:
332         * Wenn Element (etwa prev) nicht existent, nicht null zurueckgeben,
333         * sondern Element gar nicht zurueckgeben (aus hash loeschen).
334         *
335         * @param $seiten_id A seiten_id string or nothing for taking the current active string
336         * @returns an array(prev=>..., next=>...) or empty array, elements are SimpleXML a links
337         **/
338        function get_page_relations($seiten_id=false) {
339                if($this->xml_is_defective())
340                        return array(); // cannot construct relations due to bad XML file
341                if(!$seiten_id) $seiten_id = $this->conf['seiten_id'];
342               
343                $xml = $this->xml->xpath(self::sidebar_menu);
344                if(!$xml) { print "<i>Sidebar not found</i>"; return; }
345                $sidebar = $xml[0];
346               
347                $return = array();
348                $current_a = $sidebar->xpath("//a[@seiten_id='$seiten_id']");
349                if(count($current_a)) {
350                        // wenn aktuelle seite eine geraeteseite ist
351                        if(in_array('geraete', $this->get_link_ul_classes($seiten_id))) {
352                                //  pfad:                        a ->li->ul.geraete->li->li/a
353                                $geraetelink = $current_a[0]->xpath("../../../a");
354                                if(count($geraetelink))
355                                        $return['prev'] = $geraetelink[0];
356                                $return['next'] = null; // kein Link nach vorne
357                        } else {
358                                foreach(array(
359                                  "prev" => "preceding::a[@seiten_id]",
360                                  "next" => "following::a[@seiten_id]") as $rel => $xpath) {
361                                        $nodes = $current_a[0]->xpath($xpath);
362                                        foreach($rel == "prev" ? array_reverse($nodes) : $nodes as $link) {
363                                                $is_geraete = count($link->xpath("ancestor::ul[contains(@class, 'geraete')]"));
364                                                if($is_geraete) continue; // skip geraete links
365                                                $return[$rel] = $link;
366                                                break; // just take the first matching element
367                                        }
368                                } // end for prev next
369                        } // end if geraete
370                } else {
371                        // TODO PENDING: Der Fall tritt derzeit niemals ein, da das XML
372                        // sich dann doch irgendwie auf alles bezieht ($sidebar = alles) und
373                        // ueberall gesucht wird. Ist aber okay. oder?
374                        $return['start'] = t29Menu::dom_new_link('#', 'bla');
375                }
376               
377                // Linkliste aufarbeiten: Nullen rausschmeissen (nur deko) und
378                // Links *klonen*, denn sie werden durch print_menu sonst veraendert
379                // ("Übergeordnete Kategorie der aktuellen Seite" steht dann drin)
380                // und wir wollen sie unveraendert haben.
381                foreach($return as $key => $node) {
382                        if(!$node) {
383                                unset($return[$key]);
384                                continue;
385                        }
386                        $dn = dom_import_simplexml($node);
387                        $dnc = simplexml_import_dom($dn->cloneNode(true));
388                        $return[$key] = $dnc;
389                }
390               
391                return $return;
392        }
393
394} // 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