Project

General

Profile

1
<?php
2
/**
3
 *
4
 * @category        module
5
 * @package         show_menu2
6
 * @author          WebsiteBaker Project
7
 * @copyright       Brodie Thiesfield
8
 * @copyright       2009-2013, WebsiteBaker Org. e.V.
9
 * @link            http://www.websitebaker.org/
10
 * @license         http://www.gnu.org/licenses/gpl.html
11
 * @platform        WebsiteBaker 2.7.0 | 2.8.x
12
 * @requirements    PHP 5.2.2 and higher
13
 * @version         $Id: include.php 2114 2014-12-01 10:22:07Z darkviper $
14
 * @filesource      $HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/modules/ShowMenu2/include.php $
15
 * @lastmodified    $Date: 2014-12-01 11:22:07 +0100 (Mon, 01 Dec 2014) $
16
 *
17
 */
18

    
19
// Must include code to stop this file being access directly
20
if(defined('WB_PATH') == false) { die("Cannot access this file directly"); }
21

    
22
/**
23
 * future replacement for the function show_menu2()
24
 */
25
class SM2
26
{
27
    const ROOT =          -1000;
28
    const CURR =          -2000;
29
    const ALLMENU =          -1;
30
    const START =          1000;
31
    const MAX =            2000;
32
    const ALL =          0x0001; // bit 0 (group 1) (Note: also used for max level!)
33
    const TRIM =         0x0002; // bit 1 (group 1)
34
    const CRUMB =        0x0004; // bit 2 (group 1)
35
    const SIBLING =      0x0008; // bit 3 (group 1)
36
    const NUMCLASS =     0x0010; // bit 4
37
    const ALLINFO =      0x0020; // bit 5
38
    const NOCACHE =      0x0040; // bit 6
39
    const PRETTY =       0x0080; // bit 7
40
    const ESCAPE =       0x0100; // bit 8
41
    const NOESCAPE =          0; // NOOP, unnecessary with WB 2.6.7+
42
    const NOBUFFER =     0x0200; // bit 9
43
    const CURRTREE =     0x0400; // bit 10
44
    const SHOWHIDDEN =   0x0800; // bit 11
45
    const XHTML_STRICT = 0x1000; // bit 12
46
    const NO_TITLE =     0x2000; // bit 13
47
    const _GROUP_1 =     0x000F; // exactly one flag from group 1 is required
48
    const CONDITIONAL =  'if\s*\(([^\)]+)\)\s*{([^}]*)}\s*(?:else\s*{([^}]*)}\s*)?';
49
    const COND_TERM =    '\s*(\w+)\s*(<|<=|==|=|=>|>|!=)\s*([\w\-]+)\s*';
50
}
51

    
52
// Implement support for page_menu and show_menu using show_menu2. If you remove
53
// the comments characters from the beginning of the following include, all menu
54
// functions in Website Baker will be implemented using show_menu2. While it is
55
// commented out, the original WB functions will be used.
56
//include('legacy.php');
57

    
58
// This class is the default menu formatter for sm2. If desired, you can
59
// create your own formatter class and pass the object into show_menu2
60
// as $aItemFormat.
61

    
62

    
63
class SM2_Formatter
64
{
65
    var $output;
66
    var $flags;
67
    var $itemOpen;
68
    var $itemClose;
69
    var $menuOpen;
70
    var $menuClose;
71
    var $topItemOpen;
72
    var $topMenuOpen;
73

    
74
    var $isFirst;
75
    var $page;
76
    var $url;
77
    var $currSib;
78
    var $sibCount;
79
    var $currClass;
80
    var $prettyLevel;
81

    
82
    // output the data
83
    function output($aString) {
84
        if ($this->flags & SM2::NOBUFFER) {
85
            echo $aString;
86
        } else {
87
            $this->output .= $aString;
88
        }
89
    }
90

    
91
    // set the default values for all of our formatting items
92
    function set($aFlags, $aItemOpen, $aItemClose, $aMenuOpen, $aMenuClose, $aTopItemOpen, $aTopMenuOpen) {
93
        $this->flags        = $aFlags;
94
        $this->itemOpen     = is_string($aItemOpen)    ? $aItemOpen    : '[li][a][menu_title]</a>';
95
        $this->itemClose    = is_string($aItemClose)   ? $aItemClose   : '</li>';
96
        $this->menuOpen     = is_string($aMenuOpen)    ? $aMenuOpen    : '[ul]';
97
        $this->menuClose    = is_string($aMenuClose)   ? $aMenuClose   : '</ul>';
98
        $this->topItemOpen  = is_string($aTopItemOpen) ? $aTopItemOpen : $this->itemOpen;
99
        $this->topMenuOpen  = is_string($aTopMenuOpen) ? $aTopMenuOpen : $this->menuOpen;
100
    }
101

    
102
    // initialize the state of the formatter before anything is output
103
    function initialize() {
104
        $this->output = '';
105
        $this->prettyLevel = 0;
106
        if ($this->flags & SM2::PRETTY) {
107
            $this->output("\n<!-- show_menu2 -->");
108
        }
109
    }
110

    
111
    // start a menu
112
    function startList(&$aPage, &$aUrl) {
113
        $currClass = '';
114
        $currItem = $this->menuOpen;
115

    
116
        // use the top level menu open if this is the first menu
117
        if ($this->topMenuOpen) {
118
            $currItem = $this->topMenuOpen;
119
            $currClass .= ' menu-top';
120
            $this->topMenuOpen = false;
121
        }
122

    
123
        // add the numbered menu class only if requested
124
        if (($this->flags & SM2::NUMCLASS) == SM2::NUMCLASS) {
125
            $currClass .= ' menu-'.$aPage['level'];
126
        }
127

    
128
        $this->prettyLevel += 1;
129

    
130
        // replace all keywords in the output
131
        if ($this->flags & SM2::PRETTY) {
132
            $this->output("\n".str_repeat(' ',$this->prettyLevel).
133
                $this->format($aPage, $aUrl, $currItem, $currClass));
134
        }
135
        else {
136
            $this->output($this->format($aPage, $aUrl, $currItem, $currClass));
137
        }
138

    
139
        $this->prettyLevel += 3;
140
    }
141

    
142
    // start an item within the menu
143
    function startItem(&$aPage, &$aUrl, $aCurrSib, $aSibCount) {
144
        // generate our class list
145
        $currClass = '';
146
        if (($this->flags & SM2::NUMCLASS) == SM2::NUMCLASS) {
147
            $currClass .= ' menu-'.$aPage['level'];
148
        }
149
        if (array_key_exists('sm2_has_child', $aPage)) {
150
            // not set if false, so existence = true
151
            $currClass .= ' menu-expand';
152
        }
153
        if (array_key_exists('sm2_is_curr', $aPage)) {
154
            $currClass .= ' menu-current';
155
        }
156
        elseif (array_key_exists('sm2_is_parent', $aPage)) {
157
            // not set if false, so existence = true
158
            $currClass .= ' menu-parent';
159
        }
160
        elseif (array_key_exists('sm2_is_sibling', $aPage)) {
161
            // not set if false, so existence = true
162
            $currClass .= ' menu-sibling';
163
        }
164
        elseif (array_key_exists('sm2_child_level',$aPage)) {
165
            // not set if not a child
166
            $currClass .= ' menu-child';
167
            if (($this->flags & SM2::NUMCLASS) == SM2::NUMCLASS) {
168
                $currClass .= ' menu-child-'.($aPage['sm2_child_level']-1);
169
            }
170
        }
171
        if ($aCurrSib == 1) {
172
            $currClass .= ' menu-first';
173
        }
174
        if ($aCurrSib == $aSibCount) {
175
            $currClass .= ' menu-last';
176
        }
177

    
178
        // use the top level item if this is the first item
179
        $currItem = $this->itemOpen;
180
        if ($this->topItemOpen) {
181
            $currItem = $this->topItemOpen;
182
            $this->topItemOpen = false;
183
        }
184

    
185
        // replace all keywords in the output
186
        if ($this->flags & SM2::PRETTY) {
187
            $this->output("\n".str_repeat(' ',$this->prettyLevel));
188
        }
189
        $this->output($this->format($aPage, $aUrl, $currItem, $currClass, $aCurrSib, $aSibCount));
190
    }
191

    
192
    // find and replace all keywords, setting the state variables first
193
    function format(&$aPage, &$aUrl, &$aCurrItem, &$aCurrClass,
194
        $aCurrSib = 0, $aSibCount = 0)
195
    {
196
        $this->page      = &$aPage;
197
        $this->url       = &$aUrl;
198
        $this->currClass = trim($aCurrClass);
199
        $this->currSib   = $aCurrSib;
200
        $this->sibCount  = $aSibCount;
201

    
202
        $item = $this->format2($aCurrItem);
203

    
204
        unset($this->page);
205
        unset($this->url);
206
        unset($this->currClass);
207

    
208
        return $item;
209
    }
210

    
211
    // find and replace all keywords
212
    function format2(&$aCurrItem) {
213
        if (!is_string($aCurrItem)) return '';
214
        return preg_replace_callback(
215
            '@\[('.
216
                'a|ac|/a|li|/li|ul|/ul|menu_title|menu_icon_0|menu_icon_1|'.
217
                'page_title|page_icon|url|target|page_id|tooltip|'.
218
                'parent|level|sib|sibCount|class|description|keywords|'.
219
                SM2::CONDITIONAL.
220
            ')\]@',
221
            array($this, 'replace'),
222
            $aCurrItem);
223
    }
224

    
225
    // replace the keywords
226
    function replace($aMatches) {
227
        $aMatch = $aMatches[1];
228
        $retval = '['.$aMatch.'=UNKNOWN]';
229
        switch ($aMatch) {
230
        case 'a':
231
            $retval = '<a href="'.$this->url.'"';
232
            // break; // ignore 'break' to add the rest of <a>-tag
233
        case 'ac':
234
            if( substr($retval, 0, 2) != '<a'){
235
                $retval = '<a href="'.$this->url.'" class="'.$this->currClass.'"';
236
            }
237
            if(($this->flags & SM2::NO_TITLE)) {
238
                $retval .= ' title="'.$this->page['tooltip'].'"';
239
            }
240
            if(!($this->flags & SM2::XHTML_STRICT)) {
241
                $retval .= ' target="'.$this->page['target'].'"';
242
            }
243
            $retval .= '>';
244
            break;
245
        case '/a':
246
            $retval = '</a>'; break;
247
        case 'li':
248
            $retval = '<li class="'.$this->currClass.'">'; break;
249
        case '/li':
250
            $retval = '</li>'; break;
251
        case 'ul':
252
            $retval = '<ul class="'.$this->currClass.'">'; break;
253
        case '/ul':
254
            $retval = '</ul>'; break;
255
        case 'url':
256
            $retval = $this->url; break;
257
        case 'sib':
258
            $retval = $this->currSib; break;
259
        case 'sibCount':
260
            $retval = $this->sibCount; break;
261
        case 'class':
262
            $retval = $this->currClass; break;
263
        default:
264
            if (array_key_exists($aMatch, $this->page)) {
265
                if ($this->flags & SM2::ESCAPE) {
266
                    $retval = htmlspecialchars($this->page[$aMatch], ENT_QUOTES);
267
                }
268
                else {
269
                    $retval = $this->page[$aMatch];
270
                }
271
            }
272
            if (preg_match('/'.SM2::CONDITIONAL.'/', $aMatch, $rgMatches)) {
273
                $retval = $this->replaceIf($rgMatches[1], $rgMatches[2], $rgMatches[3]);
274
            }
275
        }
276
        return $retval;
277
    }
278

    
279
    // conditional replacement
280
    function replaceIf(&$aExpression, &$aIfValue, &$aElseValue) {
281
        // evaluate all of the tests in the conditional (we don't do short-circuit
282
        // evaluation) and replace the string test with the boolean result
283
        $rgTests = preg_split('/(\|\||\&\&)/', $aExpression, -1, PREG_SPLIT_DELIM_CAPTURE);
284
        for ($n = 0; $n < count($rgTests); $n += 2) {
285
            if (preg_match('/'.SM2::COND_TERM.'/', $rgTests[$n], $rgMatches)) {
286
                $rgTests[$n] = $this->ifTest($rgMatches[1], $rgMatches[2], $rgMatches[3]);
287
            }
288
            else {
289
                @error_logs("show_menu2 error: conditional expression is invalid!");
290
                $rgTests[$n] = false;
291
            }
292
        }
293

    
294
        // combine all test results for a final result
295
        $ok = $rgTests[0];
296
        for ($n = 1; $n+1 < count($rgTests); $n += 2) {
297
            if ($rgTests[$n] == '||') {
298
                $ok = $ok || $rgTests[$n+1];
299
            }
300
            else {
301
                $ok = $ok && $rgTests[$n+1];
302
            }
303
        }
304

    
305
        // return the formatted expression if the test succeeded
306
        return $ok ? $this->format2($aIfValue) : $this->format2($aElseValue);
307
    }
308

    
309
    // conditional test
310
    function ifTest(&$aKey, &$aOperator, &$aValue) {
311
        global $wb;
312

    
313
        // find the correct operand
314
        $operand = false;
315
        switch($aKey) {
316
        case 'class':
317
            // we need to wrap the class names in spaces so we can test for a unique
318
            // class name that will not match prefixes or suffixes. Same must be done
319
            // for the value we are testing.
320
            $operand = " $this->currClass ";
321
            break;
322
        case 'target':
323
            $operand = $this->page['target'];
324
            break;
325
        case 'sib':
326
            $operand = $this->currSib;
327
            if ($aValue == 'sibCount') {
328
                $aValue = $this->sibCount;
329
            }
330
            break;
331
        case 'sibCount':
332
            $operand = $this->sibCount;
333
            break;
334
        case 'level':
335
            $operand = $this->page['level'];
336
            switch ($aValue) {
337
            case 'root':    $aValue = 0; break;
338
            case 'granny':  $aValue = $wb->page['level']-2; break;
339
            case 'parent':  $aValue = $wb->page['level']-1; break;
340
            case 'current': $aValue = $wb->page['level'];   break;
341
            case 'child':   $aValue = $wb->page['level']+1; break;
342
            }
343
            if ($aValue < 0) $aValue = 0;
344
            break;
345
        case 'id':
346
            $operand = $this->page['page_id'];
347
            switch ($aValue) {
348
            case 'parent':  $aValue = $wb->page['parent'];  break;
349
            case 'current': $aValue = $wb->page['page_id']; break;
350
            }
351
            break;
352
        default:
353
            return '';
354
        }
355

    
356
        // do the test
357
        $ok = false;
358
        switch ($aOperator) {
359
        case '<':
360
            $ok = ($operand < $aValue);
361
            break;
362
        case '<=':
363
            $ok = ($operand <= $aValue);
364
            break;
365
        case '=':
366
        case '==':
367
        case '!=':
368
            if ($aKey == 'class') {
369
                $ok = strstr($operand, " $aValue ") !== FALSE;
370
            }
371
            else {
372
                $ok = ($operand == $aValue);
373
            }
374
            if ($aOperator == '!=') {
375
                $ok = !$ok;
376
            }
377
            break;
378
        case '>=':
379
            $ok = ($operand >= $aValue);
380
        case '>':
381
            $ok = ($operand > $aValue);
382
        }
383

    
384
        return $ok;
385
    }
386

    
387
    // finish the current menu item
388
    function finishItem() {
389
        if ($this->flags & SM2::PRETTY) {
390
            $this->output(str_repeat(' ',$this->prettyLevel).$this->itemClose);
391
        }
392
        else {
393
            $this->output($this->itemClose);
394
        }
395
    }
396

    
397
    // finish the current menu
398
    function finishList() {
399
        $this->prettyLevel -= 3;
400

    
401
        if ($this->flags & SM2::PRETTY) {
402
            $this->output("\n".str_repeat(' ',$this->prettyLevel).$this->menuClose."\n");
403
        }
404
        else {
405
            $this->output($this->menuClose);
406
        }
407

    
408
        $this->prettyLevel -= 1;
409
    }
410

    
411
    // cleanup the state of the formatter after everything has been output
412
    function finalize() {
413
        if ($this->flags & SM2::PRETTY) {
414
            $this->output("\n");
415
        }
416
    }
417

    
418
    // return the output
419
    function getOutput() {
420
        return $this->output;
421
    }
422
};
423

    
424
function error_logs($error_str)
425
{
426
                $log_error = true;
427
                if ( ! function_exists('error_log') )
428
                        $log_error = false;
429

    
430
                $log_file = @ini_get('error_log');
431
                if ( !empty($log_file) && ('syslog' != $log_file) && !@is_writable($log_file) )
432
                        $log_error = false;
433

    
434
                if ( $log_error )
435
                        @error_log($error_str, 0);
436
}
437

    
438
function show_menu2(
439
    $aMenu          = 0,
440
    $aStart         = SM2::ROOT,
441
    $aMaxLevel      = -1999, // SM2::CURR+1
442
    $aOptions       = SM2::TRIM,
443
    $aItemOpen      = false,
444
    $aItemClose     = false,
445
    $aMenuOpen      = false,
446
    $aMenuClose     = false,
447
    $aTopItemOpen   = false,
448
    $aTopMenuOpen   = false
449
    )
450
{
451
    global $wb;
452
    $database = WbDatabase::getInstance();
453
    $iQueryStart = $database->getQueryCount;
454
    // extract the flags and set $aOptions to an array
455
    $flags = 0;
456
    if (is_int($aOptions)) {
457
        $flags = $aOptions;
458
        $aOptions = array();
459
    }
460
    else if (isset($aOptions['flags'])) {
461
        $flags = $aOptions['flags'];
462
    }
463
    else {
464
        $flags = SM2::TRIM;
465
        $aOptions = array();
466
        @error_logs('show_menu2 error: $aOptions is invalid. No flags supplied!');
467
    }
468

    
469
    // ensure we have our group 1 flag, we don't check for the "exactly 1" part, but
470
    // we do ensure that they provide at least one.
471
    if (0 == ($flags & SM2::_GROUP_1)) {
472
        @error_logs('show_menu2 error: $aOptions is invalid. No flags from group 1 supplied!');
473
        $flags |= SM2::TRIM; // default to TRIM
474
    }
475

    
476
    // search page results don't have any of the page data loaded by WB, so we load it
477
    // ourselves using the referrer ID as the current page
478
    $CURR_PAGE_ID = defined('REFERRER_ID') ? REFERRER_ID : PAGE_ID;
479
    if (count($wb->page) == 0 && defined('REFERRER_ID') && REFERRER_ID > 0) {
480
        global $database;
481
        $sql = 'SELECT * FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.REFERRER_ID.'';
482
        $result = $database->query($sql);
483
        if ($result->numRows() == 1) {
484
            $wb->page = $result->fetchRow();
485
        }
486
        unset($result);
487
    }
488

    
489
    // fix up the menu number to default to the menu number
490
    // of the current page if no menu has been supplied
491
    if ($aMenu == 0) {
492
        $aMenu = $wb->page['menu'] == '' ? 1 : $wb->page['menu'];
493
    }
494

    
495
    // Set some of the $wb->page[] settings to defaults if not set
496
    $pageLevel  = $wb->page['level']  == '' ? 0 : $wb->page['level'];
497
    $pageParent = $wb->page['parent'] == '' ? 0 : $wb->page['parent'];
498

    
499
    // adjust the start level and start page ID as necessary to
500
    // handle the special values that can be passed in as $aStart
501
    $aStartLevel = 0;
502
    if ($aStart < SM2::ROOT) {   // SM2::CURR+N
503
        if ($aStart == SM2::CURR) {
504
            $aStartLevel = $pageLevel;
505
            $aStart = $pageParent;
506
        }
507
        else {
508
            $aStartLevel = $pageLevel + $aStart - SM2::CURR;
509
            $aStart = $CURR_PAGE_ID;
510
        }
511
    }
512
    elseif ($aStart < 0) {   // SM2::ROOT+N
513
        $aStartLevel = $aStart - SM2::ROOT;
514
        $aStart = 0;
515
    }
516

    
517
    // we get the menu data once and store it in a global variable. This allows
518
    // multiple calls to show_menu2 in a single page with only a single call to
519
    // the database. If this variable exists, then we have already retrieved all
520
    // of the information and processed it, so we don't need to do it again.
521
    if (($flags & SM2::NOCACHE) != 0
522
        || !array_key_exists('show_menu2_data', $GLOBALS)
523
        || !array_key_exists($aMenu, $GLOBALS['show_menu2_data']))
524
    {
525
        global $database;
526

    
527
        // create an array of all parents of the current page. As the page_trail
528
        // doesn't include the theoretical root element 0, we add it ourselves.
529
        $rgCurrParents = explode(",", '0,'.$wb->page['page_trail']);
530
        array_pop($rgCurrParents); // remove the current page
531
        $rgParent = array();
532

    
533
        // if the caller wants all menus gathered together (e.g. for a sitemap)
534
        // then we don't limit our SQL query
535
        $menuLimitSql = ' AND `menu`='.$aMenu;
536
        if ($aMenu == SM2::ALLMENU) {
537
            $menuLimitSql = '';
538
        }
539

    
540
        // we only load the description and keywords if we have been told to,
541
        // this cuts the memory load for pages that don't use them. Note that if
542
        // we haven't been told to load these fields the *FIRST TIME* show_menu2
543
        // is called (i.e. where the database is loaded) then the info won't
544
        // exist anyhow.
545
        $fields  = '`parent`,`page_id`,`menu_title`,`page_title`,`link`,`target`,';
546
        $fields .= '`level`,`visibility`,`viewing_groups`,`viewing_users`,';
547
        $fields .= '`menu_icon_0`,`menu_icon_1`,`page_icon`,`tooltip`';
548
        if ($flags & SM2::ALLINFO) {
549
            $fields = '*';
550
        }
551

    
552
        // we request all matching rows from the database for the menu that we
553
        // are about to create it is cheaper for us to get everything we need
554
        // from the database once and create the menu from memory then make
555
        // multiple calls to the database.
556
        $sql  = 'SELECT '.$fields.' FROM `'.TABLE_PREFIX.'pages` ';
557
        $sql .= 'WHERE '.$wb->extra_where_sql.' '.$menuLimitSql.' ';
558
        $sql .= 'ORDER BY `level` ASC, `position` ASC';
559
        $sql = str_replace('hidden', 'IGNOREME', $sql); // we want the hidden pages
560
        $oRowset = $database->query($sql);
561
        if (is_object($oRowset) && $oRowset->numRows() > 0) {
562
            // create an in memory array of the database data based on the item's parent.
563
            // The array stores all elements in the correct display order.
564
            while ($page = $oRowset->fetchRow()) {
565
                // ignore all pages that the current user is not permitted to view
566
                if(version_compare(WB_VERSION, '2.7', '>=')) { // WB >= 2.7
567
                    // 1. hidden pages aren't shown unless they are on the current page
568
                    if ($page['visibility'] == 'hidden') {
569
                        $page['sm2_hide'] = true;
570
                    }
571

    
572
                    // 2. all pages with no active sections (unless it is the top page) are ignored
573
                    else if (!$wb->page_is_active($page) && $page['link'] != $wb->default_link && !INTRO_PAGE) {
574
                        continue;
575
                    }
576

    
577
                    // 3. all pages not visible to this user (unless always visible to registered users) are ignored
578
                    else if (!$wb->page_is_visible($page) && $page['visibility'] != 'registered') {
579
                        continue;
580
                    }
581
                }
582
                if(isset($page['page_icon']) && $page['page_icon'] != '') {
583
                    $page['page_icon'] = WB_URL.$page['page_icon'];
584
                }
585
                if(isset($page['menu_icon_0']) && $page['menu_icon_0'] != '') {
586
                    $page['menu_icon_0'] = WB_URL.$page['menu_icon_0'];
587
                }
588
                if(isset($page['menu_icon_1']) && $page['menu_icon_1'] != '') {
589
                    $page['menu_icon_1'] = WB_URL.$page['menu_icon_1'];
590
                }
591

    
592
                if(!isset($page['tooltip'])) { $page['tooltip'] = $page['page_title']; }
593
                // ensure that we have an array entry in the table to add this to
594
                $idx = $page['parent'];
595
                if (!array_key_exists($idx, $rgParent)) {
596
                    $rgParent[$idx] = array();
597
                }
598

    
599
                // mark our current page as being on the current path
600
                if ($page['page_id'] == $CURR_PAGE_ID) {
601
                    $page['sm2_is_curr'] = true;
602
                    $page['sm2_on_curr_path'] = true;
603
                    if ($flags & SM2::SHOWHIDDEN)
604
                    {
605
                        // show hidden pages if active and SHOWHIDDEN flag supplied
606
                        unset($page['sm2_hide']);
607
                    }
608
                }
609

    
610
                // mark parents of the current page as such
611
                if (in_array($page['page_id'], $rgCurrParents)) {
612
                    $page['sm2_is_parent'] = true;
613
                    $page['sm2_on_curr_path'] = true;
614
                    if ($flags & SM2::SHOWHIDDEN)
615
                    {
616
                        // show hidden pages if active and SHOWHIDDEN flag supplied
617
                        unset($page['sm2_hide']); // don't hide a parent page
618
                    }
619
                }
620

    
621
                // add the entry to the array
622
                $rgParent[$idx][] = $page;
623
            }
624
        }
625
        unset($oRowset);
626

    
627
        // mark all elements that are siblings of any element on the current path
628
        foreach ($rgCurrParents as $x) {
629
            if (array_key_exists($x, $rgParent)) {
630
                foreach (array_keys($rgParent[$x]) as $y) {
631
                    $mark =& $rgParent[$x][$y];
632
                    $mark['sm2_path_sibling'] = true;
633
                    unset($mark);
634
                }
635
            }
636
        }
637

    
638
        // mark all elements that have children and are siblings of the current page
639
        $parentId = $pageParent;
640
        foreach (array_keys($rgParent) as $x) {
641
            $childSet =& $rgParent[$x];
642
            foreach (array_keys($childSet) as $y) {
643
                $mark =& $childSet[$y];
644
                if (array_key_exists($mark['page_id'], $rgParent)) {
645
                    $mark['sm2_has_child'] = true;
646
                }
647
                if ($mark['parent'] == $parentId && $mark['page_id'] != $CURR_PAGE_ID) {
648
                    $mark['sm2_is_sibling'] = true;
649
                }
650
                unset($mark);
651
            }
652
            unset($childSet);
653
        }
654

    
655
        // mark all children of the current page. We don't do this when
656
        // $CURR_PAGE_ID is 0, as 0 is the parent of everything.
657
        // $CURR_PAGE_ID == 0 occurs on special pages like search results
658
        // when no referrer is available.s
659
        if ($CURR_PAGE_ID != 0) {
660
            sm2_mark_children($rgParent, $CURR_PAGE_ID, 1);
661
        }
662

    
663
        // store the complete processed menu data as a global. We don't
664
        // need to read this from the database anymore regardless of how
665
        // many menus are displayed on the same page.
666
        if (!array_key_exists('show_menu2_data', $GLOBALS)) {
667
            $GLOBALS['show_menu2_data'] = array();
668
        }
669
        $GLOBALS['show_menu2_data'][$aMenu] =& $rgParent;
670
        unset($rgParent);
671
    }
672

    
673
    // adjust $aMaxLevel to the level number of the final level that
674
    // will be displayed. That is, we display all levels <= aMaxLevel.
675
    if ($aMaxLevel == SM2::ALL) {
676
        $aMaxLevel = 1000;
677
    }
678
    elseif ($aMaxLevel < 0) {   // SM2::CURR+N
679
        $aMaxLevel += $pageLevel - SM2::CURR;
680
    }
681
    elseif ($aMaxLevel >= SM2::MAX) { // SM2::MAX+N
682
        $aMaxLevel += $aStartLevel - SM2::MAX;
683
        if ($aMaxLevel > $pageLevel) {
684
            $aMaxLevel = $pageLevel;
685
        }
686
    }
687
    else {  // SM2::START+N
688
        $aMaxLevel += $aStartLevel - SM2::START;
689
    }
690

    
691
    // generate the menu
692
    $retval = false;
693
    if (array_key_exists($aStart, $GLOBALS['show_menu2_data'][$aMenu])) {
694
        $formatter = $aItemOpen;
695
        if (!is_object($aItemOpen)) {
696
            static $sm2formatter;
697
            if (!isset($sm2formatter)) {
698
                $sm2formatter = new SM2_Formatter;
699
            }
700
            $formatter = $sm2formatter;
701
            $formatter->set($flags, $aItemOpen, $aItemClose,
702
                $aMenuOpen, $aMenuClose, $aTopItemOpen, $aTopMenuOpen);
703
        }
704

    
705
        // adjust the level until we show everything and ignore the SM2_TRIM flag.
706
        // Usually this will be less than the start level to disable it.
707
        $showAllLevel = $aStartLevel - 1;
708
        if (isset($aOptions['notrim'])) {
709
            $showAllLevel = $aStartLevel + $aOptions['notrim'];
710
        }
711

    
712
        // display the menu
713
        $formatter->initialize();
714
        sm2_recurse(
715
            $GLOBALS['show_menu2_data'][$aMenu],
716
            $aStart,    // parent id to start displaying sub-menus
717
            $aStartLevel, $showAllLevel, $aMaxLevel, $flags,
718
            $formatter);
719
        $formatter->finalize();
720

    
721
        // if we are returning something, get the data
722
        if (($flags & SM2::NOBUFFER) == 0) {
723
            $retval = $formatter->getOutput();
724
        }
725
    }
726

    
727
    // clear the data if we aren't caching it
728
    if (($flags & SM2::NOCACHE) != 0) {
729
        unset($GLOBALS['show_menu2_data'][$aMenu]);
730
    }
731
    if(defined('DEBUG') && (DEBUG)) {
732
        $iQueriesDone = $database->getQueryCount - $iQueryStart;
733
        return $retval."\n".'<!-- Queries: '.$iQueriesDone.' -->'."\n";
734
    }
735
    return $retval;
736
}
737

    
738
function sm2_mark_children(&$rgParent, $aStart, $aChildLevel)
739
{
740
    if (array_key_exists($aStart, $rgParent)) {
741
        foreach (array_keys($rgParent[$aStart]) as $y) {
742
            $mark =& $rgParent[$aStart][$y];
743
            $mark['sm2_child_level'] = $aChildLevel;
744
            $mark['sm2_on_curr_path'] = true;
745
            sm2_mark_children($rgParent, $mark['page_id'], $aChildLevel+1);
746
        }
747
    }
748
}
749

    
750
function sm2_recurse(
751
    &$rgParent, $aStart,
752
    $aStartLevel, $aShowAllLevel, $aMaxLevel, $aFlags,
753
    &$aFormatter
754
    )
755
{
756
    global $wb;
757

    
758
    // on entry to this function we know that there are entries for this
759
    // parent and all entries for that parent are being displayed. We also
760
    // need to check if any of the children need to be displayed too.
761
    $isListOpen = false;
762
    $currentLevel = $wb->page['level'] == '' ? 0 : $wb->page['level'];
763

    
764
    // get the number of siblings skipping the hidden pages so we can pass
765
    // this in and check if the item is first or last
766
    $sibCount = 0;
767
    foreach ($rgParent[$aStart] as $page) {
768
        if (!array_key_exists('sm2_hide', $page)) $sibCount++;
769
    }
770

    
771
    $currSib = 0;
772
    foreach ($rgParent[$aStart] as $page) {
773
        // skip all hidden pages
774
        if (array_key_exists('sm2_hide', $page)) { // not set if false, so existence = true
775
            continue;
776
        }
777

    
778
        $currSib++;
779

    
780
        // skip any elements that are lower than the maximum level
781
        $pageLevel = $page['level'];
782
        if ($pageLevel > $aMaxLevel) {
783
            continue;
784
        }
785

    
786
        // this affects ONLY the top level
787
        if ($aStart == 0 && ($aFlags & SM2::CURRTREE)) {
788
            if (!array_key_exists('sm2_on_curr_path', $page)) { // not set if false, so existence = true
789
                continue;
790
            }
791
            $sibCount = 1;
792
        }
793

    
794
        // trim the tree as appropriate
795
        if ($aFlags & SM2::SIBLING) {
796
            // parents, and siblings and children of current only
797
            if (!array_key_exists('sm2_on_curr_path', $page)      // not set if false, so existence = true
798
                && !array_key_exists('sm2_is_sibling', $page)     // not set if false, so existence = true
799
                && !array_key_exists('sm2_child_level', $page)) { // not set if false, so existence = true
800
                continue;
801
            }
802
        }
803
        else if ($aFlags & SM2::TRIM) {
804
            // parents and siblings of parents
805
            if ($pageLevel > $aShowAllLevel  // permit all levels to be shown
806
                && !array_key_exists('sm2_on_curr_path', $page)    // not set if false, so existence = true
807
                && !array_key_exists('sm2_path_sibling', $page)) {  // not set if false, so existence = true
808
                continue;
809
            }
810
        }
811
        elseif ($aFlags & SM2::CRUMB) {
812
            // parents only
813
            if (!array_key_exists('sm2_on_curr_path', $page)    // not set if false, so existence = true
814
                || array_key_exists('sm2_child_level', $page)) {  // not set if false, so existence = true
815
                continue;
816
            }
817
        }
818

    
819
        // depth first traverse
820
        $nextParent = $page['page_id'];
821

    
822
        // display the current element if we have reached the start level
823
        if ($pageLevel >= $aStartLevel) {
824
            // massage the link into the correct form
825
            if(!INTRO_PAGE && $page['link'] == $wb->default_link) {
826
                $url = WB_URL.'/';
827
            }
828
            else {
829
                $url = $wb->page_link($page['link']);
830
            }
831

    
832
            // we open the list only when we absolutely need to
833
            if (!$isListOpen) {
834
                $aFormatter->startList($page, $url);
835
                $isListOpen = true;
836
            }
837

    
838
            $aFormatter->startItem($page, $url, $currSib, $sibCount);
839
        }
840

    
841
        // display children as appropriate
842
        if ($pageLevel + 1 <= $aMaxLevel
843
            && array_key_exists('sm2_has_child', $page)) {  // not set if false, so existence = true
844
            sm2_recurse(
845
                $rgParent, $nextParent, // parent id to start displaying sub-menus
846
                $aStartLevel, $aShowAllLevel, $aMaxLevel, $aFlags,
847
                $aFormatter);
848
        }
849

    
850
        // close the current element if appropriate
851
        if ($pageLevel >= $aStartLevel) {
852
            $aFormatter->finishItem($pageLevel, $page);
853
        }
854
    }
855

    
856
    // close the list if we opened one
857
    if ($isListOpen) {
858
        $aFormatter->finishList();
859
    }
860
}
(1-1/8)