]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/main.php
reformatting
[SourceForge/phpwiki.git] / lib / main.php
1 <?php //-*-php-*-
2 rcs_id('$Id: main.php,v 1.201 2005-01-20 10:18:17 rurban Exp $');
3
4 define ('USE_PREFS_IN_PAGE', true);
5
6 //include "lib/config.php";
7 require_once(dirname(__FILE__)."/stdlib.php");
8 require_once('lib/Request.php');
9 require_once('lib/WikiDB.php');
10 if (ENABLE_USER_NEW)
11     require_once("lib/WikiUserNew.php");
12 else
13     require_once("lib/WikiUser.php");
14 require_once("lib/WikiGroup.php");
15 if (ENABLE_PAGEPERM)
16     require_once("lib/PagePerm.php");
17
18 /**
19  * Check permission per page.
20  * Returns true or false.
21  */
22 function mayAccessPage ($access, $pagename) {
23     if (ENABLE_PAGEPERM)
24         return _requiredAuthorityForPagename($access, $pagename); // typically [10-20ms per page]
25     else
26         return true;
27 }
28
29 class WikiRequest extends Request {
30     // var $_dbi;
31
32     function WikiRequest () {
33         $this->_dbi = WikiDB::open($GLOBALS['DBParams']);
34          // first mysql request costs [958ms]! [670ms] is mysql_connect()
35         
36         if (in_array('File', $this->_dbi->getAuthParam('USER_AUTH_ORDER'))) {
37             // force our local copy, until the pear version is fixed.
38             include_once(dirname(__FILE__)."/pear/File_Passwd.php");
39         }
40         if (ENABLE_USER_NEW) {
41             // load all necessary userclasses (otherwise session => __PHP_Incomplete_Class_Name)
42             // There's no way to demandload it later. (This way it's much slower but needs less memory than loading all)
43             if (ALLOW_BOGO_LOGIN)
44                 include_once("lib/WikiUser/BogoLogin.php");
45             foreach ($GLOBALS['USER_AUTH_ORDER'] as $method) {
46                 include_once("lib/WikiUser/$method.php");
47                 if ($method == 'Db')
48                     switch($GLOBALS['DBParams']['dbtype']) {
49                         case 'SQL' : include_once("lib/WikiUser/PearDb.php"); break;
50                         case 'ADODB': include_once("lib/WikiUser/AdoDb.php"); break;
51                     }
52             }
53             unset($method);
54         }
55         if (USE_DB_SESSION) {
56             include_once('lib/DbSession.php');
57             $dbi =& $this->_dbi;
58             $this->_dbsession = new DbSession($dbi, $dbi->getParam('prefix') . $dbi->getParam('db_session_table'));
59         }
60 // Fixme: Does pear reset the error mask to 1? We have to find the culprit
61 //$x = error_reporting();
62 $this->version = phpwiki_version();
63         $this->Request(); // [90ms]
64
65         // Normalize args...
66         $this->setArg('pagename', $this->_deducePagename());
67         $this->setArg('action', $this->_deduceAction());
68
69         if ((DEBUG & _DEBUG_SQL) or (time() % 50 == 0)) {
70             if ($this->_dbi->_backend->optimize())
71                 trigger_error(_("Optimizing database"), E_USER_NOTICE);
72         }
73         
74         // Restore auth state. This doesn't check for proper authorization!
75         if (ENABLE_USER_NEW) {
76             $userid = $this->_deduceUsername(); 
77             if (isset($this->_user) and 
78                 !empty($this->_user->_authhow) and 
79                 $this->_user->_authhow == 'session')
80             {
81                 // users might switch in a session between the two objects.
82                 // restore old auth level here or in updateAuthAndPrefs?
83                 //$user = $this->getSessionVar('wiki_user');
84                 // revive db handle, because these don't survive sessions
85                 if (isset($this->_user) and 
86                      ( ! isa($this->_user, WikiUserClassname())
87                        or (strtolower(get_class($this->_user)) == '_passuser')))
88                 {
89                     $this->_user = WikiUser($userid, $this->_user->_prefs);
90                 }
91                 // revive other db handle
92                 if (isset($this->_user->_prefs->_method)
93                     and ($this->_user->_prefs->_method == 'SQL' 
94                          or $this->_user->_prefs->_method == 'ADODB' 
95                          or $this->_user->_prefs->_method == 'HomePage')) {
96                     $this->_user->_HomePagehandle = $this->getPage($userid);
97                 }
98                 // need to update the lockfile filehandle
99                 if ( isa($this->_user,'_FilePassUser') 
100                      and $this->_user->_file->lockfile 
101                      and !$this->_user->_file->fplock )
102                 {
103                     //$level = $this->_user->_level;
104                     $this->_user = UpgradeUser($this->_user, 
105                                                new _FilePassUser($userid, $this->_user->_prefs, $this->_user->_file->filename));
106                     //$this->_user->_level = $level;
107                 }
108                 $this->_prefs = & $this->_user->_prefs;
109             } else {
110                 $user = WikiUser($userid);
111                 $this->_user = & $user;
112                 $this->_prefs = & $this->_user->_prefs;
113             }
114         } else {
115             $this->_user = new WikiUser($this, $this->_deduceUsername());
116             $this->_prefs = $this->_user->getPreferences();
117         }
118     }
119
120     function initializeLang () {
121         $user_lang = $this->getPref('lang');
122         $_lang = @$this->_prefs->_prefs['lang'];
123         //check changed LANG and THEME inside a session. 
124         // (e.g. by using another baseurl)
125         if (isset($this->_user->_authhow) and 
126             $this->_user->_authhow == 'session' and 
127             !isset($_lang->lang) and 
128             $user_lang != $GLOBALS['LANG'])
129         {
130             $user_lang = $GLOBALS['LANG'];
131         }
132         if (isset($user_lang)) {
133             //trigger_error("DEBUG: initializeLang() ". $user_lang ." calling update_locale()...");
134             update_locale($user_lang);
135             FindLocalizedButtonFile(".",'missing_ok','reinit');
136         }
137     }
138
139     function initializeTheme () {
140         global $WikiTheme;
141
142         // Load theme
143         $user_theme = $this->getPref('theme');
144         $_theme = @$this->_prefs->_prefs['theme'];
145         //check changed LANG and THEME inside a session. 
146         // (e.g. by using another baseurl)
147         if (isset($this->_user->_authhow) and 
148             $this->_user->_authhow == 'session' and 
149             !isset($_theme->theme) and
150             defined('THEME') and 
151             $user_theme != THEME)
152         {
153             include_once("themes/" . THEME . "/themeinfo.php");
154         }
155         if (empty($WikiTheme) and isset($user_theme)) {
156             if (strcspn($user_theme,"./\x00]") != strlen($user_theme)) {
157                 trigger_error(sprintf("invalid theme '%s': Invalid characters detected", $user_theme),
158                               E_USER_WARNING);
159                 $user_theme = "default";
160             }
161             include_once("themes/$user_theme/themeinfo.php");
162         }
163         if (empty($WikiTheme) and defined('THEME'))
164             include_once("themes/" . THEME . "/themeinfo.php");
165         if (empty($WikiTheme))
166             include_once("themes/default/themeinfo.php");
167         assert(!empty($WikiTheme));
168     }
169
170     // This really maybe should be part of the constructor, but since it
171     // may involve HTML/template output, the global $request really needs
172     // to be initialized before we do this stuff.
173     // [50ms]: 36ms is wikidb_page::exists
174     function updateAuthAndPrefs () {
175
176         if (isset($this->_user) and (!isa($this->_user,WikiUserClassname()))) {
177             $this->_user = false;       
178         }
179         // Handle authentication request, if any.
180         if ($auth_args = $this->getArg('auth')) {
181             $this->setArg('auth', false);
182             $this->_handleAuthRequest($auth_args); // possible NORETURN
183         }
184         elseif ( ! $this->_user 
185                  or (isa($this->_user, WikiUserClassname()) 
186                      and ! $this->_user->isSignedIn())) {
187             // If not auth request, try to sign in as saved user.
188             if (($saved_user = $this->getPref('userid')) != false) {
189                 $this->_signIn($saved_user);
190             }
191         }
192
193         // Save preferences in session and cookie
194         if (!defined('WIKI_XMLRPC') or !WIKI_XMLRPC) {
195             if (isset($this->_user)) {
196                 if (!isset($this->_user->_authhow) or $this->_user->_authhow != 'session') {
197                     $this->_user->setPreferences($this->_prefs, true);
198                 }
199             }
200             $this->setSessionVar('wiki_user', $this->_user);
201         }
202
203         // Ensure user has permissions for action
204         // HACK ALERT: We may not set the request arg to create, 
205         // since the pageeditor has an ugly logic for action == create.
206         $action = $this->getArg('action');
207         if ($action == 'edit' or $action == 'create') {
208             $page = $this->getPage();
209             if (! $page->exists() )
210                 $action = 'create';
211             else
212                 $action = 'edit';
213         }
214         $require_level = $this->requiredAuthority($action);
215         if (! $this->_user->hasAuthority($require_level))
216             $this->_notAuthorized($require_level); // NORETURN
217     }
218
219     function & getUser () {
220         if (isset($this->_user))
221             return $this->_user;
222         else
223             return $GLOBALS['ForbiddenUser'];
224     }
225     
226     function & getGroup () {
227         if (isset($this->_user) and isset($this->_user->_group))
228             return $this->_user->_group;
229         else
230             return WikiGroup::getGroup();
231     }
232
233     function & getPrefs () {
234         return $this->_prefs;
235     }
236
237     // Convenience function:
238     function getPref ($key) {
239         if (isset($this->_prefs)) {
240             return $this->_prefs->get($key);
241         }
242     }
243     function & getDbh () {
244         return $this->_dbi;
245     }
246
247     /**
248      * Get requested page from the page database.
249      * By default it will grab the page requested via the URL
250      *
251      * This is a convenience function.
252      * @param string $pagename Name of page to get.
253      * @return WikiDB_Page Object with methods to pull data from
254      * database for the page requested.
255      */
256     function getPage ($pagename = false) {
257         //if (!isset($this->_dbi)) $this->getDbh();
258         if (!$pagename) 
259             $pagename = $this->getArg('pagename');
260         return $this->_dbi->getPage($pagename);
261     }
262
263     /** Get URL for POST actions.
264      *
265      * Officially, we should just use SCRIPT_NAME (or some such),
266      * but that causes problems when we try to issue a redirect, e.g.
267      * after saving a page.
268      *
269      * Some browsers (at least NS4 and Mozilla 0.97 won't accept
270      * a redirect from a page to itself.)
271      *
272      * So, as a HACK, we include pagename and action as query args in
273      * the URL.  (These should be ignored when we receive the POST
274      * request.)
275      */
276     function getPostURL ($pagename=false) {
277         global $HTTP_GET_VARS;
278
279         if ($pagename === false)
280             $pagename = $this->getArg('pagename');
281         $action = $this->getArg('action');
282         if (!empty($HTTP_GET_VARS['start_debug'])) // zend ide support
283             return WikiURL($pagename, array('action' => $action, 'start_debug' => 1));
284         else
285             return WikiURL($pagename, array('action' => $action));
286     }
287     
288     function _handleAuthRequest ($auth_args) {
289         if (!is_array($auth_args))
290             return;
291
292         // Ignore password unless POST'ed.
293         if (!$this->isPost())
294             unset($auth_args['passwd']);
295
296         $olduser = $this->_user;
297         $user = $this->_user->AuthCheck($auth_args);
298         if (isa($user, WikiUserClassname())) {
299             // Successful login (or logout.)
300             $this->_setUser($user);
301         }
302         elseif (is_string($user)) {
303             // Login attempt failed.
304             $fail_message = $user;
305             $auth_args['pass_required'] = true;
306             // if clicked just on to the "sign in as:" button dont print invalid username.
307             if (!empty($auth_args['login']) and empty($auth_args['userid']))
308                 $fail_message = '';
309             // If no password was submitted, it's not really
310             // a failure --- just need to prompt for password...
311             if (!ALLOW_USER_PASSWORDS 
312                 and ALLOW_BOGO_LOGIN 
313                 and !isset($auth_args['passwd'])) 
314             {
315                 $fail_message = false;
316             }
317             $olduser->PrintLoginForm($this, $auth_args, $fail_message, 'newpage');
318             $this->finish();    //NORETURN
319         }
320         else {
321             // Login request cancelled.
322         }
323     }
324
325     /**
326      * Attempt to sign in (bogo-login).
327      *
328      * Fails silently.
329      *
330      * @param $userid string Userid to attempt to sign in as.
331      * @access private
332      */
333     function _signIn ($userid) {
334         if (ENABLE_USER_NEW) {
335             if (! $this->_user )
336                 $this->_user = new _BogoUser($userid);
337             // FIXME: is this always false? shouldn't we try passuser first?
338             if (! $this->_user ) 
339                 $this->_user = new _PassUser($userid);
340         }
341         $user = $this->_user->AuthCheck(array('userid' => $userid));
342         if (isa($user,WikiUserClassname())) {
343             $this->_setUser($user); // success!
344         }
345     }
346
347     // login or logout or restore state
348     function _setUser (&$user) {
349         $this->_user =& $user;
350         if (defined('MAIN_setUser')) return;
351         define('MAIN_setUser',true);
352         $this->setCookieVar('WIKI_ID', $user->getAuthenticatedId(),
353                             COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
354         if ($user->isSignedIn())
355             $user->_authhow = 'signin';
356
357         // Save userid to prefs..
358         if ( empty($this->_user->_prefs)) {
359             $this->_user->_prefs = $this->_user->getPreferences();
360             $this->_prefs =& $this->_user->_prefs;
361         }
362         $this->_user->_group = $this->getGroup();
363         $this->setSessionVar('wiki_user', $user);
364         $this->_prefs->set('userid',
365                            $user->isSignedIn() ? $user->getId() : '');
366         $this->initializeTheme();
367     }
368
369     /* Permission system */
370     function getLevelDescription($level) {
371         static $levels = false;
372         if (!$levels) 
373             $levels = array('x-1' => _("FORBIDDEN"),
374                             'x0'  => _("ANON"),
375                             'x1'  => _("BOGO"),
376                             'x2'  => _("USER"),
377                             'x10' => _("ADMIN"),
378                             'x100'=> _("UNOBTAINABLE"));
379         if (!empty($level))
380             $level = '0';
381         if (!empty($levels["x".$level]))
382             return $levels["x".$level];
383         else
384             return _("ANON");
385     }
386     
387     function _notAuthorized ($require_level) {
388         // Display the authority message in the Wiki's default
389         // language, in case it is not english.
390         //
391         // Note that normally a user will not see such an error once
392         // logged in, unless the admin has altered the default
393         // disallowed wikiactions. In that case we should probably
394         // check the user's language prefs too at this point; this
395         // would be a situation which is not really handled with the
396         // current code.
397         if (empty($GLOBALS['LANG']))
398             update_locale(DEFAULT_LANGUAGE);
399
400         // User does not have required authority.  Prompt for login.
401         $what = $this->getActionDescription($this->getArg('action'));
402         $pass_required = ($require_level >= WIKIAUTH_USER);
403         if ($require_level == WIKIAUTH_UNOBTAINABLE) {
404             global $DisabledActions;
405             if ($DisabledActions and in_array($action, $DisabledActions)) {
406                 $msg = fmt("%s is disallowed on this wiki.",
407                            $this->getDisallowedActionDescription($this->getArg('action')));
408                 $this->finish();
409                 return;
410             }
411             // Is the reason a missing ACL or just wrong user or password?
412             if (class_exists('PagePermission')) {
413                 $user =& $this->_user;
414                 $status = $user->isAuthenticated() ? _("authenticated") : _("not authenticated");
415                 $msg = fmt("%s %s %s is disallowed on this wiki for %s user '%s' (level: %s).",
416                            _("Missing PagePermission:"),
417                            action2access($this->getArg('action')),
418                            $this->getArg('pagename'),
419                            $status, $user->getId(), $this->getLevelDescription($user->_level));
420                 // TODO: add link to action=setacl
421                 $user->PrintLoginForm($this, compact('pass_required'), $msg);
422                 $this->finish();
423                 return;
424             } else {
425                 $msg = fmt("%s is disallowed on this wiki.",
426                            $this->getDisallowedActionDescription($this->getArg('action')));
427                 $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
428                 $this->finish();
429                 return;
430             }
431         }
432         elseif ($require_level == WIKIAUTH_BOGO)
433             $msg = fmt("You must sign in to %s.", $what);
434         elseif ($require_level == WIKIAUTH_USER)
435             $msg = fmt("You must log in to %s.", $what);
436         elseif ($require_level == WIKIAUTH_ANON)
437             $msg = fmt("Access for you is forbidden to %s.", $what);
438         else
439             $msg = fmt("You must be an administrator to %s.", $what);
440
441         $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
442         $this->finish();    // NORETURN
443     }
444
445     // Fixme: for PagePermissions we'll need other strings, 
446     // relevant to the requested page, not just for the action on the whole wiki.
447     function getActionDescription($action) {
448         static $actionDescriptions;
449         if (! $actionDescriptions) {
450             $actionDescriptions
451             = array('browse'     => _("view this page"),
452                     'diff'       => _("diff this page"),
453                     'dumphtml'   => _("dump html pages"),
454                     'dumpserial' => _("dump serial pages"),
455                     'edit'       => _("edit this page"),
456                     'revert'     => _("revert to a previous version of this page"),
457                     'create'     => _("create this page"),
458                     'loadfile'   => _("load files into this wiki"),
459                     'lock'       => _("lock this page"),
460                     'remove'     => _("remove this page"),
461                     'unlock'     => _("unlock this page"),
462                     'upload'     => _("upload a zip dump"),
463                     'verify'     => _("verify the current action"),
464                     'viewsource' => _("view the source of this page"),
465                     'xmlrpc'     => _("access this wiki via XML-RPC"),
466                     'soap'       => _("access this wiki via SOAP"),
467                     'zip'        => _("download a zip dump from this wiki"),
468                     'ziphtml'    => _("download an html zip dump from this wiki")
469                     );
470         }
471         if (in_array($action, array_keys($actionDescriptions)))
472             return $actionDescriptions[$action];
473         else
474             return $action;
475     }
476     
477     /**
478 TODO: check against these cases:
479         if ($DisabledActions and in_array($action, $DisabledActions))
480             return WIKIAUTH_UNOBTAINABLE;
481
482         if (ENABLE_PAGEPERM and class_exists("PagePermission")) {
483            return requiredAuthorityForPage($action);
484            
485 => Browsing pages is disallowed on this wiki for authenticated user 'rurban' (level: BOGO).
486     */
487     function getDisallowedActionDescription($action) {
488         static $disallowedActionDescriptions;
489         
490         if (! $disallowedActionDescriptions) {
491             $disallowedActionDescriptions
492             = array('browse'     => _("Browsing pages"),
493                     'diff'       => _("Diffing pages"),
494                     'dumphtml'   => _("Dumping html pages"),
495                     'dumpserial' => _("Dumping serial pages"),
496                     'edit'       => _("Editing pages"),
497                     'revert'     => _("Reverting to a previous version of pages"),
498                     'create'     => _("Creating pages"),
499                     'loadfile'   => _("Loading files"),
500                     'lock'       => _("Locking pages"),
501                     'remove'     => _("Removing pages"),
502                     'unlock'     => _("Unlocking pages"),
503                     'upload'     => _("Uploading zip dumps"),
504                     'verify'     => _("Verify the current action"),
505                     'viewsource' => _("Viewing the source of pages"),
506                     'xmlrpc'     => _("XML-RPC access"),
507                     'soap'       => _("SOAP access"),
508                     'zip'        => _("Downloading zip dumps"),
509                     'ziphtml'    => _("Downloading html zip dumps")
510                     );
511         }
512         if (in_array($action, array_keys($disallowedActionDescriptions)))
513             return $disallowedActionDescriptions[$action];
514         else
515             return $action;
516     }
517
518     function requiredAuthority ($action) {
519         $auth = $this->requiredAuthorityForAction($action);
520         if (!ALLOW_ANON_USER) return WIKIAUTH_USER;
521         
522         /*
523          * This is a hook for plugins to require authority
524          * for posting to them.
525          *
526          * IMPORTANT: this is not a secure check, so the plugin
527          * may not assume that any POSTs to it are authorized.
528          * All this does is cause PhpWiki to prompt for login
529          * if the user doesn't have the required authority.
530          */
531         if ($this->isPost()) {
532             $post_auth = $this->getArg('require_authority_for_post');
533             if ($post_auth !== false)
534                 $auth = max($auth, $post_auth);
535         }
536         return $auth;
537     }
538         
539     function requiredAuthorityForAction ($action) {
540         global $DisabledActions;
541         
542         if ($DisabledActions and in_array($action, $DisabledActions))
543             return WIKIAUTH_UNOBTAINABLE;
544             
545         if (ENABLE_PAGEPERM and class_exists("PagePermission")) {
546            return requiredAuthorityForPage($action);
547         } else {
548           // FIXME: clean up. 
549           switch ($action) {
550             case 'browse':
551             case 'viewsource':
552             case 'diff':
553             case 'select':
554             case 'xmlrpc':
555             case 'search':
556             case 'pdf':
557                 return WIKIAUTH_ANON;
558
559             case 'zip':
560             case 'ziphtml':
561                 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
562                     return WIKIAUTH_ADMIN;
563                 return WIKIAUTH_ANON;
564
565             case 'edit':
566             case 'revert':
567             case 'soap':
568                 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
569                     return WIKIAUTH_BOGO;
570                 return WIKIAUTH_ANON;
571                 // return WIKIAUTH_BOGO;
572
573             case 'create':
574                 $page = $this->getPage();
575                 $current = $page->getCurrentRevision();
576                 if ($current->hasDefaultContents())
577                     return $this->requiredAuthorityForAction('edit');
578                 return $this->requiredAuthorityForAction('browse');
579
580             case 'upload':
581             case 'dumpserial':
582             case 'dumphtml':
583             case 'loadfile':
584             case 'remove':
585             case 'lock':
586             case 'unlock':
587             case 'upgrade':
588             case 'chown':
589             case 'setacl':
590             case 'rename':
591                 return WIKIAUTH_ADMIN;
592
593             /* authcheck occurs only in the plugin.
594                required actionpage RateIt */
595             /*
596             case 'rate':
597             case 'delete_rating':
598                 // Perhaps this should be WIKIAUTH_USER
599                 return WIKIAUTH_BOGO;
600             */
601
602             default:
603                 global $WikiNameRegexp;
604                 if (preg_match("/$WikiNameRegexp\Z/A", $action))
605                     return WIKIAUTH_ANON; // ActionPage.
606                 else
607                     return WIKIAUTH_ADMIN;
608           }
609         }
610     }
611     /* End of Permission system */
612
613     function possiblyDeflowerVirginWiki () {
614         if ($this->getArg('action') != 'browse')
615             return;
616         if ($this->getArg('pagename') != HOME_PAGE)
617             return;
618
619         $page = $this->getPage();
620         $current = $page->getCurrentRevision();
621         if ($current->getVersion() > 0)
622             return;             // Homepage exists.
623
624         include('lib/loadsave.php');
625         SetupWiki($this);
626         $this->finish();        // NORETURN
627     }
628     
629     // [574ms] mainly template:printexpansion: 393ms and template::expandsubtemplate [100+70+60ms]
630     function handleAction () {
631         $action = $this->getArg('action');
632         if ($this->isPost()) {
633             $page = $this->getPage();
634             if (!$this->_user->isAdmin() and $action != 'browse' and $page->get('moderation')) {
635                 require_once("lib/WikiPlugin.php");
636                 $loader = new WikiPluginLoader();
637                 $plugin = $loader->getPlugin("ModeratedPage");
638                 if ($plugin->handler($this, $page)) {
639                     $CONTENT = HTML::div(array('class' => 'wikitext'),
640                                                  fmt("%s: action forwarded to a moderator.", 
641                                                      $action), 
642                                          HTML::br(),
643                                          _("You must wait for moderator approval."));
644                     if ($plugin->_tokens['CONTENT'])
645                         $plugin->_tokens['CONTENT']->pushContent
646                             (
647                              HTML::br(),
648                              _("You must wait for moderator approval."));
649                     else
650                         $plugin->_tokens['CONTENT'] = $CONTENT;
651                     require_once("lib/Template.php");
652                     $title = WikiLink($page->getName());
653                     $title->pushContent(' : ', WikiLink(_("ModeratedPage")));
654                     GeneratePage(Template('browse', $plugin->_tokens), 
655                                  $title,
656                                  $page->getCurrentRevision());
657                     $this->finish();
658                 }
659             }
660         }
661         $method = "action_$action";
662         if (method_exists($this, $method)) {
663             $this->{$method}();
664         }
665         elseif ($page = $this->findActionPage($action)) {
666             $this->actionpage($page);
667         }
668         else {
669             $this->finish(fmt("%s: Bad action", $action));
670         }
671     }
672     
673     function finish ($errormsg = false) {
674         static $in_exit = 0;
675
676         if ($in_exit)
677             exit();        // just in case CloseDataBase calls us
678         $in_exit = true;
679
680         global $ErrorManager;
681         $ErrorManager->flushPostponedErrors();
682
683         if (!empty($errormsg)) {
684             PrintXML(HTML::br(),
685                      HTML::hr(),
686                      HTML::h2(_("Fatal PhpWiki Error")),
687                      $errormsg);
688             // HACK:
689             echo "\n</body></html>";
690         }
691         if (is_object($this->_user)) {
692             $this->_user->page   = $this->getArg('pagename');
693             $this->_user->action = $this->getArg('action');
694             unset($this->_user->_HomePagehandle);
695             unset($this->_user->_auth_dbi);
696         }
697         Request::finish();
698         exit;
699     }
700
701     /**
702      * Generally pagename is rawurlencoded for older browsers or mozilla.
703      * Typing a pagename into the IE bar will utf-8 encode it, so we have to 
704      * fix that with fixTitleEncoding().
705      * If USE_PATH_INFO = true, the pagename is stripped from the "/DATA_PATH/PageName&arg=value" line.
706      * If false, we support either "/index.php?pagename=PageName&arg=value",
707      * or the first arg (1.2.x style): "/index.php?PageName&arg=value"
708      */
709     function _deducePagename () {
710         if (trim(rawurldecode($this->getArg('pagename'))))
711             return fixTitleEncoding(rawurldecode($this->getArg('pagename')));
712
713         if (USE_PATH_INFO) {
714             $pathinfo = $this->get('PATH_INFO');
715             if (empty($pathinfo)) { // fix for CGI
716                 $path = $this->get('REQUEST_URI');
717                 $script = $this->get('SCRIPT_NAME');
718                 $pathinfo = substr($path,strlen($script));
719                 $pathinfo = preg_replace('/\?.+$/','',$pathinfo);
720             }
721             $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
722
723             if (trim($tail) != '' and $pathinfo == PATH_INFO_PREFIX . $tail) {
724                 return fixTitleEncoding($tail);
725             }
726         }
727         elseif ($this->isPost()) {
728             /*
729              * In general, for security reasons, HTTP_GET_VARS should be ignored
730              * on POST requests, but we make an exception here (only for pagename).
731              *
732              * The justification for this hack is the following
733              * asymmetry: When POSTing with USE_PATH_INFO set, the
734              * pagename can (and should) be communicated through the
735              * request URL via PATH_INFO.  When POSTing with
736              * USE_PATH_INFO off, this cannot be done --- the only way
737              * to communicate the pagename through the URL is via
738              * QUERY_ARGS (HTTP_GET_VARS).
739              */
740             global $HTTP_GET_VARS;
741             if (isset($HTTP_GET_VARS['pagename']) and trim($HTTP_GET_VARS['pagename'])) { 
742                 return fixTitleEncoding(rawurldecode($HTTP_GET_VARS['pagename']));
743             }
744         }
745
746         /*
747          * Support for PhpWiki 1.2 style requests.
748          * Strip off "&" args (?PageName&action=...&start_debug,...)
749          */
750         $query_string = $this->get('QUERY_STRING');
751         if (trim(rawurldecode($query_string)) and preg_match('/^([^&=]+)(&.+)?$/', $query_string, $m)) {
752             return fixTitleEncoding(rawurldecode($m[1]));
753         }
754
755         return fixTitleEncoding(HOME_PAGE);
756     }
757
758     function _deduceAction () {
759         if (!($action = $this->getArg('action'))) {
760             // Detect XML-RPC requests
761             if ($this->isPost()
762                 && $this->get('CONTENT_TYPE') == 'text/xml') {
763                 global $HTTP_RAW_POST_DATA;
764                 if (strstr($HTTP_RAW_POST_DATA, '<methodCall>')) {
765                     return 'xmlrpc';
766                 }
767             }
768             return 'browse';    // Default if no action specified.
769         }
770
771         if (method_exists($this, "action_$action"))
772             return $action;
773
774         // Allow for, e.g. action=LikePages
775         if ($this->isActionPage($action))
776             return $action;
777
778         // Handle untranslated actionpages in non-english
779         // (people playing with switching languages)
780         if (0 and $GLOBALS['LANG'] != 'en') {
781             require_once("lib/plugin/_WikiTranslation.php");
782             $trans = new WikiPlugin__WikiTranslation();
783             $en_action = $trans->translate($action,'en',$GLOBALS['LANG']);
784             if ($this->isActionPage($en_action))
785                 return $en_action;
786         }
787
788         trigger_error("$action: Unknown action", E_USER_NOTICE);
789         return 'browse';
790     }
791
792     function _deduceUsername() {
793         global $HTTP_SERVER_VARS, $HTTP_ENV_VARS;
794
795         if (!empty($this->args['auth']) and !empty($this->args['auth']['userid']))
796             return $this->args['auth']['userid'];
797
798         if (!empty($HTTP_SERVER_VARS['PHP_AUTH_USER']))
799             return $HTTP_SERVER_VARS['PHP_AUTH_USER'];
800         if (!empty($HTTP_ENV_VARS['REMOTE_USER']))
801             return $HTTP_ENV_VARS['REMOTE_USER'];
802             
803         if ($user = $this->getSessionVar('wiki_user')) {
804             // switched auth between sessions. 
805             // Note: There's no way to demandload a missing class-definition afterwards! (Stupid php)
806             if (isa($user, WikiUserClassname())) {
807                 $this->_user = $user;
808                 $this->_user->_authhow = 'session';
809                 return ENABLE_USER_NEW ? $user->UserName() : $this->_user;
810             }
811         }
812         if ($userid = $this->getCookieVar('WIKI_ID')) {
813             if (!empty($userid) and substr($userid,0,2) != 's:') {
814                 $this->_user->authhow = 'cookie';
815                 return $userid;
816             }
817         }
818         return false;
819     }
820     
821     function _isActionPage ($pagename) {
822         $dbi = $this->getDbh();
823         $page = $dbi->getPage($pagename);
824         if (!$page) return false;
825         $rev = $page->getCurrentRevision();
826         // FIXME: more restrictive check for sane plugin?
827         if (strstr($rev->getPackedContent(), '<?plugin'))
828             return true;
829         if (!$rev->hasDefaultContents())
830             trigger_error("$pagename: Does not appear to be an 'action page'", E_USER_NOTICE);
831         return false;
832     }
833
834     function findActionPage ($action) {
835         static $cache;
836
837         // check for translated version, as per users preferred language
838         // (or system default in case it is not en)
839         $translation = gettext($action);
840
841         if (isset($cache) and isset($cache[$translation]))
842             return $cache[$translation];
843
844         // check for cached translated version
845         if ($this->_isActionPage($translation))
846             return $cache[$action] = $translation;
847
848         // Allow for, e.g. action=LikePages
849         if (!isWikiWord($action))
850             return $cache[$action] = false;
851
852         // check for translated version (default language)
853         global $LANG;
854         if ($LANG != "en") {
855             require_once("lib/WikiPlugin.php");
856             require_once("lib/plugin/_WikiTranslation.php");
857             $trans = new WikiPlugin__WikiTranslation();
858             $trans->lang = $LANG;
859             $default = $trans->translate_to_en($action, $LANG);
860             if ($this->_isActionPage($default))
861                 return $cache[$action] = $default;
862         } else {
863             $default = $translation;
864         }
865         
866         // check for english version
867         if ($action != $translation and $action != $default) {
868             if ($this->_isActionPage($action))
869                 return $cache[$action] = $action;
870         }
871
872         trigger_error("$action: Cannot find action page", E_USER_NOTICE);
873         return $cache[$action] = false;
874     }
875     
876     function isActionPage ($pagename) {
877         return $this->findActionPage($pagename);
878     }
879
880     function action_browse () {
881         $this->buffer_output();
882         include_once("lib/display.php");
883         displayPage($this);
884     }
885
886     function action_verify () {
887         $this->action_browse();
888     }
889
890     function actionpage ($action) {
891         $this->buffer_output();
892         include_once("lib/display.php");
893         actionPage($this, $action);
894     }
895
896     function adminActionSubpage ($subpage) {
897         $page = _("PhpWikiAdministration")."/".$subpage;
898         $action = $this->findActionPage($page);
899         if ($action) {
900             $this->setArg('s',$this->getArg('pagename'));
901             $this->setArg('verify',1);
902             $this->setArg('action',$action);
903             $this->actionpage($action);
904         } else {
905             trigger_error($page.": Cannot find action page", E_USER_WARNING);
906         }
907     }
908
909     function action_chown () {
910         $this->adminActionSubpage(_("Chown"));
911     }
912
913     function action_setacl () {
914         $this->adminActionSubpage(_("SetAcl"));
915     }
916
917     function action_rename () {
918         $this->adminActionSubpage(_("Rename"));
919     }
920
921     function action_dump () {
922         $action = $this->findActionPage(_("PageDump"));
923         if ($action) {
924             $this->actionpage($action);
925         } else {
926             // redirect to action=upgrade if admin?
927             trigger_error(_("PageDump").": Cannot find action page", E_USER_WARNING);
928         }
929     }
930
931     function action_diff () {
932         $this->buffer_output();
933         include_once "lib/diff.php";
934         showDiff($this);
935     }
936
937     function action_search () {
938         // This is obsolete: reformulate URL and redirect.
939         // FIXME: this whole section should probably be deleted.
940         if ($this->getArg('searchtype') == 'full') {
941             $search_page = _("FullTextSearch");
942         }
943         else {
944             $search_page = _("TitleSearch");
945         }
946         $this->redirect(WikiURL($search_page,
947                                 array('s' => $this->getArg('searchterm')),
948                                 'absolute_url'));
949     }
950
951     function action_edit () {
952         $this->buffer_output();
953         include "lib/editpage.php";
954         $e = new PageEditor ($this);
955         $e->editPage();
956     }
957
958     function action_create () {
959         $this->action_edit();
960     }
961     
962     function action_viewsource () {
963         $this->buffer_output();
964         include "lib/editpage.php";
965         $e = new PageEditor ($this);
966         $e->viewSource();
967     }
968
969     function action_lock () {
970         $page = $this->getPage();
971         $page->set('locked', true);
972         $this->_dbi->touch();
973         // check ModeratedPage hook
974         if ($moderated = $page->get('moderated')) {
975             require_once("lib/WikiPlugin.php");
976             $plugin = WikiPluginLoader::getPlugin("ModeratedPage");
977             if ($retval = $plugin->lock_check($this, $page, $moderated))
978                 $this->setArg('errormsg', $retval);
979         } 
980         // check if a link to ModeratedPage exists
981         elseif ($action_page = $page->existLink(_("ModeratedPage"))) {
982             require_once("lib/WikiPlugin.php");
983             $plugin = WikiPluginLoader::getPlugin("ModeratedPage");
984             if ($retval = $plugin->lock_add($this, $page, $action_page))
985                 $this->setArg('errormsg', $retval);
986         }
987         $this->action_browse();
988     }
989
990     function action_unlock () {
991         $page = $this->getPage();
992         $page->set('locked', false);
993         $this->_dbi->touch();
994         $this->action_browse();
995     }
996
997     function action_remove () {
998         // FIXME: This check is redundant.
999         //$user->requireAuth(WIKIAUTH_ADMIN);
1000         $pagename = $this->getArg('pagename');
1001         if (strstr($pagename,_('PhpWikiAdministration'))) {
1002             $this->action_browse();
1003         } else {
1004             include('lib/removepage.php');
1005             RemovePage($this);
1006         }
1007     }
1008
1009     function action_xmlrpc () {
1010         include_once("lib/XmlRpcServer.php");
1011         $xmlrpc = new XmlRpcServer($this);
1012         $xmlrpc->service();
1013     }
1014     
1015     function action_revert () {
1016         include_once "lib/loadsave.php";
1017         RevertPage($this);
1018     }
1019
1020     function action_zip () {
1021         include_once("lib/loadsave.php");
1022         MakeWikiZip($this);
1023         // I don't think it hurts to add cruft at the end of the zip file.
1024         //echo "\n========================================================\n";
1025         //echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
1026     }
1027
1028     function action_ziphtml () {
1029         include_once("lib/loadsave.php");
1030         MakeWikiZipHtml($this);
1031         // I don't think it hurts to add cruft at the end of the zip file.
1032         echo "\n========================================================\n";
1033         echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
1034     }
1035
1036     function action_dumpserial () {
1037         include_once("lib/loadsave.php");
1038         DumpToDir($this);
1039     }
1040
1041     function action_dumphtml () {
1042         include_once("lib/loadsave.php");
1043         DumpHtmlToDir($this);
1044     }
1045
1046     function action_upload () {
1047         include_once("lib/loadsave.php");
1048         LoadPostFile($this);
1049     }
1050
1051     function action_upgrade () {
1052         include_once("lib/loadsave.php");
1053         include_once("lib/upgrade.php");
1054         DoUpgrade($this);
1055     }
1056
1057     function action_loadfile () {
1058         include_once("lib/loadsave.php");
1059         LoadFileOrDir($this);
1060     }
1061
1062     function action_pdf () {
1063         include_once("lib/pdf.php");
1064         ConvertAndDisplayPdf($this);
1065     }
1066     
1067 }
1068
1069 //FIXME: deprecated
1070 function is_safe_action ($action) {
1071     return WikiRequest::requiredAuthorityForAction($action) < WIKIAUTH_ADMIN;
1072 }
1073
1074 function validateSessionPath() {
1075     // Try to defer any session.save_path PHP errors before any html
1076     // is output, which causes some versions of IE to display a blank
1077     // page (due to its strict mode while parsing a page?).
1078     if (! is_writeable(ini_get('session.save_path'))) {
1079         $tmpdir = defined('SESSION_SAVE_PATH') ? SESSION_SAVE_PATH : '/tmp';
1080         if (!is_writeable($tmpdir))
1081             $tmpdir = '/tmp';
1082         trigger_error
1083             (sprintf(_("%s is not writable."),
1084                      _("The session.save_path directory"))
1085              . "\n"
1086              . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."),
1087                        sprintf(_("the session.save_path directory '%s'"),
1088                                ini_get('session.save_path')),
1089                        'SESSION_SAVE_PATH')
1090              . "\n"
1091              . sprintf(_("Attempting to use the directory '%s' instead."),
1092                        $tmpdir)
1093              , E_USER_NOTICE);
1094         if (! is_writeable($tmpdir)) {
1095             trigger_error
1096                 (sprintf(_("%s is not writable."), $tmpdir)
1097                  . "\n"
1098                  . _("Users will not be able to sign in.")
1099                  , E_USER_NOTICE);
1100         }
1101         else
1102             ini_set('session.save_path', $tmpdir);
1103     }
1104 }
1105
1106 function main () {
1107     if (!USE_DB_SESSION)
1108         validateSessionPath();
1109
1110     global $request;
1111     if ((DEBUG & _DEBUG_APD) and extension_loaded("apd"))
1112         apd_set_session_trace(9);
1113
1114     // Postpone warnings
1115     global $ErrorManager;
1116     if (defined('E_STRICT')) // and (E_ALL & E_STRICT)) // strict php5?
1117         $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE|E_USER_WARNING|E_WARNING|E_STRICT);
1118     else
1119         $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE|E_USER_WARNING|E_WARNING);
1120     $request = new WikiRequest();
1121
1122     $action = $request->getArg('action');
1123     if (substr($action, 0, 3) != 'zip') {
1124         if ($action == 'pdf')
1125             $ErrorManager->setPostponedErrorMask(-1); // everything
1126         //else // reject postponing of warnings
1127         //    $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
1128     }
1129
1130     /*
1131      * Allow for disabling of markup cache.
1132      * (Mostly for debugging ... hopefully.)
1133      *
1134      * See also <?plugin WikiAdminUtils action=purge-cache ?>
1135      */
1136     if (!defined('WIKIDB_NOCACHE_MARKUP') and $request->getArg('nocache'))
1137         define('WIKIDB_NOCACHE_MARKUP', $request->getArg('nocache'));
1138     
1139     // Initialize with system defaults in case user not logged in.
1140     // Should this go into constructor?
1141     $request->initializeTheme();
1142
1143     $request->updateAuthAndPrefs();
1144     $request->initializeLang();
1145     
1146     //FIXME:
1147     //if ($user->is_authenticated())
1148     //  $LogEntry->user = $user->getId();
1149
1150     // Memory optimization:
1151     // http://www.procata.com/blog/archives/2004/05/27/rephlux-and-php-memory-usage/
1152     // kill the global PEAR _PEAR_destructor_object_list
1153     if (!empty($_PEAR_destructor_object_list))
1154         $_PEAR_destructor_object_list = array();
1155     $request->possiblyDeflowerVirginWiki();
1156     
1157 // hack! define proper actions for these.
1158 if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
1159 if (defined('WIKI_SOAP')   and WIKI_SOAP)   return;
1160
1161     $validators = array('wikiname' => WIKI_NAME,
1162                         'args'     => hash($request->getArgs()),
1163                         'prefs'    => hash($request->getPrefs()));
1164     if (CACHE_CONTROL == 'STRICT') {
1165         $dbi = $request->getDbh();
1166         $timestamp = $dbi->getTimestamp();
1167         $validators['mtime'] = $timestamp;
1168         $validators['%mtime'] = (int)$timestamp;
1169     }
1170     // FIXME: we should try to generate strong validators when possible,
1171     // but for now, our validator is weak, since equal validators do not
1172     // indicate byte-level equality of content.  (Due to DEBUG timing output, etc...)
1173     //
1174     // (If DEBUG if off, this may be a strong validator, but I'm going
1175     // to go the paranoid route here pending further study and testing.)
1176     //
1177     $validators['%weak'] = true;
1178     $request->setValidators($validators);
1179    
1180     $request->handleAction();
1181
1182     if (DEBUG and DEBUG & _DEBUG_INFO) phpinfo(INFO_VARIABLES | INFO_MODULES);
1183     $request->finish();
1184 }
1185
1186 //$x = error_reporting();  // DEBUG: why is it 1 here? should be E_ALL
1187 if (defined('E_STRICT') and (E_ALL & E_STRICT)) // strict php5?
1188     error_reporting(E_ALL & ~E_STRICT);         // exclude E_STRICT
1189 else
1190     error_reporting(E_ALL); // php4
1191 // don't run the main loop for special requests (test, getimg, xmlrpc, soap, ...)
1192 if (!defined('PHPWIKI_NOMAIN') or !PHPWIKI_NOMAIN)
1193     main();
1194
1195
1196 // $Log: not supported by cvs2svn $
1197 // Revision 1.200  2004/12/26 17:08:36  rurban
1198 // php5 fixes: case-sensitivity, no & new
1199 //
1200 // Revision 1.199  2004/12/19 00:58:01  rurban
1201 // Enforce PASSWORD_LENGTH_MINIMUM in almost all PassUser checks,
1202 // Provide an errormessage if so. Just PersonalPage and BogoLogin not.
1203 // Simplify httpauth logout handling and set sessions for all methods.
1204 // fix main.php unknown index "x" getLevelDescription() warning.
1205 //
1206 // Revision 1.198  2004/12/17 16:49:51  rurban
1207 // avoid Invalid username message on Sign In button click
1208 //
1209 // Revision 1.197  2004/12/17 16:39:55  rurban
1210 // enable sessions for HttpAuth
1211 //
1212 // Revision 1.196  2004/12/10 02:36:43  rurban
1213 // More help with the new native xmlrpc lib. no warnings, no user cookie on xmlrpc.
1214 //
1215 // Revision 1.195  2004/12/09 22:24:44  rurban
1216 // optimize on _DEBUG_SQL only. but now again on every 50th request, not just save.
1217 //
1218 // Revision 1.194  2004/11/30 17:46:49  rurban
1219 // added ModeratedPage POST action hook (part 2/3)
1220 //
1221 // Revision 1.193  2004/11/30 07:51:08  rurban
1222 // fixed SESSION_SAVE_PATH warning msg
1223 //
1224 // Revision 1.192  2004/11/21 11:59:20  rurban
1225 // remove final \n to be ob_cache independent
1226 //
1227 // Revision 1.191  2004/11/19 19:22:03  rurban
1228 // ModeratePage part1: change status
1229 //
1230 // Revision 1.190  2004/11/15 15:56:40  rurban
1231 // don't load PagePerm on ENABLE_PAGEPERM = false to save memory. Move mayAccessPage() to main.php
1232 //
1233 // Revision 1.189  2004/11/09 17:11:16  rurban
1234 // * revert to the wikidb ref passing. there's no memory abuse there.
1235 // * use new wikidb->_cache->_id_cache[] instead of wikidb->_iwpcache, to effectively
1236 //   store page ids with getPageLinks (GleanDescription) of all existing pages, which
1237 //   are also needed at the rendering for linkExistingWikiWord().
1238 //   pass options to pageiterator.
1239 //   use this cache also for _get_pageid()
1240 //   This saves about 8 SELECT count per page (num all pagelinks).
1241 // * fix passing of all page fields to the pageiterator.
1242 // * fix overlarge session data which got broken with the latest ACCESS_LOG_SQL changes
1243 //
1244 // Revision 1.188  2004/11/07 16:02:52  rurban
1245 // new sql access log (for spam prevention), and restructured access log class
1246 // dbh->quote (generic)
1247 // pear_db: mysql specific parts seperated (using replace)
1248 //
1249 // Revision 1.187  2004/11/05 22:08:52  rurban
1250 // Ok: Fix loading all required userclasses beforehand. This is much slower than before but safes a few bytes RAM
1251 //
1252 // Revision 1.186  2004/11/05 20:53:35  rurban
1253 // login cleanup: better debug msg on failing login,
1254 // checked password less immediate login (bogo or anon),
1255 // checked olduser pref session error,
1256 // better PersonalPage without password warning on minimal password length=0
1257 //   (which is default now)
1258 //
1259 // Revision 1.185  2004/11/01 13:55:05  rurban
1260 // fix against switching user new/old between sessions
1261 //
1262 // Revision 1.184  2004/11/01 10:43:57  rurban
1263 // seperate PassUser methods into seperate dir (memory usage)
1264 // fix WikiUser (old) overlarge data session
1265 // remove wikidb arg from various page class methods, use global ->_dbi instead
1266 // ...
1267 //
1268 // Revision 1.183  2004/10/14 19:23:58  rurban
1269 // remove debugging prints
1270 //
1271 // Revision 1.182  2004/10/12 13:13:19  rurban
1272 // php5 compatibility (5.0.1 ok)
1273 //
1274 // Revision 1.181  2004/10/07 16:08:58  rurban
1275 // fixed broken FileUser session handling.
1276 //   thanks to Arnaud Fontaine for detecting this.
1277 // enable file user Administrator membership.
1278 //
1279 // Revision 1.180  2004/10/04 23:39:34  rurban
1280 // just aesthetics
1281 //
1282 // Revision 1.179  2004/09/25 18:57:42  rurban
1283 // better ACL error message: view not browse, change not setacl, ...
1284 //
1285 // Revision 1.178  2004/09/25 16:27:36  rurban
1286 // better not allowed description: on global disallowed, and on missing pageperms
1287 //
1288 // Revision 1.177  2004/09/14 10:31:09  rurban
1289 // exclude E_STRICT for php5: untested. I believe this must be set earlier because the parsing step is already strict, and this is called at run-time
1290 //
1291 // Revision 1.176  2004/08/05 17:33:22  rurban
1292 // aesthetic typo
1293 //
1294 // Revision 1.175  2004/07/13 13:08:25  rurban
1295 // fix PEAR memory waste issues
1296 //
1297 // Revision 1.174  2004/07/08 13:50:32  rurban
1298 // various unit test fixes: print error backtrace on _DEBUG_TRACE; allusers fix; new PHPWIKI_NOMAIN constant for omitting the mainloop
1299 //
1300 // Revision 1.173  2004/07/05 12:57:54  rurban
1301 // add mysql timeout
1302 //
1303 // Revision 1.172  2004/07/03 08:04:19  rurban
1304 // fixed implicit PersonalPage login (e.g. on edit), fixed to check against create ACL on create, not edit
1305 //
1306 // Revision 1.171  2004/06/29 09:30:42  rurban
1307 // force string hash
1308 //
1309 // Revision 1.170  2004/06/25 14:29:20  rurban
1310 // WikiGroup refactoring:
1311 //   global group attached to user, code for not_current user.
1312 //   improved helpers for special groups (avoid double invocations)
1313 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
1314 // fixed a XHTML validation error on userprefs.tmpl
1315 //
1316 // Revision 1.169  2004/06/20 14:42:54  rurban
1317 // various php5 fixes (still broken at blockparser)
1318 //
1319 // Revision 1.168  2004/06/17 10:39:18  rurban
1320 // fix reverse translation of possible actionpage
1321 //
1322 // Revision 1.167  2004/06/16 13:21:16  rurban
1323 // stabilize on failing ldap queries or bind
1324 //
1325 // Revision 1.166  2004/06/15 09:15:52  rurban
1326 // IMPORTANT: fixed passwd handling for passwords stored in prefs:
1327 //   fix encrypted usage, actually store and retrieve them from db
1328 //   fix bogologin with passwd set.
1329 // fix php crashes with call-time pass-by-reference (references wrongly used
1330 //   in declaration AND call). This affected mainly Apache2 and IIS.
1331 //   (Thanks to John Cole to detect this!)
1332 //
1333 // Revision 1.165  2004/06/14 11:31:37  rurban
1334 // renamed global $Theme to $WikiTheme (gforge nameclash)
1335 // inherit PageList default options from PageList
1336 //   default sortby=pagename
1337 // use options in PageList_Selectable (limit, sortby, ...)
1338 // added action revert, with button at action=diff
1339 // added option regex to WikiAdminSearchReplace
1340 //
1341 // Revision 1.164  2004/06/13 13:54:25  rurban
1342 // Catch fatals on the four dump calls (as file and zip, as html and mimified)
1343 // FoafViewer: Check against external requirements, instead of fatal.
1344 // Change output for xhtmldumps: using file:// urls to the local fs.
1345 // Catch SOAP fatal by checking for GOOGLE_LICENSE_KEY
1346 // Import GOOGLE_LICENSE_KEY and FORTUNE_DIR from config.ini.
1347 //
1348 // Revision 1.163  2004/06/13 11:35:32  rurban
1349 // check for create action on action=edit not to fool PagePerm checks
1350 //
1351 // Revision 1.162  2004/06/08 10:05:11  rurban
1352 // simplified admin action shortcuts
1353 //
1354 // Revision 1.161  2004/06/07 22:58:40  rurban
1355 // simplified chown, setacl, dump actions
1356 //
1357 // Revision 1.160  2004/06/07 22:44:14  rurban
1358 // added simplified chown, setacl actions
1359 //
1360 // Revision 1.159  2004/06/06 16:58:51  rurban
1361 // added more required ActionPages for foreign languages
1362 // install now english ActionPages if no localized are found. (again)
1363 // fixed default anon user level to be 0, instead of -1
1364 //   (wrong "required administrator to view this page"...)
1365 //
1366 // Revision 1.158  2004/06/04 20:32:53  rurban
1367 // Several locale related improvements suggested by Pierrick Meignen
1368 // LDAP fix by John Cole
1369 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
1370 //
1371 // Revision 1.157  2004/06/04 12:40:21  rurban
1372 // Restrict valid usernames to prevent from attacks against external auth or compromise
1373 // possible holes.
1374 // Fix various WikiUser old issues with default IMAP,LDAP,POP3 configs. Removed these.
1375 // Fxied more warnings
1376 //
1377 // Revision 1.156  2004/06/03 17:58:16  rurban
1378 // support immediate LANG and THEME switch inside a session
1379 //
1380 // Revision 1.155  2004/06/03 10:18:19  rurban
1381 // fix FileUser locking issues, new config ENABLE_PAGEPERM
1382 //
1383 // Revision 1.154  2004/06/02 18:01:46  rurban
1384 // init global FileFinder to add proper include paths at startup
1385 //   adds PHPWIKI_DIR if started from another dir, lib/pear also
1386 // fix slashify for Windows
1387 // fix USER_AUTH_POLICY=old, use only USER_AUTH_ORDER methods (besides HttpAuth)
1388 //
1389 // Revision 1.153  2004/06/01 15:28:00  rurban
1390 // AdminUser only ADMIN_USER not member of Administrators
1391 // some RateIt improvements by dfrankow
1392 // edit_toolbar buttons
1393 //
1394 // Revision 1.152  2004/05/27 17:49:06  rurban
1395 // renamed DB_Session to DbSession (in CVS also)
1396 // added WikiDB->getParam and WikiDB->getAuthParam method to get rid of globals
1397 // remove leading slash in error message
1398 // added force_unlock parameter to File_Passwd (no return on stale locks)
1399 // fixed adodb session AffectedRows
1400 // added FileFinder helpers to unify local filenames and DATA_PATH names
1401 // editpage.php: new edit toolbar javascript on ENABLE_EDIT_TOOLBAR
1402 //
1403 // Revision 1.151  2004/05/25 12:40:48  rurban
1404 // trim the pagename
1405 //
1406 // Revision 1.150  2004/05/25 10:18:44  rurban
1407 // Check for UTF-8 URLs; Internet Explorer produces these if you
1408 // type non-ASCII chars in the URL bar or follow unescaped links.
1409 // Fixes sf.net bug #953949
1410 // src: languages/Language.php:checkTitleEncoding() from mediawiki
1411 //
1412 // Revision 1.149  2004/05/18 13:31:19  rurban
1413 // hold warnings until headers are sent. new Error-style with collapsed output of repeated messages
1414 //
1415 // Revision 1.148  2004/05/17 17:43:29  rurban
1416 // CGI: no PATH_INFO fix
1417 //
1418 // Revision 1.147  2004/05/15 19:48:33  rurban
1419 // fix some too loose PagePerms for signed, but not authenticated users
1420 //  (admin, owner, creator)
1421 // no double login page header, better login msg.
1422 // moved action_pdf to lib/pdf.php
1423 //
1424 // Revision 1.146  2004/05/15 18:31:01  rurban
1425 // some action=pdf Request fixes: With MSIE it works now. Now the work with the page formatting begins.
1426 //
1427 // Revision 1.145  2004/05/12 10:49:55  rurban
1428 // require_once fix for those libs which are loaded before FileFinder and
1429 //   its automatic include_path fix, and where require_once doesn't grok
1430 //   dirname(__FILE__) != './lib'
1431 // upgrade fix with PearDB
1432 // navbar.tmpl: remove spaces for IE &nbsp; button alignment
1433 //
1434 // Revision 1.144  2004/05/06 19:26:16  rurban
1435 // improve stability, trying to find the InlineParser endless loop on sf.net
1436 //
1437 // remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
1438 //
1439 // Revision 1.143  2004/05/06 17:30:38  rurban
1440 // CategoryGroup: oops, dos2unix eol
1441 // improved phpwiki_version:
1442 //   pre -= .0001 (1.3.10pre: 1030.099)
1443 //   -p1 += .001 (1.3.9-p1: 1030.091)
1444 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1445 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1446 //   backend->backendType(), backend->database(),
1447 //   backend->listOfFields(),
1448 //   backend->listOfTables(),
1449 //
1450 // Revision 1.142  2004/05/04 22:34:25  rurban
1451 // more pdf support
1452 //
1453 // Revision 1.141  2004/05/03 13:16:47  rurban
1454 // fixed UserPreferences update, esp for boolean and int
1455 //
1456 // Revision 1.140  2004/05/02 21:26:38  rurban
1457 // limit user session data (HomePageHandle and auth_dbi have to invalidated anyway)
1458 //   because they will not survive db sessions, if too large.
1459 // extended action=upgrade
1460 // some WikiTranslation button work
1461 // revert WIKIAUTH_UNOBTAINABLE (need it for main.php)
1462 // some temp. session debug statements
1463 //
1464 // Revision 1.139  2004/05/02 15:10:07  rurban
1465 // new finally reliable way to detect if /index.php is called directly
1466 //   and if to include lib/main.php
1467 // new global AllActionPages
1468 // SetupWiki now loads all mandatory pages: HOME_PAGE, action pages, and warns if not.
1469 // WikiTranslation what=buttons for Carsten to create the missing MacOSX buttons
1470 // PageGroupTestOne => subpages
1471 // renamed PhpWikiRss to PhpWikiRecentChanges
1472 // more docs, default configs, ...
1473 //
1474 // Revision 1.138  2004/05/01 15:59:29  rurban
1475 // more php-4.0.6 compatibility: superglobals
1476 //
1477 // Revision 1.137  2004/04/29 19:39:44  rurban
1478 // special support for formatted plugins (one-liners)
1479 //   like <small><plugin BlaBla ></small>
1480 // iter->asArray() helper for PopularNearby
1481 // db_session for older php's (no &func() allowed)
1482 //
1483 // Revision 1.136  2004/04/29 17:18:19  zorloc
1484 // Fixes permission failure issues.  With PagePermissions and Disabled Actions when user did not have permission WIKIAUTH_FORBIDDEN was returned.  In WikiUser this was ok because WIKIAUTH_FORBIDDEN had a value of 11 -- thus no user could perform that action.  But WikiUserNew has a WIKIAUTH_FORBIDDEN value of -1 -- thus a user without sufficent permission to do anything.  The solution is a new high value permission level (WIKIAUTH_UNOBTAINABLE) to be the default level for access failure.
1485 //
1486 // Revision 1.135  2004/04/26 12:15:01  rurban
1487 // check default config values
1488 //
1489 // Revision 1.134  2004/04/23 06:46:37  zorloc
1490 // Leave DB connection open when USE_DB_SESSION is true so that session info can be written to the DB.
1491 //
1492 // Revision 1.133  2004/04/20 18:10:31  rurban
1493 // config refactoring:
1494 //   FileFinder is needed for WikiFarm scripts calling index.php
1495 //   config run-time calls moved to lib/IniConfig.php:fix_configs()
1496 //   added PHPWIKI_DIR smart-detection code (Theme finder)
1497 //   moved FileFind to lib/FileFinder.php
1498 //   cleaned lib/config.php
1499 //
1500 // Revision 1.132  2004/04/19 21:51:41  rurban
1501 // php5 compatibility: it works!
1502 //
1503 // Revision 1.131  2004/04/19 18:27:45  rurban
1504 // Prevent from some PHP5 warnings (ref args, no :: object init)
1505 //   php5 runs now through, just one wrong XmlElement object init missing
1506 // Removed unneccesary UpgradeUser lines
1507 // Changed WikiLink to omit version if current (RecentChanges)
1508 //
1509 // Revision 1.130  2004/04/18 00:25:53  rurban
1510 // allow "0" pagename
1511 //
1512 // Revision 1.129  2004/04/07 23:13:19  rurban
1513 // fixed pear/File_Passwd for Windows
1514 // fixed FilePassUser sessions (filehandle revive) and password update
1515 //
1516 // Revision 1.128  2004/04/02 15:06:55  rurban
1517 // fixed a nasty ADODB_mysql session update bug
1518 // improved UserPreferences layout (tabled hints)
1519 // fixed UserPreferences auth handling
1520 // improved auth stability
1521 // improved old cookie handling: fixed deletion of old cookies with paths
1522 //
1523 // Revision 1.127  2004/03/25 17:00:31  rurban
1524 // more code to convert old-style pref array to new hash
1525 //
1526 // Revision 1.126  2004/03/24 19:39:03  rurban
1527 // php5 workaround code (plus some interim debugging code in XmlElement)
1528 //   php5 doesn't work yet with the current XmlElement class constructors,
1529 //   WikiUserNew does work better than php4.
1530 // rewrote WikiUserNew user upgrading to ease php5 update
1531 // fixed pref handling in WikiUserNew
1532 // added Email Notification
1533 // added simple Email verification
1534 // removed emailVerify userpref subclass: just a email property
1535 // changed pref binary storage layout: numarray => hash of non default values
1536 // print optimize message only if really done.
1537 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
1538 //   prefs should be stored in db or homepage, besides the current session.
1539 //
1540 // Revision 1.125  2004/03/14 16:30:52  rurban
1541 // db-handle session revivification, dba fixes
1542 //
1543 // Revision 1.124  2004/03/12 15:48:07  rurban
1544 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
1545 // simplified lib/stdlib.php:explodePageList
1546 //
1547 // Revision 1.123  2004/03/10 15:41:27  rurban
1548 // use default pref mysql table
1549 //
1550 // Revision 1.122  2004/03/08 18:17:09  rurban
1551 // added more WikiGroup::getMembersOf methods, esp. for special groups
1552 // fixed $LDAP_SET_OPTIONS
1553 // fixed _AuthInfo group methods
1554 //
1555 // Revision 1.121  2004/03/01 13:48:45  rurban
1556 // rename fix
1557 // p[] consistency fix
1558 //
1559 // Revision 1.120  2004/03/01 10:22:41  rurban
1560 // initializeTheme optimize
1561 //
1562 // Revision 1.119  2004/02/26 20:45:06  rurban
1563 // check for ALLOW_ANON_USER = false
1564 //
1565 // Revision 1.118  2004/02/26 01:32:03  rurban
1566 // fixed session login with old WikiUser object. strangely, the errormask gets corruoted to 1, Pear???
1567 //
1568 // Revision 1.117  2004/02/24 17:19:37  rurban
1569 // debugging helpers only
1570 //
1571 // Revision 1.116  2004/02/24 15:17:14  rurban
1572 // improved auth errors with individual pages. the fact that you may not browse a certain admin page does not conclude that you may not browse the whole wiki. renamed browse => view
1573 //
1574 // Revision 1.115  2004/02/15 21:34:37  rurban
1575 // PageList enhanced and improved.
1576 // fixed new WikiAdmin... plugins
1577 // editpage, Theme with exp. htmlarea framework
1578 //   (htmlarea yet committed, this is really questionable)
1579 // WikiUser... code with better session handling for prefs
1580 // enhanced UserPreferences (again)
1581 // RecentChanges for show_deleted: how should pages be deleted then?
1582 //
1583 // Revision 1.114  2004/02/15 17:30:13  rurban
1584 // workaround for lost db connnection handle on session restauration (->_auth_dbi)
1585 // fixed getPreferences() (esp. from sessions)
1586 // fixed setPreferences() (update and set),
1587 // fixed AdoDb DB statements,
1588 // update prefs only at UserPreferences POST (for testing)
1589 // unified db prefs methods (but in external pref classes yet)
1590 //
1591 // Revision 1.113  2004/02/12 13:05:49  rurban
1592 // Rename functional for PearDB backend
1593 // some other minor changes
1594 // SiteMap comes with a not yet functional feature request: includepages (tbd)
1595 //
1596 // Revision 1.112  2004/02/09 03:58:12  rurban
1597 // for now default DB_SESSION to false
1598 // PagePerm:
1599 //   * not existing perms will now query the parent, and not
1600 //     return the default perm
1601 //   * added pagePermissions func which returns the object per page
1602 //   * added getAccessDescription
1603 // WikiUserNew:
1604 //   * added global ->prepare (not yet used) with smart user/pref/member table prefixing.
1605 //   * force init of authdbh in the 2 db classes
1606 // main:
1607 //   * fixed session handling (not triple auth request anymore)
1608 //   * don't store cookie prefs with sessions
1609 // stdlib: global obj2hash helper from _AuthInfo, also needed for PagePerm
1610 //
1611 // Revision 1.111  2004/02/07 10:41:25  rurban
1612 // fixed auth from session (still double code but works)
1613 // fixed GroupDB
1614 // fixed DbPassUser upgrade and policy=old
1615 // added GroupLdap
1616 //
1617 // Revision 1.110  2004/02/03 09:45:39  rurban
1618 // LDAP cleanup, start of new Pref classes
1619 //
1620 // Revision 1.109  2004/01/30 19:57:58  rurban
1621 // fixed DBAuthParams['pref_select']: wrong _auth_dbi object used.
1622 //
1623 // Revision 1.108  2004/01/28 14:34:14  rurban
1624 // session table takes the common prefix
1625 // + various minor stuff
1626 // reallow password changing
1627 //
1628 // Revision 1.107  2004/01/27 23:23:39  rurban
1629 // renamed ->Username => _userid for consistency
1630 // renamed mayCheckPassword => mayCheckPass
1631 // fixed recursion problem in WikiUserNew
1632 // fixed bogo login (but not quite 100% ready yet, password storage)
1633 //
1634 // Revision 1.106  2004/01/26 09:17:49  rurban
1635 // * changed stored pref representation as before.
1636 //   the array of objects is 1) bigger and 2)
1637 //   less portable. If we would import packed pref
1638 //   objects and the object definition was changed, PHP would fail.
1639 //   This doesn't happen with an simple array of non-default values.
1640 // * use $prefs->retrieve and $prefs->store methods, where retrieve
1641 //   understands the interim format of array of objects also.
1642 // * simplified $prefs->get() and fixed $prefs->set()
1643 // * added $user->_userid and class '_WikiUser' portability functions
1644 // * fixed $user object ->_level upgrading, mostly using sessions.
1645 //   this fixes yesterdays problems with loosing authorization level.
1646 // * fixed WikiUserNew::checkPass to return the _level
1647 // * fixed WikiUserNew::isSignedIn
1648 // * added explodePageList to class PageList, support sortby arg
1649 // * fixed UserPreferences for WikiUserNew
1650 // * fixed WikiPlugin for empty defaults array
1651 // * UnfoldSubpages: added pagename arg, renamed pages arg,
1652 //   removed sort arg, support sortby arg
1653 //
1654 // Revision 1.105  2004/01/25 03:57:15  rurban
1655 // WikiUserNew support (temp. ENABLE_USER_NEW constant)
1656 //
1657 // Revision 1.104  2003/12/26 06:41:16  carstenklapp
1658 // Bugfix: Try to defer OS errors about session.save_path and ACCESS_LOG,
1659 // so they don't prevent IE from partially (or not at all) rendering the
1660 // page. This should help a little for the IE user who encounters trouble
1661 // when setting up a new PhpWiki for the first time.
1662 //
1663 // Revision 1.103  2003/12/02 00:10:00  carstenklapp
1664 // Bugfix: Ongoing work to untangle UserPreferences/WikiUser/request code
1665 // mess: UserPreferences should take effect immediately now upon signing
1666 // in.
1667 //
1668 // Revision 1.102  2003/11/25 22:55:32  carstenklapp
1669 // Localization bugfix: For wikis where English is not the default system
1670 // language, make sure that the authority error message (i.e. "You must
1671 // sign in to edit pages in this wiki" etc.) is displayed in the wiki's
1672 // default language. Previously it would always display in English.
1673 // (Added call to update_locale() before displaying any messages prior to
1674 // the login prompt.)
1675 //
1676 // Revision 1.101  2003/11/25 21:49:44  carstenklapp
1677 // Bugfix: For a non-english wiki or when the user's preference is not
1678 // english, the wiki would always use the english ActionPage first if it
1679 // was present rather than the appropriate localised variant. (PhpWikis
1680 // running only in english or Wikis running ONLY without any english
1681 // ActionPages would not notice this bug, only when both english and
1682 // localised ActionPages were in the DB.) Now we check for the localised
1683 // variant first.
1684 //
1685 // Revision 1.100  2003/11/18 16:54:18  carstenklapp
1686 // Reformatting only: Tabs to spaces, added rcs log.
1687 //
1688
1689
1690 // Local Variables:
1691 // mode: php
1692 // tab-width: 8
1693 // c-basic-offset: 4
1694 // c-hanging-comment-ender-p: nil
1695 // indent-tabs-mode: nil
1696 // End:
1697 ?>