Project

General

Profile

1 827 doc
<?php
2
/*
3
    show_menu2: show_menu replacement for Website Baker
4
    Copyright (C) 2006-2008, Brodie Thiesfield
5
6
    This program is free software; you can redistribute it and/or
7
    modify it under the terms of the GNU General Public License
8
    as published by the Free Software Foundation; either version 2
9
    of the License, or (at your option) any later version.
10
11
    This program is distributed in the hope that it will be useful,
12
    but WITHOUT ANY WARRANTY; without even the implied warranty of
13
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
    GNU General Public License for more details.
15
16
    You should have received a copy of the GNU General Public License
17
    along with this program; if not, write to the Free Software
18
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19
    02110-1301, USA.
20
21
    ***********************************************
22 859 Ruebenwurz
    ** Version 4.7: see README for documentation **
23 827 doc
    ***********************************************
24
*/
25
26
define('SM2_ROOT',       -1000);
27
define('SM2_CURR',       -2000);
28
define('SM2_ALLMENU',       -1);
29
define('SM2_START',       1000);
30
define('SM2_MAX',         2000);
31
define('SM2_ALL',       0x0001); // bit 0 (group 1) (Note: also used for max level!)
32
define('SM2_TRIM',      0x0002); // bit 1 (group 1)
33
define('SM2_CRUMB',     0x0004); // bit 2 (group 1)
34
define('SM2_SIBLING',   0x0008); // bit 3 (group 1)
35
define('SM2_NUMCLASS',  0x0010); // bit 4
36
define('SM2_ALLINFO',   0x0020); // bit 5
37
define('SM2_NOCACHE',   0x0040); // bit 6
38
define('SM2_PRETTY',    0x0080); // bit 7
39
define('SM2_ESCAPE',    0x0100); // bit 8
40
define('SM2_NOESCAPE',       0); // NOOP, unnecessary with WB 2.6.7+
41
define('SM2_BUFFER',    0x0200); // bit 9
42
define('SM2_CURRTREE',  0x0400); // bit 10
43
44
define('_SM2_GROUP_1',  0x000F); // exactly one flag from group 1 is required
45
46
47
// Implement support for page_menu and show_menu using show_menu2. If you remove
48
// the comments characters from the beginning of the following include, all menu
49
// functions in Website Baker will be implemented using show_menu2. While it is
50
// commented out, the original WB functions will be used.
51
//include('legacy.php');
52
53
// This class is the default menu formatter for sm2. If desired, you can
54
// create your own formatter class and pass the object into show_menu2
55
// as $aItemFormat.
56
define('SM2_CONDITIONAL','if\s*\(([^\)]+)\)\s*{([^}]*)}\s*(?:else\s*{([^}]*)}\s*)?');
57
define('SM2_COND_TERM','\s*(\w+)\s*(<|<=|==|=|=>|>|!=)\s*([\w\-]+)\s*');
58
class SM2_Formatter
59
{
60
    var $output;
61
    var $flags;
62
    var $itemOpen;
63
    var $itemClose;
64
    var $menuOpen;
65
    var $menuClose;
66
    var $topItemOpen;
67
    var $topMenuOpen;
68
69
    var $isFirst;
70
    var $page;
71
    var $url;
72
    var $currSib;
73
    var $sibCount;
74
    var $currClass;
75
    var $prettyLevel;
76
77
    // output the data
78
    function output($aString) {
79
        if ($this->flags & SM2_BUFFER) {
80
            $this->output .= $aString;
81
        }
82
        else {
83
            echo $aString;
84
        }
85
    }
86
87
    // set the default values for all of our formatting items
88
    function set($aFlags, $aItemOpen, $aItemClose, $aMenuOpen, $aMenuClose, $aTopItemOpen, $aTopMenuOpen) {
89
        $this->flags        = $aFlags;
90
        $this->itemOpen     = is_string($aItemOpen)    ? $aItemOpen    : '[li][a][menu_title]</a>';
91
        $this->itemClose    = is_string($aItemClose)   ? $aItemClose   : '</li>';
92
        $this->menuOpen     = is_string($aMenuOpen)    ? $aMenuOpen    : '[ul]';
93
        $this->menuClose    = is_string($aMenuClose)   ? $aMenuClose   : '</ul>';
94
        $this->topItemOpen  = is_string($aTopItemOpen) ? $aTopItemOpen : $this->itemOpen;
95
        $this->topMenuOpen  = is_string($aTopMenuOpen) ? $aTopMenuOpen : $this->menuOpen;
96
    }
97
98
    // initialize the state of the formatter before anything is output
99
    function initialize() {
100
        $this->output = '';
101
        $this->prettyLevel = 0;
102
        if ($this->flags & SM2_PRETTY) {
103
            $this->output("\n<!-- show_menu2 -->");
104
        }
105
    }
106
107
    // start a menu
108
    function startList(&$aPage, &$aUrl) {
109
        $currClass = '';
110
        $currItem = $this->menuOpen;
111
112
        // use the top level menu open if this is the first menu
113
        if ($this->topMenuOpen) {
114
            $currItem = $this->topMenuOpen;
115
            $currClass .= ' menu-top';
116
            $this->topMenuOpen = false;
117
        }
118
119
        // add the numbered menu class only if requested
120
        if (($this->flags & SM2_NUMCLASS) == SM2_NUMCLASS) {
121
            $currClass .= ' menu-'.$aPage['level'];
122
        }
123
124
        $this->prettyLevel += 1;
125
126
        // replace all keywords in the output
127
        if ($this->flags & SM2_PRETTY) {
128
            $this->output("\n".str_repeat(' ',$this->prettyLevel).
129
                $this->format($aPage, $aUrl, $currItem, $currClass));
130
        }
131
        else {
132
            $this->output($this->format($aPage, $aUrl, $currItem, $currClass));
133
        }
134
135
        $this->prettyLevel += 3;
136
    }
137
138
    // start an item within the menu
139
    function startItem(&$aPage, &$aUrl, $aCurrSib, $aSibCount) {
140
        // generate our class list
141
        $currClass = '';
142
        if (($this->flags & SM2_NUMCLASS) == SM2_NUMCLASS) {
143
            $currClass .= ' menu-'.$aPage['level'];
144
        }
145
        if (array_key_exists('sm2_has_child', $aPage)) {
146
            // not set if false, so existence = true
147
            $currClass .= ' menu-expand';
148
        }
149 845 doc
        if (array_key_exists('sm2_is_curr', $aPage)) {
150 827 doc
            $currClass .= ' menu-current';
151
        }
152
        elseif (array_key_exists('sm2_is_parent', $aPage)) {
153
            // not set if false, so existence = true
154
            $currClass .= ' menu-parent';
155
        }
156
        elseif (array_key_exists('sm2_is_sibling', $aPage)) {
157
            // not set if false, so existence = true
158
            $currClass .= ' menu-sibling';
159
        }
160
        elseif (array_key_exists('sm2_child_level',$aPage)) {
161
            // not set if not a child
162
            $currClass .= ' menu-child';
163
            if (($this->flags & SM2_NUMCLASS) == SM2_NUMCLASS) {
164
                $currClass .= ' menu-child-'.($aPage['sm2_child_level']-1);
165
            }
166
        }
167
        if ($aCurrSib == 1) {
168
            $currClass .= ' menu-first';
169
        }
170
        if ($aCurrSib == $aSibCount) {
171
            $currClass .= ' menu-last';
172
        }
173
174
        // use the top level item if this is the first item
175
        $currItem = $this->itemOpen;
176
        if ($this->topItemOpen) {
177
            $currItem = $this->topItemOpen;
178
            $this->topItemOpen = false;
179
        }
180
181
        // replace all keywords in the output
182
        if ($this->flags & SM2_PRETTY) {
183
            $this->output("\n".str_repeat(' ',$this->prettyLevel));
184
        }
185
        $this->output($this->format($aPage, $aUrl, $currItem, $currClass, $aCurrSib, $aSibCount));
186
    }
187
188
    // find and replace all keywords, setting the state variables first
189
    function format(&$aPage, &$aUrl, &$aCurrItem, &$aCurrClass,
190
        $aCurrSib = 0, $aSibCount = 0)
191
    {
192
        $this->page      = &$aPage;
193
        $this->url       = &$aUrl;
194
        $this->currClass = trim($aCurrClass);
195
        $this->currSib   = $aCurrSib;
196
        $this->sibCount  = $aSibCount;
197
198
        $item = $this->format2($aCurrItem);
199
200
        unset($this->page);
201
        unset($this->url);
202
        unset($this->currClass);
203
204
        return $item;
205
    }
206
207
    // find and replace all keywords
208
    function format2(&$aCurrItem) {
209
        if (!is_string($aCurrItem)) return '';
210
        return preg_replace(
211
            '@\[('.
212
                'a|ac|/a|li|/li|ul|/ul|menu_title|page_title|url|target|page_id|'.
213
                'parent|level|sib|sibCount|class|description|keywords|'.
214
                SM2_CONDITIONAL.
215
            ')\]@e',
216
            '$this->replace("\1")', $aCurrItem);
217
    }
218
219
    // replace the keywords
220
    function replace($aMatch) {
221
        switch ($aMatch) {
222
        case 'a':
223
            return '<a href="'.$this->url.'" target="'.$this->page['target'].'">';
224
        case 'ac':
225
            return '<a href="'.$this->url.'" target="'.$this->page['target'].'" class="'.$this->currClass.'">';
226
        case '/a':
227
            return '</a>';
228
        case 'li':
229
            return '<li class="'.$this->currClass.'">';
230
        case '/li':
231
            return '</li>';
232
        case 'ul':
233
            return '<ul class="'.$this->currClass.'">';
234
        case '/ul':
235
            return '</ul>';
236
        case 'url':
237
            return $this->url;
238
        case 'sib':
239
            return $this->currSib;
240
        case 'sibCount':
241
            return $this->sibCount;
242
        case 'class':
243
            return $this->currClass;
244
        default:
245
            if (array_key_exists($aMatch, $this->page)) {
246
                if ($this->flags & SM2_ESCAPE) {
247
                    return htmlspecialchars($this->page[$aMatch], ENT_QUOTES);
248
                }
249
                else {
250
                    return $this->page[$aMatch];
251
                }
252
            }
253
            if (preg_match('/'.SM2_CONDITIONAL.'/', $aMatch, $rgMatches)) {
254
                return $this->replaceIf($rgMatches[1], $rgMatches[2], $rgMatches[3]);
255
            }
256
        }
257
        return "[$aMatch=UNKNOWN]";
258
    }
259
260
    // conditional replacement
261
    function replaceIf(&$aExpression, &$aIfValue, &$aElseValue) {
262
        // evaluate all of the tests in the conditional (we don't do short-circuit
263
        // evaluation) and replace the string test with the boolean result
264
        $rgTests = preg_split('/(\|\||\&\&)/', $aExpression, -1, PREG_SPLIT_DELIM_CAPTURE);
265
        for ($n = 0; $n < count($rgTests); $n += 2) {
266
            if (preg_match('/'.SM2_COND_TERM.'/', $rgTests[$n], $rgMatches)) {
267
                $rgTests[$n] = $this->ifTest($rgMatches[1], $rgMatches[2], $rgMatches[3]);
268
            }
269
            else {
270
                error_log("show_menu2 error: conditional expression is invalid!");
271
                $rgTests[$n] = false;
272
            }
273
        }
274
275
        // combine all test results for a final result
276
        $ok = $rgTests[0];
277
        for ($n = 1; $n+1 < count($rgTests); $n += 2) {
278
            if ($rgTests[$n] == '||') {
279
                $ok = $ok || $rgTests[$n+1];
280
            }
281
            else {
282
                $ok = $ok && $rgTests[$n+1];
283
            }
284
        }
285
286
        // return the formatted expression if the test succeeded
287
        return $ok ? $this->format2($aIfValue) : $this->format2($aElseValue);
288
    }
289
290
    // conditional test
291
    function ifTest(&$aKey, &$aOperator, &$aValue) {
292
        global $wb;
293
294
        // find the correct operand
295
        $operand = false;
296
        switch($aKey) {
297
        case 'class':
298
            // we need to wrap the class names in spaces so we can test for a unique
299
            // class name that will not match prefixes or suffixes. Same must be done
300
            // for the value we are testing.
301
            $operand = " $this->currClass ";
302
            break;
303
        case 'sib':
304
            $operand = $this->currSib;
305
            if ($aValue == 'sibCount') {
306
                $aValue = $this->sibCount;
307
            }
308
            break;
309
        case 'sibCount':
310
            $operand = $this->sibCount;
311
            break;
312
        case 'level':
313
            $operand = $this->page['level'];
314
            switch ($aValue) {
315
            case 'root':    $aValue = 0; break;
316
            case 'granny':  $aValue = $wb->page['level']-2; break;
317
            case 'parent':  $aValue = $wb->page['level']-1; break;
318
            case 'current': $aValue = $wb->page['level'];   break;
319
            case 'child':   $aValue = $wb->page['level']+1; break;
320
            }
321
            if ($aValue < 0) $aValue = 0;
322
            break;
323
        case 'id':
324
            $operand = $this->page['page_id'];
325
            switch ($aValue) {
326
            case 'parent':  $aValue = $wb->page['parent'];  break;
327
            case 'current': $aValue = $wb->page['page_id']; break;
328
            }
329
            break;
330
        default:
331
            return '';
332
        }
333
334
        // do the test
335
        $ok = false;
336
        switch ($aOperator) {
337
        case '<':
338
            $ok = ($operand < $aValue);
339
            break;
340
        case '<=':
341
            $ok = ($operand <= $aValue);
342
            break;
343
        case '=':
344
        case '==':
345
        case '!=':
346
            if ($aKey == 'class') {
347
                $ok = strstr($operand, " $aValue ") !== FALSE;
348
            }
349
            else {
350
                $ok = ($operand == $aValue);
351
            }
352
            if ($aOperator == '!=') {
353
                $ok = !$ok;
354
            }
355
            break;
356
        case '>=':
357
            $ok = ($operand >= $aValue);
358
        case '>':
359
            $ok = ($operand > $aValue);
360
        }
361
362
        return $ok;
363
    }
364
365
    // finish the current menu item
366
    function finishItem() {
367
        if ($this->flags & SM2_PRETTY) {
368
            $this->output(str_repeat(' ',$this->prettyLevel).$this->itemClose);
369
        }
370
        else {
371
            $this->output($this->itemClose);
372
        }
373
    }
374
375
    // finish the current menu
376
    function finishList() {
377
        $this->prettyLevel -= 3;
378
379
        if ($this->flags & SM2_PRETTY) {
380
            $this->output("\n".str_repeat(' ',$this->prettyLevel).$this->menuClose."\n");
381
        }
382
        else {
383
            $this->output($this->menuClose);
384
        }
385
386
        $this->prettyLevel -= 1;
387
    }
388
389
    // cleanup the state of the formatter after everything has been output
390
    function finalize() {
391
        if ($this->flags & SM2_PRETTY) {
392
            $this->output("\n");
393
        }
394
    }
395
396
    // return the output
397
    function getOutput() {
398
        return $this->output;
399
    }
400
};
401
402
function show_menu2(
403
    $aMenu          = 0,
404
    $aStart         = SM2_ROOT,
405
    $aMaxLevel      = -1999, // SM2_CURR+1
406 859 Ruebenwurz
    $aOptions       = SM2_TRIM,
407 827 doc
    $aItemOpen      = false,
408
    $aItemClose     = false,
409
    $aMenuOpen      = false,
410
    $aMenuClose     = false,
411
    $aTopItemOpen   = false,
412
    $aTopMenuOpen   = false
413
    )
414
{
415
    global $wb;
416
417 859 Ruebenwurz
    // extract the flags and set $aOptions to an array
418
    $flags = 0;
419
    if (is_int($aOptions)) {
420
        $flags = $aOptions;
421
        $aOptions = array();
422
    }
423
    else if (isset($aOptions['flags'])) {
424
        $flags = $aOptions['flags'];
425
    }
426
    else {
427
        $flags = SM2_TRIM;
428
        $aOptions = array();
429
        error_log('show_menu2 error: $aOptions is invalid. No flags supplied!');
430
    }
431
432 827 doc
    // ensure we have our group 1 flag, we don't check for the "exactly 1" part, but
433
    // we do ensure that they provide at least one.
434 859 Ruebenwurz
    if (0 == ($flags & _SM2_GROUP_1)) {
435
        error_log('show_menu2 error: $aOptions is invalid. No flags from group 1 supplied!');
436
        $flags |= SM2_TRIM; // default to TRIM
437 827 doc
    }
438
439 845 doc
    // search page results don't have any of the page data loaded by WB, so we load it
440
    // ourselves using the referrer ID as the current page
441
    $CURR_PAGE_ID = defined('REFERRER_ID') ? REFERRER_ID : PAGE_ID;
442
    if (count($wb->page) == 0 && defined('REFERRER_ID') && REFERRER_ID > 0) {
443
        global $database;
444
        $sql = "SELECT * FROM ".TABLE_PREFIX."pages WHERE page_id = '".REFERRER_ID."'";
445
        $result = $database->query($sql);
446
        if ($result->numRows() == 1) {
447
            $wb->page = $result->fetchRow();
448
        }
449
        unset($result);
450
    }
451
452 827 doc
    // fix up the menu number to default to the menu number
453
    // of the current page if no menu has been supplied
454
    if ($aMenu == 0) {
455
        $aMenu = $wb->page['menu'] == '' ? 1 : $wb->page['menu'];
456
    }
457
458
    // Set some of the $wb->page[] settings to defaults if not set
459 845 doc
    $pageLevel  = $wb->page['level']  == '' ? 0 : $wb->page['level'];
460 827 doc
    $pageParent = $wb->page['parent'] == '' ? 0 : $wb->page['parent'];
461
462
    // adjust the start level and start page ID as necessary to
463
    // handle the special values that can be passed in as $aStart
464
    $aStartLevel = 0;
465
    if ($aStart < SM2_ROOT) {   // SM2_CURR+N
466
        if ($aStart == SM2_CURR) {
467
            $aStartLevel = $pageLevel;
468 845 doc
            $aStart = $pageParent;
469 827 doc
        }
470
        else {
471
            $aStartLevel = $pageLevel + $aStart - SM2_CURR;
472 845 doc
            $aStart = $CURR_PAGE_ID;
473 827 doc
        }
474
    }
475
    elseif ($aStart < 0) {   // SM2_ROOT+N
476
        $aStartLevel = $aStart - SM2_ROOT;
477
        $aStart = 0;
478
    }
479
480
    // we get the menu data once and store it in a global variable. This allows
481
    // multiple calls to show_menu2 in a single page with only a single call to
482
    // the database. If this variable exists, then we have already retrieved all
483
    // of the information and processed it, so we don't need to do it again.
484 859 Ruebenwurz
    if (($flags & SM2_NOCACHE) != 0
485 827 doc
        || !array_key_exists('show_menu2_data', $GLOBALS)
486
        || !array_key_exists($aMenu, $GLOBALS['show_menu2_data']))
487
    {
488
        global $database;
489
490
        // create an array of all parents of the current page. As the page_trail
491
        // doesn't include the theoretical root element 0, we add it ourselves.
492
        $rgCurrParents = split(',', '0,'.$wb->page['page_trail']);
493
        array_pop($rgCurrParents); // remove the current page
494
        $rgParent = array();
495
496
        // if the caller wants all menus gathered together (e.g. for a sitemap)
497
        // then we don't limit our SQL query
498
        $menuLimitSql = ' AND menu = ' .$aMenu;
499
        if ($aMenu == SM2_ALLMENU) {
500
            $menuLimitSql = '';
501
        }
502
503
        // we only load the description and keywords if we have been told to,
504
        // this cuts the memory load for pages that don't use them. Note that if
505
        // we haven't been told to load these fields the *FIRST TIME* show_menu2
506
        // is called (i.e. where the database is loaded) then the info won't
507
        // exist anyhow.
508
        $fields = 'parent,page_id,menu_title,page_title,link,target,level,visibility,viewing_groups';
509 845 doc
        if (version_compare(WB_VERSION, '2.7', '>=')) { // WB 2.7+
510 827 doc
            $fields .= ',viewing_users';
511
        }
512 859 Ruebenwurz
        if ($flags & SM2_ALLINFO) {
513 827 doc
            $fields = '*';
514
        }
515
516
        // get this once for performance. We really should be calling only need to
517
        // call $wb->get_group_id() but that outputs a warning notice if the
518
        // groupid isn't set in the session, so we check it first here.
519
        $currGroup = array_key_exists('GROUP_ID', $_SESSION) ?
520
            ','.$wb->get_group_id().',' : 'NOGROUP';
521
522
        // we request all matching rows from the database for the menu that we
523
        // are about to create it is cheaper for us to get everything we need
524
        // from the database once and create the menu from memory then make
525
        // multiple calls to the database.
526
        $sql = "SELECT $fields FROM ".TABLE_PREFIX.
527
               "pages WHERE $wb->extra_where_sql $menuLimitSql ".
528
               'ORDER BY level ASC, position ASC';
529
        $oRowset = $database->query($sql);
530
        if (is_object($oRowset) && $oRowset->numRows() > 0) {
531
            // create an in memory array of the database data based on the item's parent.
532
            // The array stores all elements in the correct display order.
533
            while ($page = $oRowset->fetchRow()) {
534 845 doc
                // ignore all pages that the current user is not permitted to view
535 827 doc
                if(version_compare(WB_VERSION, '2.7', '>=')) { // WB >= 2.7
536
                    // 1. all pages with no active sections (unless it is the top page) are ignored
537 845 doc
                    if (!$wb->page_is_active($page) && $page['link'] != $wb->default_link && !INTRO_PAGE) {
538 827 doc
                      continue;
539
                    }
540
                    // 2. all pages not visible to this user (unless always visible to registered users) are ignored
541 845 doc
                    if (!$wb->page_is_visible($page) && $page['visibility'] != 'registered') {
542 827 doc
                        continue;
543
                    }
544
                }
545
                else {  // WB < 2.7
546
                    // We can't do this in SQL as the viewing_groups column contains multiple
547
                    // values which are hard to process correctly in SQL. Essentially we add the
548
                    // following limit to the SQL query above:
549
                    //  (visibility <> "private" OR $wb->get_group_id() IN viewing_groups)
550
                    if ($page['visibility'] == 'private'
551
                        && false === strstr(",{$page['viewing_groups']},", $currGroup))
552
                    {
553
                        continue;
554
                    }
555
                }
556
557
                // ensure that we have an array entry in the table to add this to
558
                $idx = $page['parent'];
559
                if (!array_key_exists($idx, $rgParent)) {
560
                    $rgParent[$idx] = array();
561
                }
562
563
                // mark our current page as being on the current path
564 845 doc
                if ($page['page_id'] == $CURR_PAGE_ID) {
565
                    $page['sm2_is_curr'] = true;
566 827 doc
                    $page['sm2_on_curr_path'] = true;
567
                }
568
569
                // mark parents of the current page as such
570
                if (in_array($page['page_id'], $rgCurrParents)) {
571
                    $page['sm2_is_parent'] = true;
572
                    $page['sm2_on_curr_path'] = true;
573
                }
574
575
                // add the entry to the array
576
                $rgParent[$idx][] = $page;
577
            }
578
        }
579
        unset($oRowset);
580
581
        // mark all elements that are siblings of any element on the current path
582
        foreach ($rgCurrParents as $x) {
583
            if (array_key_exists($x, $rgParent)) {
584
                foreach (array_keys($rgParent[$x]) as $y) {
585
                    $mark =& $rgParent[$x][$y];
586
                    $mark['sm2_path_sibling'] = true;
587
                    unset($mark);
588
                }
589
            }
590
        }
591
592
        // mark all elements that have children and are siblings of the current page
593
        $parentId = $pageParent;
594
        foreach (array_keys($rgParent) as $x) {
595
            $childSet =& $rgParent[$x];
596
            foreach (array_keys($childSet) as $y) {
597
                $mark =& $childSet[$y];
598
                if (array_key_exists($mark['page_id'], $rgParent)) {
599
                    $mark['sm2_has_child'] = true;
600
                }
601 845 doc
                if ($mark['parent'] == $parentId && $mark['page_id'] != $CURR_PAGE_ID) {
602 827 doc
                    $mark['sm2_is_sibling'] = true;
603
                }
604
                unset($mark);
605
            }
606
            unset($childSet);
607
        }
608
609
        // mark all children of the current page. We don't do this when
610 845 doc
        // $CURR_PAGE_ID is 0, as 0 is the parent of everything.
611
        // $CURR_PAGE_ID == 0 occurs on special pages like search results
612
        // when no referrer is available.s
613
        if ($CURR_PAGE_ID != 0) {
614
            sm2_mark_children($rgParent, $CURR_PAGE_ID, 1);
615 827 doc
        }
616
617
        // store the complete processed menu data as a global. We don't
618
        // need to read this from the database anymore regardless of how
619
        // many menus are displayed on the same page.
620
        if (!array_key_exists('show_menu2_data', $GLOBALS)) {
621
            $GLOBALS['show_menu2_data'] = array();
622
        }
623
        $GLOBALS['show_menu2_data'][$aMenu] =& $rgParent;
624
        unset($rgParent);
625
    }
626
627
    // adjust $aMaxLevel to the level number of the final level that
628
    // will be displayed. That is, we display all levels <= aMaxLevel.
629
    if ($aMaxLevel == SM2_ALL) {
630
        $aMaxLevel = 1000;
631
    }
632
    elseif ($aMaxLevel < 0) {   // SM2_CURR+N
633
        $aMaxLevel += $pageLevel - SM2_CURR;
634
    }
635
    elseif ($aMaxLevel >= SM2_MAX) { // SM2_MAX+N
636
        $aMaxLevel += $aStartLevel - SM2_MAX;
637
        if ($aMaxLevel > $pageLevel) {
638
            $aMaxLevel = $pageLevel;
639
        }
640
    }
641
    else {  // SM2_START+N
642
        $aMaxLevel += $aStartLevel - SM2_START;
643
    }
644
645
    // generate the menu
646
    $retval = false;
647
    if (array_key_exists($aStart, $GLOBALS['show_menu2_data'][$aMenu])) {
648
        $formatter = $aItemOpen;
649
        if (!is_object($aItemOpen)) {
650
            static $sm2formatter;
651
            if (!isset($sm2formatter)) {
652
                $sm2formatter = new SM2_Formatter;
653
            }
654
            $formatter = $sm2formatter;
655 859 Ruebenwurz
            $formatter->set($flags, $aItemOpen, $aItemClose,
656 827 doc
                $aMenuOpen, $aMenuClose, $aTopItemOpen, $aTopMenuOpen);
657
        }
658
659 859 Ruebenwurz
        // adjust the level until we show everything and ignore the SM2_TRIM flag.
660
        // Usually this will be less than the start level to disable it.
661
        $showAllLevel = $aStartLevel - 1;
662
        if (isset($aOptions['notrim'])) {
663
            $showAllLevel = $aStartLevel + $aOptions['notrim'];
664
        }
665
666 827 doc
        // display the menu
667
        $formatter->initialize();
668
        sm2_recurse(
669
            $GLOBALS['show_menu2_data'][$aMenu],
670
            $aStart,    // parent id to start displaying sub-menus
671 859 Ruebenwurz
            $aStartLevel, $showAllLevel, $aMaxLevel, $flags,
672 827 doc
            $formatter);
673
        $formatter->finalize();
674
675
        // if we are returning something, get the data
676 859 Ruebenwurz
        if (($flags & SM2_BUFFER) != 0) {
677 827 doc
            $retval = $formatter->getOutput();
678
        }
679
    }
680
681
    // clear the data if we aren't caching it
682 859 Ruebenwurz
    if (($flags & SM2_NOCACHE) != 0) {
683 827 doc
        unset($GLOBALS['show_menu2_data'][$aMenu]);
684
    }
685
686
    return $retval;
687
}
688
689
function sm2_mark_children(&$rgParent, $aStart, $aChildLevel)
690
{
691
    if (array_key_exists($aStart, $rgParent)) {
692
        foreach (array_keys($rgParent[$aStart]) as $y) {
693
            $mark =& $rgParent[$aStart][$y];
694
            $mark['sm2_child_level'] = $aChildLevel;
695
            $mark['sm2_on_curr_path'] = true;
696
            sm2_mark_children($rgParent, $mark['page_id'], $aChildLevel+1);
697
        }
698
    }
699
}
700
701
function sm2_recurse(
702
    &$rgParent, $aStart,
703 859 Ruebenwurz
    $aStartLevel, $aShowAllLevel, $aMaxLevel, $aFlags,
704 827 doc
    &$aFormatter
705
    )
706
{
707
    global $wb;
708
709
    // on entry to this function we know that there are entries for this
710
    // parent and all entries for that parent are being displayed. We also
711
    // need to check if any of the children need to be displayed too.
712
    $isListOpen = false;
713
    $currentLevel = $wb->page['level'] == '' ? 0 : $wb->page['level'];
714
715
    // get the number of siblings so we can check pass this and check if the
716
    // item is first or last
717
    $sibCount = count($rgParent[$aStart]);
718
    $currSib = 0;
719
    foreach ($rgParent[$aStart] as $page) {
720
        $currSib++;
721
722
        // skip any elements that are lower than the maximum level
723
        $pageLevel = $page['level'];
724
        if ($pageLevel > $aMaxLevel) {
725
            continue;
726
        }
727
728
        // this affects ONLY the top level
729
        if ($aStart == 0 && ($aFlags & SM2_CURRTREE)) {
730
            if (!array_key_exists('sm2_on_curr_path', $page)) { // not set if false, so existence = true
731
                continue;
732
            }
733
            $sibCount = 1;
734
        }
735
736
        // trim the tree as appropriate
737
        if ($aFlags & SM2_SIBLING) {
738
            // parents, and siblings and children of current only
739
            if (!array_key_exists('sm2_on_curr_path', $page)      // not set if false, so existence = true
740
                && !array_key_exists('sm2_is_sibling', $page)     // not set if false, so existence = true
741
                && !array_key_exists('sm2_child_level', $page)) { // not set if false, so existence = true
742
                continue;
743
            }
744
        }
745
        else if ($aFlags & SM2_TRIM) {
746
            // parents and siblings of parents
747 859 Ruebenwurz
            if ($pageLevel > $aShowAllLevel  // permit all levels to be shown
748
                && !array_key_exists('sm2_on_curr_path', $page)    // not set if false, so existence = true
749 827 doc
                && !array_key_exists('sm2_path_sibling', $page)) {  // not set if false, so existence = true
750
                continue;
751
            }
752
        }
753
        elseif ($aFlags & SM2_CRUMB) {
754
            // parents only
755
            if (!array_key_exists('sm2_on_curr_path', $page)    // not set if false, so existence = true
756
                || array_key_exists('sm2_child_level', $page)) {  // not set if false, so existence = true
757
                continue;
758
            }
759
        }
760
761
        // depth first traverse
762
        $nextParent = $page['page_id'];
763
764
        // display the current element if we have reached the start level
765
        if ($pageLevel >= $aStartLevel) {
766
            // massage the link into the correct form
767
            if(!INTRO_PAGE && $page['link'] == $wb->default_link) {
768
                $url = WB_URL;
769
            }
770
            else {
771
                $url = $wb->page_link($page['link']);
772
            }
773
774
            // we open the list only when we absolutely need to
775
            if (!$isListOpen) {
776
                $aFormatter->startList($page, $url);
777
                $isListOpen = true;
778
            }
779
780
            $aFormatter->startItem($page, $url, $currSib, $sibCount);
781
        }
782
783
        // display children as appropriate
784
        if ($pageLevel + 1 <= $aMaxLevel
785
            && array_key_exists('sm2_has_child', $page)) {  // not set if false, so existence = true
786
            sm2_recurse(
787
                $rgParent, $nextParent, // parent id to start displaying sub-menus
788 859 Ruebenwurz
                $aStartLevel, $aShowAllLevel, $aMaxLevel, $aFlags,
789 827 doc
                $aFormatter);
790
        }
791
792
        // close the current element if appropriate
793
        if ($pageLevel >= $aStartLevel) {
794
            $aFormatter->finishItem($pageLevel, $page);
795
        }
796
    }
797
798
    // close the list if we opened one
799
    if ($isListOpen) {
800
        $aFormatter->finishList();
801
    }
802
}
803
804
?>