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

Last change on this file since 357 was 350, checked in by sven, 11 years ago
  • Eintrag "Pianola" unter Lernprojekten geht jetzt auch auf Geraete-Extraseite "Funktionserklaerung" statt auf Lernprojekt
  • Halbe Implementierung von durch linkspezifische Attribute seitenweise ein/ausstellbare Relationsnavigationssichtbarkeit, Ticket #6.
  • Property svn:keywords set to Id
File size: 13.5 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         * @returns array or empty array in case of error
161         **/
162        function get_link_classes($seiten_id=false) {
163                $link = $this->get_link($seiten_id);
164                print "link:"; var_dump($this->xml);
165                if(!$link) return array();
166                var_dump($link); exit;
167                return isset($link['class']) ? explode(' ',$link['class']) : array();
168        }
169
170        ///////////////////// INTER LANGUAGE DETECTION
171        /**
172         * @param seiten_id Get interlanguage link for that seiten_id or default.
173         **/
174        function get_interlanguage_link($seiten_id=false) {
175                if(!$seiten_id) $seiten_id = $this->conf['seiten_id'];
176               
177                $interlinks = array(); // using a loop instead of mappings since php is stupid
178                foreach($this->conf['languages'] as $lang => $lconf) {
179                        $foreign_menu = new t29Menu(array(
180                                'webroot' => $this->conf['webroot'],
181                                'seiten_id' => $this->conf['seiten_id'],
182                                'languages' => $this->conf['languages'],
183                                'lang' => $lang,
184                                'lang_path' => $lconf[1],
185                        ));
186
187                        $link = $foreign_menu->get_link($seiten_id);
188                        $interlinks[$lang] = $link;
189                }
190               
191                return $interlinks;
192        }
193
194        // helper methods
195       
196        /** Check if a simplexml element has an attribute. Lightweight operation
197         *  over the DOM.
198         * @returns boolean
199         **/
200        public static function dom_has_attribute($simplexml_element, $attribute_name) {
201                $dom = dom_import_simplexml($simplexml_element); // is a fast operation
202                return $dom->hasAttribute($attribute_name);
203        }
204       
205        public static function dom_prepend_attribute($simplexml_element, $attribute_name, $content, $seperator='') {
206                if(!is_array($simplexml_element)) $simplexml_element = array($simplexml_element);
207                foreach($simplexml_element as $e)
208                        $e[$attribute_name] = $content . (self::dom_has_attribute($e, $attribute_name) ? ($seperator.$e[$attribute_name]) : '');
209        }
210       
211        public static function dom_append_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] = (self::dom_has_attribute($e, $attribute_name) ? ($e[$attribute_name].$seperator) : '') . $content;
215        }
216       
217        /**
218         * Appends a (CSS) class to a simplexml element, seperated by whitespace. Just an alias.
219         **/
220        public static function dom_add_class($simplexml_element, $value) {
221                self::dom_append_attribute($simplexml_element, 'class', $value, ' ');
222        }
223       
224        public static function dom_new_link($href, $label) {
225                return new SimpleXMLElement(sprintf('<a href="%s">%s</a>', $href, $label));
226        }
227
228
229        ///////////////////// MENU ACTIVE LINK DETECTION
230        /**
231         * print_menu is the central method in this class. It converts the $this->xml
232         * XML tree to valid HTML with all enrichments for appropriate CSS styling.
233         * It also removes all 'seiten_id' attributes.
234         * This method does *not* clone the structure, so this instance won't produce
235         * the same results any more after print_menu invocation! This especially will
236         * affect get_link().
237         *
238         * @arg $xpath_menu_selection  one of the horizontal_menu / sidebar_menu consts.
239         * @arg $host Instance of t29Host which can be used for link rewriting if given.
240         * @returns nothing, since the output is printed out
241         **/
242        function print_menu($xpath_menu_selection, $host=null) {
243                if($this->xml_is_defective()) {
244                        print "The Menu file is broken.";
245                        return false;
246                }
247                $seiten_id = $this->conf['seiten_id'];
248                $_ = $this->conf['msg']->get_shorthand_returner();
249               
250                // find wanted menu
251                $xml = $this->xml->xpath($xpath_menu_selection);
252                if(!$xml) {
253                        print "Menu <i>$xpath_menu_selection</i> not found!";
254                        return false;
255                }
256                $xml = $xml[0]; // just take the first result (should only one result be present)
257               
258                /*
259                // work on a deep copy of the data. Thus this method won't make the overall
260                // class useless.
261                $dom = dom_import_simplexml($xml);
262                $xml = simplexml_import_dom($dom->cloneNode(true));
263                */
264
265                // aktuelle Seite anmarkern und Hierarchie hochgehen
266                // (<ul><li>bla<ul><li>bla<ul><li>hierbin ich <- hochgehen.)
267                $current_a = $xml->xpath("//a[@seiten_id='$seiten_id']");
268                if(count($current_a)) {
269                        $current_li = $current_a[0]->xpath("parent::li");
270                        self::dom_add_class($current_li[0], 'current');
271                        self::dom_prepend_attribute($current_a, 'title', $_('nav-hierarchy-current'), ': ');
272
273                        $actives = $current_li[0]->xpath("ancestor-or-self::li");
274                        array_walk($actives, function($i) { t29Menu::dom_add_class($i, 'active'); });
275                       
276                        $ancestors = $current_li[0]->xpath("ancestor::li");
277                        foreach($ancestors as $i)
278                                t29Menu::dom_prepend_attribute($i->xpath("./a[1]"), 'title', $_('nav-hierarchy-ancestor'), ': ');
279                }
280
281                // Seiten-IDs (ungueltiges HTML) ummoddeln
282                $all_ids = $xml->xpath("//a[@seiten_id]");
283                foreach($all_ids as $a) {
284                        $a['id'] = "sidebar_link_".$a['seiten_id'];
285                        // umweg ueber DOM um Node zu loeschen
286                        $adom = dom_import_simplexml($a);
287                        $adom->removeAttribute('seiten_id');
288                }
289
290                // Geraete-Seiten entfernen
291                if(self::hide_geraete_seiten) {
292                        $geraete_uls = $xml->xpath("//ul[contains(@class, 'geraete')]");
293                        foreach($geraete_uls as $ul) {
294                                $uld = dom_import_simplexml($ul);
295                                $uld->parentNode->removeChild($uld);
296                        }
297                }
298               
299                // alle Links mittels t29Host umwandeln (idR .php-Endung entfernen),
300                // falls erwuenscht
301                if($host) {
302                        $links = $xml->xpath("//a[@href]");
303                        foreach($links as $a)
304                                $a['href'] = $host->rewrite_link($a['href']);
305                }
306       
307                if($xpath_menu_selection == self::horizontal_menu) {
308                        # inject news
309                        $news_ul_content = $this->convert_news_data($host);
310                        $magic_comment = '<!--# INSERT_NEWS #-->';
311                        $menu = $xml->ul->asXML();
312                        print str_replace($magic_comment, $news_ul_content, $menu);
313                } else {
314                        print $xml->ul->asXML();
315                }
316        }
317
318        ///////////////////// PAGE RELATIONS
319        /**
320         * Usage:
321         * foreach(get_page_relations() as $a) {
322         *    echo "Link $a going to $a[href]";
323         * }
324         *
325         * Hinweis:
326         * Wenn Element (etwa prev) nicht existent, nicht null zurueckgeben,
327         * sondern Element gar nicht zurueckgeben (aus hash loeschen).
328         *
329         * @param $seiten_id A seiten_id string or nothing for taking the current active string
330         * @returns an array(prev=>..., next=>...) or empty array, elements are SimpleXML a links
331         **/
332        function get_page_relations($seiten_id=false) {
333                if($this->xml_is_defective())
334                        return array(); // cannot construct relations due to bad XML file
335                if(!$seiten_id) $seiten_id = $this->conf['seiten_id'];
336               
337                $xml = $this->xml->xpath(self::sidebar_menu);
338                if(!$xml) { print "<i>Sidebar not found</i>"; return; }
339                $sidebar = $xml[0];
340               
341                $return = array();
342                $current_a = $sidebar->xpath("//a[@seiten_id='$seiten_id']");
343                if(count($current_a)) {
344                        // wenn aktuelle seite eine geraeteseite ist
345                        if(in_array('geraete', $this->get_link_ul_classes($seiten_id))) {
346                                //  pfad:                        a ->li->ul.geraete->li->li/a
347                                $geraetelink = $current_a[0]->xpath("../../../a");
348                                if(count($geraetelink))
349                                        $return['prev'] = $geraetelink[0];
350                                $return['next'] = null; // kein Link nach vorne
351                        } else {
352                                foreach(array(
353                                  "prev" => "preceding::a[@seiten_id]",
354                                  "next" => "following::a[@seiten_id]") as $rel => $xpath) {
355                                        $nodes = $current_a[0]->xpath($xpath);
356                                        foreach($rel == "prev" ? array_reverse($nodes) : $nodes as $link) {
357                                                $is_geraete = count($link->xpath("ancestor::ul[contains(@class, 'geraete')]"));
358                                                if($is_geraete) continue; // skip geraete links
359                                                $return[$rel] = $link;
360                                                break; // just take the first matching element
361                                        }
362                                } // end for prev next
363                        } // end if geraete
364                } else {
365                        // TODO PENDING: Der Fall tritt derzeit niemals ein, da das XML
366                        // sich dann doch irgendwie auf alles bezieht ($sidebar = alles) und
367                        // ueberall gesucht wird. Ist aber okay. oder?
368                        $return['start'] = t29Menu::dom_new_link('#', 'bla');
369                }
370               
371                // Linkliste aufarbeiten: Nullen rausschmeissen (nur deko) und
372                // Links *klonen*, denn sie werden durch print_menu sonst veraendert
373                // ("Übergeordnete Kategorie der aktuellen Seite" steht dann drin)
374                // und wir wollen sie unveraendert haben.
375                foreach($return as $key => $node) {
376                        if(!$node) {
377                                unset($return[$key]);
378                                continue;
379                        }
380                        $dn = dom_import_simplexml($node);
381                        $dnc = simplexml_import_dom($dn->cloneNode(true));
382                        $return[$key] = $dnc;
383                }
384               
385                return $return;
386        }
387
388} // 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