includes/paths.php~
changeset 3 2b2084ca1e60
parent 2 0931d60f5bdb
child 4 0b3a0aedfd53
equal deleted inserted replaced
2:0931d60f5bdb 3:2b2084ca1e60
     1 <?php
       
     2 
       
     3 /**
       
     4  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
       
     5  * Version 1.0 (Banshee)
       
     6  * Copyright (C) 2006-2007 Dan Fuhry
       
     7  * paths.php - The part of Enano that actually manages content. Everything related to page handling and namespaces is in here.
       
     8  *
       
     9  * This program is Free Software; you can redistribute and/or modify it under the terms of the GNU General Public License
       
    10  * as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
       
    11  *
       
    12  * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
       
    13  * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.
       
    14  *
       
    15  * @package Enano
       
    16  * @subpackage PathManager
       
    17  * @see http://enano.homelinux.org/Help:API_Documentation
       
    18  */
       
    19  
       
    20 class pathManager {
       
    21   var $pages, $custom_page, $cpage, $page, $fullpage, $page_exists, $namespace, $nslist, $admin_tree, $wiki_mode, $page_protected, $template_cache;
       
    22   function __construct()
       
    23   {
       
    24     global $db, $session, $paths, $template, $plugins; // Common objects
       
    25     
       
    26     $GLOBALS['paths'] =& $this;
       
    27     $this->pages = Array();
       
    28     
       
    29     dc_here('paths: setting up namespaces, admin nodes');
       
    30     
       
    31     // DEFINE NAMESPACES HERE
       
    32     // The key names should NOT EVER be changed, or Enano will be very broken
       
    33     $this->nslist = Array(
       
    34       'Article' =>'',
       
    35       'User'    =>'User:',
       
    36       'File'    =>'File:',
       
    37       'Help'    =>'Help:',
       
    38       'Admin'   =>'Admin:',
       
    39       'Special' =>'Special:',
       
    40       'System'  =>'Enano:',
       
    41       'Template'=>'Template:',
       
    42       'Category'=>'Category:',
       
    43       'Project' =>str_replace(' ', '_', getConfig('site_name')).':',
       
    44       );
       
    45     
       
    46     // ACL types
       
    47     // Note: you can set any of these to AUTH_DENY to universally and unconditionally deny access to the selected action.
       
    48     // These can also be added from within plugins
       
    49     
       
    50     $session->register_acl_type('read',                   AUTH_ALLOW,    'Read page(s)');
       
    51     $session->register_acl_type('post_comments',          AUTH_ALLOW,    'Post comments',                                                                                            Array('read'),                                            'Article|User|Project|Template|File|Help|System|Category');
       
    52     $session->register_acl_type('edit_comments',          AUTH_ALLOW,    'Edit own comments',                                                                                        Array('post_comments'),                                   'Article|User|Project|Template|File|Help|System|Category');
       
    53     $session->register_acl_type('edit_page',              AUTH_WIKIMODE, 'Edit page',                                                                                                Array('view_source'),                                     'Article|User|Project|Template|File|Help|System|Category');
       
    54     $session->register_acl_type('view_source',            AUTH_WIKIMODE, 'View source',                                                                                              Array('read'),                                            'Article|User|Project|Template|File|Help|System|Category'); // Only used if the page is protected
       
    55     $session->register_acl_type('mod_comments',           AUTH_DISALLOW, 'Moderate comments',                                                                                        Array('edit_comments'),                                   'Article|User|Project|Template|File|Help|System|Category');
       
    56     $session->register_acl_type('history_view',           AUTH_WIKIMODE, 'View history/diffs',                                                                                       Array('read'),                                            'Article|User|Project|Template|File|Help|System|Category');
       
    57     $session->register_acl_type('history_rollback',       AUTH_DISALLOW, 'Rollback history',                                                                                         Array('history_view'),                                    'Article|User|Project|Template|File|Help|System|Category');
       
    58     $session->register_acl_type('history_rollback_extra', AUTH_DISALLOW, 'Undelete page(s)',                                                                                         Array('history_rollback'),                                'Article|User|Project|Template|File|Help|System|Category');
       
    59     $session->register_acl_type('protect',                AUTH_DISALLOW, 'Protect page(s)',                                                                                          Array('read'),                                            'Article|User|Project|Template|File|Help|System|Category');
       
    60     $session->register_acl_type('rename',                 AUTH_WIKIMODE, 'Rename page(s)',                                                                                           Array('read'),                                            'Article|User|Project|Template|File|Help|System|Category');
       
    61     $session->register_acl_type('clear_logs',             AUTH_DISALLOW, 'Clear page logs (dangerous)',                                                                              Array('read', 'protect', 'even_when_protected'),          'Article|User|Project|Template|File|Help|System|Category');
       
    62     $session->register_acl_type('vote_delete',            AUTH_ALLOW,    'Vote to delete',                                                                                           Array('read'),                                            'Article|User|Project|Template|File|Help|System|Category');
       
    63     $session->register_acl_type('vote_reset',             AUTH_DISALLOW, 'Reset delete votes',                                                                                       Array('read'),                                            'Article|User|Project|Template|File|Help|System|Category');
       
    64     $session->register_acl_type('delete_page',            AUTH_DISALLOW, 'Delete page(s)',                                                                                           Array(),                                                  'Article|User|Project|Template|File|Help|System|Category');
       
    65     $session->register_acl_type('set_wiki_mode',          AUTH_DISALLOW, 'Set per-page wiki mode',                                                                                   Array('read'),                                            'Article|User|Project|Template|File|Help|System|Category');
       
    66     $session->register_acl_type('password_set',           AUTH_DISALLOW, 'Set password',                                                                                             Array('read'),                                            'Article|User|Project|Template|File|Help|System|Category');
       
    67     $session->register_acl_type('password_reset',         AUTH_DISALLOW, 'Disable/reset password',                                                                                   Array('read'),                                            'Article|User|Project|Template|File|Help|System|Category');
       
    68     $session->register_acl_type('mod_misc',               AUTH_DISALLOW, 'Super moderator (generate SQL backtraces, view IP addresses, and send large numbers of private messages)', Array(),                                                  'All');
       
    69     $session->register_acl_type('edit_cat',               AUTH_WIKIMODE, 'Edit categorization',                                                                                      Array('read'),                                            'Article|User|Project|Template|File|Help|System|Category');
       
    70     $session->register_acl_type('even_when_protected',    AUTH_DISALLOW, 'Allow editing, renaming, and categorization even when protected',                                          Array('edit_page', 'rename', 'mod_comments', 'edit_cat'), 'Article|User|Project|Template|File|Help|System|Category');
       
    71     $session->register_acl_type('upload_files',           AUTH_DISALLOW, 'Upload files',                                                                                             Array('create_page'),                                     'Article|User|Project|Template|File|Help|System|Category|Special');
       
    72     $session->register_acl_type('upload_new_version',     AUTH_WIKIMODE, 'Upload new versions of files',                                                                             Array('upload_files'),                                    'Article|User|Project|Template|File|Help|System|Category|Special');
       
    73     $session->register_acl_type('create_page',            AUTH_WIKIMODE, 'Create pages',                                                                                             Array(),                                                  'Article|User|Project|Template|File|Help|System|Category|Special');
       
    74     $session->register_acl_type('php_in_pages',           AUTH_DISALLOW, 'Embed PHP code in pages',                                                                                  Array('edit_page'),                                       'Article|User|Project|Template|File|Help|System|Category');
       
    75     $session->register_acl_type('edit_acl',               AUTH_DISALLOW, 'Edit access control lists', Array('read', 'post_comments', 'edit_comments', 'edit_page', 'view_source', 'mod_comments', 'history_view', 'history_rollback', 'history_rollback_extra', 'protect', 'rename', 'clear_logs', 'vote_delete', 'vote_reset', 'delete_page', 'set_wiki_mode', 'password_set', 'password_reset', 'mod_misc', 'edit_cat', 'even_when_protected', 'upload_files', 'upload_new_version', 'create_page', 'php_in_pages'));
       
    76     
       
    77     // DO NOT add new admin pages here! Use a plugin to call $paths->addAdminNode();
       
    78     $this->addAdminNode('General', 'General Configuration', 'GeneralConfig');
       
    79     $this->addAdminNode('General', 'File uploads', 'UploadConfig');
       
    80     $this->addAdminNode('General', 'Allowed file types', 'UploadAllowedMimeTypes');
       
    81     $this->addAdminNode('General', 'Manage Plugins', 'PluginManager');
       
    82     $this->addAdminNode('General', 'Backup database', 'DBBackup');
       
    83     $this->addAdminNode('Content', 'Manage Pages', 'PageManager');
       
    84     $this->addAdminNode('Content', 'Edit page content', 'PageEditor');
       
    85     $this->addAdminNode('Appearance', 'Manage themes', 'ThemeManager');
       
    86     $this->addAdminNode('Users', 'Manage users', 'UserManager');
       
    87     $this->addAdminNode('Users', 'Edit groups', 'GroupManager');
       
    88     $this->addAdminNode('Users', 'Ban control', 'BanControl');
       
    89     $this->addAdminNode('Users', 'Mass e-mail', 'MassEmail');
       
    90     
       
    91     $code = $plugins->setHook('acl_rule_init');
       
    92     foreach ( $code as $cmd )
       
    93     {
       
    94       eval($cmd);
       
    95     }
       
    96     
       
    97     $this->wiki_mode = (int)getConfig('wiki_mode')=='1';
       
    98     $this->template_cache = Array();
       
    99   }
       
   100   function pathManager()
       
   101   {
       
   102     $this->__construct();
       
   103   }
       
   104   function init()
       
   105   {
       
   106     global $db, $session, $paths, $template, $plugins; // Common objects
       
   107     
       
   108     dc_here('paths: selecting master page data');
       
   109     
       
   110     $code = $plugins->setHook('paths_init_before');
       
   111     foreach ( $code as $cmd )
       
   112     {
       
   113       eval($cmd);
       
   114     }
       
   115     
       
   116     $e = $db->sql_query('SELECT name,urlname,namespace,special,visible,comments_on,protected,delvotes,delvote_ips,wiki_mode,password FROM '.table_prefix.'pages ORDER BY name;');
       
   117     if( !$e )
       
   118     {
       
   119       $db->_die('The error seems to have occured while selecting the page information. File: includes/paths.php; line: '.__LINE__);
       
   120     }
       
   121     while($r = $db->fetchrow())
       
   122     {
       
   123       
       
   124       $r['urlname_nons'] = $r['urlname'];
       
   125       $r['urlname'] = $this->nslist[$r['namespace']] . $r['urlname']; // Applies the User:/File:/etc prefixes to the URL names
       
   126       
       
   127       if ( $r['delvotes'] == null)
       
   128       {
       
   129         $r['delvotes'] = 0;
       
   130       }
       
   131       if ( $r['protected'] == 0 || $r['protected'] == 1 )
       
   132       {
       
   133         $r['really_protected'] = (int)$r['protected'];
       
   134       }
       
   135       else if ( $r['protected'] == 2 && getConfig('wiki_mode') == '1')
       
   136       {
       
   137         $r['really_protected'] = 1;
       
   138       }
       
   139       else if ( $r['protected'] == 2 && getConfig('wiki_mode') == '0' )
       
   140       {
       
   141         $r['really_protected'] = 0;
       
   142       }
       
   143       
       
   144       $this->pages[$r['urlname']] = $r;
       
   145       $this->pages[] =& $this->pages[$r['urlname']];
       
   146       
       
   147     }
       
   148     $db->free_result();
       
   149     dc_here('paths: determining page ID');
       
   150     if( isset($_GET['title']) )
       
   151     {
       
   152       if ( $_GET['title'] == '' && getConfig('main_page') != '' )
       
   153       {
       
   154         $this->main_page();
       
   155       }
       
   156       if(strstr($_GET['title'], ' '))
       
   157       {
       
   158         $loc = urldecode(rawurldecode($_SERVER['REQUEST_URI']));
       
   159         $loc = str_replace(' ', '_', $loc);
       
   160         $loc = str_replace('+', '_', $loc);
       
   161         $loc = str_replace('%20', '_', $loc);
       
   162         redirect($loc, 'Redirecting...', 'Space detected in the URL, please wait whilst you are redirected', 0);
       
   163         exit;
       
   164       }
       
   165       $url_namespace_special = substr($_GET['title'], 0, strlen($this->nslist['Special']) );
       
   166       $url_namespace_template = substr($_GET['title'], 0, strlen($this->nslist['Template']) );
       
   167       if($url_namespace_special == $this->nslist['Special'] || $url_namespace_template == $this->nslist['Template'] )
       
   168       {
       
   169         $ex = explode('/', $_GET['title']);
       
   170         $this->page = $ex[0];
       
   171       }
       
   172       else
       
   173       {
       
   174         $this->page = $_GET['title'];
       
   175       }
       
   176       $this->fullpage = $_GET['title'];
       
   177     }
       
   178     elseif( isset($_SERVER['PATH_INFO']) )
       
   179     {
       
   180       $pi = explode('/', $_SERVER['PATH_INFO']);
       
   181       
       
   182       if( !isset($pi[1]) || (isset($pi[1]) && $pi[1] == '' && getConfig('main_page') != '') )
       
   183       {
       
   184         $this->main_page();
       
   185       }
       
   186       if( strstr($pi[1], ' ') )
       
   187       {
       
   188         $loc = str_replace(' ', '_', urldecode(rawurldecode($_SERVER['REQUEST_URI'])));
       
   189         $loc = str_replace('+', '_', $loc);
       
   190         $loc = str_replace('%20', '_', $loc);
       
   191         redirect($loc, 'Redirecting...', 'Please wait whilst you are redirected', 3);
       
   192         exit;
       
   193       }
       
   194       unset($pi[0]);
       
   195       if( substr($pi[1], 0, strlen($this->nslist['Special'])) == $this->nslist['Special'] || substr($pi[1], 0, strlen($this->nslist['Template'])) == $this->nslist['Template'] )
       
   196       {
       
   197         $pi2 = $pi[1];
       
   198       }
       
   199       else
       
   200       {
       
   201         $pi2 = implode('/', $pi);
       
   202       }
       
   203       $this->page = $pi2;
       
   204       $this->fullpage = implode('/', $pi);
       
   205     }
       
   206     else
       
   207     {
       
   208       $k = array_keys($_GET);
       
   209       foreach($k as $c)
       
   210       {
       
   211         if(substr($c, 0, 1) == '/')
       
   212         {
       
   213           $this->page = substr($c, 1, strlen($c));
       
   214           
       
   215           // Bugfix for apache somehow passing dots as underscores
       
   216           global $mime_types;
       
   217           $exts = array_keys($mime_types);
       
   218           $exts = '(' . implode('|', $exts) . ')';
       
   219           if ( preg_match( '#_'.$exts.'#i', $this->page ) )
       
   220             $this->page = preg_replace( '#_'.$exts.'#i', '.\\1', $this->page );
       
   221           
       
   222           $this->fullpage = $this->page;
       
   223           
       
   224           if(substr($this->page, 0, strlen($this->nslist['Special']))==$this->nslist['Special'] || substr($this->page, 0, strlen($this->nslist['Template']))==$this->nslist['Template'])
       
   225           {
       
   226             $ex = explode('/', $this->page);
       
   227             $this->page = $ex[0];
       
   228           }
       
   229           if(strstr($this->page, ' '))
       
   230           {
       
   231             $loc = str_replace(' ', '_', urldecode(rawurldecode($_SERVER['REQUEST_URI'])));
       
   232             $loc = str_replace('+', '_', $loc);
       
   233             $loc = str_replace('%20', '_', $loc);
       
   234             redirect($loc, 'Redirecting...', 'Space in the URL detected, please wait whilst you are redirected', 0);
       
   235             exit;
       
   236           }
       
   237           break;
       
   238         }
       
   239       }
       
   240       if(!$this->page && !($this->page == '' && getConfig('main_page') == ''))
       
   241       {
       
   242         $this->main_page();
       
   243       }
       
   244     }
       
   245     
       
   246     dc_here('paths: setting $paths->cpage');
       
   247     
       
   248     if(isset($this->pages[$this->page]))
       
   249     {
       
   250       dc_here('paths: page existence verified, our page ID is: '.$this->page);
       
   251       $this->page_exists = true;
       
   252       $this->cpage = $this->pages[$this->page];
       
   253       $this->namespace = $this->cpage['namespace'];
       
   254       if(!isset($this->cpage['wiki_mode'])) $this->cpage['wiki_mode'] = 2;
       
   255       
       
   256       // Determine the wiki mode for this page, now that we have this->cpage established
       
   257       if($this->cpage['wiki_mode'] == 2)
       
   258       {
       
   259         $this->wiki_mode = (int)getConfig('wiki_mode');
       
   260       }
       
   261       else
       
   262       {
       
   263         $this->wiki_mode = $this->cpage['wiki_mode'];
       
   264       }
       
   265       // Allow the user to create/modify his user page uncondtionally (admins can still protect the page)
       
   266       if($this->page == $this->nslist['User'].str_replace(' ', '_', $session->username))
       
   267       {
       
   268         $this->wiki_mode = true;
       
   269       }
       
   270       // And above all, if the site requires wiki mode to be off for non-logged-in users, disable it now
       
   271       if(getConfig('wiki_mode_require_login')=='1' && !$session->user_logged_in)
       
   272       {
       
   273         $this->wiki_mode = false;
       
   274       }
       
   275       if($this->cpage['protected'] == 2)
       
   276       {
       
   277         // The page is semi-protected, determine permissions
       
   278         if($session->user_logged_in && $session->reg_time + 60*60*24*4 < time()) 
       
   279         {
       
   280           $this->page_protected = 0;
       
   281         }
       
   282         else
       
   283         {
       
   284           $this->page_protected = 1;
       
   285         }
       
   286       }
       
   287       else
       
   288       {
       
   289         $this->page_protected = $this->cpage['protected'];
       
   290       }
       
   291     }
       
   292     else
       
   293     {
       
   294       dc_here('paths: page doesn\'t exist, creating new page in memory<br />our page ID is: '.$this->page);
       
   295       $this->page_exists = false;
       
   296       $this->cpage = Array(
       
   297         'name'=>str_replace('_', ' ', $this->page),
       
   298         'urlname'=>$this->page,
       
   299         'namespace'=>'Article',
       
   300         'special'=>0,
       
   301         'visible'=>0,
       
   302         'comments_on'=>1,
       
   303         'protected'=>0,
       
   304         'delvotes'=>0,
       
   305         'delvote_ips'=>'',
       
   306         'wiki_mode'=>2,
       
   307         );
       
   308       // Look for a namespace prefix in the urlname, and assign a different namespace, if necessary
       
   309       $k = array_keys($this->nslist);
       
   310       for($i=0;$i<sizeof($this->nslist);$i++)
       
   311       {
       
   312         $ln = strlen($this->nslist[$k[$i]]);
       
   313         if( substr($this->page, 0, $ln) == $this->nslist[$k[$i]] )
       
   314         {
       
   315           $this->cpage['namespace'] = $k[$i];
       
   316           $this->cpage['urlname_nons'] = substr($this->page, strlen($this->nslist[$this->cpage['namespace']]), strlen($this->page));
       
   317           if(!isset($this->cpage['wiki_mode'])) 
       
   318           {
       
   319             $this->cpage['wiki_mode'] = 2;
       
   320           }
       
   321         }
       
   322       }
       
   323       $this->namespace = $this->cpage['namespace'];
       
   324       
       
   325       if($this->namespace=='System') 
       
   326       {
       
   327         $this->cpage['protected'] = 1;
       
   328       }
       
   329       if($this->namespace=='Special')
       
   330       {
       
   331         // Can't load nonexistent pages
       
   332         $this->main_page();
       
   333       }
       
   334       // Allow the user to create/modify his user page uncondtionally (admins can still protect the page)
       
   335       if($this->page == $this->nslist['User'].str_replace(' ', '_', $session->username)) 
       
   336       {
       
   337         $this->wiki_mode = true;
       
   338       }
       
   339     }
       
   340     // This is used in the admin panel to keep track of form submission targets
       
   341     $this->cpage['module'] = $this->cpage['urlname'];
       
   342     
       
   343     // Page is set up, call any hooks
       
   344     $code = $plugins->setHook('page_set');
       
   345     foreach ( $code as $cmd )
       
   346     {
       
   347       eval($cmd);
       
   348     }
       
   349     
       
   350     $session->init_permissions();
       
   351   }
       
   352   
       
   353   function add_page($flags)
       
   354   {
       
   355     //dc_dump($flags, 'paths: page added by plugin:');
       
   356     $flags['urlname_nons'] = $flags['urlname'];
       
   357     $flags['urlname'] = $this->nslist[$flags['namespace']] . $flags['urlname']; // Applies the User:/File:/etc prefixes to the URL names
       
   358     $pages_len = sizeof($this->pages)/2;
       
   359     $this->pages[$pages_len] = $flags;
       
   360     $this->pages[$flags['urlname']] =& $this->pages[$pages_len];
       
   361   }
       
   362   
       
   363   function main_page()
       
   364   {
       
   365     if( is_string(getConfig('main_page')) )
       
   366     {
       
   367       header('Location: '.makeUrl(getConfig('main_page')));
       
   368       die('If you aren\'t redirected, <a href="' . makeUrl(getConfig('main_page')) . '">click here</a>.');
       
   369     }
       
   370     else
       
   371     {
       
   372       header('Location: '.makeUrl($this->pages[0]['urlname']));
       
   373       die('If you aren\'t redirected, <a href="' . makeUrl($this->pages[0]['urlname']) . '">click here</a>.');
       
   374     }
       
   375     exit;
       
   376   }
       
   377   
       
   378   function sysmsg($n)
       
   379   {
       
   380     global $db, $session, $paths, $template, $plugins; // Common objects
       
   381     dc_here('paths: system message requested: '.$n);
       
   382     $q = $db->sql_query('SELECT page_text, char_tag FROM '.table_prefix.'page_text WHERE page_id=\''.$db->escape($n).'\' AND namespace=\'System\'');
       
   383     if( !$q )
       
   384     {
       
   385       $db->_die('Error during generic selection of system page data.');
       
   386     }
       
   387     if($db->numrows() < 1)
       
   388     {
       
   389       return false;
       
   390       //$db->_die('Error during generic selection of system page data: there were no rows in the text table that matched the page text query.');
       
   391     }
       
   392     $r = $db->fetchrow();
       
   393     $db->free_result();
       
   394     $message = $r['page_text'];
       
   395     
       
   396     $message = preg_replace('/<noinclude>(.*?)<\/noinclude>/is', '', $message);
       
   397     
       
   398     return $message;
       
   399   }
       
   400   function get_pageid_from_url()
       
   401   {
       
   402     if(isset($_GET['title']))
       
   403     {
       
   404       if( $_GET['title'] == '' && getConfig('main_page') != '' )
       
   405       {
       
   406         $this->main_page();
       
   407       }
       
   408       if(strstr($_GET['title'], ' '))
       
   409       {
       
   410         $loc = urldecode(rawurldecode($_SERVER['REQUEST_URI']));
       
   411         $loc = str_replace(' ', '_', $loc);
       
   412         $loc = str_replace('+', '_', $loc);
       
   413         header('Location: '.$loc);
       
   414         exit;
       
   415       }
       
   416       $ret = $_GET['title'];
       
   417     }
       
   418     elseif(isset($_SERVER['PATH_INFO']))
       
   419     {
       
   420       $pi = explode('/', $_SERVER['PATH_INFO']);
       
   421       
       
   422       if(!isset($pi[1]) || (isset($pi[1]) && $pi[1] == ''))
       
   423       {
       
   424         return false;
       
   425       }
       
   426       
       
   427       if(strstr($pi[1], ' '))
       
   428       {
       
   429         $loc = urldecode(rawurldecode($_SERVER['REQUEST_URI']));
       
   430         $loc = str_replace(' ', '_', $loc);
       
   431         $loc = str_replace('+', '_', $loc);
       
   432         header('Location: '.$loc);
       
   433         exit;
       
   434       }
       
   435       if( !( substr($pi[1], 0, strlen($this->nslist['Special'])) == $this->nslist['Special'] ) )
       
   436       {
       
   437         unset($pi[0]);
       
   438         $pi[1] = implode('/', $pi);
       
   439       }
       
   440       $ret = $pi[1];
       
   441     }
       
   442     else
       
   443     {
       
   444       $k = array_keys($_GET);
       
   445       foreach($k as $c)
       
   446       {
       
   447         if(substr($c, 0, 1) == '/')
       
   448         {
       
   449           $ret = substr($c, 1, strlen($c));
       
   450           if(substr($ret, 0, strlen($this->nslist['Special'])) == $this->nslist['Special'] ||
       
   451              substr($ret, 0, strlen($this->nslist['Admin'])) == $this->nslist['Admin'])
       
   452           {
       
   453             $ret = explode('/', $ret);
       
   454             $ret = $ret[0];
       
   455           }
       
   456           break;
       
   457         }
       
   458       }
       
   459     }
       
   460     
       
   461     return ( isset($ret) ) ? $ret : false;
       
   462   }
       
   463   // Parses a (very carefully formed) array into Javascript code compatible with the Tigra Tree Menu used in the admin menu
       
   464   function parseAdminTree() 
       
   465   {
       
   466     $k = array_keys($this->admin_tree);
       
   467     $i = 0;
       
   468     $ret = '';
       
   469     $ret .= "var TREE_ITEMS = [\n  ['Administration panel home', 'javascript:ajaxPage(\'".$this->nslist['Admin']."Home\');',\n    ";
       
   470     foreach($k as $key)
       
   471     {
       
   472       $i++;
       
   473       $ret .= "['".$key."', 'javascript:trees[0].toggle($i)', \n";
       
   474       foreach($this->admin_tree[$key] as $c)
       
   475       {
       
   476         $i++;
       
   477         $ret .= "        ['".$c['name']."', 'javascript:ajaxPage(\\'".$this->nslist['Admin'].$c['pageid']."\\');'],\n";
       
   478       }
       
   479       $ret .= "      ],\n";
       
   480     }
       
   481     $ret .= "    ['Log out of admin panel', 'javascript:ajaxPage(\\'".$this->nslist['Admin']."AdminLogout\\');'],\n";
       
   482     // I used this while I painstakingly wrote the Runt code that auto-expands certain nodes based on the value of a bitfield stored in a cookie. *shudders*
       
   483     // $ret .= "    ['(debug) Clear menu bitfield', 'javascript:createCookie(\\'admin_menu_state\\', \\'1\\', 365);'],\n";
       
   484     $ret .= "]\n];";
       
   485     return $ret;
       
   486   }
       
   487   function addAdminNode($section, $page_title, $url)
       
   488   {
       
   489     if(!isset($this->admin_tree[$section]))
       
   490     {
       
   491       $this->admin_tree[$section] = Array();
       
   492     }
       
   493     $this->admin_tree[$section][] = Array(
       
   494         'name'=>$page_title,
       
   495         'pageid'=>$url
       
   496       );
       
   497   }
       
   498   function getParam($id = 0)
       
   499   {
       
   500     if(isset($_SERVER['PATH_INFO']))
       
   501     {
       
   502       $pi = explode('/', $_SERVER['PATH_INFO']);
       
   503       $id = $id + 2;
       
   504       return isset($pi[$id]) ? $pi[$id] : false;
       
   505     }
       
   506     else if( isset($_GET['title']) )
       
   507     {
       
   508       $pi = explode('/', $_GET['title']);
       
   509       $id = $id + 1;
       
   510       return isset($pi[$id]) ? $pi[$id] : false;
       
   511     }
       
   512     else
       
   513     {
       
   514       $k = array_keys($_GET);
       
   515       foreach($k as $c)
       
   516       {
       
   517         if(substr($c, 0, 1) == '/')
       
   518         {
       
   519           
       
   520           // Bugfix for apache somehow passing dots as underscores
       
   521           global $mime_types;
       
   522           $exts = array_keys($mime_types);
       
   523           $exts = '(' . implode('|', $exts) . ')';
       
   524           if ( preg_match( '#_'.$exts.'#i', $c ) )
       
   525             $c = preg_replace( '#_'.$exts.'#i', '.\\1', $c );
       
   526           
       
   527           $pi = explode('/', $c);
       
   528           $id = $id + 2;
       
   529           return isset($pi[$id]) ? $pi[$id] : false;
       
   530         }
       
   531       }
       
   532       return false;
       
   533     }
       
   534   }
       
   535   
       
   536   function getAllParams()
       
   537   {
       
   538     if(isset($_SERVER['PATH_INFO']))
       
   539     {
       
   540       $pi = explode('/', $_SERVER['PATH_INFO']);
       
   541       unset($pi[0], $pi[1]);
       
   542       return implode('/', $pi);
       
   543     }
       
   544     else if( isset($_GET['title']) )
       
   545     {
       
   546       $pi = explode('/', $_GET['title']);
       
   547       unset($pi[0]);
       
   548       return implode('/', $pi);
       
   549     }
       
   550     else
       
   551     {
       
   552       $k = array_keys($_GET);
       
   553       foreach($k as $c)
       
   554       {
       
   555         if(substr($c, 0, 1) == '/')
       
   556         {
       
   557           // Bugfix for apache somehow passing dots as underscores
       
   558           global $mime_types;
       
   559           $exts = array_keys($mime_types);
       
   560           $exts = '(' . implode('|', $exts) . ')';
       
   561           if ( preg_match( '#_'.$exts.'#i', $c ) )
       
   562             $c = preg_replace( '#_'.$exts.'#i', '.\\1', $c );
       
   563           
       
   564           $pi = explode('/', $c);
       
   565           unset($pi[0], $pi[1]);
       
   566           return implode('/', $pi);
       
   567         }
       
   568       }
       
   569       return false;
       
   570     }
       
   571   }
       
   572   
       
   573   /**
       
   574    * Creates a new namespace in memory
       
   575    * @param string $id the namespace ID
       
   576    * @param string $prefix the URL prefix, must not be blank or already used
       
   577    * @return bool true on success false on failure
       
   578    */
       
   579   
       
   580   function create_namespace($id, $prefix)
       
   581   {
       
   582     if(in_array($prefix, $this->nslist))
       
   583     {
       
   584       // echo '<b>Warning:</b> pathManager::create_namespace: Prefix "'.$prefix.'" is already taken<br />';
       
   585       return false;
       
   586     }
       
   587     if( isset($this->nslist[$id]) )
       
   588     {
       
   589       // echo '<b>Warning:</b> pathManager::create_namespace: Namespace ID "'.$prefix.'" is already taken<br />';
       
   590       return false;
       
   591     }
       
   592     $this->nslist[$id] = $prefix;
       
   593   }
       
   594   
       
   595   /**
       
   596    * Fetches the page texts for searching
       
   597    */
       
   598    
       
   599   function fetch_page_search_texts()
       
   600   {
       
   601     global $db, $session, $paths, $template, $plugins; // Common objects
       
   602     $texts = Array();
       
   603     $q = $db->sql_query('SELECT t.page_id,t.namespace,t.page_text,t.char_tag FROM '.table_prefix.'page_text AS t
       
   604                            LEFT JOIN '.table_prefix.'pages AS p
       
   605                              ON t.page_id=p.urlname
       
   606                            WHERE p.namespace=t.namespace
       
   607                              AND ( p.password=\'\' OR p.password=\'da39a3ee5e6b4b0d3255bfef95601890afd80709\' )
       
   608                              AND p.visible=1;'); // Only indexes "visible" pages
       
   609     
       
   610     if( !$q )
       
   611     {
       
   612       return false;
       
   613     }
       
   614     while($row = $db->fetchrow())
       
   615     {
       
   616       $pid = $this->nslist[$row['namespace']] . $row['page_id'];
       
   617       $texts[$pid] = $row['page_text'];
       
   618     }
       
   619     $db->free_result();
       
   620     
       
   621     return $texts;
       
   622   }
       
   623   
       
   624   /**
       
   625    * Fetches a MySQL search query to use for Searcher::searchMySQL()
       
   626    */
       
   627    
       
   628   function fetch_page_search_resource()
       
   629   {
       
   630     global $db, $session, $paths, $template, $plugins; // Common objects
       
   631     // sha1('') returns "da39a3ee5e6b4b0d3255bfef95601890afd80709"
       
   632     $texts = 'SELECT t.page_text,CONCAT(\'ns=\',t.namespace,\';pid=\',t.page_id) FROM '.table_prefix.'page_text AS t
       
   633                            LEFT JOIN '.table_prefix.'pages AS p
       
   634                              ON ( t.page_id=p.urlname AND t.namespace=p.namespace )
       
   635                            WHERE p.namespace=t.namespace
       
   636                              AND ( p.password=\'\' OR p.password=\'da39a3ee5e6b4b0d3255bfef95601890afd80709\' )
       
   637                              AND p.visible=1;'; // Only indexes "visible" pages
       
   638     return $texts;
       
   639   }
       
   640   
       
   641   /**
       
   642    * Rebuilds the search index
       
   643    */
       
   644    
       
   645   function rebuild_search_index()
       
   646   {
       
   647     global $db, $session, $paths, $template, $plugins; // Common objects
       
   648     $search = new Searcher();
       
   649     $texts = Array();
       
   650     $textq = $db->sql_unbuffered_query($this->fetch_page_search_resource());
       
   651     if(!$textq) $db->_die('');
       
   652     while($row = $db->fetchrow_num())
       
   653     {
       
   654       $texts[(string)$row[1]] = $row[0];
       
   655     }
       
   656     $search->buildIndex($texts);
       
   657     // echo '<pre>'.print_r($search->index, true).'</pre>';
       
   658     // return;
       
   659     $q = $db->sql_query('DELETE FROM '.table_prefix.'search_index');
       
   660     if(!$q) return false;
       
   661     $secs = Array();
       
   662     $q = 'INSERT INTO '.table_prefix.'search_index(word,page_names) VALUES';
       
   663     foreach($search->index as $word => $pages)
       
   664     {
       
   665       $secs[] = '(\''.$db->escape($word).'\', \''.$db->escape($pages).'\')';
       
   666     }
       
   667     $q .= implode(',', $secs);
       
   668     unset($secs);
       
   669     $q .= ';';
       
   670     $result = $db->sql_query($q);
       
   671     $db->free_result();
       
   672     if($result)
       
   673       return true;
       
   674     else
       
   675       $db->_die('The search index was trying to rebuild itself when the error occured.');
       
   676   }
       
   677   
       
   678   /**
       
   679    * Partially rebuilds the search index, removing/inserting entries only for the current page
       
   680    * @param string $page_id
       
   681    * @param string $namespace
       
   682    */
       
   683   
       
   684   function rebuild_page_index($page_id, $namespace)
       
   685   {
       
   686     global $db, $session, $paths, $template, $plugins; // Common objects
       
   687     if(!$db->sql_query('SELECT page_text FROM '.table_prefix.'page_text
       
   688       WHERE page_id=\''.$db->escape($page_id).'\' AND namespace=\''.$db->escape($namespace).'\';'))
       
   689     {
       
   690       return $db->get_error();
       
   691     }
       
   692     $row = $db->fetchrow();
       
   693     $db->free_result();
       
   694     $search = new Searcher();
       
   695     $search->buildIndex(Array("ns={$namespace};pid={$page_id}"=>$row['page_text']));
       
   696     $new_index = $search->index;
       
   697     
       
   698     $keys = array_keys($search->index);
       
   699     foreach($keys as $i => $k)
       
   700     {
       
   701       $c =& $keys[$i];
       
   702       $c = hexencode($c, '', '');
       
   703     }
       
   704     $keys = "word=0x" . implode ( " OR word=0x", $keys ) . "";
       
   705     
       
   706     // Zap the cache
       
   707     $cache = array_keys($search->index);
       
   708     if ( count($cache) < 1 )
       
   709     {
       
   710       return false;
       
   711     }
       
   712     $cache = "query LIKE '%" . implode ( "%' OR query LIKE '%", $cache ) . "%'";
       
   713     $db->sql_query('DELETE FROM '.table_prefix.'search_cache WHERE '.$cache);
       
   714     
       
   715     $query = $db->sql_query('SELECT word,page_names FROM '.table_prefix.'search_index WHERE '.$keys.';');
       
   716     
       
   717     while($row = $db->fetchrow())
       
   718     {
       
   719       $row['word'] = rtrim($row['word'], "\0");
       
   720       $new_index[ $row['word'] ] = $row['page_names'] . ',' . $search->index[ $row['word'] ];
       
   721     }
       
   722     $db->free_result();
       
   723     
       
   724     $db->sql_query('DELETE FROM '.table_prefix.'search_index WHERE '.$keys.';');
       
   725     
       
   726     $secs = Array();
       
   727     $q = 'INSERT INTO '.table_prefix.'search_index(word,page_names) VALUES';
       
   728     foreach($new_index as $word => $pages)
       
   729     {
       
   730       $secs[] = '(\''.$db->escape($word).'\', \''.$db->escape($pages).'\')';
       
   731     }
       
   732     $q .= implode(',', $secs);
       
   733     unset($secs);
       
   734     $q .= ';';
       
   735     if(!$db->check_query($q))
       
   736     {
       
   737       die('BUG: PathManager::rebuild_page_index: Query rejected by SQL parser:<pre>'.$q.'</pre>');
       
   738     }
       
   739     $result = $db->sql_query($q);
       
   740     if($result)
       
   741       return true;
       
   742     else
       
   743       $db->_die('The search index was trying to rebuild itself when the error occured.');
       
   744     
       
   745   }
       
   746   
       
   747   /**
       
   748    * Creates an instance of the Searcher class, including index info
       
   749    * @return object
       
   750    */
       
   751    
       
   752   function makeSearcher($match_case = false)
       
   753   {
       
   754     global $db, $session, $paths, $template, $plugins; // Common objects
       
   755     $search = new Searcher();
       
   756     $q = $db->sql_query('SELECT word,page_names FROM '.table_prefix.'search_index;');
       
   757     if(!$q)
       
   758     {
       
   759       echo $db->get_error();
       
   760       return false;
       
   761     }
       
   762     $idx = Array();
       
   763     while($row = $db->fetchrow($q))
       
   764     {
       
   765       $row['word'] = rtrim($row['word'], "\0");
       
   766       $idx[$row['word']] = $row['page_names'];
       
   767     }
       
   768     $db->free_result();
       
   769     $search->index = $idx;
       
   770     if($match_case)
       
   771       $search->match_case = true;
       
   772     return $search;
       
   773   }
       
   774   
       
   775   /**
       
   776    * Creates an associative array filled with the values of all the page titles
       
   777    * @return array
       
   778    */
       
   779    
       
   780   function get_page_titles()
       
   781   {
       
   782     $texts = Array();
       
   783     for ( $i = 0; $i < sizeof($this->pages) / 2; $i++ )
       
   784     {
       
   785       $texts[$this->pages[$i]['urlname']] = $this->pages[$i]['name'];
       
   786     }
       
   787     return $texts;
       
   788   }
       
   789   
       
   790   /**
       
   791    * Creates an instance of the Searcher class, including index info for page titles
       
   792    * @return object
       
   793    */
       
   794    
       
   795   function makeTitleSearcher($match_case = false)
       
   796   {
       
   797     global $db, $session, $paths, $template, $plugins; // Common objects
       
   798     $search = new Searcher();
       
   799     $texts = $this->get_page_titles();
       
   800     $search->buildIndex($texts);
       
   801     if($match_case)
       
   802       $search->match_case = true;
       
   803     return $search;
       
   804   }
       
   805   
       
   806 }
       
   807   
       
   808 ?>