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

Last change on this file since 348 was 348, checked in by sven, 11 years ago

Kleiner Fix, sodass auch Links im Menue und ein paar Header-Links
bereinigt erscheinen (ohne Dateiendung).

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