Project

General

Profile

1
<?php
2
/**
3
 *
4
 * @category        module
5
 * @package         show_menu2
6
 * @author          WebsiteBaker Project
7
 * @copyright       2004-2009, Ryan Djurovich
8
 * @copyright       2009-2011, Website Baker Org. e.V.
9
 * @link			http://www.websitebaker2.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 1475 2011-07-12 23:07:10Z Luisehahne $
14
 * @filesource		$HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/modules/show_menu2/include.php $
15
 * @lastmodified    $Date: 2011-07-13 01:07:10 +0200 (Wed, 13 Jul 2011) $
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
define('SM2_ROOT',          -1000);
23
define('SM2_CURR',          -2000);
24
define('SM2_ALLMENU',          -1);
25
define('SM2_START',          1000);
26
define('SM2_MAX',            2000);
27
define('SM2_ALL',          0x0001); // bit 0 (group 1) (Note: also used for max level!)
28
define('SM2_TRIM',         0x0002); // bit 1 (group 1)
29
define('SM2_CRUMB',        0x0004); // bit 2 (group 1)
30
define('SM2_SIBLING',      0x0008); // bit 3 (group 1)
31
define('SM2_NUMCLASS',     0x0010); // bit 4
32
define('SM2_ALLINFO',      0x0020); // bit 5
33
define('SM2_NOCACHE',      0x0040); // bit 6
34
define('SM2_PRETTY',       0x0080); // bit 7
35
define('SM2_ESCAPE',       0x0100); // bit 8
36
define('SM2_NOESCAPE',          0); // NOOP, unnecessary with WB 2.6.7+
37
define('SM2_BUFFER',       0x0200); // bit 9
38
define('SM2_CURRTREE',     0x0400); // bit 10
39
define('SM2_SHOWHIDDEN',   0x0800); // bit 11
40
define('SM2_XHTML_STRICT', 0x1000); // bit 12
41
define('SM2_NO_TITLE',     0x1001); // bit 13
42

    
43
define('_SM2_GROUP_1',  0x000F); // exactly one flag from group 1 is required
44

    
45

    
46
// Implement support for page_menu and show_menu using show_menu2. If you remove
47
// the comments characters from the beginning of the following include, all menu
48
// functions in Website Baker will be implemented using show_menu2. While it is
49
// commented out, the original WB functions will be used.
50
//include('legacy.php');
51

    
52
// This class is the default menu formatter for sm2. If desired, you can 
53
// create your own formatter class and pass the object into show_menu2 
54
// as $aItemFormat.
55
define('SM2_CONDITIONAL','if\s*\(([^\)]+)\)\s*{([^}]*)}\s*(?:else\s*{([^}]*)}\s*)?');
56
define('SM2_COND_TERM','\s*(\w+)\s*(<|<=|==|=|=>|>|!=)\s*([\w\-]+)\s*');
57
class SM2_Formatter
58
{
59
    var $output;
60
    var $flags;
61
    var $itemOpen;
62
    var $itemClose;
63
    var $menuOpen;
64
    var $menuClose;
65
    var $topItemOpen;
66
    var $topMenuOpen;
67
    
68
    var $isFirst;
69
    var $page;
70
    var $url;
71
    var $currSib;
72
    var $sibCount;
73
    var $currClass;
74
    var $prettyLevel;
75

    
76
    // output the data
77
    function output($aString) {
78
        if ($this->flags & SM2_BUFFER) {
79
            $this->output .= $aString;
80
        }
81
        else {
82
            echo $aString;
83
        }
84
    }
85
    
86
    // set the default values for all of our formatting items
87
    function set($aFlags, $aItemOpen, $aItemClose, $aMenuOpen, $aMenuClose, $aTopItemOpen, $aTopMenuOpen) {
88
        $this->flags        = $aFlags;
89
        $this->itemOpen     = is_string($aItemOpen)    ? $aItemOpen    : '[li][a][menu_title]</a>';
90
        $this->itemClose    = is_string($aItemClose)   ? $aItemClose   : '</li>';
91
        $this->menuOpen     = is_string($aMenuOpen)    ? $aMenuOpen    : '[ul]';
92
        $this->menuClose    = is_string($aMenuClose)   ? $aMenuClose   : '</ul>';
93
        $this->topItemOpen  = is_string($aTopItemOpen) ? $aTopItemOpen : $this->itemOpen;
94
        $this->topMenuOpen  = is_string($aTopMenuOpen) ? $aTopMenuOpen : $this->menuOpen;
95
    }
96

    
97
    // initialize the state of the formatter before anything is output
98
    function initialize() {
99
        $this->output = '';
100
        $this->prettyLevel = 0;
101
        if ($this->flags & SM2_PRETTY) {
102
            $this->output("\n<!-- show_menu2 -->");
103
        }
104
    }
105

    
106
    // start a menu     
107
    function startList(&$aPage, &$aUrl) {
108
        $currClass = '';
109
        $currItem = $this->menuOpen;
110
        
111
        // use the top level menu open if this is the first menu
112
        if ($this->topMenuOpen) {
113
            $currItem = $this->topMenuOpen;
114
            $currClass .= ' menu-top';
115
            $this->topMenuOpen = false;
116
        }
117
        
118
        // add the numbered menu class only if requested
119
        if (($this->flags & SM2_NUMCLASS) == SM2_NUMCLASS) {
120
            $currClass .= ' menu-'.$aPage['level'];
121
        }
122
        
123
        $this->prettyLevel += 1;
124
        
125
        // replace all keywords in the output
126
        if ($this->flags & SM2_PRETTY) {
127
            $this->output("\n".str_repeat(' ',$this->prettyLevel).
128
                $this->format($aPage, $aUrl, $currItem, $currClass));
129
        }
130
        else {
131
            $this->output($this->format($aPage, $aUrl, $currItem, $currClass));
132
        }
133
        
134
        $this->prettyLevel += 3;
135
    }
136
    
137
    // start an item within the menu
138
    function startItem(&$aPage, &$aUrl, $aCurrSib, $aSibCount) {
139
        // generate our class list
140
        $currClass = '';
141
        if (($this->flags & SM2_NUMCLASS) == SM2_NUMCLASS) {
142
            $currClass .= ' menu-'.$aPage['level'];
143
        }
144
        if (array_key_exists('sm2_has_child', $aPage)) {
145
            // not set if false, so existence = true
146
            $currClass .= ' menu-expand';
147
        }
148
        if (array_key_exists('sm2_is_curr', $aPage)) { 
149
            $currClass .= ' menu-current';
150
        }
151
        elseif (array_key_exists('sm2_is_parent', $aPage)) { 
152
            // not set if false, so existence = true
153
            $currClass .= ' menu-parent';
154
        }
155
        elseif (array_key_exists('sm2_is_sibling', $aPage)) {
156
            // not set if false, so existence = true
157
            $currClass .= ' menu-sibling';
158
        }
159
        elseif (array_key_exists('sm2_child_level',$aPage)) {
160
            // not set if not a child
161
            $currClass .= ' menu-child';
162
            if (($this->flags & SM2_NUMCLASS) == SM2_NUMCLASS) {
163
                $currClass .= ' menu-child-'.($aPage['sm2_child_level']-1);
164
            }
165
        }
166
        if ($aCurrSib == 1) {
167
            $currClass .= ' menu-first';
168
        }
169
        if ($aCurrSib == $aSibCount) {
170
            $currClass .= ' menu-last';
171
        }
172

    
173
        // use the top level item if this is the first item
174
        $currItem = $this->itemOpen;
175
        if ($this->topItemOpen) {
176
            $currItem = $this->topItemOpen;
177
            $this->topItemOpen = false;
178
        }
179

    
180
        // replace all keywords in the output
181
        if ($this->flags & SM2_PRETTY) {
182
            $this->output("\n".str_repeat(' ',$this->prettyLevel));
183
        }
184
        $this->output($this->format($aPage, $aUrl, $currItem, $currClass, $aCurrSib, $aSibCount));
185
    }
186
    
187
    // find and replace all keywords, setting the state variables first
188
    function format(&$aPage, &$aUrl, &$aCurrItem, &$aCurrClass, 
189
        $aCurrSib = 0, $aSibCount = 0) 
190
    {
191
        $this->page      = &$aPage;
192
        $this->url       = &$aUrl;
193
        $this->currClass = trim($aCurrClass);
194
        $this->currSib   = $aCurrSib;
195
        $this->sibCount  = $aSibCount;
196
        
197
        $item = $this->format2($aCurrItem);
198
        
199
        unset($this->page);
200
        unset($this->url);
201
        unset($this->currClass);
202
        
203
        return $item;
204
    }
205
    
206
    // find and replace all keywords
207
    function format2(&$aCurrItem) {
208
        if (!is_string($aCurrItem)) return '';
209
        return preg_replace(
210
            '@\[('.
211
                'a|ac|/a|li|/li|ul|/ul|menu_title|menu_icon_0|menu_icon_1|'.
212
				'page_title|page_icon|url|target|page_id|tooltip|'.
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
        $retval = '['.$aMatch.'=UNKNOWN]';
222
        switch ($aMatch) {
223
        case 'a':
224
            $retval = '<a href="'.$this->url.'"';
225
			// break; // ignore 'break' to add the rest of <a>-tag
226
		case 'ac':
227
			if( substr($retval, 0, 2) != '<a'){
228
				$retval = '<a href="'.$this->url.'" class="'.$this->currClass.'"';
229
			}
230
			if(($this->flags & SM2_NO_TITLE)) {
231
				$retval .= ' title="'.$this->page['tooltip'].'"';
232
			}
233
			if(!($this->flags & SM2_XHTML_STRICT)) {
234
				$retval .= ' target="'.$this->page['target'].'"';
235
			}
236
			$retval .= '>';
237
			break;
238
        case '/a':
239
            $retval = '</a>'; break;
240
        case 'li':
241
            $retval = '<li class="'.$this->currClass.'">'; break;
242
        case '/li':
243
            $retval = '</li>'; break;
244
        case 'ul':
245
            $retval = '<ul class="'.$this->currClass.'">'; break;
246
        case '/ul':
247
            $retval = '</ul>'; break;
248
        case 'url':
249
            $retval = $this->url; break;
250
        case 'sib':
251
            $retval = $this->currSib; break;
252
        case 'sibCount':
253
            $retval = $this->sibCount; break;
254
        case 'class':
255
            $retval = $this->currClass; break;
256
        default:
257
            if (array_key_exists($aMatch, $this->page)) {
258
                if ($this->flags & SM2_ESCAPE) {
259
                    $retval = htmlspecialchars($this->page[$aMatch], ENT_QUOTES);
260
                }
261
                else {
262
                    $retval = $this->page[$aMatch];
263
                }
264
            }
265
            if (preg_match('/'.SM2_CONDITIONAL.'/', $aMatch, $rgMatches)) {
266
                $retval = $this->replaceIf($rgMatches[1], $rgMatches[2], $rgMatches[3]);
267
            }
268
        }
269
        return $retval;
270
    }
271
    
272
    // conditional replacement
273
    function replaceIf(&$aExpression, &$aIfValue, &$aElseValue) {
274
        // evaluate all of the tests in the conditional (we don't do short-circuit
275
        // evaluation) and replace the string test with the boolean result
276
        $rgTests = preg_split('/(\|\||\&\&)/', $aExpression, -1, PREG_SPLIT_DELIM_CAPTURE);
277
        for ($n = 0; $n < count($rgTests); $n += 2) {
278
            if (preg_match('/'.SM2_COND_TERM.'/', $rgTests[$n], $rgMatches)) {
279
                $rgTests[$n] = $this->ifTest($rgMatches[1], $rgMatches[2], $rgMatches[3]);
280
            }
281
            else {
282
                @error_logs("show_menu2 error: conditional expression is invalid!");
283
                $rgTests[$n] = false;
284
            }
285
        }
286

    
287
        // combine all test results for a final result
288
        $ok = $rgTests[0];
289
        for ($n = 1; $n+1 < count($rgTests); $n += 2) {
290
            if ($rgTests[$n] == '||') {
291
                $ok = $ok || $rgTests[$n+1];
292
            }
293
            else {
294
                $ok = $ok && $rgTests[$n+1];
295
            }
296
        }
297
        
298
        // return the formatted expression if the test succeeded
299
        return $ok ? $this->format2($aIfValue) : $this->format2($aElseValue);
300
    }
301

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

    
349
        // do the test        
350
        $ok = false;
351
        switch ($aOperator) { 
352
        case '<':
353
            $ok = ($operand < $aValue); 
354
            break;
355
        case '<=':
356
            $ok = ($operand <= $aValue); 
357
            break;
358
        case '=':
359
        case '==':
360
        case '!=':
361
            if ($aKey == 'class') {
362
                $ok = strstr($operand, " $aValue ") !== FALSE;
363
            }
364
            else {
365
                $ok = ($operand == $aValue); 
366
            }
367
            if ($aOperator == '!=') {
368
                $ok = !$ok;
369
            }
370
            break;
371
        case '>=':
372
            $ok = ($operand >= $aValue); 
373
        case '>':
374
            $ok = ($operand > $aValue); 
375
        }
376
        
377
        return $ok;
378
    }
379
    
380
    // finish the current menu item
381
    function finishItem() {
382
        if ($this->flags & SM2_PRETTY) {
383
            $this->output(str_repeat(' ',$this->prettyLevel).$this->itemClose);
384
        }
385
        else {
386
            $this->output($this->itemClose);
387
        }
388
    }
389

    
390
    // finish the current menu
391
    function finishList() {
392
        $this->prettyLevel -= 3;
393
        
394
        if ($this->flags & SM2_PRETTY) {
395
            $this->output("\n".str_repeat(' ',$this->prettyLevel).$this->menuClose."\n");
396
        }
397
        else {
398
            $this->output($this->menuClose);
399
        }
400
        
401
        $this->prettyLevel -= 1;
402
    }
403
    
404
    // cleanup the state of the formatter after everything has been output
405
    function finalize() {
406
        if ($this->flags & SM2_PRETTY) {
407
            $this->output("\n");
408
        }
409
    }
410

    
411
    // return the output
412
    function getOutput() {
413
        return $this->output;
414
    }
415
};
416

    
417
function error_logs($error_str)
418
{
419
                $log_error = true;
420
                if ( ! function_exists('error_log') )
421
                        $log_error = false;
422

    
423
                $log_file = @ini_get('error_log');
424
                if ( !empty($log_file) && ('syslog' != $log_file) && !@is_writable($log_file) )
425
                        $log_error = false;
426

    
427
                if ( $log_error )
428
                        @error_log($error_str, 0);
429
}
430

    
431
function show_menu2(
432
    $aMenu          = 0,
433
    $aStart         = SM2_ROOT,
434
    $aMaxLevel      = -1999, // SM2_CURR+1
435
    $aOptions       = SM2_TRIM,
436
    $aItemOpen      = false,
437
    $aItemClose     = false,
438
    $aMenuOpen      = false,
439
    $aMenuClose     = false,
440
    $aTopItemOpen   = false,
441
    $aTopMenuOpen   = false
442
    )
443
{
444
    global $wb;
445

    
446
    // extract the flags and set $aOptions to an array
447
    $flags = 0;
448
    if (is_int($aOptions)) {
449
        $flags = $aOptions;
450
        $aOptions = array();
451
    }
452
    else if (isset($aOptions['flags'])) {
453
        $flags = $aOptions['flags'];
454
    }
455
    else {
456
        $flags = SM2_TRIM;
457
        $aOptions = array();
458
        @error_logs('show_menu2 error: $aOptions is invalid. No flags supplied!');
459
    }
460
    
461
    // ensure we have our group 1 flag, we don't check for the "exactly 1" part, but
462
    // we do ensure that they provide at least one.
463
    if (0 == ($flags & _SM2_GROUP_1)) {
464
        @error_logs('show_menu2 error: $aOptions is invalid. No flags from group 1 supplied!');
465
        $flags |= SM2_TRIM; // default to TRIM
466
    }
467
    
468
    // search page results don't have any of the page data loaded by WB, so we load it 
469
    // ourselves using the referrer ID as the current page
470
    $CURR_PAGE_ID = defined('REFERRER_ID') ? REFERRER_ID : PAGE_ID;
471
    if (count($wb->page) == 0 && defined('REFERRER_ID') && REFERRER_ID > 0) {
472
        global $database;
473
        $sql = 'SELECT * FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.REFERRER_ID.'';
474
        $result = $database->query($sql);
475
        if ($result->numRows() == 1) {
476
            $wb->page = $result->fetchRow();
477
        }
478
        unset($result);
479
    }
480
    
481
    // fix up the menu number to default to the menu number
482
    // of the current page if no menu has been supplied
483
    if ($aMenu == 0) {
484
        $aMenu = $wb->page['menu'] == '' ? 1 : $wb->page['menu'];
485
    } 
486

    
487
    // Set some of the $wb->page[] settings to defaults if not set
488
    $pageLevel  = $wb->page['level']  == '' ? 0 : $wb->page['level'];
489
    $pageParent = $wb->page['parent'] == '' ? 0 : $wb->page['parent'];
490
    
491
    // adjust the start level and start page ID as necessary to
492
    // handle the special values that can be passed in as $aStart
493
    $aStartLevel = 0;
494
    if ($aStart < SM2_ROOT) {   // SM2_CURR+N
495
        if ($aStart == SM2_CURR) {
496
            $aStartLevel = $pageLevel;
497
            $aStart = $pageParent;
498
        }
499
        else {
500
            $aStartLevel = $pageLevel + $aStart - SM2_CURR;
501
            $aStart = $CURR_PAGE_ID; 
502
        }
503
    }
504
    elseif ($aStart < 0) {   // SM2_ROOT+N
505
        $aStartLevel = $aStart - SM2_ROOT;
506
        $aStart = 0;
507
    }
508

    
509
    // we get the menu data once and store it in a global variable. This allows 
510
    // multiple calls to show_menu2 in a single page with only a single call to 
511
    // the database. If this variable exists, then we have already retrieved all
512
    // of the information and processed it, so we don't need to do it again.
513
    if (($flags & SM2_NOCACHE) != 0
514
        || !array_key_exists('show_menu2_data', $GLOBALS)
515
        || !array_key_exists($aMenu, $GLOBALS['show_menu2_data'])) 
516
    {
517
        global $database;
518

    
519
        // create an array of all parents of the current page. As the page_trail
520
        // doesn't include the theoretical root element 0, we add it ourselves.
521
        $rgCurrParents = explode(",", '0,'.$wb->page['page_trail']);
522
        array_pop($rgCurrParents); // remove the current page
523
        $rgParent = array();
524

    
525
        // if the caller wants all menus gathered together (e.g. for a sitemap)
526
        // then we don't limit our SQL query
527
        $menuLimitSql = ' AND `menu`='.$aMenu;
528
        if ($aMenu == SM2_ALLMENU) {
529
            $menuLimitSql = '';
530
        }
531

    
532
        // we only load the description and keywords if we have been told to,
533
        // this cuts the memory load for pages that don't use them. Note that if
534
        // we haven't been told to load these fields the *FIRST TIME* show_menu2
535
        // is called (i.e. where the database is loaded) then the info won't
536
        // exist anyhow.
537
        $fields  = '`parent`,`page_id`,`menu_title`,`page_title`,`link`,`target`,';
538
		$fields .= '`level`,`visibility`,`viewing_groups`';
539
        if (version_compare(WB_VERSION, '2.7', '>=')) { // WB 2.7+
540
            $fields .= ',`viewing_users`';
541
        }
542
		if(version_compare(WB_VERSION, '2.9.0', '>=')) {
543
            $fields .= ',`menu_icon_0`,`menu_icon_1`,`page_icon`,`tooltip`';
544
		}
545
        if ($flags & SM2_ALLINFO) {
546
            $fields = '*';
547
        }
548

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

    
574
                    // 3. all pages not visible to this user (unless always visible to registered users) are ignored
575
                    else if (!$wb->page_is_visible($page) && $page['visibility'] != 'registered') {
576
                        continue;
577
                    }
578
                }
579
				if(!isset($page['tooltip'])) { $page['tooltip'] = $page['page_title']; }
580
                // ensure that we have an array entry in the table to add this to
581
                $idx = $page['parent'];
582
                if (!array_key_exists($idx, $rgParent)) {
583
                    $rgParent[$idx] = array();
584
                }
585

    
586
                // mark our current page as being on the current path
587
                if ($page['page_id'] == $CURR_PAGE_ID) {
588
                    $page['sm2_is_curr'] = true;
589
                    $page['sm2_on_curr_path'] = true;
590
                    if ($flags & SM2_SHOWHIDDEN) 
591
					{ 
592
                        // show hidden pages if active and SHOWHIDDEN flag supplied
593
                        unset($page['sm2_hide']); 
594
                    }
595
                }
596

    
597
                // mark parents of the current page as such
598
                if (in_array($page['page_id'], $rgCurrParents)) {
599
                    $page['sm2_is_parent'] = true;
600
                    $page['sm2_on_curr_path'] = true;
601
                    if ($flags & SM2_SHOWHIDDEN) 
602
					{
603
                        // show hidden pages if active and SHOWHIDDEN flag supplied
604
						unset($page['sm2_hide']); // don't hide a parent page                
605
                    }
606
                }
607
                
608
                // add the entry to the array                
609
                $rgParent[$idx][] = $page;
610
            }
611
        }    
612
        unset($oRowset);
613

    
614
        // mark all elements that are siblings of any element on the current path
615
        foreach ($rgCurrParents as $x) {
616
            if (array_key_exists($x, $rgParent)) {
617
                foreach (array_keys($rgParent[$x]) as $y) {
618
                    $mark =& $rgParent[$x][$y];
619
                    $mark['sm2_path_sibling'] = true;
620
                    unset($mark);
621
                }
622
            }
623
        }
624

    
625
        // mark all elements that have children and are siblings of the current page
626
        $parentId = $pageParent;
627
        foreach (array_keys($rgParent) as $x) {
628
            $childSet =& $rgParent[$x];
629
            foreach (array_keys($childSet) as $y) {
630
                $mark =& $childSet[$y];
631
                if (array_key_exists($mark['page_id'], $rgParent)) {
632
                    $mark['sm2_has_child'] = true;
633
                }
634
                if ($mark['parent'] == $parentId && $mark['page_id'] != $CURR_PAGE_ID) {
635
                    $mark['sm2_is_sibling'] = true;
636
                }
637
                unset($mark);
638
            }
639
            unset($childSet);
640
        }
641
        
642
        // mark all children of the current page. We don't do this when 
643
        // $CURR_PAGE_ID is 0, as 0 is the parent of everything. 
644
        // $CURR_PAGE_ID == 0 occurs on special pages like search results
645
        // when no referrer is available.s
646
        if ($CURR_PAGE_ID != 0) {
647
            sm2_mark_children($rgParent, $CURR_PAGE_ID, 1);
648
        }
649
        
650
        // store the complete processed menu data as a global. We don't 
651
        // need to read this from the database anymore regardless of how 
652
        // many menus are displayed on the same page.
653
        if (!array_key_exists('show_menu2_data', $GLOBALS)) {
654
            $GLOBALS['show_menu2_data'] = array();
655
        }
656
        $GLOBALS['show_menu2_data'][$aMenu] =& $rgParent;
657
        unset($rgParent);
658
    }
659

    
660
    // adjust $aMaxLevel to the level number of the final level that 
661
    // will be displayed. That is, we display all levels <= aMaxLevel.
662
    if ($aMaxLevel == SM2_ALL) {
663
        $aMaxLevel = 1000;
664
    }
665
    elseif ($aMaxLevel < 0) {   // SM2_CURR+N
666
        $aMaxLevel += $pageLevel - SM2_CURR;
667
    }
668
    elseif ($aMaxLevel >= SM2_MAX) { // SM2_MAX+N
669
        $aMaxLevel += $aStartLevel - SM2_MAX;
670
        if ($aMaxLevel > $pageLevel) {
671
            $aMaxLevel = $pageLevel;
672
        }
673
    }
674
    else {  // SM2_START+N
675
        $aMaxLevel += $aStartLevel - SM2_START;
676
    }
677

    
678
    // generate the menu
679
    $retval = false;
680
    if (array_key_exists($aStart, $GLOBALS['show_menu2_data'][$aMenu])) {
681
        $formatter = $aItemOpen;
682
        if (!is_object($aItemOpen)) {
683
            static $sm2formatter;
684
            if (!isset($sm2formatter)) {
685
                $sm2formatter = new SM2_Formatter;
686
            }
687
            $formatter = $sm2formatter;
688
            $formatter->set($flags, $aItemOpen, $aItemClose, 
689
                $aMenuOpen, $aMenuClose, $aTopItemOpen, $aTopMenuOpen);
690
        }
691
        
692
        // adjust the level until we show everything and ignore the SM2_TRIM flag.
693
        // Usually this will be less than the start level to disable it.
694
        $showAllLevel = $aStartLevel - 1;
695
        if (isset($aOptions['notrim'])) {
696
            $showAllLevel = $aStartLevel + $aOptions['notrim'];
697
        }
698
        
699
        // display the menu
700
        $formatter->initialize();
701
        sm2_recurse(
702
            $GLOBALS['show_menu2_data'][$aMenu],
703
            $aStart,    // parent id to start displaying sub-menus
704
            $aStartLevel, $showAllLevel, $aMaxLevel, $flags, 
705
            $formatter);
706
        $formatter->finalize();
707
        
708
        // if we are returning something, get the data
709
        if (($flags & SM2_BUFFER) != 0) {
710
            $retval = $formatter->getOutput();
711
        }
712
    }
713

    
714
    // clear the data if we aren't caching it
715
    if (($flags & SM2_NOCACHE) != 0) {
716
        unset($GLOBALS['show_menu2_data'][$aMenu]);
717
    }
718
    
719
    return $retval;
720
}
721

    
722
function sm2_mark_children(&$rgParent, $aStart, $aChildLevel)
723
{
724
    if (array_key_exists($aStart, $rgParent)) {
725
        foreach (array_keys($rgParent[$aStart]) as $y) {
726
            $mark =& $rgParent[$aStart][$y];
727
            $mark['sm2_child_level'] = $aChildLevel;
728
            $mark['sm2_on_curr_path'] = true;
729
            sm2_mark_children($rgParent, $mark['page_id'], $aChildLevel+1);
730
        }
731
    }
732
}
733

    
734
function sm2_recurse(
735
    &$rgParent, $aStart, 
736
    $aStartLevel, $aShowAllLevel, $aMaxLevel, $aFlags, 
737
    &$aFormatter
738
    )
739
{
740
    global $wb;
741

    
742
    // on entry to this function we know that there are entries for this 
743
    // parent and all entries for that parent are being displayed. We also 
744
    // need to check if any of the children need to be displayed too.
745
    $isListOpen = false;
746
    $currentLevel = $wb->page['level'] == '' ? 0 : $wb->page['level'];
747

    
748
    // get the number of siblings skipping the hidden pages so we can pass 
749
    // this in and check if the item is first or last
750
    $sibCount = 0;
751
    foreach ($rgParent[$aStart] as $page) {
752
        if (!array_key_exists('sm2_hide', $page)) $sibCount++;
753
    }
754
    
755
    $currSib = 0;
756
    foreach ($rgParent[$aStart] as $page) {
757
        // skip all hidden pages 
758
        if (array_key_exists('sm2_hide', $page)) { // not set if false, so existence = true
759
            continue;
760
        }
761
        
762
        $currSib++;
763

    
764
        // skip any elements that are lower than the maximum level
765
        $pageLevel = $page['level'];
766
        if ($pageLevel > $aMaxLevel) {
767
            continue;
768
        }
769
        
770
        // this affects ONLY the top level
771
        if ($aStart == 0 && ($aFlags & SM2_CURRTREE)) {
772
            if (!array_key_exists('sm2_on_curr_path', $page)) { // not set if false, so existence = true
773
                continue;
774
            }
775
            $sibCount = 1;
776
        }
777
        
778
        // trim the tree as appropriate
779
        if ($aFlags & SM2_SIBLING) {
780
            // parents, and siblings and children of current only
781
            if (!array_key_exists('sm2_on_curr_path', $page)      // not set if false, so existence = true
782
                && !array_key_exists('sm2_is_sibling', $page)     // not set if false, so existence = true
783
                && !array_key_exists('sm2_child_level', $page)) { // not set if false, so existence = true
784
                continue;
785
            }
786
        }
787
        else if ($aFlags & SM2_TRIM) {
788
            // parents and siblings of parents
789
            if ($pageLevel > $aShowAllLevel  // permit all levels to be shown
790
                && !array_key_exists('sm2_on_curr_path', $page)    // not set if false, so existence = true
791
                && !array_key_exists('sm2_path_sibling', $page)) {  // not set if false, so existence = true
792
                continue;
793
            }
794
        }
795
        elseif ($aFlags & SM2_CRUMB) {
796
            // parents only
797
            if (!array_key_exists('sm2_on_curr_path', $page)    // not set if false, so existence = true
798
                || array_key_exists('sm2_child_level', $page)) {  // not set if false, so existence = true
799
                continue;
800
            }
801
        }
802

    
803
        // depth first traverse
804
        $nextParent = $page['page_id'];
805

    
806
        // display the current element if we have reached the start level
807
        if ($pageLevel >= $aStartLevel) {
808
            // massage the link into the correct form
809
            if(!INTRO_PAGE && $page['link'] == $wb->default_link) {
810
                $url = WB_URL.'/';
811
            }
812
            else {
813
                $url = $wb->page_link($page['link']);
814
            }
815
                    
816
            // we open the list only when we absolutely need to
817
            if (!$isListOpen) {
818
                $aFormatter->startList($page, $url);
819
                $isListOpen = true;
820
            }
821

    
822
            $aFormatter->startItem($page, $url, $currSib, $sibCount);
823
        }
824
        
825
        // display children as appropriate
826
        if ($pageLevel + 1 <= $aMaxLevel 
827
            && array_key_exists('sm2_has_child', $page)) {  // not set if false, so existence = true
828
            sm2_recurse(
829
                $rgParent, $nextParent, // parent id to start displaying sub-menus
830
                $aStartLevel, $aShowAllLevel, $aMaxLevel, $aFlags, 
831
                $aFormatter);
832
        }
833
        
834
        // close the current element if appropriate
835
        if ($pageLevel >= $aStartLevel) {
836
            $aFormatter->finishItem($pageLevel, $page);
837
        }
838
    }
839

    
840
    // close the list if we opened one
841
    if ($isListOpen) {
842
        $aFormatter->finishList();
843
    }
844
}
845

    
(4-4/10)