From a3e09f418f251bedac53bbf884e4700b1dc71494 Mon Sep 17 00:00:00 2001 From: vargenau Date: Fri, 5 Oct 2012 16:47:39 +0000 Subject: [PATCH] Reformat code git-svn-id: svn://svn.code.sf.net/p/phpwiki/code/trunk@8397 96ab9672-09ca-45d6-a79d-3d69d39ca109 --- lib/plugin/AddComment.php | 82 +-- lib/plugin/AllPages.php | 96 +-- lib/plugin/AllUsers.php | 37 +- lib/plugin/AnalyseAccessLogSql.php | 439 +++++++------ lib/plugin/AppendText.php | 60 +- lib/plugin/AsciiMath.php | 36 +- lib/plugin/AsciiSVG.php | 48 +- lib/plugin/AtomFeed.php | 28 +- lib/plugin/AuthorHistory.php | 124 ++-- lib/plugin/BackLinks.php | 111 ++-- lib/plugin/BlogArchives.php | 65 +- lib/plugin/BlogJournal.php | 45 +- lib/plugin/BoxRight.php | 19 +- lib/plugin/CacheTest.php | 46 +- lib/plugin/Calendar.php | 162 ++--- lib/plugin/CalendarList.php | 136 ++-- lib/plugin/CategoryPage.php | 44 +- lib/plugin/Chart.php | 80 ++- lib/plugin/Comment.php | 18 +- lib/plugin/CreateBib.php | 65 +- lib/plugin/CreatePage.php | 47 +- lib/plugin/CreateToc.php | 373 ++++++----- lib/plugin/CurrentTime.php | 20 +- lib/plugin/DeadEndPages.php | 9 +- lib/plugin/Diff.php | 120 ++-- lib/plugin/DynamicIncludePage.php | 66 +- lib/plugin/EditMetaData.php | 88 +-- lib/plugin/ExternalSearch.php | 87 +-- lib/plugin/FacebookLike.php | 73 ++- lib/plugin/FileInfo.php | 209 +++--- lib/plugin/FoafViewer.php | 207 +++--- lib/plugin/FrameInclude.php | 76 ++- lib/plugin/FullTextSearch.php | 80 ++- lib/plugin/FuzzyPages.php | 99 +-- lib/plugin/GoTo.php | 36 +- lib/plugin/GoogleMaps.php | 94 +-- lib/plugin/GooglePlugin.php | 85 +-- lib/plugin/GraphViz.php | 238 +++---- lib/plugin/HelloWorld.php | 22 +- lib/plugin/HtmlConverter.php | 174 ++--- lib/plugin/Imdb.php | 42 +- lib/plugin/IncludePage.php | 75 ++- lib/plugin/IncludePages.php | 28 +- lib/plugin/IncludeSiteMap.php | 50 +- lib/plugin/IncludeTree.php | 52 +- lib/plugin/InterWikiSearch.php | 119 ++-- lib/plugin/JabberPresence.php | 36 +- lib/plugin/LdapSearch.php | 112 ++-- lib/plugin/LikePages.php | 52 +- lib/plugin/LinkDatabase.php | 104 +-- lib/plugin/LinkSearch.php | 132 ++-- lib/plugin/ListPages.php | 50 +- lib/plugin/ListRelations.php | 31 +- lib/plugin/ListSubpages.php | 53 +- lib/plugin/MediawikiTable.php | 72 ++- lib/plugin/ModeratedPage.php | 266 ++++---- lib/plugin/MostPopular.php | 48 +- lib/plugin/NewPagesPerUser.php | 118 ++-- lib/plugin/NoCache.php | 20 +- lib/plugin/OldStyleTable.php | 56 +- lib/plugin/OrphanedPages.php | 46 +- lib/plugin/PageDump.php | 218 ++++--- lib/plugin/PageGroup.php | 96 +-- lib/plugin/PageHistory.php | 227 ++++--- lib/plugin/PageInfo.php | 29 +- lib/plugin/PageTrail.php | 30 +- lib/plugin/PasswordReset.php | 110 ++-- lib/plugin/PhotoAlbum.php | 531 ++++++++-------- lib/plugin/PhpHighlight.php | 60 +- lib/plugin/PhpWeather.php | 66 +- lib/plugin/Ploticus.php | 163 ++--- lib/plugin/PluginManager.php | 67 +- lib/plugin/PopUp.php | 86 +-- lib/plugin/PopularNearby.php | 99 +-- lib/plugin/PopularTags.php | 46 +- lib/plugin/PreferenceApp.php | 133 ++-- lib/plugin/PrevNext.php | 60 +- lib/plugin/Processing.php | 48 +- lib/plugin/RandomPage.php | 45 +- lib/plugin/RateIt.php | 201 +++--- lib/plugin/RawHtml.php | 174 ++--- lib/plugin/RecentChanges.php | 883 +++++++++++++++----------- lib/plugin/RecentChangesCached.php | 32 +- lib/plugin/RecentComments.php | 64 +- lib/plugin/RecentEdits.php | 18 +- lib/plugin/RecentReferrers.php | 49 +- lib/plugin/RedirectTo.php | 36 +- lib/plugin/RelatedChanges.php | 49 +- lib/plugin/RichTable.php | 53 +- lib/plugin/RssFeed.php | 83 +-- lib/plugin/SearchHighlight.php | 48 +- lib/plugin/SemanticRelations.php | 149 +++-- lib/plugin/SemanticSearch.php | 428 +++++++------ lib/plugin/SemanticSearchAdvanced.php | 139 ++-- lib/plugin/SiteMap.php | 85 +-- lib/plugin/SpellCheck.php | 59 +- lib/plugin/SqlResult.php | 104 +-- lib/plugin/SyncWiki.php | 177 +++--- lib/plugin/SyntaxHighlighter.php | 93 +-- lib/plugin/SystemInfo.php | 448 +++++++------ lib/plugin/TeX2png.php | 110 ++-- lib/plugin/Template.php | 89 +-- lib/plugin/TexToPng.php | 192 +++--- lib/plugin/TitleSearch.php | 43 +- lib/plugin/Transclude.php | 67 +- lib/plugin/TranslateText.php | 90 +-- lib/plugin/UnfoldSubpages.php | 130 ++-- lib/plugin/UpLoad.php | 167 +++-- lib/plugin/UriResolver.php | 23 +- lib/plugin/UserPreferences.php | 76 ++- lib/plugin/UserRatings.php | 135 ++-- lib/plugin/Video.php | 68 +- lib/plugin/VisualWiki.php | 328 +++++----- lib/plugin/WantedPages.php | 89 +-- lib/plugin/WantedPagesOld.php | 100 +-- lib/plugin/WatchPage.php | 91 +-- lib/plugin/WhoIsOnline.php | 151 +++-- lib/plugin/WikiAdminChmod.php | 103 +-- lib/plugin/WikiAdminChown.php | 89 +-- lib/plugin/WikiAdminMarkup.php | 82 +-- lib/plugin/WikiAdminPurge.php | 60 +- lib/plugin/WikiAdminRemove.php | 128 ++-- lib/plugin/WikiAdminRename.php | 205 +++--- lib/plugin/WikiAdminSearchReplace.php | 144 +++-- lib/plugin/WikiAdminSelect.php | 132 ++-- lib/plugin/WikiAdminSetAcl.php | 152 ++--- lib/plugin/WikiAdminSetAclSimple.php | 119 ++-- lib/plugin/WikiAdminSetExternal.php | 56 +- lib/plugin/WikiAdminUtils.php | 214 ++++--- lib/plugin/WikiBlog.php | 189 +++--- lib/plugin/WikiForm.php | 124 ++-- lib/plugin/WikiFormRich.php | 451 ++++++------- lib/plugin/WikiForum.php | 69 +- lib/plugin/WikiPoll.php | 295 +++++---- lib/plugin/WikicreoleTable.php | 97 +-- lib/plugin/YouTube.php | 170 ++--- lib/plugin/_AuthInfo.php | 142 +++-- lib/plugin/_BackendInfo.php | 121 ++-- lib/plugin/_GroupInfo.php | 34 +- lib/plugin/_PreferencesInfo.php | 22 +- lib/plugin/_Retransform.php | 41 +- lib/plugin/_WikiTranslation.php | 386 +++++------ lib/plugin/text2png.php | 113 ++-- 143 files changed, 9050 insertions(+), 7629 deletions(-) diff --git a/lib/plugin/AddComment.php b/lib/plugin/AddComment.php index f8d868209..6523ecbd1 100644 --- a/lib/plugin/AddComment.php +++ b/lib/plugin/AddComment.php @@ -33,14 +33,16 @@ include_once 'lib/plugin/WikiBlog.php'; class WikiPlugin_AddComment -extends WikiPlugin_WikiBlog + extends WikiPlugin_WikiBlog { - function getName () { + function getName() + { return _("AddComment"); } - function getDescription () { - return sprintf(_("Show and add comments for %s"),'[pagename]'); + function getDescription() + { + return sprintf(_("Show and add comments for %s"), '[pagename]'); } // Arguments: @@ -57,17 +59,19 @@ extends WikiPlugin_WikiBlog // jshide - boolean - quick javascript expansion of the comments // and addcomment box - function getDefaultArguments() { - return array('pagename' => '[pagename]', - 'order' => 'normal', - 'mode' => 'add,show', - 'jshide' => '0', - 'noheader' => false, - //'sortby' => '-pagename' // oldest first. reverse by order=reverse - ); + function getDefaultArguments() + { + return array('pagename' => '[pagename]', + 'order' => 'normal', + 'mode' => 'add,show', + 'jshide' => '0', + 'noheader' => false, + //'sortby' => '-pagename' // oldest first. reverse by order=reverse + ); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); if (!$args['pagename']) { return $this->error(sprintf(_("A required argument '%s' is missing."), 'pagename')); @@ -89,54 +93,56 @@ extends WikiPlugin_WikiBlog // for new comments $html = HTML(); if ($args['jshide']) { - $div = HTML::div(array('id'=>'comments','style'=>'display:none;')); + $div = HTML::div(array('id' => 'comments', 'style' => 'display:none;')); //$list->setAttr('style','display:none;'); $div->pushContent(Javascript(" function togglecomments(a) { comments=document.getElementById('comments'); if (comments.style.display=='none') { comments.style.display='block'; - a.title='"._("Click to hide the comments")."'; + a.title='" . _("Click to hide the comments") . "'; } else { comments.style.display='none'; - a.title='"._("Click to display all comments")."'; + a.title='" . _("Click to display all comments") . "'; } }")); - $html->pushContent(HTML::h4(HTML::a(array('name'=>'comment-header', - 'class'=>'wikiaction', - 'title'=>_("Click to display"), - 'onclick'=>"togglecomments(this)"), - _("Comments")))); + $html->pushContent(HTML::h4(HTML::a(array('name' => 'comment-header', + 'class' => 'wikiaction', + 'title' => _("Click to display"), + 'onclick' => "togglecomments(this)"), + _("Comments")))); } else { - $div = HTML::div(array('id'=>'comments')); + $div = HTML::div(array('id' => 'comments')); } foreach (explode(',', $args['mode']) as $show) { if (!empty($seen[$show])) continue; $seen[$show] = 1; switch ($show) { - case 'show': - $show = $this->showAll($request, $args, 'comment'); - //if ($args['jshide']) $show->setAttr('style','display:none;'); - $div->pushContent($show); - break; - case 'add': - global $WikiTheme; - if (!$WikiTheme->DUMP_MODE) { - $add = $this->showForm($request, $args, 'addcomment'); - //if ($args['jshide']) $add->setAttr('style','display:none;'); - $div->pushContent($add); - } - break; - default: - return $this->error(sprintf("Bad mode ('%s')", $show)); + case 'show': + $show = $this->showAll($request, $args, 'comment'); + //if ($args['jshide']) $show->setAttr('style','display:none;'); + $div->pushContent($show); + break; + case 'add': + global $WikiTheme; + if (!$WikiTheme->DUMP_MODE) { + $add = $this->showForm($request, $args, 'addcomment'); + //if ($args['jshide']) $add->setAttr('style','display:none;'); + $div->pushContent($add); + } + break; + default: + return $this->error(sprintf("Bad mode ('%s')", $show)); } } $html->pushContent($div); return $html; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/AllPages.php b/lib/plugin/AllPages.php index 3bec8699b..d9e87a638 100644 --- a/lib/plugin/AllPages.php +++ b/lib/plugin/AllPages.php @@ -28,27 +28,30 @@ require_once 'lib/PageList.php'; * AllPagesCreatedByMe, AllPagesOwnedByMe, AllPagesLastAuthoredByMe */ class WikiPlugin_AllPages -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("AllPages"); } - function getDescription () { + function getDescription() + { return _("List all pages in this wiki."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array_merge - ( - PageList::supportedArgs(), - array( - 'noheader' => false, - 'include_empty' => false, - 'info' => '', - 'debug' => false, - 'userpages' => false - )); + ( + PageList::supportedArgs(), + array( + 'noheader' => false, + 'include_empty' => false, + 'info' => '', + 'debug' => false, + 'userpages' => false + )); } // info arg allows multiple columns @@ -57,7 +60,8 @@ extends WikiPlugin // sortby: [+|-] pagename|mtime|hits // 2004-07-08 22:05:35 rurban: turned off &$request to prevent from strange bug below - function run($dbi, $argstr, $request, $basepage) { + function run($dbi, $argstr, $request, $basepage) + { $args = $this->getArgs($argstr, $request); $pages = false; @@ -67,55 +71,55 @@ extends WikiPlugin } $caption = _("All pages in this wiki (%d total):"); - if ( !empty($args['userpages']) ) { + if (!empty($args['userpages'])) { $pages = PageList::allUserPages($args['include_empty'], - $args['sortby'], '' - ); + $args['sortby'], '' + ); $caption = _("List of user-created pages (%d total):"); $args['count'] = $request->getArg('count'); - } elseif ( !empty($args['owner']) ) { + } elseif (!empty($args['owner'])) { $pages = PageList::allPagesByOwner($args['owner'], $args['include_empty'], - $args['sortby'], '' - ); + $args['sortby'], '' + ); $args['count'] = $request->getArg('count'); if (!$args['count']) $args['count'] = $dbi->numPages($args['include_empty'], $args['exclude']); $caption = fmt("List of pages owned by [%s] (%d total):", - WikiLink($args['owner'] == '[]' - ? $request->_user->getAuthenticatedId() - : $args['owner'], - 'if_known'), $args['count']); + WikiLink($args['owner'] == '[]' + ? $request->_user->getAuthenticatedId() + : $args['owner'], + 'if_known'), $args['count']); $pages->_options['count'] = $args['count']; - } elseif ( !empty($args['author']) ) { + } elseif (!empty($args['author'])) { $pages = PageList::allPagesByAuthor($args['author'], $args['include_empty'], - $args['sortby'], '' - ); + $args['sortby'], '' + ); $args['count'] = $request->getArg('count'); if (!$args['count']) $args['count'] = $dbi->numPages($args['include_empty'], $args['exclude']); $caption = fmt("List of pages last edited by [%s] (%d total):", - WikiLink($args['author'] == '[]' - ? $request->_user->getAuthenticatedId() - : $args['author'], - 'if_known'), $args['count']); + WikiLink($args['author'] == '[]' + ? $request->_user->getAuthenticatedId() + : $args['author'], + 'if_known'), $args['count']); $pages->_options['count'] = $args['count']; - } elseif ( !empty($args['creator']) ) { + } elseif (!empty($args['creator'])) { $pages = PageList::allPagesByCreator($args['creator'], $args['include_empty'], - $args['sortby'], '' - ); + $args['sortby'], '' + ); $args['count'] = $request->getArg('count'); if (!$args['count']) $args['count'] = $dbi->numPages($args['include_empty'], $args['exclude']); $caption = fmt("List of pages created by [%s] (%d total):", - WikiLink($args['creator'] == '[]' - ? $request->_user->getAuthenticatedId() - : $args['creator'], - 'if_known'), $args['count']); + WikiLink($args['creator'] == '[]' + ? $request->_user->getAuthenticatedId() + : $args['creator'], + 'if_known'), $args['count']); $pages->_options['count'] = $args['count']; - //} elseif ($pages) { - // $args['count'] = count($pages); + //} elseif ($pages) { + // $args['count'] = count($pages); } else { - if (! $request->getArg('count')) + if (!$request->getArg('count')) $args['count'] = $dbi->numPages($args['include_empty'], $args['exclude']); else $args['count'] = $request->getArg('count'); @@ -132,16 +136,18 @@ extends WikiPlugin if ($pages !== false) $pagelist->addPageList($pages); else - $pagelist->addPages( $dbi->getAllPages($args['include_empty'], $args['sortby'], - $args['limit']) ); + $pagelist->addPages($dbi->getAllPages($args['include_empty'], $args['sortby'], + $args['limit'])); if (DEBUG && $args['debug']) { return HTML($pagelist, - HTML::p(fmt("Elapsed time: %s s", $timer->getStats()))); + HTML::p(fmt("Elapsed time: %s s", $timer->getStats()))); } else { return $pagelist; } } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/AllUsers.php b/lib/plugin/AllUsers.php index 1c5c12551..c1458177a 100644 --- a/lib/plugin/AllUsers.php +++ b/lib/plugin/AllUsers.php @@ -31,25 +31,29 @@ require_once 'lib/PageList.php'; * externally authenticated users with a db users table, if auth_user_exists is defined. */ class WikiPlugin_AllUsers -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("AllUsers"); } - function getDescription() { + function getDescription() + { return _("List all once authenticated users."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array_merge - ( - PageList::supportedArgs(), - array('noheader' => false, - 'include_empty' => true, - 'debug' => false - )); + ( + PageList::supportedArgs(), + array('noheader' => false, + 'include_empty' => true, + 'debug' => false + )); } + // info arg allows multiple columns // info=mtime,hits,summary,version,author,locked,minor,markup or all // exclude arg allows multiple pagenames exclude=WikiAdmin,.SecretUser @@ -59,7 +63,8 @@ extends WikiPlugin // // sortby: [+|-] pagename|mtime|hits - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); extract($args); @@ -68,7 +73,7 @@ extends WikiPlugin } $group = $request->getGroup(); - if (method_exists($group,'_allUsers')) { + if (method_exists($group, '_allUsers')) { $allusers = $group->_allUsers(); } else { $allusers = array(); @@ -84,7 +89,7 @@ extends WikiPlugin if (!$pagesize) { $pagelist->addPageList($allusers); } else { - for ($i=$offset; $i < $offset + $pagesize - 1; $i++) { + for ($i = $offset; $i < $offset + $pagesize - 1; $i++) { if ($i >= $args['count']) break; $pagelist->addPage(trim($allusers[$i])); } @@ -99,12 +104,14 @@ extends WikiPlugin if (defined('DEBUG') && DEBUG and $debug) { return HTML($pagelist, - HTML::p(fmt("Elapsed time: %s s", $timer->getStats()))); + HTML::p(fmt("Elapsed time: %s s", $timer->getStats()))); } else { return $pagelist; } } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/AnalyseAccessLogSql.php b/lib/plugin/AnalyseAccessLogSql.php index 9325e903f..c8c9d8d6e 100644 --- a/lib/plugin/AnalyseAccessLogSql.php +++ b/lib/plugin/AnalyseAccessLogSql.php @@ -27,7 +27,7 @@ * To add a new query, see _getQueryString() */ class WikiPlugin_AnalyseAccessLogSql -extends WikiPlugin + extends WikiPlugin { /** * Build the query string @@ -53,7 +53,8 @@ extends WikiPlugin * ."WHERE referer IS NOT NULL " * .$where_conditions */ - function _getQueryString(&$args) { + function _getQueryString(&$args) + { // extract any parametrised conditions from the arguments, // in particular, how much history to select $where_conditions = $this->_getWhereConditions($args); @@ -61,202 +62,214 @@ extends WikiPlugin // get the correct name for the table //FIXME is there a more correct way to do this? global $DBParams, $request; - $accesslog = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '')."accesslog"; + $accesslog = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '') . "accesslog"; $query = ''; $backend_type = $request->_dbi->_backend->backendType(); switch ($backend_type) { - case 'mysql': - $Referring_URL = "left(referer,length(referer)-instr(reverse(referer),'?'))"; break; - case 'pgsql': - case 'postgres7': - $Referring_URL = "substr(referer,0,position('?' in referer))"; break; - default: - $Referring_URL = "referer"; - } - switch ($args['mode']) { - case 'referring_urls': - if ($where_conditions<>'') - $where_conditions = 'WHERE '.$where_conditions.' '; - $query = "SELECT " - . "$Referring_URL AS Referring_URL, " - . "count(*) AS Referral_Count " - . "FROM $accesslog " - . $where_conditions - . "GROUP BY Referring_URL"; - break; - case 'external_referers': - $args['local_referrers'] = 'false'; - $where_conditions = $this->_getWhereConditions($args); - if ($where_conditions<>'') - $where_conditions = 'WHERE '.$where_conditions.' '; - $query = "SELECT " - . "$Referring_URL AS Referring_URL, " - . "count(*) AS Referral_Count " - . "FROM $accesslog " - . $where_conditions - . "GROUP BY Referring_URL"; - break; - case 'referring_domains': - if ($where_conditions<>'') - $where_conditions = 'WHERE '.$where_conditions.' '; - switch ($backend_type) { case 'mysql': - $Referring_Domain = "left(referer, if(locate('/', referer, 8) > 0,locate('/', referer, 8) -1, length(referer)))"; break; - case 'pgsql': - case 'postgres7': - $Referring_Domain = "substr(referer,0,8) || regexp_replace(substr(referer,8), '/.*', '')"; break; - default: - $Referring_Domain = "referer"; break; - } - $query = "SELECT " - . "$Referring_Domain AS Referring_Domain, " - . "count(*) AS Referral_Count " - . "FROM $accesslog " - . $where_conditions - . "GROUP BY Referring_Domain"; - break; - case 'remote_hosts': - if ($where_conditions<>'') - $where_conditions = 'WHERE '.$where_conditions.' '; - $query = "SELECT " - ."remote_host AS Remote_Host, " - ."count(*) AS Access_Count " - ."FROM $accesslog " - .$where_conditions - ."GROUP BY Remote_Host"; - break; - case 'users': - if ($where_conditions<>'') - $where_conditions = 'WHERE '.$where_conditions.' '; - $query = "SELECT " - ."remote_user AS User, " - ."count(*) AS Access_Count " - ."FROM $accesslog " - .$where_conditions - ."GROUP BY remote_user"; - break; - case 'host_users': - if ($where_conditions<>'') - $where_conditions = 'WHERE '.$where_conditions.' '; - $query = "SELECT " - ."remote_host AS Remote_Host, " - ."remote_user AS User, " - ."count(*) AS Access_Count " - ."FROM $accesslog " - .$where_conditions - ."GROUP BY remote_host, remote_user"; - break; - case "search_bots": - // This queries for all entries in the SQL access log table that - // have a dns name that I know to be a web search engine crawler and - // categorises the results into time buckets as per the list below - // 0 - 1 minute - 60 - // 1 - 1 hour - 3600 = 60 * 60 - // 2 - 1 day - 86400 = 60 * 60 * 24 - // 3 - 1 week - 604800 = 60 * 60 * 24 * 7 - // 4 - 1 month - 2629800 = 60 * 60 * 24 * 365.25 / 12 - // 5 - 1 year - 31557600 = 60 * 60 * 24 * 365.25 - $now = time(); - $query = "SELECT " - ."CASE WHEN $now-time_stamp<60 THEN '"._("0 - last minute")."' ELSE " - ."CASE WHEN $now-time_stamp<3600 THEN '"._("1 - 1 minute to 1 hour")."' ELSE " - ."CASE WHEN $now-time_stamp<86400 THEN '"._("2 - 1 hour to 1 day")."' ELSE " - ."CASE WHEN $now-time_stamp<604800 THEN '"._("3 - 1 day to 1 week")."' ELSE " - ."CASE WHEN $now-time_stamp<2629800 THEN '"._("4 - 1 week to 1 month")."' ELSE " - ."CASE WHEN $now-time_stamp<31557600 THEN '"._("5 - 1 month to 1 year")."' ELSE " - ."'"._("6 - more than 1 year")."' END END END END END END AS Time_Scale, " - ."remote_host AS Remote_Host, " - ."count(*) AS Access_Count " - ."FROM $accesslog " - ."WHERE (remote_host LIKE '%googlebot.com' " - ."OR remote_host LIKE '%alexa.com' " - ."OR remote_host LIKE '%inktomisearch.com' " - ."OR remote_host LIKE '%msnbot.msn.com') " - .($where_conditions ? 'AND '.$where_conditions : '') - ."GROUP BY Time_Scale, remote_host"; - break; - case "search_bots_hits": - // This queries for all entries in the SQL access log table that - // have a dns name that I know to be a web search engine crawler and - // displays the URI that was hit. - // If PHPSESSID appears in the URI, just display the URI to the left of this - $sessname = session_name(); - switch ($backend_type) { - case 'mysql': - $Request_URI = "IF(instr(request_uri, '$sessname')=0, request_uri,left(request_uri, instr(request_uri, '$sessname')-2))"; + $Referring_URL = "left(referer,length(referer)-instr(reverse(referer),'?'))"; break; case 'pgsql': case 'postgres7': - $Request_URI = "regexp_replace(request_uri, '$sessname.*', '')"; break; + $Referring_URL = "substr(referer,0,position('?' in referer))"; + break; default: - $Request_URI = 'request_uri'; break; - } - $now = time(); - $query = "SELECT " - ."CASE WHEN $now-time_stamp<60 THEN '"._("0 - last minute")."' ELSE " - ."CASE WHEN $now-time_stamp<3600 THEN '"._("1 - 1 minute to 1 hour")."' ELSE " - ."CASE WHEN $now-time_stamp<86400 THEN '"._("2 - 1 hour to 1 day")."' ELSE " - ."CASE WHEN $now-time_stamp<604800 THEN '"._("3 - 1 day to 1 week")."' ELSE " - ."CASE WHEN $now-time_stamp<2629800 THEN '"._("4 - 1 week to 1 month")."' ELSE " - ."CASE WHEN $now-time_stamp<31557600 THEN '"._("5 - 1 month to 1 year")."' ELSE " - ."'"._("6 - more than 1 year")."' END END END END END END AS Time_Scale, " - ."remote_host AS Remote_Host, " - ."$Request_URI AS Request_URI " - ."FROM $accesslog " - ."WHERE (remote_host LIKE '%googlebot.com' " - ."OR remote_host LIKE '%alexa.com' " - ."OR remote_host LIKE '%inktomisearch.com' " - ."OR remote_host LIKE '%msnbot.msn.com') " - .($where_conditions ? 'AND '.$where_conditions : '') - ."ORDER BY time_stamp"; + $Referring_URL = "referer"; + } + switch ($args['mode']) { + case 'referring_urls': + if ($where_conditions <> '') + $where_conditions = 'WHERE ' . $where_conditions . ' '; + $query = "SELECT " + . "$Referring_URL AS Referring_URL, " + . "count(*) AS Referral_Count " + . "FROM $accesslog " + . $where_conditions + . "GROUP BY Referring_URL"; + break; + case 'external_referers': + $args['local_referrers'] = 'false'; + $where_conditions = $this->_getWhereConditions($args); + if ($where_conditions <> '') + $where_conditions = 'WHERE ' . $where_conditions . ' '; + $query = "SELECT " + . "$Referring_URL AS Referring_URL, " + . "count(*) AS Referral_Count " + . "FROM $accesslog " + . $where_conditions + . "GROUP BY Referring_URL"; + break; + case 'referring_domains': + if ($where_conditions <> '') + $where_conditions = 'WHERE ' . $where_conditions . ' '; + switch ($backend_type) { + case 'mysql': + $Referring_Domain = "left(referer, if(locate('/', referer, 8) > 0,locate('/', referer, 8) -1, length(referer)))"; + break; + case 'pgsql': + case 'postgres7': + $Referring_Domain = "substr(referer,0,8) || regexp_replace(substr(referer,8), '/.*', '')"; + break; + default: + $Referring_Domain = "referer"; + break; + } + $query = "SELECT " + . "$Referring_Domain AS Referring_Domain, " + . "count(*) AS Referral_Count " + . "FROM $accesslog " + . $where_conditions + . "GROUP BY Referring_Domain"; + break; + case 'remote_hosts': + if ($where_conditions <> '') + $where_conditions = 'WHERE ' . $where_conditions . ' '; + $query = "SELECT " + . "remote_host AS Remote_Host, " + . "count(*) AS Access_Count " + . "FROM $accesslog " + . $where_conditions + . "GROUP BY Remote_Host"; + break; + case 'users': + if ($where_conditions <> '') + $where_conditions = 'WHERE ' . $where_conditions . ' '; + $query = "SELECT " + . "remote_user AS User, " + . "count(*) AS Access_Count " + . "FROM $accesslog " + . $where_conditions + . "GROUP BY remote_user"; + break; + case 'host_users': + if ($where_conditions <> '') + $where_conditions = 'WHERE ' . $where_conditions . ' '; + $query = "SELECT " + . "remote_host AS Remote_Host, " + . "remote_user AS User, " + . "count(*) AS Access_Count " + . "FROM $accesslog " + . $where_conditions + . "GROUP BY remote_host, remote_user"; + break; + case "search_bots": + // This queries for all entries in the SQL access log table that + // have a dns name that I know to be a web search engine crawler and + // categorises the results into time buckets as per the list below + // 0 - 1 minute - 60 + // 1 - 1 hour - 3600 = 60 * 60 + // 2 - 1 day - 86400 = 60 * 60 * 24 + // 3 - 1 week - 604800 = 60 * 60 * 24 * 7 + // 4 - 1 month - 2629800 = 60 * 60 * 24 * 365.25 / 12 + // 5 - 1 year - 31557600 = 60 * 60 * 24 * 365.25 + $now = time(); + $query = "SELECT " + . "CASE WHEN $now-time_stamp<60 THEN '" . _("0 - last minute") . "' ELSE " + . "CASE WHEN $now-time_stamp<3600 THEN '" . _("1 - 1 minute to 1 hour") . "' ELSE " + . "CASE WHEN $now-time_stamp<86400 THEN '" . _("2 - 1 hour to 1 day") . "' ELSE " + . "CASE WHEN $now-time_stamp<604800 THEN '" . _("3 - 1 day to 1 week") . "' ELSE " + . "CASE WHEN $now-time_stamp<2629800 THEN '" . _("4 - 1 week to 1 month") . "' ELSE " + . "CASE WHEN $now-time_stamp<31557600 THEN '" . _("5 - 1 month to 1 year") . "' ELSE " + . "'" . _("6 - more than 1 year") . "' END END END END END END AS Time_Scale, " + . "remote_host AS Remote_Host, " + . "count(*) AS Access_Count " + . "FROM $accesslog " + . "WHERE (remote_host LIKE '%googlebot.com' " + . "OR remote_host LIKE '%alexa.com' " + . "OR remote_host LIKE '%inktomisearch.com' " + . "OR remote_host LIKE '%msnbot.msn.com') " + . ($where_conditions ? 'AND ' . $where_conditions : '') + . "GROUP BY Time_Scale, remote_host"; + break; + case "search_bots_hits": + // This queries for all entries in the SQL access log table that + // have a dns name that I know to be a web search engine crawler and + // displays the URI that was hit. + // If PHPSESSID appears in the URI, just display the URI to the left of this + $sessname = session_name(); + switch ($backend_type) { + case 'mysql': + $Request_URI = "IF(instr(request_uri, '$sessname')=0, request_uri,left(request_uri, instr(request_uri, '$sessname')-2))"; + break; + case 'pgsql': + case 'postgres7': + $Request_URI = "regexp_replace(request_uri, '$sessname.*', '')"; + break; + default: + $Request_URI = 'request_uri'; + break; + } + $now = time(); + $query = "SELECT " + . "CASE WHEN $now-time_stamp<60 THEN '" . _("0 - last minute") . "' ELSE " + . "CASE WHEN $now-time_stamp<3600 THEN '" . _("1 - 1 minute to 1 hour") . "' ELSE " + . "CASE WHEN $now-time_stamp<86400 THEN '" . _("2 - 1 hour to 1 day") . "' ELSE " + . "CASE WHEN $now-time_stamp<604800 THEN '" . _("3 - 1 day to 1 week") . "' ELSE " + . "CASE WHEN $now-time_stamp<2629800 THEN '" . _("4 - 1 week to 1 month") . "' ELSE " + . "CASE WHEN $now-time_stamp<31557600 THEN '" . _("5 - 1 month to 1 year") . "' ELSE " + . "'" . _("6 - more than 1 year") . "' END END END END END END AS Time_Scale, " + . "remote_host AS Remote_Host, " + . "$Request_URI AS Request_URI " + . "FROM $accesslog " + . "WHERE (remote_host LIKE '%googlebot.com' " + . "OR remote_host LIKE '%alexa.com' " + . "OR remote_host LIKE '%inktomisearch.com' " + . "OR remote_host LIKE '%msnbot.msn.com') " + . ($where_conditions ? 'AND ' . $where_conditions : '') + . "ORDER BY time_stamp"; } return $query; } /** Honeypot for xgettext. Those strings are translated dynamically. */ - function _locale_dummy() { + function _locale_dummy() + { $dummy = array( - // mode caption - _("referring_urls"), - _("external_referers"), - _("referring_domains"), - _("remote_hosts"), - _("users"), - _("host_users"), - _("search_bots"), - _("search_bots_hits"), - // period header - _("minutes"), - _("hours"), - _("days"), - _("weeks"), - ); + // mode caption + _("referring_urls"), + _("external_referers"), + _("referring_domains"), + _("remote_hosts"), + _("users"), + _("host_users"), + _("search_bots"), + _("search_bots_hits"), + // period header + _("minutes"), + _("hours"), + _("days"), + _("weeks"), + ); } - function getDefaultArguments() { + function getDefaultArguments() + { return array( - 'mode' => 'referring_domains', - // referring_domains, referring_urls, remote_hosts, users, host_users, search_bots, search_bots_hits - 'caption' => '', - // blank means use the mode as the caption/title for the output - 'local_referrers' => 'true', // only show external referring sites - 'period' => '', // the type of period to report: - // may be weeks, days, hours, minutes, or blank for all - 'count' => '0' // the number of periods to report - ); + 'mode' => 'referring_domains', + // referring_domains, referring_urls, remote_hosts, users, host_users, search_bots, search_bots_hits + 'caption' => '', + // blank means use the mode as the caption/title for the output + 'local_referrers' => 'true', // only show external referring sites + 'period' => '', // the type of period to report: + // may be weeks, days, hours, minutes, or blank for all + 'count' => '0' // the number of periods to report + ); } - function getName () { + function getName() + { return _("AnalyseAccessLogSql"); } - function getDescription () { + function getDescription() + { return _("Show summary information from the access log table."); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { // flag that the output may not be cached - i.e. it is dynamic $request->setArg('nocache', 1); @@ -274,24 +287,25 @@ extends WikiPlugin $query = $this->_getQueryString($args); - if ($query=='') - return HTML::p(sprintf( _("Unrecognised parameter 'mode=%s'"), - $args['mode'])); + if ($query == '') + return HTML::p(sprintf(_("Unrecognised parameter 'mode=%s'"), + $args['mode'])); // get the data back. // Note that this must be done before the final generation ofthe table, // otherwise the headers will not be ready $tbody = $this->_getQueryResults($query, $dbi); - return HTML::table(array('border' => 1, - 'cellspacing' => 1, - 'cellpadding' => 1), - HTML::caption(HTML::h1(HTML::br(),$this->_getCaption($args))), - HTML::thead($this->_theadrow), - $tbody); + return HTML::table(array('border' => 1, + 'cellspacing' => 1, + 'cellpadding' => 1), + HTML::caption(HTML::h1(HTML::br(), $this->_getCaption($args))), + HTML::thead($this->_theadrow), + $tbody); } - function _getQueryResults($query, &$dbi) { + function _getQueryResults($query, &$dbi) + { $queryResult = $dbi->genericSqlIter($query); if (!$queryResult) { $tbody = HTML::tbody(HTML::tr(HTML::td(_("")))); @@ -302,7 +316,7 @@ extends WikiPlugin $tr = HTML::tr(); foreach ($row as $value) { // output a '-' for empty values, otherwise the table looks strange - $tr->pushContent(HTML::td( empty($value) ? '-' : $value )); + $tr->pushContent(HTML::td(empty($value) ? '-' : $value)); } $tbody->pushContent($tr); } @@ -311,7 +325,8 @@ extends WikiPlugin return $tbody; } - function _setHeaders($row) { + function _setHeaders($row) + { if (!$this->_headerSet) { foreach ($row as $key => $value) { $this->_theadrow->pushContent(HTML::th(_($key))); @@ -320,63 +335,67 @@ extends WikiPlugin } } - function _getWhereConditions(&$args) { + function _getWhereConditions(&$args) + { $where_conditions = ''; - if ($args['period']<>'') { + if ($args['period'] <> '') { $since = 0; - if ($args['period']=='minutes') { + if ($args['period'] == 'minutes') { $since = 60; - } elseif ($args['period']=='hours') { + } elseif ($args['period'] == 'hours') { $since = 60 * 60; - } elseif ($args['period']=='days') { + } elseif ($args['period'] == 'days') { $since = 60 * 60 * 24; - } elseif ($args['period']=='weeks') { + } elseif ($args['period'] == 'weeks') { $since = 60 * 60 * 24 * 7; } $since = $since * $args['count']; - if ($since>0) { - if ($where_conditions<>'') - $where_conditions = $where_conditions.' AND '; + if ($since > 0) { + if ($where_conditions <> '') + $where_conditions = $where_conditions . ' AND '; $since = time() - $since; - $where_conditions = $where_conditions."time_stamp > $since"; + $where_conditions = $where_conditions . "time_stamp > $since"; } } - if ($args['local_referrers']<>'true') { + if ($args['local_referrers'] <> 'true') { global $request; - if ($where_conditions<>'') - $where_conditions = $where_conditions.' AND '; + if ($where_conditions <> '') + $where_conditions = $where_conditions . ' AND '; $localhost = SERVER_URL; $len = strlen($localhost); $backend_type = $request->_dbi->_backend->backendType(); switch ($backend_type) { - case 'mysql': - $ref_localhost = "left(referer,$len)<>'$localhost'"; break; - case 'pgsql': - case 'postgres7': - $ref_localhost = "substr(referer,0,$len)<>'$localhost'"; break; - default: - $ref_localhost = ""; + case 'mysql': + $ref_localhost = "left(referer,$len)<>'$localhost'"; + break; + case 'pgsql': + case 'postgres7': + $ref_localhost = "substr(referer,0,$len)<>'$localhost'"; + break; + default: + $ref_localhost = ""; } - $where_conditions = $where_conditions.$ref_localhost; + $where_conditions = $where_conditions . $ref_localhost; } // The assumed contract is that there is a space at the end of the // conditions string, so that following SQL clauses (such as GROUP BY) // will not cause a syntax error - if ($where_conditions<>'') - $where_conditions = $where_conditions.' '; + if ($where_conditions <> '') + $where_conditions = $where_conditions . ' '; return $where_conditions; } - function _getCaption(&$args) { + function _getCaption(&$args) + { $caption = $args['caption']; - if ($caption=='') + if ($caption == '') $caption = gettext($args['mode']); - if ($args['period']<>'' && $args['count']) - $caption = $caption." - ".$args['count']." ". gettext($args['period']); + if ($args['period'] <> '' && $args['count']) + $caption = $caption . " - " . $args['count'] . " " . gettext($args['period']); return $caption; } diff --git a/lib/plugin/AppendText.php b/lib/plugin/AppendText.php index 81d5dd824..faf0f5b42 100644 --- a/lib/plugin/AppendText.php +++ b/lib/plugin/AppendText.php @@ -31,33 +31,38 @@ * Todo: multiple pages. e.g. AppendText s=~[CategoryINtime~] page= */ class WikiPlugin_AppendText -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("AppendText"); } - function getDescription() { + function getDescription() + { return _("Append text to any page in this wiki."); } - function getDefaultArguments() { - return array('page' => '[pagename]', - 'pages' => false, - 's' => '', // Text to append. - 'before' => '', // Add before (ignores after if defined) - 'after' => '', // Add after line beginning with this - 'redirect' => false // Redirect to modified page - ); + function getDefaultArguments() + { + return array('page' => '[pagename]', + 'pages' => false, + 's' => '', // Text to append. + 'before' => '', // Add before (ignores after if defined) + 'after' => '', // Add after line beginning with this + 'redirect' => false // Redirect to modified page + ); } - function _fallback($addtext, $oldtext, $notfound, &$message) { - $message->pushContent(sprintf(_("%s not found"), $notfound).". ". - _("Appending at the end.")."\n"); + function _fallback($addtext, $oldtext, $notfound, &$message) + { + $message->pushContent(sprintf(_("%s not found"), $notfound) . ". " . + _("Appending at the end.") . "\n"); return $oldtext . "\n" . $addtext; } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); if (!$args['pages'] or !$request->isPost()) { @@ -65,7 +70,7 @@ extends WikiPlugin } else { $html = HTML(); if ($args['page'] != $basepage) - $html->pushContent("pages argument overrides page argument. ignored.",HTML::br()); + $html->pushContent("pages argument overrides page argument. ignored.", HTML::br()); foreach ($args['pages'] as $pagename) { $html->pushContent($this->_work($pagename, $args, $dbi, $request)); } @@ -73,7 +78,8 @@ extends WikiPlugin } } - function _work($pagename, $args, $dbi, &$request) { + function _work($pagename, $args, $dbi, &$request) + { if (empty($args['s'])) { if ($request->isPost()) { if ($pagename != _("AppendText")) @@ -87,7 +93,7 @@ extends WikiPlugin if (!$page->exists()) { // We might want to create it? $message->pushContent(sprintf(_("Page could not be updated. %s doesn't exist!"), - $pagename)); + $pagename)); return $message; } @@ -101,16 +107,16 @@ extends WikiPlugin // Insert before $newtext = preg_match("/\n${before}/", $oldtext) ? preg_replace("/(\n${before})/", - "\n" . preg_quote($text, "/") . "\\1", - $oldtext) + "\n" . preg_quote($text, "/") . "\\1", + $oldtext) : $this->_fallback($text, $oldtext, $args['before'], $message); } elseif (!empty($args['after'])) { // Insert after $after = preg_quote($args['after'], "/"); $newtext = preg_match("/\n${after}/", $oldtext) ? preg_replace("/(\n${after})/", - "\\1\n" . preg_quote($text, "/"), - $oldtext) + "\\1\n" . preg_quote($text, "/"), + $oldtext) : $this->_fallback($text, $oldtext, $args['after'], $message); } else { // Append at the end @@ -123,18 +129,18 @@ extends WikiPlugin $meta['summary'] = sprintf(_("AppendText to %s"), $pagename); if ($page->save($newtext, $current->getVersion() + 1, $meta)) { $message->pushContent(HTML::p(array('class' => 'feedback'), - _("Page successfully updated."))); + _("Page successfully updated."))); } // AppendText has been called from the same page that got modified // so we directly show the page. - if ( $request->getArg($pagename) == $pagename ) { + if ($request->getArg($pagename) == $pagename) { // TODO: Just invalidate the cache, if AppendText didn't // change anything before. // return $request->redirect(WikiURL($pagename, false, 'absurl'), false); - // The user asked to be redirected to the modified page + // The user asked to be redirected to the modified page } elseif ($args['redirect']) { return $request->redirect(WikiURL($pagename, false, 'absurl'), false); @@ -145,7 +151,9 @@ extends WikiPlugin return $message; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/AsciiMath.php b/lib/plugin/AsciiMath.php index 7d4ea0702..c1436438d 100644 --- a/lib/plugin/AsciiMath.php +++ b/lib/plugin/AsciiMath.php @@ -33,33 +33,39 @@ if (phpversion() >= '5') { * Syntax: http://www1.chapman.edu/~jipsen/mathml/asciimathsyntax.xml * Example: "int_-1^1 sqrt(1-x^2)dx = pi/2" * => - -11 - 1-x2 - d - x - = - π2 - +-11 +1-x2 +d +x += +π2 + */ class WikiPlugin_AsciiMath -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("AsciiMath"); } - function getDescription() { + function getDescription() + { return _("Render ASCII Math as MathML"); } - function getDefaultArguments() { + function getDefaultArguments() + { return array(); } - function handle_plugin_args_cruft(&$argstr, &$args) { + + function handle_plugin_args_cruft(&$argstr, &$args) + { $this->source = $argstr; } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); if (empty($this->source)) { return HTML::div(array('class' => "error"), "Please provide a formula to AsciiMath plugin"); @@ -74,7 +80,9 @@ extends WikiPlugin $ascii_math->genMathML(); return HTML::raw($ascii_math->getMathML()); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/AsciiSVG.php b/lib/plugin/AsciiSVG.php index 545be9d8e..f86129fd7 100644 --- a/lib/plugin/AsciiSVG.php +++ b/lib/plugin/AsciiSVG.php @@ -26,28 +26,34 @@ * Syntax: http://www1.chapman.edu/~jipsen/svg/asciisvgcommands.html */ class WikiPlugin_AsciiSVG -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("AsciiSVG"); } - function getDescription() { + function getDescription() + { return _("Render inline ASCII SVG"); } - function getDefaultArguments() { - return array('width' => 200, - 'height' => 200, - 'script' => false, // one line script. not very likely - 'onmousemove' => false - ); + function getDefaultArguments() + { + return array('width' => 200, + 'height' => 200, + 'script' => false, // one line script. not very likely + 'onmousemove' => false + ); } - function handle_plugin_args_cruft(&$argstr, &$args) { + + function handle_plugin_args_cruft(&$argstr, &$args) + { $this->source = $argstr; } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { global $WikiTheme; $args = $this->getArgs($argstr, $request); if (empty($this->source)) @@ -55,7 +61,7 @@ extends WikiPlugin $html = HTML(); if (empty($WikiTheme->_asciiSVG)) { $js = JavaScript('', array - ('src' => $WikiTheme->_findData('ASCIIsvg.js'))); + ('src' => $WikiTheme->_findData('ASCIIsvg.js'))); if (empty($WikiTheme->_headers_printed)) $WikiTheme->addMoreHeaders($js); else @@ -67,10 +73,10 @@ extends WikiPlugin $this->source = $m[1]; $args['script'] = $m[2]; } - $embedargs = array('width' => $args['width'], - 'height' => $args['height'], - //'src' => "d.svg", - 'script' => $this->source); + $embedargs = array('width' => $args['width'], + 'height' => $args['height'], + //'src' => "d.svg", + 'script' => $this->source); // additional onmousemove argument if ($args['onmousemove']) $embedargs['onmousemove'] = $args['onmousemove']; // we need script='data' and not script="data" @@ -79,10 +85,14 @@ extends WikiPlugin if ($args['script']) $html->pushContent(JavaScript($args['script'])); return $html; } -}; +} -class AsciiSVG_HTML extends HtmlElement { - function startTag() { +; + +class AsciiSVG_HTML extends HtmlElement +{ + function startTag() + { $start = "<" . $this->_tag; $this->_setClasses(); foreach ($this->_attr as $attr => $val) { diff --git a/lib/plugin/AtomFeed.php b/lib/plugin/AtomFeed.php index 787c6b6dd..7db20c7b0 100644 --- a/lib/plugin/AtomFeed.php +++ b/lib/plugin/AtomFeed.php @@ -26,27 +26,31 @@ require_once 'lib/WikiPlugin.php'; require_once 'lib/AtomParser.php'; class WikiPlugin_AtomFeed -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _('AtomFeed'); } - function getDescription() { + function getDescription() + { return _('Atom Aggregator Plugin'); } - function getDefaultArguments() { + function getDefaultArguments() + { return array( - 'feed' => "", - 'description' => "", - 'url' => "", - 'maxitem' => 0, - 'titleonly' => false + 'feed' => "", + 'description' => "", + 'url' => "", + 'maxitem' => 0, + 'titleonly' => false ); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { extract($this->getArgs($argstr, $request)); $parser = new AtomParser(); @@ -59,7 +63,7 @@ extends WikiPlugin foreach ($parser->feed as $feed) { $title = HTML::h3(HTML::a(array('href' => $feed["links"]["0"]["href"]), $feed["title"])); $counter = 1; - foreach($parser->entries as $entry) { + foreach ($parser->entries as $entry) { $item = HTML::dt(HTML::a(array('href' => $entry["links"]["0"]["href"]), $entry["title"])); $items->pushContent($item); @@ -75,7 +79,7 @@ extends WikiPlugin } $counter++; } - $html = HTML::div(array('class'=> 'rss'), $title); + $html = HTML::div(array('class' => 'rss'), $title); $html->pushContent($items); } diff --git a/lib/plugin/AuthorHistory.php b/lib/plugin/AuthorHistory.php index 24ac720e0..e2c342d97 100644 --- a/lib/plugin/AuthorHistory.php +++ b/lib/plugin/AuthorHistory.php @@ -57,32 +57,37 @@ require_once 'lib/PageList.php'; class WikiPlugin_AuthorHistory -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("AuthorHistory"); } - function getDescription() { + function getDescription() + { return sprintf(_("List all page revisions edited by one user with diff links, or show a PageHistory-like list of a single page for only one user.")); } - function getDefaultArguments() { + function getDefaultArguments() + { global $request; - return array('exclude' => '', - 'noheader' => false, - 'includeminor' => false, - 'includedeleted' => false, - 'author' => $request->_user->UserName(), - 'page' => '[pagename]', - 'info' => 'version,minor,author,summary,mtime' - ); + return array('exclude' => '', + 'noheader' => false, + 'includeminor' => false, + 'includedeleted' => false, + 'author' => $request->_user->UserName(), + 'page' => '[pagename]', + 'info' => 'version,minor,author,summary,mtime' + ); } + // info arg allows multiple columns // info=mtime,hits,summary,version,author,locked,minor // exclude arg allows multiple pagenames exclude=HomePage,RecentChanges - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $this->_args = $this->getArgs($argstr, $request); extract($this->_args); //trigger_error("1 p= $page a= $author"); @@ -98,20 +103,20 @@ extends WikiPlugin global $WikiTheme; // date & time formatting - $table = HTML::table(array('class'=> 'pagelist')); + $table = HTML::table(array('class' => 'pagelist')); $thead = HTML::thead(); $tbody = HTML::tbody(); - if (! ($page == 'all')) { + if (!($page == 'all')) { $p = $dbi->getPage($page); - $thead->pushContent(HTML::tr(HTML::th(array('align'=> 'right'), - _("Version")), - $includeminor ? HTML::th(_("Minor")) : "", - HTML::th(_("Author")), - HTML::th(_("Summary")), - HTML::th(_("Modified")) - )); + $thead->pushContent(HTML::tr(HTML::th(array('align' => 'right'), + _("Version")), + $includeminor ? HTML::th(_("Minor")) : "", + HTML::th(_("Author")), + HTML::th(_("Summary")), + HTML::th(_("Modified")) + )); $allrevisions_iter = $p->getAllRevisions(); while ($rev = $allrevisions_iter->next()) { @@ -121,17 +126,17 @@ extends WikiPlugin if ($authordoesmatch && (!$isminor || ($includeminor && $isminor))) { $difflink = Button(array('action' => 'diff', - 'previous' => 'minor'), - $rev->getversion(), $rev); - $tr = HTML::tr(HTML::td(array('align'=> 'right'), - $difflink, $nbsp), - $includeminor ? (HTML::td($nbsp, ($isminor ? "minor" : "major"), $nbsp)) : "", - HTML::td($nbsp, WikiLink($rev->get('author'), - 'if_known'), $nbsp), - HTML::td($nbsp, $rev->get('summary')), - HTML::td(array('align'=> 'right'), - $WikiTheme->formatdatetime($rev->get('mtime'))) - ); + 'previous' => 'minor'), + $rev->getversion(), $rev); + $tr = HTML::tr(HTML::td(array('align' => 'right'), + $difflink, $nbsp), + $includeminor ? (HTML::td($nbsp, ($isminor ? "minor" : "major"), $nbsp)) : "", + HTML::td($nbsp, WikiLink($rev->get('author'), + 'if_known'), $nbsp), + HTML::td($nbsp, $rev->get('summary')), + HTML::td(array('align' => 'right'), + $WikiTheme->formatdatetime($rev->get('mtime'))) + ); $class = $isminor ? 'evenrow' : 'oddrow'; $tr->setAttr('class', $class); @@ -139,21 +144,20 @@ extends WikiPlugin //$pagelist->addPage($rev->getPage()); } } - $captext = fmt($includeminor ? "History of all major and minor edits by %s to page %s." : "History of all major edits by %s to page %s." , - WikiLink($author, 'auto'), - WikiLink($page, 'auto')); - } - else { + $captext = fmt($includeminor ? "History of all major and minor edits by %s to page %s." : "History of all major edits by %s to page %s.", + WikiLink($author, 'auto'), + WikiLink($page, 'auto')); + } else { //search all pages for all edits by this author $thead->pushContent(HTML::tr(HTML::th(_("Page Name")), - HTML::th(array('align'=> 'right'), - _("Version")), - $includeminor ? HTML::th(_("Minor")) : "", - HTML::th(_("Summary")), - HTML::th(_("Modified")) - )); + HTML::th(array('align' => 'right'), + _("Version")), + $includeminor ? HTML::th(_("Minor")) : "", + HTML::th(_("Summary")), + HTML::th(_("Modified")) + )); $allpages_iter = $dbi->getAllPages($includedeleted); while ($p = $allpages_iter->next()) { @@ -164,19 +168,19 @@ extends WikiPlugin $authordoesmatch = $author == $rev->get('author'); if ($authordoesmatch && (!$isminor || ($includeminor && $isminor))) { $difflink = Button(array('action' => 'diff', - 'previous' => 'minor'), - $rev->getversion(), $rev); + 'previous' => 'minor'), + $rev->getversion(), $rev); $tr = HTML::tr( - HTML::td($nbsp, - ($isminor ? $rev->_pagename : WikiLink($rev->_pagename, 'auto')) - ), - HTML::td(array('align'=> 'right'), - $difflink, $nbsp), - $includeminor ? (HTML::td($nbsp, ($isminor ? "minor" : "major"), $nbsp)) : "", - HTML::td($nbsp, $rev->get('summary')), - HTML::td(array('align'=> 'right'), - $WikiTheme->formatdatetime($rev->get('mtime')), $nbsp) - ); + HTML::td($nbsp, + ($isminor ? $rev->_pagename : WikiLink($rev->_pagename, 'auto')) + ), + HTML::td(array('align' => 'right'), + $difflink, $nbsp), + $includeminor ? (HTML::td($nbsp, ($isminor ? "minor" : "major"), $nbsp)) : "", + HTML::td($nbsp, $rev->get('summary')), + HTML::td(array('align' => 'right'), + $WikiTheme->formatdatetime($rev->get('mtime')), $nbsp) + ); $class = $isminor ? 'evenrow' : 'oddrow'; $tr->setAttr('class', $class); @@ -186,8 +190,8 @@ extends WikiPlugin } } - $captext = fmt($includeminor ? "History of all major and minor modifications for any page edited by %s." : "History of major modifications for any page edited by %s." , - WikiLink($author, 'auto')); + $captext = fmt($includeminor ? "History of all major and minor modifications for any page edited by %s." : "History of major modifications for any page edited by %s.", + WikiLink($author, 'auto')); } $table->pushContent(HTML::caption($captext)); @@ -215,7 +219,9 @@ extends WikiPlugin // return $pagelist; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/BackLinks.php b/lib/plugin/BackLinks.php index dd4bb9636..4d1d7c37c 100644 --- a/lib/plugin/BackLinks.php +++ b/lib/plugin/BackLinks.php @@ -23,26 +23,29 @@ require_once 'lib/PageList.php'; class WikiPlugin_BackLinks -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("BackLinks"); } - function getDescription() { + function getDescription() + { return sprintf(_("List all pages which link to %s."), '[pagename]'); } - function getDefaultArguments() { + function getDefaultArguments() + { return array_merge - ( - PageList::supportedArgs(), - array('include_self' => false, - 'noheader' => false, - 'page' => '[pagename]', - 'linkmore' => '', // If count>0 and limit>0 display a link with - // the number of all results, linked to the given pagename. - )); + ( + PageList::supportedArgs(), + array('include_self' => false, + 'noheader' => false, + 'page' => '[pagename]', + 'linkmore' => '', // If count>0 and limit>0 display a link with + // the number of all results, linked to the given pagename. + )); } // info arg allows multiple columns @@ -50,7 +53,8 @@ extends WikiPlugin // exclude arg allows multiple pagenames exclude=HomePage,RecentChanges // NEW: info=count : number of links // page=foo,bar : backlinks to both pages - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); extract($args); @@ -62,7 +66,7 @@ extends WikiPlugin $exclude[] = $page; if ($info) { $info = explode(",", $info); - if (in_array('count',$info)) + if (in_array('count', $info)) $args['types']['count'] = new _PageList_Column_BackLinks_count('count', _("#"), 'center'); } @@ -105,42 +109,41 @@ extends WikiPlugin // distinction as it does with English in this case. :) if (!$noheader) { if ($page == $request->getArg('pagename') - and !$dbi->isWikiPage($page)) - { - // BackLinks plugin is more than likely being called - // upon for an empty page on said page, while either - // 'browse'ing, 'create'ing or 'edit'ing. - // - // Don't bother displaying a WikiLink 'unknown', just - // the Un~WikiLink~ified (plain) name of the uncreated - // page currently being viewed. - $pagelink = $page; - - if ($pagelist->isEmpty()) - return HTML::p(fmt("No other page links to %s yet.", $pagelink)); - - if ($total == 1) - $pagelist->setCaption(fmt("One page would link to %s:", - $pagelink)); - // Some future localizations will actually require - // this... (BelieveItOrNot, English-only-speakers!(:) - // - // else if ($pagelist->getTotal() == 2) - // $pagelist->setCaption(fmt("Two pages would link to %s:", - // $pagelink)); - else - $pagelist->setCaption(fmt("%s pages would link to %s:", - $total, $pagelink)); - } - else { + and !$dbi->isWikiPage($page) + ) { + // BackLinks plugin is more than likely being called + // upon for an empty page on said page, while either + // 'browse'ing, 'create'ing or 'edit'ing. + // + // Don't bother displaying a WikiLink 'unknown', just + // the Un~WikiLink~ified (plain) name of the uncreated + // page currently being viewed. + $pagelink = $page; + + if ($pagelist->isEmpty()) + return HTML::p(fmt("No other page links to %s yet.", $pagelink)); + + if ($total == 1) + $pagelist->setCaption(fmt("One page would link to %s:", + $pagelink)); + // Some future localizations will actually require + // this... (BelieveItOrNot, English-only-speakers!(:) + // + // else if ($pagelist->getTotal() == 2) + // $pagelist->setCaption(fmt("Two pages would link to %s:", + // $pagelink)); + else + $pagelist->setCaption(fmt("%s pages would link to %s:", + $total, $pagelink)); + } else { if ($count) { $tmp_pages = $pages; $p = array_shift($tmp_pages); $pagelink = HTML(WikiLink($p, 'auto')); foreach ($tmp_pages as $p) - $pagelink->pushContent(" ",_("AND")," ",WikiLink($p, 'auto')); + $pagelink->pushContent(" ", _("AND"), " ", WikiLink($p, 'auto')); } else - // BackLinks plugin is being displayed on a normal page. + // BackLinks plugin is being displayed on a normal page. $pagelink = WikiLink($page, 'auto'); if ($pagelist->isEmpty()) @@ -150,7 +153,7 @@ extends WikiPlugin if ($total == 1) $pagelist->setCaption(fmt("One page links to %s:", - $pagelink)); + $pagelink)); // Some future localizations will actually require // this... (BelieveItOrNot, English-only-speakers!(:) // @@ -159,23 +162,27 @@ extends WikiPlugin // $pagelink)); else $pagelist->setCaption(fmt("%s pages link to %s:", - $limit > 0 ? $total : _("Those"), - $pagelink)); + $limit > 0 ? $total : _("Those"), + $pagelink)); } } if (!empty($args['linkmore']) and $dbi->isWikiPage($args['linkmore']) - and $limit > 0 and $total > $limit - ) + and $limit > 0 and $total > $limit + ) $pagelist->addCaption(WikiLink($args['linkmore'], "auto", _("More..."))); return $pagelist; } -}; +} + +; // how many links from this backLink to other pages -class _PageList_Column_BackLinks_count extends _PageList_Column { - function _getValue($page, &$revision_handle) { +class _PageList_Column_BackLinks_count extends _PageList_Column +{ + function _getValue($page, &$revision_handle) + { $iter = $page->getPageLinks(); $count = $iter->count(); return $count; diff --git a/lib/plugin/BlogArchives.php b/lib/plugin/BlogArchives.php index 3344db538..d08099d88 100644 --- a/lib/plugin/BlogArchives.php +++ b/lib/plugin/BlogArchives.php @@ -33,29 +33,33 @@ require_once 'lib/plugin/WikiBlog.php'; * @author: Reini Urban */ class WikiPlugin_BlogArchives -extends WikiPlugin_WikiBlog + extends WikiPlugin_WikiBlog { - function getName() { + function getName() + { return _("Archives"); } - function getDescription() { + function getDescription() + { return _("List blog months links for the current or ADMIN user"); } - function getDefaultArguments() { + function getDefaultArguments() + { return //array_merge - //( - //PageList::supportedArgs(), - array('user' => '', - 'order' => 'reverse', // latest first - 'info' => 'month,numpages', // ignored - 'month' => false, - 'noheader' => 0 - ); + //( + //PageList::supportedArgs(), + array('user' => '', + 'order' => 'reverse', // latest first + 'info' => 'month,numpages', // ignored + 'month' => false, + 'noheader' => 0 + ); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { if (is_array($argstr)) { // can do with array also. $args =& $argstr; if (!isset($args['order'])) $args['order'] = 'reverse'; @@ -72,7 +76,7 @@ extends WikiPlugin_WikiBlog } if (!$args['user'] or $args['user'] == ADMIN_USER) { if (BLOG_DEFAULT_EMPTY_PREFIX) - $args['user'] = ''; // "Blogs/day" pages + $args['user'] = ''; // "Blogs/day" pages else $args['user'] = ADMIN_USER; // "Admin/Blogs/day" pages } @@ -86,22 +90,22 @@ extends WikiPlugin_WikiBlog $sp = HTML::Raw('· '); if (!empty($args['month'])) { $prefix = $parent . $this->_blogPrefix('wikiblog') . SUBPAGE_SEPARATOR . $args['month']; - $pages = $dbi->titleSearch(new TextSearchQuery("^".$prefix, true, 'posix')); + $pages = $dbi->titleSearch(new TextSearchQuery("^" . $prefix, true, 'posix')); $html = HTML::ul(); while ($page = $pages->next()) { - $rev = $page->getCurrentRevision(false); - if ($rev->get('pagetype') != 'wikiblog') continue; + $rev = $page->getCurrentRevision(false); + if ($rev->get('pagetype') != 'wikiblog') continue; $blog = $this->_blog($rev); $html->pushContent(HTML::li(WikiLink($page, 'known', $rev->get('summary')))); } if (!$args['noheader']) return HTML(HTML::h3(sprintf(_("Blog Entries for %s:"), $this->_monthTitle($args['month']))), - $html); + $html); else return $html; } - $blogs = $this->findBlogs ($dbi, $args['user'], 'wikiblog'); + $blogs = $this->findBlogs($dbi, $args['user'], 'wikiblog'); if ($blogs) { if (!$basepage) $basepage = _("BlogArchives"); $html = HTML::ul(); @@ -112,21 +116,21 @@ extends WikiPlugin_WikiBlog $months = array(); foreach ($blogs as $rev) { $blog = $this->_blog($rev); - $mon = $blog['month']; + $mon = $blog['month']; if (empty($months[$mon])) $months[$mon] = array('title' => $this->_monthTitle($mon), - 'num' => 1, - 'month' => $mon, - 'link' => WikiURL($basepage, - $this->_nonDefaultArgs(array('month' => $mon)))); + 'num' => 1, + 'month' => $mon, + 'link' => WikiURL($basepage, + $this->_nonDefaultArgs(array('month' => $mon)))); else $months[$mon]['num']++; } foreach ($months as $m) { - $html->pushContent(HTML::li(HTML::a(array('href'=>$m['link'], - 'class' => 'named-wiki'), - $m['title'] . " (".$m['num'].")"))); + $html->pushContent(HTML::li(HTML::a(array('href' => $m['link'], + 'class' => 'named-wiki'), + $m['title'] . " (" . $m['num'] . ")"))); } if (!$args['noheader']) return HTML(HTML::h3(_("Blog Archives:")), $html); @@ -137,13 +141,16 @@ extends WikiPlugin_WikiBlog } // box is used to display a fixed-width, narrow version with common header - function box($args=false, $request=false, $basepage=false) { + function box($args = false, $request = false, $basepage = false) + { if (!$request) $request =& $GLOBALS['request']; if (!$args or empty($args['limit'])) $args['limit'] = 10; $args['noheader'] = 1; return $this->makeBox(_("Archives"), $this->run($request->_dbi, $args, $request, $basepage)); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/BlogJournal.php b/lib/plugin/BlogJournal.php index 1120ab311..cd04f579e 100644 --- a/lib/plugin/BlogJournal.php +++ b/lib/plugin/BlogJournal.php @@ -32,26 +32,30 @@ require_once 'lib/plugin/WikiBlog.php'; * @author: Reini Urban */ class WikiPlugin_BlogJournal -extends WikiPlugin_WikiBlog + extends WikiPlugin_WikiBlog { - function getName() { + function getName() + { return _("BlogJournal"); } - function getDescription() { + function getDescription() + { return _("Include latest blog entries for the current or ADMIN user"); } - function getDefaultArguments() { - return array('count' => 7, - 'user' => '', - 'order' => 'reverse', // latest first - 'month' => false, - 'noheader' => 0 - ); + function getDefaultArguments() + { + return array('count' => 7, + 'user' => '', + 'order' => 'reverse', // latest first + 'month' => false, + 'noheader' => 0 + ); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { if (is_array($argstr)) { // can do with array also. $args =& $argstr; if (!isset($args['order'])) $args['order'] = 'reverse'; @@ -68,7 +72,7 @@ extends WikiPlugin_WikiBlog } if (!$args['user'] or $args['user'] == ADMIN_USER) { if (BLOG_DEFAULT_EMPTY_PREFIX) { - $args['user'] = ''; // "Blogs/day" pages + $args['user'] = ''; // "Blogs/day" pages } else { $args['user'] = ADMIN_USER; // "Admin/Blogs/day" pages } @@ -79,8 +83,9 @@ extends WikiPlugin_WikiBlog $prefix = $base = $parent . $this->_blogPrefix('wikiblog'); if ($args['month']) $prefix .= (SUBPAGE_SEPARATOR . $args['month']); - $pages = $dbi->titleSearch(new TextSearchQuery("^".$prefix.SUBPAGE_SEPARATOR, true, 'posix')); - $html = HTML(); $i = 0; + $pages = $dbi->titleSearch(new TextSearchQuery("^" . $prefix . SUBPAGE_SEPARATOR, true, 'posix')); + $html = HTML(); + $i = 0; while (($page = $pages->next()) and $i < $args['count']) { $rev = $page->getCurrentRevision(false); if ($rev->get('pagetype') != 'wikiblog') continue; @@ -90,18 +95,20 @@ extends WikiPlugin_WikiBlog $html->pushContent($rev->getTransformedContent('wikiblog')); } if ($args['user'] == $user->UserName() or $args['user'] == '') - $html->pushContent(Button(array('action'=>'WikiBlog', - 'mode'=>'add'), - _("New entry"), $base)); + $html->pushContent(Button(array('action' => 'WikiBlog', + 'mode' => 'add'), + _("New entry"), $base)); if (!$i) return HTML(HTML::h3(_("No Blog Entries")), $html); if (!$args['noheader']) return HTML(HTML::h3(sprintf(_("Blog Entries for %s:"), $this->_monthTitle($args['month']))), - $html); + $html); else return $html; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/BoxRight.php b/lib/plugin/BoxRight.php index db08b452e..5af761ac1 100644 --- a/lib/plugin/BoxRight.php +++ b/lib/plugin/BoxRight.php @@ -24,34 +24,39 @@ * A simple plugin for
with wikimarkup */ class WikiPlugin_BoxRight -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return "BoxRight"; } - function getDescription () { + function getDescription() + { return _("A simple plugin for
with wikimarkup"); } - function getDefaultArguments() { + function getDefaultArguments() + { return array(); } - function managesValidators() { + function managesValidators() + { // The plugin output will only change if the plugin // invocation (page text) changes --- so the necessary // validators have already been handled by displayPage. return true; } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { if (!$basepage) { return $this->error("$basepage unset?"); } include_once 'lib/BlockParser.php'; $page = $request->getPage($basepage); - return HTML::div(array('class'=>'boxright'), TransformText($argstr)); + return HTML::div(array('class' => 'boxright'), TransformText($argstr)); } } diff --git a/lib/plugin/CacheTest.php b/lib/plugin/CacheTest.php index 813acd3ff..5bc83e855 100644 --- a/lib/plugin/CacheTest.php +++ b/lib/plugin/CacheTest.php @@ -52,26 +52,30 @@ require_once 'lib/WikiPluginCached.php'; class WikiPlugin_CacheTest -extends WikiPluginCached + extends WikiPluginCached { /* --------- overwrite virtual or abstract methods ---------------- */ - function getPluginType() { + function getPluginType() + { return PLUGIN_CACHED_IMG_ONDEMAND; } - function getName() { + function getName() + { return "CacheTest"; } - function getDescription() { + function getDescription() + { return 'This is a simple example using WikiPluginCached.'; } - function getDefaultArguments() { + function getDefaultArguments() + { return array('text' => $this->getDescription(), - 'font' => '3', - 'type' => 'png' ); + 'font' => '3', + 'type' => 'png'); } // should return image handle @@ -81,15 +85,17 @@ extends WikiPluginCached // image handle to an error image if you do not, // WikiPluginImageCache will do so. - function getImage($dbi, $argarray, $request) { + function getImage($dbi, $argarray, $request) + { extract($argarray); - return $this->produceGraphics($text,$font); + return $this->produceGraphics($text, $font); // This should also work // return $this->lazy_produceGraphics($text,$font); } // getImage - function getImageType($dbi, $argarray, $request) { + function getImageType($dbi, $argarray, $request) + { extract($argarray); if (in_array($type, array('png', 'gif', 'jpg'))) { return $type; @@ -97,31 +103,34 @@ extends WikiPluginCached return 'png'; } - function getAlt($dbi, $argarray, $request) { + function getAlt($dbi, $argarray, $request) + { // ALT-text for tag extract($argarray); return $text; } - function getExpire($dbi, $argarray, $request) { + function getExpire($dbi, $argarray, $request) + { return '+600'; // 600 seconds life time } /* -------------------- extremely simple converter -------------------- */ - function produceGraphics($text, $font ) { + function produceGraphics($text, $font) + { // The idea (and some code) is stolen from the text2png plugin // but I did not want to use TTF. ImageString is quite ugly // and quite compatible. It's only a usage example. - if ($font<1 || $font>5) { + if ($font < 1 || $font > 5) { $text = "Fontnr. (font=\"$font\") should be in range 1-5"; $this->complain($text); $font = 3; } $ok = ($im = @ImageCreate(400, 40)); - $bg_color = ImageColorAllocate($im, 240, 240, 240); + $bg_color = ImageColorAllocate($im, 240, 240, 240); $text_color1 = ImageColorAllocate($im, 120, 120, 120); $text_color2 = ImageColorAllocate($im, 0, 0, 0); @@ -147,8 +156,9 @@ extends WikiPluginCached // we could have used the simple built-in text2img function // instead of writing our own: - function lazy_produceGraphics( $text, $font ) { - if ($font<1 || $font>5) { + function lazy_produceGraphics($text, $font) + { + if ($font < 1 || $font > 5) { $text = "Fontnr. (font=\"$font\") should be in range 1-5"; $this->complain($text); $font = 3; @@ -156,7 +166,7 @@ extends WikiPluginCached } return $this->text2img($text, $font, array(0, 0, 0), - array(255, 255, 255)); + array(255, 255, 255)); } // lazy_produceGraphics } diff --git a/lib/plugin/Calendar.php b/lib/plugin/Calendar.php index cd6e09728..23d94bf3f 100644 --- a/lib/plugin/Calendar.php +++ b/lib/plugin/Calendar.php @@ -33,26 +33,29 @@ if (!defined('SECONDS_PER_DAY')) // easier.) class WikiPlugin_Calendar -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("Calendar"); } - function getDescription () { + function getDescription() + { return _("Calendar"); } - function getDefaultArguments() { - return array('prefix' => '[pagename]' . SUBPAGE_SEPARATOR, - 'date_format' => '%Y-%m-%d', - 'year' => '', - 'month' => '', - 'month_offset' => 0, - 'month_format' => '%B %Y', - 'wday_format' => '%a', - 'start_wday' => '1', // start now with Monday - 'display_weeknum' => 0); + function getDefaultArguments() + { + return array('prefix' => '[pagename]' . SUBPAGE_SEPARATOR, + 'date_format' => '%Y-%m-%d', + 'year' => '', + 'month' => '', + 'month_offset' => 0, + 'month_format' => '%B %Y', + 'wday_format' => '%a', + 'start_wday' => '1', // start now with Monday + 'display_weeknum' => 0); } /** @@ -62,7 +65,8 @@ extends WikiPlugin * @param string $basepage The pagename the plugin is invoked from. * @return array List of pagenames linked to (or false). */ - function getWikiPageLinks ($argstr, $basepage) { + function getWikiPageLinks($argstr, $basepage) + { if (isset($this->_links)) return $this->_links; else { @@ -72,43 +76,45 @@ extends WikiPlugin } } - function __header($pagename, $time) { + function __header($pagename, $time) + { $args = &$this->args; $t = localtime($time - SECONDS_PER_DAY, 1); $prev_url = WikiURL($pagename, array('month' => $t['tm_mon'] + 1, - 'year' => $t['tm_year'] + 1900)); + 'year' => $t['tm_year'] + 1900)); $t = localtime($time + 32 * SECONDS_PER_DAY, 1); $next_url = WikiURL($pagename, array('month' => $t['tm_mon'] + 1, - 'year' => $t['tm_year'] + 1900)); + 'year' => $t['tm_year'] + 1900)); - $prev = HTML::a(array('href' => $prev_url, - 'class' => 'cal-arrow', - 'title' => _("Previous Month")), - '<'); - $next = HTML::a(array('href' => $next_url, - 'class' => 'cal-arrow', - 'title' => _("Next Month")), - '>'); + $prev = HTML::a(array('href' => $prev_url, + 'class' => 'cal-arrow', + 'title' => _("Previous Month")), + '<'); + $next = HTML::a(array('href' => $next_url, + 'class' => 'cal-arrow', + 'title' => _("Next Month")), + '>'); $row = HTML::tr(HTML::td(array('align' => 'left'), $prev), - HTML::td(array('align' => 'center'), - HTML::strong(array('class' => 'cal-header'), - strftime($args['month_format'], - $time))), - HTML::td(array('align' => 'right'), $next)); + HTML::td(array('align' => 'center'), + HTML::strong(array('class' => 'cal-header'), + strftime($args['month_format'], + $time))), + HTML::td(array('align' => 'right'), $next)); return HTML::tr(HTML::td(array('colspan' => $args['display_weeknum'] ? 8 : 7, - 'align' => 'center'), - HTML::table(array('width' => '100%', - 'class' => 'cal-header'), - $row))); + 'align' => 'center'), + HTML::table(array('width' => '100%', + 'class' => 'cal-header'), + $row))); } - function __daynames($start_wday) { - $time = mktime(12, 0, 0, 1, 1, 2001); - $t = localtime($time, 1); + function __daynames($start_wday) + { + $time = mktime(12, 0, 0, 1, 1, 2001); + $t = localtime($time, 1); $time += (7 + $start_wday - $t['tm_wday']) * SECONDS_PER_DAY; $t = localtime($time, 1); @@ -119,22 +125,23 @@ extends WikiPlugin $row->setattr('class', 'cal-dayname'); if ($this->args['display_weeknum']) $row->pushContent(HTML::td(array('class' => 'cal-dayname', - 'align' => 'center'), - _("Wk"))); + 'align' => 'center'), + _("Wk"))); for ($i = 0; $i < 7; $i++) { $row->pushContent(HTML::td(array('class' => 'cal-dayname', - 'align' => 'center'), - strftime($fs, $time))); + 'align' => 'center'), + strftime($fs, $time))); $time += SECONDS_PER_DAY; } return $row; } - function __date($dbi, $time) { + function __date($dbi, $time) + { $args = &$this->args; $page_for_date = $args['prefix'] . strftime($args['date_format'], - $time); + $time); $t = localtime($time, 1); $td = HTML::td(array('align' => 'center')); @@ -143,8 +150,7 @@ extends WikiPlugin if ($mday == $this->_today) { $mday = HTML::strong($mday); $td->setAttr('class', 'cal-today'); - } - else if ($dbi->isWikiPage($page_for_date)) { + } else if ($dbi->isWikiPage($page_for_date)) { $this->_links[] = $page_for_date; $td->setAttr('class', 'cal-day'); } @@ -152,50 +158,50 @@ extends WikiPlugin if ($dbi->isWikiPage($page_for_date)) { $this->_links[] = $page_for_date; $date = HTML::a(array('class' => 'cal-day', - 'href' => WikiURL($page_for_date), - 'title' => $page_for_date), - HTML::em($mday)); - } - else { + 'href' => WikiURL($page_for_date), + 'title' => $page_for_date), + HTML::em($mday)); + } else { $date = HTML::a(array('class' => 'cal-hide', - 'rel' => 'nofollow', - 'href' => WikiURL($page_for_date, - array('action' => 'edit')), - 'title' => sprintf(_("Edit %s"), - $page_for_date)), - $mday); + 'rel' => 'nofollow', + 'href' => WikiURL($page_for_date, + array('action' => 'edit')), + 'title' => sprintf(_("Edit %s"), + $page_for_date)), + $mday); } $td->pushContent(HTML::raw(' '), $date, HTML::raw(' ')); return $td; } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $this->args = $this->getArgs($argstr, $request); - $args = &$this->args; + $args = &$this->args; $this->_links = array(); $now = localtime(time() + 3600 * $request->getPref('timeOffset'), 1); - foreach ( array('month' => $now['tm_mon'] + 1, - 'year' => $now['tm_year'] + 1900) - as $param => $dflt ) { + foreach (array('month' => $now['tm_mon'] + 1, + 'year' => $now['tm_year'] + 1900) + as $param => $dflt) { if (!($args[$param] = intval($args[$param]))) - $args[$param] = $dflt; + $args[$param] = $dflt; } - $time = mktime(12, 0, 0, // hh, mm, ss, - $args['month'] + $args['month_offset'], // month (1-12) - 1, // mday (1-31) - $args['year']); + $time = mktime(12, 0, 0, // hh, mm, ss, + $args['month'] + $args['month_offset'], // month (1-12) + 1, // mday (1-31) + $args['year']); $colnum = $args['display_weeknum'] ? 8 : 7; $cal = HTML::table(array('cellspacing' => 0, - 'cellpadding' => 2, - 'class' => 'cal'), - HTML::thead( - $this->__header($request->getArg('pagename'), - $time), - $this->__daynames($args['start_wday']))); + 'cellpadding' => 2, + 'class' => 'cal'), + HTML::thead( + $this->__header($request->getArg('pagename'), + $time), + $this->__daynames($args['start_wday']))); $t = localtime($time, 1); @@ -209,7 +215,7 @@ extends WikiPlugin if ($args['display_weeknum']) $row->pushContent(HTML::td(array('class' => 'cal-weeknum'), - ((int)strftime("%U", $time))+1)); // %U problem. starts with 0 + ((int)strftime("%U", $time)) + 1)); // %U problem. starts with 0 $col = (7 + $t['tm_wday'] - $args['start_wday']) % 7; if ($col > 0) $row->pushContent(HTML::td(array('colspan' => $col))); @@ -224,11 +230,11 @@ extends WikiPlugin } $time += SECONDS_PER_DAY; - $t = localtime($time, 1); - $done = $t['tm_mday'] == 1; + $t = localtime($time, 1); + $done = $t['tm_mday'] == 1; if (!$col and !$done and $args['display_weeknum']) $row->pushContent(HTML::td(array('class' => 'cal-weeknum'), - ((int)strftime("%U", $time))+1)); // starts with 0 + ((int)strftime("%U", $time)) + 1)); // starts with 0 } if ($row->getContent()) { @@ -238,7 +244,9 @@ extends WikiPlugin $cal->pushContent($tbody); return $cal; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/CalendarList.php b/lib/plugin/CalendarList.php index 6499ebec1..8f10860f0 100644 --- a/lib/plugin/CalendarList.php +++ b/lib/plugin/CalendarList.php @@ -22,15 +22,15 @@ // if not defined in config.ini if (!defined('PLUGIN_CALENDARLIST_ORDER')) - define('PLUGIN_CALENDARLIST_ORDER', 'normal'); + define('PLUGIN_CALENDARLIST_ORDER', 'normal'); if (!defined('PLUGIN_CALENDARLIST_NEXT_N_DAYS')) - define('PLUGIN_CALENDARLIST_NEXT_N_DAYS',''); + define('PLUGIN_CALENDARLIST_NEXT_N_DAYS', ''); if (!defined('PLUGIN_CALENDARLIST_NEXT_N')) - define('PLUGIN_CALENDARLIST_NEXT_N', ''); + define('PLUGIN_CALENDARLIST_NEXT_N', ''); if (!defined('PLUGIN_CALENDARLIST_LAST_N_DAYS')) - define('PLUGIN_CALENDARLIST_LAST_N_DAYS',''); + define('PLUGIN_CALENDARLIST_LAST_N_DAYS', ''); if (!defined('PLUGIN_CALENDARLIST_LAST_N')) - define('PLUGIN_CALENDARLIST_LAST_N', ''); + define('PLUGIN_CALENDARLIST_LAST_N', ''); /** * This is a list of calendar appointments. @@ -47,33 +47,36 @@ if (!defined('PLUGIN_CALENDARLIST_LAST_N')) * */ class WikiPlugin_CalendarList -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("CalendarList"); } - function getDescription () { + function getDescription() + { return _("CalendarList"); } - function getDefaultArguments() { - return array('prefix' => '[pagename]', - 'date_format' => '%Y-%m-%d', - 'order' => PLUGIN_CALENDARLIST_ORDER, // normal or reverse (report sequence) - 'year' => '', - 'month' => '', - 'month_offset' => 0, - //support ranges: next n days/events - 'next_n_days' => PLUGIN_CALENDARLIST_NEXT_N_DAYS, // one or the other, not both - 'next_n' => PLUGIN_CALENDARLIST_NEXT_N, - // last n days/entries: - 'last_n_days' => PLUGIN_CALENDARLIST_LAST_N_DAYS, // one or the other, not both - 'last_n' => PLUGIN_CALENDARLIST_LAST_N, - - 'month_format' => '%B %Y', - 'wday_format' => '%a', - 'start_wday' => '1'); + function getDefaultArguments() + { + return array('prefix' => '[pagename]', + 'date_format' => '%Y-%m-%d', + 'order' => PLUGIN_CALENDARLIST_ORDER, // normal or reverse (report sequence) + 'year' => '', + 'month' => '', + 'month_offset' => 0, + //support ranges: next n days/events + 'next_n_days' => PLUGIN_CALENDARLIST_NEXT_N_DAYS, // one or the other, not both + 'next_n' => PLUGIN_CALENDARLIST_NEXT_N, + // last n days/entries: + 'last_n_days' => PLUGIN_CALENDARLIST_LAST_N_DAYS, // one or the other, not both + 'last_n' => PLUGIN_CALENDARLIST_LAST_N, + + 'month_format' => '%B %Y', + 'wday_format' => '%a', + 'start_wday' => '1'); } /** @@ -83,7 +86,8 @@ extends WikiPlugin * @param string $basepage The pagename the plugin is invoked from. * @return array List of pagenames linked to (or false). */ - function getWikiPageLinks ($argstr, $basepage) { + function getWikiPageLinks($argstr, $basepage) + { if (isset($this->_links)) return $this->_links; else { @@ -93,29 +97,31 @@ extends WikiPlugin } } - function _count_events($dbi, $n = 7, $direction = 1) { + function _count_events($dbi, $n = 7, $direction = 1) + { // This is used by the last_n/next_n options to determine the date that // accounts for the number of N events in the past/future. // RETURNS: date of N-th event or the last item found - $args = &$this->args; // gather the args array - $timeTMP = time(); // start with today's date - $t = $timeTMP; // init the control date variable to now + $args = &$this->args; // gather the args array + $timeTMP = time(); // start with today's date + $t = $timeTMP; // init the control date variable to now - for ($i=0; $i<=180; $i++) { // loop thru 180 days, past or future + for ($i = 0; $i <= 180; $i++) { // loop thru 180 days, past or future $date_string = strftime($args['date_format'], $t); $page_for_date = $args['prefix'] . SUBPAGE_SEPARATOR . $date_string; if ($dbi->isWikiPage($page_for_date)) { // if this date has any comments/events - $timeTMP = $t; // capture the date of this event for return - if ($n-- <= 0) break; // if we reached the limit, return the date + $timeTMP = $t; // capture the date of this event for return + if ($n-- <= 0) break; // if we reached the limit, return the date } - $t += 24 * 3600 * $direction; // advance one day back or forward + $t += 24 * 3600 * $direction; // advance one day back or forward } // return the date of the N-th or last, most past/future event in the range return $timeTMP; } - function _date($dbi, $time) { + function _date($dbi, $time) + { $args = &$this->args; $date_string = strftime($args['date_format'], $time); @@ -132,10 +138,10 @@ extends WikiPlugin include_once 'lib/BlockParser.php'; $content = TransformText(implode("\n", $c), $r->get('markup')); $link = HTML::a(array('class' => 'cal-hide', - 'href' => WikiURL($page_for_date, - array('action' => 'edit')), - 'title' => sprintf(_("Edit %s"), $page_for_date)), - $date_string); + 'href' => WikiURL($page_for_date, + array('action' => 'edit')), + 'title' => sprintf(_("Edit %s"), $page_for_date)), + $date_string); $this->_links[] = $page_for_date; $a = array(HTML::dt($link), HTML::dd($content)); } else { @@ -144,26 +150,26 @@ extends WikiPlugin return $a; } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $this->args = $this->getArgs($argstr, $request); - $args = &$this->args; + $args = &$this->args; $this->_links = array(); // default to this month $now = localtime(time() + 3600 * $request->getPref('timeOffset'), 1); $args['mday'] = $now['tm_mday']; - foreach ( array('month' => $now['tm_mon'] + 1, - 'year' => $now['tm_year'] + 1900, - 'mday' => $now['tm_mday']) - as $param => $dflt ) - { - if (! ($args[$param] = intval($args[$param]))) - $args[$param] = $dflt; + foreach (array('month' => $now['tm_mon'] + 1, + 'year' => $now['tm_year'] + 1900, + 'mday' => $now['tm_mday']) + as $param => $dflt) { + if (!($args[$param] = intval($args[$param]))) + $args[$param] = $dflt; } $base = mktime(0, 0, 0, // h, m, s - $args['month'], // month 1-12 - $args['mday'], - $args['year']); // must have base 1900 + $args['month'], // month 1-12 + $args['mday'], + $args['year']); // must have base 1900 // *************************************************** // start of Plugin CalendarList display logic @@ -171,34 +177,30 @@ extends WikiPlugin if ($args['last_n_days']) { // back by month // n days ago, affected by month or month_offset $start = $base - ($args['last_n_days'] * 24 * 3600.0); - } - elseif ($args['last_n']) { + } elseif ($args['last_n']) { // get date for last nth event $start = $this->_count_events($dbi, $args['last_n'], -1); - } - else { + } else { // start of requested month $start = mktime(0, 0, 0, // h, m, s - $args['month'] + $args['month_offset'], // month (1-12) - 1, // days prior - $args['year']); + $args['month'] + $args['month_offset'], // month (1-12) + 1, // days prior + $args['year']); } // determine end date if ($args['next_n_days']) { // n days from now, affected by month and year $end = $base + ($args['next_n_days'] * 24 * 3600.0); - } - elseif ($args['last_n']) { + } elseif ($args['last_n']) { // get date for next nth event $end = $this->_count_events($dbi, $args['next_n'], 1); - } - else { + } else { // trick to get last day of requested month $end = mktime(0, 0, -1, // h, m, s - $args['month'] + 1 + $args['month_offset'], // month (1-12) - 1, // days prior - $args['year']); + $args['month'] + 1 + $args['month_offset'], // month (1-12) + 1, // days prior + $args['year']); } // switch values for reverse order @@ -222,7 +224,9 @@ extends WikiPlugin return $cal; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/CategoryPage.php b/lib/plugin/CategoryPage.php index 4635a4b08..0082f879a 100644 --- a/lib/plugin/CategoryPage.php +++ b/lib/plugin/CategoryPage.php @@ -38,27 +38,31 @@ require_once 'lib/BlockParser.php'; * This has only been used in wikilens.org. */ class WikiPlugin_CategoryPage -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("CategoryPage"); } - function getDescription () { + function getDescription() + { return _("Create a Wiki page."); } - function getDefaultArguments() { - return array(// Assume the categories are listed on the HomePage - 'exclude' => false, - 'pagename' => '[pagename]', - 'plural' => false, - 'singular' => false, - 'self_on_create' => true, - 'showbuds' => false); + function getDefaultArguments() + { + return array( // Assume the categories are listed on the HomePage + 'exclude' => false, + 'pagename' => '[pagename]', + 'plural' => false, + 'singular' => false, + 'self_on_create' => true, + 'showbuds' => false); } - function run($dbi, $argstr, &$request) { + function run($dbi, $argstr, &$request) + { $args = $this->getArgs($argstr, $request); if (empty($args['singular'])) { @@ -69,14 +73,16 @@ extends WikiPlugin } return new Template('categorypage', $request, - array('EXCLUDE' => $args['exclude'], - 'PAGENAME' => $args['pagename'], - 'PLURAL' => $args['plural'], - 'SHOWBUDS' => $args['showbuds'], - 'SELF_ON_CREATE' => $args['self_on_create'], - 'SINGULAR' => $args['singular'])); + array('EXCLUDE' => $args['exclude'], + 'PAGENAME' => $args['pagename'], + 'PLURAL' => $args['plural'], + 'SHOWBUDS' => $args['showbuds'], + 'SELF_ON_CREATE' => $args['self_on_create'], + 'SINGULAR' => $args['singular'])); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/Chart.php b/lib/plugin/Chart.php index d115d33d1..3a686ff3e 100644 --- a/lib/plugin/Chart.php +++ b/lib/plugin/Chart.php @@ -44,32 +44,38 @@ */ class WikiPlugin_Chart -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("Chart"); } - function getDescription() { + function getDescription() + { return _("Render SVG charts"); } - function getDefaultArguments() { - return array('width' => 200, - 'height' => 200, - 'type' => 'line', // or 'area', 'bar', 'pie' - // 'xlabel' => 'x', // TODO - // 'ylabel' => 'y', // TODO - 'color' => 'green', - // 'legend' => false, // TODO - 'data' => false // required - ); + function getDefaultArguments() + { + return array('width' => 200, + 'height' => 200, + 'type' => 'line', // or 'area', 'bar', 'pie' + // 'xlabel' => 'x', // TODO + // 'ylabel' => 'y', // TODO + 'color' => 'green', + // 'legend' => false, // TODO + 'data' => false // required + ); } - function handle_plugin_args_cruft(&$argstr, &$args) { + + function handle_plugin_args_cruft(&$argstr, &$args) + { $this->source = $argstr; } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { global $WikiTheme; $args = $this->getArgs($argstr, $request); @@ -79,7 +85,7 @@ extends WikiPlugin extract($args); $html = HTML(); - $js = JavaScript('', array ('src' => $WikiTheme->_findData('ASCIIsvg.js'))); + $js = JavaScript('', array('src' => $WikiTheme->_findData('ASCIIsvg.js'))); $html->pushContent($js); $values = explode(",", $data); @@ -103,15 +109,15 @@ extends WikiPlugin } } - $source = 'initPicture(0,'.$x_max.','.$y_min.','.$y_max.'); axes(); stroke = "'.$color.'"; strokewidth = 5;'; + $source = 'initPicture(0,' . $x_max . ',' . $y_min . ',' . $y_max . '); axes(); stroke = "' . $color . '"; strokewidth = 5;'; if ($type == "bar") { $abscisse = 1; $source .= 'strokewidth = 10; '; foreach ($values as $value) { - $source .= 'point1 = ['.$abscisse.', 0];' - . 'point2 = ['.$abscisse.','.$value.'];' - . 'line(point1, point2);'; + $source .= 'point1 = [' . $abscisse . ', 0];' + . 'point2 = [' . $abscisse . ',' . $value . '];' + . 'line(point1, point2);'; $abscisse += 1; } } elseif ($type == "line") { @@ -119,37 +125,41 @@ extends WikiPlugin $source .= 'strokewidth = 3; p = []; '; foreach ($values as $value) { $source .= 'for (t = 1; t < 1.01; t += 1) p[p.length] = [' - . $abscisse - . ', t*' - . trim($value) - . '];'; + . $abscisse + . ', t*' + . trim($value) + . '];'; $abscisse += 1; } $source .= 'path(p);'; } elseif ($type == "pie") { - $source = 'initPicture(-1.1,1.1,-1.1,1.1); stroke = "'.$color.'"; strokewidth = 1;' - . 'center = [0, 0]; circle(center, 1);' - . 'point = [1, 0]; line(center, point);'; + $source = 'initPicture(-1.1,1.1,-1.1,1.1); stroke = "' . $color . '"; strokewidth = 1;' + . 'center = [0, 0]; circle(center, 1);' + . 'point = [1, 0]; line(center, point);'; $angle = 0; foreach ($values as $value) { if ($value > 0) { - $angle += $value/$sum; - $source .= 'point = [cos(2*pi*'.$angle.'), sin(2*pi*'.$angle.')]; line(center, point);'; + $angle += $value / $sum; + $source .= 'point = [cos(2*pi*' . $angle . '), sin(2*pi*' . $angle . ')]; line(center, point);'; } } } - $embedargs = array('width' => $args['width'], - 'height' => $args['height'], - 'script' => $source); + $embedargs = array('width' => $args['width'], + 'height' => $args['height'], + 'script' => $source); $embed = new SVG_HTML("embed", $embedargs); $html->pushContent($embed); return $html; } -}; +} -class SVG_HTML extends HtmlElement { - function startTag() { +; + +class SVG_HTML extends HtmlElement +{ + function startTag() + { $start = "<" . $this->_tag; $this->_setClasses(); foreach ($this->_attr as $attr => $val) { diff --git a/lib/plugin/Comment.php b/lib/plugin/Comment.php index 4a1959ace..4861b0086 100644 --- a/lib/plugin/Comment.php +++ b/lib/plugin/Comment.php @@ -36,25 +36,31 @@ */ class WikiPlugin_Comment -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("Comment"); } - function getDescription() { + function getDescription() + { return _("Embed hidden comments in WikiPages."); } // No arguments here. - function getDefaultArguments() { + function getDefaultArguments() + { return array(); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { return HTML::raw(''); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/CreateBib.php b/lib/plugin/CreateBib.php index 6c1b86ece..c4801be7f 100644 --- a/lib/plugin/CreateBib.php +++ b/lib/plugin/CreateBib.php @@ -31,36 +31,37 @@ */ class WikiPlugin_CreateBib -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("CreateBib"); } - function getDescription() { + function getDescription() + { return _("Automatically create a Bibtex file from linked pages"); } - function getDefaultArguments() { - return array( 'pagename' => '[pagename]', // The page from which the BibTex file is generated - ); + function getDefaultArguments() + { + return array('pagename' => '[pagename]', // The page from which the BibTex file is generated + ); } // Have to include the $starttag and $endtag to the regexps... - function extractBibTeX (&$content, $starttag, $endtag) + function extractBibTeX(&$content, $starttag, $endtag) { $bib = array(); $start = false; $stop = false; - for ($i=0; $i $thispage->get('mtime'), 'is_ascii' => 1); + $attrib = array('mtime' => $thispage->get('mtime'), 'is_ascii' => 1); - $zip = new ZipWriter("Created by PhpWiki " . PHPWIKI_VERSION, $filename); - $zip->addRegularFile( FilenameForPage($thispage->getName()), - $mailified, $attrib); - $zip->finish(); + $zip = new ZipWriter("Created by PhpWiki " . PHPWIKI_VERSION, $filename); + $zip->addRegularFile(FilenameForPage($thispage->getName()), + $mailified, $attrib); + $zip->finish(); } - function run($dbi, $argstr, $request, $basepage) { + function run($dbi, $argstr, $request, $basepage) + { extract($this->getArgs($argstr, $request)); if ($pagename) { // Expand relative page names. @@ -119,11 +122,11 @@ extends WikiPlugin $dump_url = $request->getURLtoSelf(array("file" => "tube.bib")); global $WikiTheme; $dump_button = $WikiTheme->makeButton("To File", - $dump_url , 'foo'); + $dump_url, 'foo'); - $html = HTML::div(array('class' => 'bib','align' => 'left')); + $html = HTML::div(array('class' => 'bib', 'align' => 'left')); $html->pushContent($dump_button, ' '); - $list = HTML::pre(array('id'=>'biblist', 'class' => 'bib')); + $list = HTML::pre(array('id' => 'biblist', 'class' => 'bib')); // Let's find the subpages if ($articles = $this->extractArticles($content)) { @@ -153,7 +156,9 @@ extends WikiPlugin return $html; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/CreatePage.php b/lib/plugin/CreatePage.php index 703625a5a..f1a9703bd 100644 --- a/lib/plugin/CreatePage.php +++ b/lib/plugin/CreatePage.php @@ -36,29 +36,33 @@ include_once 'lib/plugin/Template.php'; class WikiPlugin_CreatePage -extends WikiPlugin_Template + extends WikiPlugin_Template { - function getName() { + function getName() + { return _("CreatePage"); } - function getDescription() { + function getDescription() + { return _("Create a Wiki page by the provided name."); } - function getDefaultArguments() { - return array('s' => false, - 'initial_content' => '', - 'template' => false, - 'vars' => false, - 'overwrite' => false, - 'verify' => false, // true or a pagename - //'buttontext' => false, - //'method' => 'POST' - ); + function getDefaultArguments() + { + return array('s' => false, + 'initial_content' => '', + 'template' => false, + 'vars' => false, + 'overwrite' => false, + 'verify' => false, // true or a pagename + //'buttontext' => false, + //'method' => 'POST' + ); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { extract($this->getArgs($argstr, $request)); // Prevent spaces at the start and end of a page name $s = trim($s); @@ -77,7 +81,7 @@ extends WikiPlugin_Template $main = subPageSlice(0); if (!$dbi->isWikiPage(subPageSlice(0))) { $msg .= "\n" . _("The new page you want to create will be a subpage.") - . "\n" . _("Subpages cannot be created unless the parent page exists."); + . "\n" . _("Subpages cannot be created unless the parent page exists."); return alert($head, $msg); } else { $msg .= "\n" . _("The new page you want to create will be a subpage."); @@ -104,7 +108,8 @@ extends WikiPlugin_Template // FIXME: expand vars in templates here. if (strlen($url) > 255 or ($param['template']) - or preg_match('/%%\w+%%/', $initial_content)) // need variable expansion + or preg_match('/%%\w+%%/', $initial_content) + ) // need variable expansion { unset($param['initial_content']); $url = WikiURL($s, $param, 'absurl'); @@ -117,7 +122,7 @@ extends WikiPlugin_Template } else { $user = $request->getUser(); $meta = array('markup' => 2.0, - 'author' => $user->getId()); + 'author' => $user->getId()); if (!empty($param['template']) and !$initial_content) { $tmplpage = $dbi->getPage($template); $currenttmpl = $tmplpage->getCurrentRevision(); @@ -126,7 +131,7 @@ extends WikiPlugin_Template if (preg_match('/.+<\/noinclude>/s', $initial_content)) { $initial_content = preg_replace("/.+?<\/noinclude>/s", "", - $initial_content); + $initial_content); } } $meta['summary'] = _("Created by CreatePage"); @@ -138,12 +143,14 @@ extends WikiPlugin_Template $url = WikiURL($s, $param, 'absurl'); } - $page->save($content, $version+1, $meta); + $page->save($content, $version + 1, $meta); } } return HTML($request->redirect($url, true)); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/CreateToc.php b/lib/plugin/CreateToc.php index c0ccfebd3..4dda9bbd0 100644 --- a/lib/plugin/CreateToc.php +++ b/lib/plugin/CreateToc.php @@ -40,55 +40,62 @@ if (!defined('TOC_FULL_SYNTAX')) define('TOC_FULL_SYNTAX', 1); class WikiPlugin_CreateToc -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("CreateToc"); } - function getDescription() { + function getDescription() + { return _("Create a Table of Contents and automatically link to headers"); } - function getDefaultArguments() { - return array('extracollapse' => 1, // provide an entry +/- link to collapse - 'firstlevelstyle' => 'number', // 'number', 'letter' or 'roman' - 'headers' => "1,2,3,4,5", // "!!!"=>h2, "!!"=>h3, "!"=>h4 - // "1"=>h2, "2"=>h3, "3"=>h4, "4"=>h5, "5"=>h6 - 'indentstr' => '  ', - 'jshide' => 0, // collapsed TOC as DHTML button - 'liststyle' => 'dl', // 'dl' or 'ul' or 'ol' - 'noheader' => 0, // omit "Table of Contents" header - 'notoc' => 0, // do not display TOC, only number headers - 'pagename' => '[pagename]', // TOC of another page here? - 'position' => 'full', // full, right or left - 'width' => '200px', - 'with_counter' => 0, - 'with_toclink' => 0, // link back to TOC - 'version' => false, - ); + function getDefaultArguments() + { + return array('extracollapse' => 1, // provide an entry +/- link to collapse + 'firstlevelstyle' => 'number', // 'number', 'letter' or 'roman' + 'headers' => "1,2,3,4,5", // "!!!"=>h2, "!!"=>h3, "!"=>h4 + // "1"=>h2, "2"=>h3, "3"=>h4, "4"=>h5, "5"=>h6 + 'indentstr' => '  ', + 'jshide' => 0, // collapsed TOC as DHTML button + 'liststyle' => 'dl', // 'dl' or 'ul' or 'ol' + 'noheader' => 0, // omit "Table of Contents" header + 'notoc' => 0, // do not display TOC, only number headers + 'pagename' => '[pagename]', // TOC of another page here? + 'position' => 'full', // full, right or left + 'width' => '200px', + 'with_counter' => 0, + 'with_toclink' => 0, // link back to TOC + 'version' => false, + ); } + // Initialisation of toc counter - function _initTocCounter() { - $counter = array(1=>0, 2=>0, 3=>0, 4=>0, 5=>0); + function _initTocCounter() + { + $counter = array(1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0); return $counter; } // Update toc counter with a new title - function _tocCounter(&$counter, $level) { + function _tocCounter(&$counter, $level) + { $counter[$level]++; - for($i = $level+1; $i <= 5; $i++) { + for ($i = $level + 1; $i <= 5; $i++) { $counter[$i] = 0; } } - function _roman_counter($number) { + function _roman_counter($number) + { $n = intval($number); $result = ''; $lookup = array('C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40, - 'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1); + 'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1); foreach ($lookup as $roman => $value) { $matches = intval($n / $value); @@ -98,52 +105,64 @@ extends WikiPlugin return $result; } - function _letter_counter($number) { + function _letter_counter($number) + { if ($number <= 26) { return chr(ord("A") + $number - 1); } else { - return chr(ord("A") + ($number/26) - 1) . chr(ord("A") + ($number%26)); + return chr(ord("A") + ($number / 26) - 1) . chr(ord("A") + ($number % 26)); } } // Get string corresponding to the current title - function _getCounter(&$counter, $level, $firstlevelstyle) { + function _getCounter(&$counter, $level, $firstlevelstyle) + { if ($firstlevelstyle == 'roman') { - $str= $this->_roman_counter($counter[1]); + $str = $this->_roman_counter($counter[1]); } elseif ($firstlevelstyle == 'letter') { - $str= $this->_letter_counter($counter[1]); + $str = $this->_letter_counter($counter[1]); } else { - $str=$counter[1]; + $str = $counter[1]; } - for($i = 2; $i <= 5; $i++) { - if($counter[$i] != 0) - $str .= '.'.$counter[$i]; + for ($i = 2; $i <= 5; $i++) { + if ($counter[$i] != 0) + $str .= '.' . $counter[$i]; } return $str; } // Get HTML header corresponding to current level (level is set of ! or =) - function _getHeader($level) { + function _getHeader($level) + { - $count = substr_count($level,'!'); + $count = substr_count($level, '!'); switch ($count) { - case 3: return "h2"; - case 2: return "h3"; - case 1: return "h4"; + case 3: + return "h2"; + case 2: + return "h3"; + case 1: + return "h4"; } - $count = substr_count($level,'='); + $count = substr_count($level, '='); switch ($count) { - case 2: return "h2"; - case 3: return "h3"; - case 4: return "h4"; - case 5: return "h5"; - case 6: return "h6"; + case 2: + return "h2"; + case 3: + return "h3"; + case 4: + return "h4"; + case 5: + return "h5"; + case 6: + return "h6"; } return ""; } - function _quote($heading) { - if (TOC_FULL_SYNTAX ) { + function _quote($heading) + { + if (TOC_FULL_SYNTAX) { $theading = TransformInline($heading); if ($theading) return preg_quote($theading->asXML(), "/"); @@ -158,50 +177,48 @@ extends WikiPlugin * @param $hstart id (in $content) of heading start * @param $hend id (in $content) of heading end */ - function searchHeader ($content, $start_index, $heading, - $level, &$hstart, &$hend, $basepage=false) { + function searchHeader($content, $start_index, $heading, + $level, &$hstart, &$hend, $basepage = false) + { $hstart = 0; $hend = 0; $h = $this->_getHeader($level); $qheading = $this->_quote($heading); - for ($j=$start_index; $j < count($content); $j++) { + for ($j = $start_index; $j < count($content); $j++) { if (is_string($content[$j])) { if (preg_match("/<$h>$qheading<\/$h>/", - $content[$j])) + $content[$j]) + ) return $j; - } - elseif (isa($content[$j], 'cached_link')) - { - if (method_exists($content[$j],'asXML')) { + } elseif (isa($content[$j], 'cached_link')) { + if (method_exists($content[$j], 'asXML')) { $content[$j]->_basepage = $basepage; $content[$j] = $content[$j]->asXML(); } else $content[$j] = $content[$j]->asString(); // shortcut for single wikiword or link headers if ($content[$j] == $heading - and substr($content[$j-1],-4,4) == "<$h>" - and substr($content[$j+1],0,5) == "") - { - $hstart = $j-1; - $hend = $j+1; + and substr($content[$j - 1], -4, 4) == "<$h>" + and substr($content[$j + 1], 0, 5) == "" + ) { + $hstart = $j - 1; + $hend = $j + 1; return $j; // single wikiword - } - elseif (TOC_FULL_SYNTAX) { + } elseif (TOC_FULL_SYNTAX) { //DONE: To allow "!! WikiWord link" or !! http://anylink/ // Check against joined content (after cached_plugininvocation). // The first link is the anchor then. - if (preg_match("/<$h>(?!.*<\/$h>)/", $content[$j-1])) { - $hstart = $j-1; + if (preg_match("/<$h>(?!.*<\/$h>)/", $content[$j - 1])) { + $hstart = $j - 1; $joined = ''; - for ($k=max($j-1,$start_index);$kasXML(); - else + elseif (method_exists($content[$k], 'asXML')) + $joined .= $content[$k]->asXML(); else $joined .= $content[$k]->asString(); - if (preg_match("/<$h>$qheading<\/$h>/",$joined)) { - $hend=$k; + if (preg_match("/<$h>$qheading<\/$h>/", $joined)) { + $hend = $k; return $k; } } @@ -218,14 +235,15 @@ extends WikiPlugin /** prevent from duplicate anchors, * beautify spaces: " " => "_" and not "x20." */ - function _nextAnchor($s) { + function _nextAnchor($s) + { static $anchors = array(); - $s = str_replace(' ','_',$s); + $s = str_replace(' ', '_', $s); $i = 1; $anchor = $s; while (!empty($anchors[$anchor])) { - $anchor = sprintf("%s_%d",$s,$i++); + $anchor = sprintf("%s_%d", $s, $i++); } $anchors[$anchor] = $i; return $anchor; @@ -237,10 +255,10 @@ extends WikiPlugin // We must omit lines starting with "!" if inside a Mediawiki table // (they represent a table header) // Feature request: proper nesting; multiple levels (e.g. 1,3) - function extractHeaders (&$content, &$markup, $backlink=0, - $counter=0, $levels=false, $firstlevelstyle='number', $basepage='') + function extractHeaders(&$content, &$markup, $backlink = 0, + $counter = 0, $levels = false, $firstlevelstyle = 'number', $basepage = '') { - if (!$levels) $levels = array(1,2); + if (!$levels) $levels = array(1, 2); $tocCounter = $this->_initTocCounter(); reset($levels); sort($levels); @@ -248,39 +266,42 @@ extends WikiPlugin $j = 0; $insidetable = false; $insideverbatim = false; - for ($i=0; $i/', $content[$i]) - || preg_match('/^\s*/', $content[$i])) { - $insideverbatim = true; - continue; + || preg_match('/^\s*
/', $content[$i])
+                || preg_match('/^\s*/', $content[$i])
+            ) {
+                $insideverbatim = true;
+                continue;
             } elseif (preg_match('/^\s*\|}/', $content[$i])) {
-               $insidetable = false;
-               continue;
+                $insidetable = false;
+                continue;
             } elseif (preg_match('/^\s*}}}/', $content[$i])
-                    || preg_match('/^\s*<\/pre>/', $content[$i])
-                    || preg_match('/^\s*<\/verbatim>/', $content[$i])) {
-               $insideverbatim = false;
-               continue;
+                || preg_match('/^\s*<\/pre>/', $content[$i])
+                || preg_match('/^\s*<\/verbatim>/', $content[$i])
+            ) {
+                $insideverbatim = false;
+                continue;
             }
             if (($insidetable) || ($insideverbatim)) {
-               continue;
+                continue;
             }
             foreach ($levels as $level) {
                 if ($level < 1 or $level > 5) continue;
-                $phpwikiclassiclevel = 4 -$level;
+                $phpwikiclassiclevel = 4 - $level;
                 $wikicreolelevel = $level + 1;
                 $trim = trim($content[$i]);
 
                 if ((((strpos($trim, '=') === 0))
-                      && (preg_match('/^\s*(={'.$wikicreolelevel.','.$wikicreolelevel.'})([^=].*)$/', $content[$i], $match)))
-                   or (((strpos($trim, '!') === 0))
-                      && ((preg_match('/^\s*(!{'.$phpwikiclassiclevel.','.$phpwikiclassiclevel.'})([^!].*)$/', $content[$i], $match))))) {
+                    && (preg_match('/^\s*(={' . $wikicreolelevel . ',' . $wikicreolelevel . '})([^=].*)$/', $content[$i], $match)))
+                    or (((strpos($trim, '!') === 0))
+                        && ((preg_match('/^\s*(!{' . $phpwikiclassiclevel . ',' . $phpwikiclassiclevel . '})([^!].*)$/', $content[$i], $match))))
+                ) {
                     $this->_tocCounter($tocCounter, $level);
-                    if (!strstr($content[$i],'#[')) {
+                    if (!strstr($content[$i], '#[')) {
                         $s = trim($match[2]);
                         // If it is Wikicreole syntax, remove '='s at the end
                         if (string_starts_with($match[1], "=")) {
@@ -290,27 +311,27 @@ extends WikiPlugin
                         $anchor = $this->_nextAnchor($s);
                         $manchor = MangleXmlIdentifier($anchor);
                         $texts = $s;
-                        if($counter) {
-                            $texts = $this->_getCounter($tocCounter, $level, $firstlevelstyle).' '.$s;
+                        if ($counter) {
+                            $texts = $this->_getCounter($tocCounter, $level, $firstlevelstyle) . ' ' . $s;
                         }
                         $headers[] = array('text' => $texts,
-                                           'anchor' => $anchor,
-                                           'level' => $level);
+                            'anchor' => $anchor,
+                            'level' => $level);
                         // Change original wikitext, but that is useless art...
-                        $content[$i] = $match[1]." #[|$manchor][$s|#TOC]";
+                        $content[$i] = $match[1] . " #[|$manchor][$s|#TOC]";
                         // And now change the to be printed markup (XmlTree):
                         // Search $s line in markup
                         /* Url for backlink */
-                        $url = WikiURL(new WikiPageName($basepage,false,"TOC"));
+                        $url = WikiURL(new WikiPageName($basepage, false, "TOC"));
 
                         $j = $this->searchHeader($markup->_content, $j, $s,
-                                                 $match[1], $hstart, $hend,
-                                                 $markup->_basepage);
+                            $match[1], $hstart, $hend,
+                            $markup->_basepage);
                         if ($j and isset($markup->_content[$j])) {
                             $x = $markup->_content[$j];
                             $qheading = $this->_quote($s);
                             if ($counter)
-                                 $counterString = $this->_getCounter($tocCounter, $level, $firstlevelstyle);
+                                $counterString = $this->_getCounter($tocCounter, $level, $firstlevelstyle);
                             if (($hstart === 0) && is_string($markup->_content[$j])) {
                                 if ($backlink) {
                                     if ($counter)
@@ -322,12 +343,13 @@ extends WikiPlugin
                                     if ($counter)
                                         $anchorString .= "$counterString - ";
                                 }
-                                if ($x = preg_replace('/()('.$qheading.')(<\/h\d>)/',
-                                                      "\$1$anchorString\$2\$3",$x,1)) {
+                                if ($x = preg_replace('/()(' . $qheading . ')(<\/h\d>)/',
+                                    "\$1$anchorString\$2\$3", $x, 1)
+                                ) {
                                     if ($backlink) {
-                                        $x = preg_replace('/()('.$qheading.')(<\/h\d>)/',
-                                                          "\$1$anchorString\$3",
-                                                          $markup->_content[$j],1);
+                                        $x = preg_replace('/()(' . $qheading . ')(<\/h\d>)/',
+                                            "\$1$anchorString\$3",
+                                            $markup->_content[$j], 1);
                                     }
                                     $markup->_content[$j] = $x;
                                 }
@@ -343,18 +365,17 @@ extends WikiPlugin
                                          * title with a WikiWord */
                                         $anchorString = "\$1";
                                     }
-                                }
-                                else {
+                                } else {
                                     $anchorString = "\$1";
                                     if ($counter)
                                         $anchorString .= "$counterString - ";
                                 }
                                 $x = preg_replace("/(<$h>)(?!.*<\/$h>)/",
-                                                  $anchorString, $x, 1);
+                                    $anchorString, $x, 1);
                                 if ($backlink) {
-                                    $x =  preg_replace("/(<$h>)(?!.*<\/$h>)/",
-                                                      $anchorString,
-                                                      $markup->_content[$hstart],1);
+                                    $x = preg_replace("/(<$h>)(?!.*<\/$h>)/",
+                                        $anchorString,
+                                        $markup->_content[$hstart], 1);
                                 }
                                 $markup->_content[$hstart] = $x;
                             }
@@ -366,7 +387,8 @@ extends WikiPlugin
         return $headers;
     }
 
-    function run($dbi, $argstr, &$request, $basepage) {
+    function run($dbi, $argstr, &$request, $basepage)
+    {
         global $WikiTheme;
         extract($this->getArgs($argstr, $request));
         if ($pagename) {
@@ -384,8 +406,9 @@ extends WikiPlugin
             $with_counter = 1;
         }
         if ($firstlevelstyle and ($firstlevelstyle != 'number')
-                             and ($firstlevelstyle != 'letter')
-                             and ($firstlevelstyle != 'roman')) {
+            and ($firstlevelstyle != 'letter')
+                and ($firstlevelstyle != 'roman')
+        ) {
             return $this->error(_("Error: firstlevelstyle must be 'number', 'letter' or 'roman'"));
         }
 
@@ -395,21 +418,21 @@ extends WikiPlugin
         }
 
         // Check if user is allowed to get the page.
-        if (!mayAccessPage ('view', $pagename)) {
+        if (!mayAccessPage('view', $pagename)) {
             return $this->error(sprintf(_("Illegal access to page %s: no read access"),
-            $pagename));
+                $pagename));
         }
 
         $page = $dbi->getPage($pagename);
 
         if ($version) {
-            if (!is_whole_number($version) or !($version>0)) {
+            if (!is_whole_number($version) or !($version > 0)) {
                 return $this->error(_("Error: version must be a positive integer."));
             }
             $r = $page->getRevision($version);
             if ((!$r) || ($r->hasDefaultContents())) {
                 return $this->error(sprintf(_("%s: no such revision %d."),
-                                            $pagename, $version));
+                    $pagename, $version));
             }
         } else {
             $r = $page->getCurrentRevision();
@@ -418,92 +441,94 @@ extends WikiPlugin
         $current = $page->getCurrentRevision();
         //FIXME: I suspect this only to crash with Apache2
         if (!$current->get('markup') or $current->get('markup') < 2) {
-            if (in_array(php_sapi_name(),array('apache2handler','apache2filter'))) {
+            if (in_array(php_sapi_name(), array('apache2handler', 'apache2filter'))) {
                 return $this->error(_("CreateToc disabled for old markup."));
             }
         }
 
         $content = $r->getContent();
 
-        $html = HTML::div(array('class' => 'toc', 'id'=> GenerateId("toc")));
+        $html = HTML::div(array('class' => 'toc', 'id' => GenerateId("toc")));
         if ($notoc) {
-            $html->setAttr('style','display:none;');
+            $html->setAttr('style', 'display:none;');
         }
         if (($position == "left") or ($position == "right")) {
-            $html->setAttr('style','float:'.$position.'; width:'.$width.';');
+            $html->setAttr('style', 'float:' . $position . '; width:' . $width . ';');
         }
         $toclistid = GenerateId("toclist");
-        $list = HTML::div(array('id'=>$toclistid, 'class'=>'toclist'));
-        if (!strstr($headers,",")) {
+        $list = HTML::div(array('id' => $toclistid, 'class' => 'toclist'));
+        if (!strstr($headers, ",")) {
             $headers = array($headers);
         } else {
-            $headers = explode(",",$headers);
+            $headers = explode(",", $headers);
         }
         $levels = array();
         foreach ($headers as $h) {
             //replace !!! with level 1, ...
-            if (strstr($h,"!")) {
-                $hcount = substr_count($h,'!');
-                $level = min(max(1, $hcount),3);
+            if (strstr($h, "!")) {
+                $hcount = substr_count($h, '!');
+                $level = min(max(1, $hcount), 3);
                 $levels[] = $level;
             } else {
-                $level = min(max(1, (int) $h), 5);
+                $level = min(max(1, (int)$h), 5);
                 $levels[] = $level;
             }
         }
         if (TOC_FULL_SYNTAX)
             require_once 'lib/InlineParser.php';
         if ($headers = $this->extractHeaders($content, $dbi->_markup,
-                                             $with_toclink, $with_counter,
-                                             $levels, $firstlevelstyle, $basepage))
-        {
+            $with_toclink, $with_counter,
+            $levels, $firstlevelstyle, $basepage)
+        ) {
             foreach ($headers as $h) {
                 // proper heading indent
                 $level = $h['level'];
                 $indent = $level - 1;
-                $link = new WikiPageName($pagename,$page,$h['anchor']);
-                $li = WikiLink($link,'known',$h['text']);
+                $link = new WikiPageName($pagename, $page, $h['anchor']);
+                $li = WikiLink($link, 'known', $h['text']);
                 // Hack to suppress pagename before #
                 // $li->_attr["href"] = strstr($li->_attr["href"], '#');
                 $list->pushContent(HTML::p(HTML::raw
-                       (str_repeat($indentstr,$indent)),$li));
+                (str_repeat($indentstr, $indent)), $li));
             }
         }
-        $list->setAttr('style','display:'.($jshide?'none;':'block;'));
-        $open = DATA_PATH.'/'.$WikiTheme->_findFile("images/folderArrowOpen.png");
-        $close = DATA_PATH.'/'.$WikiTheme->_findFile("images/folderArrowClosed.png");
-      if ($noheader) {
-      } else {
-        $toctoggleid = GenerateId("toctoggle");
-        if ($extracollapse)
-            $toclink = HTML(_("Table of Contents"),
-                            " ",
-                            HTML::a(array('id'=>'TOC')),
-                            HTML::img(array(
-                                            'id'=>$toctoggleid,
-                                            'class'=>'wikiaction',
-                                            'title'=>_("Click to display to TOC"),
-                                            'onclick'=>"toggletoc(this, '".$open."', '".$close."', '".$toclistid."')",
-                                            'alt' => 'toctoggle',
-                                            'src' => $jshide ? $close : $open )));
-        else
-            $toclink = HTML::a(array('id'=>'TOC',
-                                     'class'=>'wikiaction',
-                                     'title'=>_("Click to display"),
-                                     'onclick'=>"toggletoc(this, '".$open."', '".$close."', '".$toclistid."')"),
-                               _("Table of Contents"),
-                               HTML::span(array('style'=>'display:none',
-                                                'id'=>$toctoggleid)," "));
-        $html->pushContent(HTML::p(array('class'=>'toctitle'), $toclink));
-      }
-      $html->pushContent($list);
-      if (count($headers) == 0) {
-          // Do not display an empty TOC
-          $html->setAttr('style','display:none;');
-      }
-      return $html;
+        $list->setAttr('style', 'display:' . ($jshide ? 'none;' : 'block;'));
+        $open = DATA_PATH . '/' . $WikiTheme->_findFile("images/folderArrowOpen.png");
+        $close = DATA_PATH . '/' . $WikiTheme->_findFile("images/folderArrowClosed.png");
+        if ($noheader) {
+        } else {
+            $toctoggleid = GenerateId("toctoggle");
+            if ($extracollapse)
+                $toclink = HTML(_("Table of Contents"),
+                    " ",
+                    HTML::a(array('id' => 'TOC')),
+                    HTML::img(array(
+                        'id' => $toctoggleid,
+                        'class' => 'wikiaction',
+                        'title' => _("Click to display to TOC"),
+                        'onclick' => "toggletoc(this, '" . $open . "', '" . $close . "', '" . $toclistid . "')",
+                        'alt' => 'toctoggle',
+                        'src' => $jshide ? $close : $open)));
+            else
+                $toclink = HTML::a(array('id' => 'TOC',
+                        'class' => 'wikiaction',
+                        'title' => _("Click to display"),
+                        'onclick' => "toggletoc(this, '" . $open . "', '" . $close . "', '" . $toclistid . "')"),
+                    _("Table of Contents"),
+                    HTML::span(array('style' => 'display:none',
+                        'id' => $toctoggleid), " "));
+            $html->pushContent(HTML::p(array('class' => 'toctitle'), $toclink));
+        }
+        $html->pushContent($list);
+        if (count($headers) == 0) {
+            // Do not display an empty TOC
+            $html->setAttr('style', 'display:none;');
+        }
+        return $html;
     }
-};
+}
+
+;
 
 // Local Variables:
 // mode: php
diff --git a/lib/plugin/CurrentTime.php b/lib/plugin/CurrentTime.php
index 681f57d01..17ed1c12f 100644
--- a/lib/plugin/CurrentTime.php
+++ b/lib/plugin/CurrentTime.php
@@ -51,23 +51,27 @@
  */
 
 class WikiPlugin_CurrentTime
-extends WikiPlugin
+    extends WikiPlugin
 {
-    function getName () {
+    function getName()
+    {
         return _("CurrentTime");
     }
 
-    function getDescription () {
+    function getDescription()
+    {
         return _("A simple plugin that displays current time and date");
 
     }
 
     // Establish default values for each of this plugin's arguments.
-    function getDefaultArguments() {
-        return array('format'  => '%Y-%m-%d %T');
+    function getDefaultArguments()
+    {
+        return array('format' => '%Y-%m-%d %T');
     }
 
-    function run($dbi, $argstr, &$request, $basepage) {
+    function run($dbi, $argstr, &$request, $basepage)
+    {
         extract($this->getArgs($argstr, $request));
 
         if ($format == 'date') {
@@ -79,7 +83,9 @@ extends WikiPlugin
 
         return HTML::raw(strftime($format, time()));
     }
-};
+}
+
+;
 
 // Local Variables:
 // mode: php
diff --git a/lib/plugin/DeadEndPages.php b/lib/plugin/DeadEndPages.php
index ba0fa4b6f..227c70b41 100644
--- a/lib/plugin/DeadEndPages.php
+++ b/lib/plugin/DeadEndPages.php
@@ -25,12 +25,15 @@
 require_once 'lib/plugin/OrphanedPages.php';
 
 class WikiPlugin_DeadEndPages
-extends WikiPlugin_OrphanedPages
+    extends WikiPlugin_OrphanedPages
 {
-    function getName () {
+    function getName()
+    {
         return _("DeadEndPages");
     }
-};
+}
+
+;
 
 // Local Variables:
 // mode: php
diff --git a/lib/plugin/Diff.php b/lib/plugin/Diff.php
index b88addd50..395fd857d 100644
--- a/lib/plugin/Diff.php
+++ b/lib/plugin/Diff.php
@@ -30,27 +30,32 @@
 require_once 'lib/diff.php';
 
 class WikiPlugin_Diff
-extends WikiPlugin {
+    extends WikiPlugin
+{
 
-    function getName () {
+    function getName()
+    {
         return _("Diff");
     }
 
-    function getDescription () {
+    function getDescription()
+    {
         return _("Display differences between revisions");
     }
 
     // Establish default values for each of this plugin's arguments.
     // todo: makes only sense with more args.
-    function getDefaultArguments() {
+    function getDefaultArguments()
+    {
         return array('pagename' => '[pagename]',
-                     'versions' => false,
-                     'version'  => false,
-                     'previous' => 'major', // author, minor or major
-                     );
+            'versions' => false,
+            'version' => false,
+            'previous' => 'major', // author, minor or major
+        );
     }
 
-    function PageInfoRow ($label, $rev, &$request) {
+    function PageInfoRow($label, $rev, &$request)
+    {
 
         global $WikiTheme, $WikiNameRegexp;
 
@@ -64,16 +69,17 @@ extends WikiPlugin {
 
             $linked_version = WikiLink($rev, 'existing', $rev->getVersion());
             $row->pushContent(HTML::td(fmt("version %s", $linked_version)),
-                              HTML::td($WikiTheme->getLastModifiedMessage($rev,
-                                                                      false)),
-                              HTML::td(fmt("by %s", $authorlink)));
+                HTML::td($WikiTheme->getLastModifiedMessage($rev,
+                    false)),
+                HTML::td(fmt("by %s", $authorlink)));
         } else {
             $row->pushContent(HTML::td(array('colspan' => '3'), _("None")));
         }
         return $row;
     }
 
-    function run($dbi, $argstr, &$request, $basepage) {
+    function run($dbi, $argstr, &$request, $basepage)
+    {
         extract($this->getArgs($argstr, $request));
         if (is_array($versions)) {
             // Version selection from pageinfo.php display:
@@ -82,9 +88,9 @@ extends WikiPlugin {
         }
 
         // Check if user is allowed to get the Page.
-        if (!mayAccessPage ('view', $pagename)) {
-                return $this->error(sprintf(_("Illegal access to page %s: no read access"),
-                                        $pagename));
+        if (!mayAccessPage('view', $pagename)) {
+            return $this->error(sprintf(_("Illegal access to page %s: no read access"),
+                $pagename));
         }
 
         // abort if page doesn't exist
@@ -92,7 +98,7 @@ extends WikiPlugin {
         $current = $page->getCurrentRevision();
         if ($current->getVersion() < 1) {
             $html = HTML(HTML::p(fmt("I'm sorry, there is no such page as %s.",
-                                     WikiLink($pagename, 'unknown'))));
+                WikiLink($pagename, 'unknown'))));
             return $html; //early return
         }
 
@@ -100,45 +106,43 @@ extends WikiPlugin {
             if (!($new = $page->getRevision($version)))
                 NoSuchRevision($request, $page, $version);
             $new_version = fmt("version %d", $version);
-        }
-        else {
+        } else {
             $new = $current;
             $new_version = _("current version");
         }
 
         if (preg_match('/^\d+$/', $previous)) {
-            if ( !($old = $page->getRevision($previous)) )
+            if (!($old = $page->getRevision($previous)))
                 NoSuchRevision($request, $page, $previous);
             $old_version = fmt("version %d", $previous);
             $others = array('major', 'minor', 'author');
-        }
-        else {
+        } else {
             switch ($previous) {
-            case 'author':
-                $old = $new;
-                while ($old = $page->getRevisionBefore($old)) {
-                    if ($old->get('author') != $new->get('author'))
-                        break;
-                }
-                $old_version = _("revision by previous author");
-                $others = array('major', 'minor');
-                break;
-            case 'minor':
-                $previous='minor';
-                $old = $page->getRevisionBefore($new);
-                $old_version = _("previous revision");
-                $others = array('major', 'author');
-                break;
-            case 'major':
-            default:
-                $old = $new;
-                while ($old && $old->get('is_minor_edit'))
-                    $old = $page->getRevisionBefore($old);
-                if ($old)
-                    $old = $page->getRevisionBefore($old);
-                $old_version = _("predecessor to the previous major change");
-                $others = array('minor', 'author');
-                break;
+                case 'author':
+                    $old = $new;
+                    while ($old = $page->getRevisionBefore($old)) {
+                        if ($old->get('author') != $new->get('author'))
+                            break;
+                    }
+                    $old_version = _("revision by previous author");
+                    $others = array('major', 'minor');
+                    break;
+                case 'minor':
+                    $previous = 'minor';
+                    $old = $page->getRevisionBefore($new);
+                    $old_version = _("previous revision");
+                    $others = array('major', 'author');
+                    break;
+                case 'major':
+                default:
+                    $old = $new;
+                    while ($old && $old->get('is_minor_edit'))
+                        $old = $page->getRevisionBefore($old);
+                    if ($old)
+                        $old = $page->getRevisionBefore($old);
+                    $old_version = _("predecessor to the previous major change");
+                    $others = array('minor', 'author');
+                    break;
             }
         }
 
@@ -147,12 +151,12 @@ extends WikiPlugin {
         $page_link = WikiLink($page);
 
         $html = HTML(HTML::p(fmt("Differences between %s and %s of %s.",
-                                 $new_link, $old_link, $page_link)));
+            $new_link, $old_link, $page_link)));
 
         $otherdiffs = HTML::p(_("Other diffs:"));
         $label = array('major' => _("Previous Major Revision"),
-                       'minor' => _("Previous Revision"),
-                       'author'=> _("Previous Author"));
+            'minor' => _("Previous Revision"),
+            'author' => _("Previous Author"));
         foreach ($others as $other) {
             $args = array('pagename' => $pagename, 'previous' => $other);
             if ($version)
@@ -170,23 +174,23 @@ extends WikiPlugin {
             $old = false;
 
         $html->pushContent(HTML::Table($this->PageInfoRow(_("Newer page:"), $new,
-                                                          $request),
-                                       $this->PageInfoRow(_("Older page:"), $old,
-                                                          $request)));
+                $request),
+            $this->PageInfoRow(_("Older page:"), $old,
+                $request)));
 
         if ($new && $old) {
             $diff = new Diff($old->getContent(), $new->getContent());
 
             if ($diff->isEmpty()) {
                 $html->pushContent(HTML::hr(),
-                                   HTML::p(_("Content of versions "), $old->getVersion(),
-                                           _(" and "), $new->getVersion(), _(" is identical.")));
+                    HTML::p(_("Content of versions "), $old->getVersion(),
+                        _(" and "), $new->getVersion(), _(" is identical.")));
                 // If two consecutive versions have the same content, it is because the page was
                 // renamed, or metadata changed: ACL, owner, markup.
                 // We give the reason by printing the summary.
                 if (($new->getVersion() - $old->getVersion()) == 1) {
                     $html->pushContent(HTML::p(_("Version "), $new->getVersion(),
-                                               _(" was created because: "), $new->get('summary')));
+                        _(" was created because: "), $new->get('summary')));
                 }
             } else {
                 $fmt = new HtmlUnifiedDiffFormatter;
@@ -196,7 +200,9 @@ extends WikiPlugin {
 
         return $html;
     }
-};
+}
+
+;
 
 // Local Variables:
 // mode: php
diff --git a/lib/plugin/DynamicIncludePage.php b/lib/plugin/DynamicIncludePage.php
index ac34e34cb..20ad7f6e2 100644
--- a/lib/plugin/DynamicIncludePage.php
+++ b/lib/plugin/DynamicIncludePage.php
@@ -29,26 +29,30 @@
 require_once 'lib/plugin/IncludePage.php';
 
 class WikiPlugin_DynamicIncludePage
-extends WikiPlugin_IncludePage
+    extends WikiPlugin_IncludePage
 {
-    function getName() {
+    function getName()
+    {
         return _("DynamicIncludePage");
     }
 
-    function getDescription() {
+    function getDescription()
+    {
         return _("Dynamically include the content from another wiki page.");
     }
 
-    function getDefaultArguments() {
-            return array_merge
-            (WikiPlugin_IncludePage::getDefaultArguments(),
-             array(
-                   'state'   => false, // initial state: false <=> [+], true <=> [-]
-                  ));
+    function getDefaultArguments()
+    {
+        return array_merge
+        (WikiPlugin_IncludePage::getDefaultArguments(),
+            array(
+                'state' => false, // initial state: false <=> [+], true <=> [-]
+            ));
     }
 
-    function run($dbi, $argstr, &$request, $basepage) {
-            global $WikiTheme;
+    function run($dbi, $argstr, &$request, $basepage)
+    {
+        global $WikiTheme;
         $args = $this->getArgs($argstr, $request, false);
         $page =& $args['page'];
         if (ENABLE_AJAX) {
@@ -56,30 +60,30 @@ extends WikiPlugin_IncludePage
                 $html = WikiPlugin_IncludePage::run($dbi, $argstr, $request, $basepage);
             else
                 $html = HTML(HTML::p(array('class' => 'transclusion-title'),
-                                 fmt(" %s :", WikiLink($page))),
-                             HTML::div(array('class' => 'transclusion'), ''));
+                        fmt(" %s :", WikiLink($page))),
+                    HTML::div(array('class' => 'transclusion'), ''));
             $ajaxuri = WikiURL($page, array('format' => 'xml'));
         } else {
             $html = WikiPlugin_IncludePage::run($dbi, $argstr, $request, $basepage);
         }
         $header = $html->_content[0];
-        $body   = $html->_content[1];
-        $id = 'DynInc-'.MangleXmlIdentifier($page);
-        $body->setAttr('id', $id.'-body');
-        $png = $WikiTheme->_findData('images/folderArrow'.
-                                    ($args['state'] ? 'Open' : 'Closed').
-                                    '.png');
-        $icon = HTML::img(array('id'  => $id.'-img',
-                                'src' => $png,
-                                'onclick' => ENABLE_AJAX
-                                  ? "showHideAsync('".$ajaxuri."','$id')"
-                                  : "showHideFolder('$id')",
-                                'alt' => _("Click to hide/show"),
-                                'title'  => _("Click to hide/show")));
+        $body = $html->_content[1];
+        $id = 'DynInc-' . MangleXmlIdentifier($page);
+        $body->setAttr('id', $id . '-body');
+        $png = $WikiTheme->_findData('images/folderArrow' .
+            ($args['state'] ? 'Open' : 'Closed') .
+            '.png');
+        $icon = HTML::img(array('id' => $id . '-img',
+            'src' => $png,
+            'onclick' => ENABLE_AJAX
+                ? "showHideAsync('" . $ajaxuri . "','$id')"
+                : "showHideFolder('$id')",
+            'alt' => _("Click to hide/show"),
+            'title' => _("Click to hide/show")));
         $header = HTML::p(array('class' => 'transclusion-title',
-                                'style' => "text-decoration: none;"),
-                          $icon,
-                          fmt(" %s :", WikiLink($page)));
+                'style' => "text-decoration: none;"),
+            $icon,
+            fmt(" %s :", WikiLink($page)));
         if ($args['state']) { // show base
             $body->setAttr('style', 'display:block');
             return HTML($header, $body);
@@ -91,7 +95,9 @@ extends WikiPlugin_IncludePage
                 return HTML($header, $body); // sync (load but display:none)
         }
     }
-};
+}
+
+;
 
 // Local Variables:
 // mode: php
diff --git a/lib/plugin/EditMetaData.php b/lib/plugin/EditMetaData.php
index 6d5c741f1..d4ed290b7 100644
--- a/lib/plugin/EditMetaData.php
+++ b/lib/plugin/EditMetaData.php
@@ -42,29 +42,33 @@
 require_once 'lib/plugin/_BackendInfo.php';
 
 class WikiPlugin_EditMetaData
-extends WikiPlugin__BackendInfo
+    extends WikiPlugin__BackendInfo
 {
-    function getName () {
+    function getName()
+    {
         return _("EditMetaData");
     }
 
-    function getDescription () {
+    function getDescription()
+    {
         return sprintf(_("Edit metadata for %s"), '[pagename]');
     }
 
-    function getDefaultArguments() {
-        return array('page'       => '[pagename]'
-                    );
+    function getDefaultArguments()
+    {
+        return array('page' => '[pagename]'
+        );
     }
 
-    function run($dbi, $argstr, &$request, $basepage) {
+    function run($dbi, $argstr, &$request, $basepage)
+    {
         $this->_args = $this->getArgs($argstr, $request);
         extract($this->_args);
         if (!$page)
             return '';
 
-        $this->hidden_pagemeta = array ('_cached_html');
-        $this->readonly_pagemeta = array ('hits', 'passwd');
+        $this->hidden_pagemeta = array('_cached_html');
+        $this->readonly_pagemeta = array('hits', 'passwd');
         $dbi = $request->getDbh();
         $p = $dbi->getPage($page);
         $pagemeta = $p->getMetaData();
@@ -75,30 +79,30 @@ extends WikiPlugin__BackendInfo
         //
         if ($request->isPost()
             and $request->_user->isAdmin()
-            and $request->getArg('metaedit'))
-        {
+                and $request->getArg('metaedit')
+        ) {
             $metafield = trim($request->getArg('metafield'));
             $metavalue = trim($request->getArg('metavalue'));
             $meta = $request->getArg('meta');
             $changed = 0;
             // meta[__global[_upgrade][name]] => 1030.13
             foreach ($meta as $key => $val) {
-                    if ($val != $pagemeta[$key]
-                    and !in_array($key, $this->readonly_pagemeta))
-                {
-                        $changed++;
+                if ($val != $pagemeta[$key]
+                    and !in_array($key, $this->readonly_pagemeta)
+                ) {
+                    $changed++;
                     $p->set($key, $val);
                 }
             }
             if ($metafield and !in_array($metafield, $this->readonly_pagemeta)) {
-                    // __global[_upgrade][name] => 1030.13
+                // __global[_upgrade][name] => 1030.13
                 if (preg_match('/^(.*?)\[(.*?)\]$/', $metafield, $matches)) {
                     list(, $array_field, $array_key) = $matches;
                     $array_value = $pagemeta[$array_field];
                     $array_value[$array_key] = $metavalue;
                     if ($pagemeta[$array_field] != $array_value) {
-                            $changed++;
-                            $p->set($array_field, $array_value);
+                        $changed++;
+                        $p->set($array_field, $array_value);
                     }
                 } elseif ($pagemeta[$metafield] != $metavalue) {
                     $changed++;
@@ -108,7 +112,7 @@ extends WikiPlugin__BackendInfo
             if ($changed) {
                 $dbi->touch();
                 $url = $request->getURLtoSelf(false,
-                                          array('meta','metaedit','metafield','metavalue'));
+                    array('meta', 'metaedit', 'metafield', 'metavalue'));
                 $request->redirect($url);
                 // The rest of the output will not be seen due to the
                 // redirect.
@@ -126,11 +130,10 @@ extends WikiPlugin__BackendInfo
             // FIXME: invalid HTML
             $html->pushContent(HTML::p(fmt("No metadata for %s", $page)));
             $table = HTML();
-        }
-        else {
+        } else {
             $table = HTML::table(array('border' => 1,
-                                       'cellpadding' => 2,
-                                       'cellspacing' => 0));
+                'cellpadding' => 2,
+                'cellspacing' => 0));
             $this->_fixupData($pagemeta);
             $table->pushContent($this->_showhash("MetaData('$page')", $pagemeta));
         }
@@ -143,16 +146,16 @@ extends WikiPlugin__BackendInfo
             $valfield = HTML::input(array('name' => 'metavalue'), '');
             $button = Button('submit:metaedit', _("Submit"), false);
             $form = HTML::form(array('action' => $action,
-                                     'method' => 'post',
-                                     'accept-charset' => $GLOBALS['charset']),
-                               $hiddenfield,
-                               // edit existing fields
-                               $table,
-                               // add new ones
-                               $instructions, HTML::br(),
-                               $keyfield, ' => ', $valfield,
-                               HTML::raw(' '), $button
-                               );
+                    'method' => 'post',
+                    'accept-charset' => $GLOBALS['charset']),
+                $hiddenfield,
+                // edit existing fields
+                $table,
+                // add new ones
+                $instructions, HTML::br(),
+                $keyfield, ' => ', $valfield,
+                HTML::raw(' '), $button
+            );
 
             $html->pushContent($form);
         } else {
@@ -161,20 +164,21 @@ extends WikiPlugin__BackendInfo
         return $html;
     }
 
-    function _showvalue ($key, $val, $prefix='') {
-            if (is_array($val) or is_object($val)) return $val;
+    function _showvalue($key, $val, $prefix = '')
+    {
+        if (is_array($val) or is_object($val)) return $val;
         if (in_array($key, $this->hidden_pagemeta)) return '';
         if ($prefix) {
             $fullkey = $prefix . '[' . $key . ']';
-            if (substr($fullkey,0,1) == '[') {
-                    $meta = "meta".$fullkey;
-                    $fullkey = preg_replace("/\]\[/", "[", substr($fullkey, 1), 1);
+            if (substr($fullkey, 0, 1) == '[') {
+                $meta = "meta" . $fullkey;
+                $fullkey = preg_replace("/\]\[/", "[", substr($fullkey, 1), 1);
             } else {
                 $meta = preg_replace("/^([^\[]+)\[/", "meta[$1][", $fullkey, 1);
             }
         } else {
             $fullkey = $key;
-            $meta = "meta[".$key."]";
+            $meta = "meta[" . $key . "]";
         }
         //$meta = "meta[".$fullkey."]";
         $arr = array('name' => $meta, 'value' => $val);
@@ -185,10 +189,12 @@ extends WikiPlugin__BackendInfo
             return HTML::input($arr);
         } else {
             return HTML(HTML::em($fullkey), HTML::br(),
-                            HTML::input($arr));
+                HTML::input($arr));
         }
     }
-};
+}
+
+;
 
 // Local Variables:
 // mode: php
diff --git a/lib/plugin/ExternalSearch.php b/lib/plugin/ExternalSearch.php
index dee3c014b..f2f2b690a 100644
--- a/lib/plugin/ExternalSearch.php
+++ b/lib/plugin/ExternalSearch.php
@@ -25,27 +25,30 @@
  * See http://phpwiki.sourceforge.net/phpwiki/ExternalSearchPlugin
  *
  * useimage sample:
-   ExternalSearch
-     url="http://www.geourl.org/near/?xsize=2048&ysize=1024&xoffset=1650&yoffset=550"
-     useimage="http://www.geourl.org/maps/au.png"
-     name="Go Godzilla All Over It"
+ExternalSearch
+url="http://www.geourl.org/near/?xsize=2048&ysize=1024&xoffset=1650&yoffset=550"
+useimage="http://www.geourl.org/maps/au.png"
+name="Go Godzilla All Over It"
  */
 if (!defined("EXTERNALSEARCH_DEFAULT_BUTTON_POSITION"))
     define("EXTERNALSEARCH_DEFAULT_BUTTON_POSITION", "right");
 
 class WikiPlugin_ExternalSearch
-extends WikiPlugin
+    extends WikiPlugin
 {
-    function getName () {
+    function getName()
+    {
         return _("ExternalSearch");
     }
 
-    function getDescription () {
+    function getDescription()
+    {
         return _("Redirects to an external web site based on form input");
         //fixme: better description
     }
 
-    function _getInterWikiUrl(&$request) {
+    function _getInterWikiUrl(&$request)
+    {
         $intermap = getInterwikiMap();
         $map = $intermap->_map;
 
@@ -58,21 +61,23 @@ extends WikiPlugin
             $this->_name = $this->getName();
     }
 
-    function getDefaultArguments() {
-        return array('s'        => false,
-                     'formsize' => 30,
-                     'url'      => false,
-                     'name'     => '',
-                     'useimage' => false,
-                     'width'    => false,
-                     'height'   => false,
-                     'debug'    => false,
-                     'button_position' => EXTERNALSEARCH_DEFAULT_BUTTON_POSITION,
-                     // 'left' or 'right'
-                     );
+    function getDefaultArguments()
+    {
+        return array('s' => false,
+            'formsize' => 30,
+            'url' => false,
+            'name' => '',
+            'useimage' => false,
+            'width' => false,
+            'height' => false,
+            'debug' => false,
+            'button_position' => EXTERNALSEARCH_DEFAULT_BUTTON_POSITION,
+            // 'left' or 'right'
+        );
     }
 
-    function run($dbi, $argstr, &$request, $basepage) {
+    function run($dbi, $argstr, &$request, $basepage)
+    {
         $args = $this->getArgs($argstr, $request);
         if (empty($args['url']))
             return '';
@@ -101,42 +106,42 @@ extends WikiPlugin
         $this->_url = $url;
         $this->_getInterWikiUrl($request);
         $form = HTML::form(array('action' => $request->getPostURL(),
-                                 'method' => 'post',
-                                 //'class'  => 'class', //fixme
-                                 'accept-charset' => $GLOBALS['charset']),
-                           HiddenInputs(array('pagename' => $basepage)));
+                'method' => 'post',
+                //'class'  => 'class', //fixme
+                'accept-charset' => $GLOBALS['charset']),
+            HiddenInputs(array('pagename' => $basepage)));
 
         $form->pushContent(HTML::input(array('type' => 'hidden',
-                                             'name'  => 'url',
-                                             'value' => $this->_url)));
+            'name' => 'url',
+            'value' => $this->_url)));
         $s = HTML::input(array('type' => 'text',
-                               'value' => $this->_s,
-                               'name'  => 's',
-                               'size'  => $formsize));
+            'value' => $this->_s,
+            'name' => 's',
+            'size' => $formsize));
         if (!empty($args["useimage"])) {
             //FIXME: This does not work with Gecko
             $button = HTML::img(array('src' => $useimage, 'alt' => 'imagebutton'));
             if (!empty($width))
-                $button->setAttr('width',$width);
+                $button->setAttr('width', $width);
             if (!empty($height))
-                $button->setAttr('height',$height);
+                $button->setAttr('height', $height);
             // on button_position => none display no input form
             if ($button_position == 'right')
                 $form->pushContent($s);
             $form->pushContent(HTML::button(array('type' => 'button',
-                                                  'class' => 'button',
-                                                  'value' => $this->_name,
-                                                  ),
-                                            $button));
+                    'class' => 'button',
+                    'value' => $this->_name,
+                ),
+                $button));
             if ($button_position == 'left')
                 $form->pushContent($s);
         } else {
             if ($button_position != 'left' and $button_position != 'right')
                 return $this->error(fmt("Invalid argument: %s=%s",
-                                        'button_position', $button_position));
+                    'button_position', $button_position));
             $button = HTML::input(array('type' => 'submit',
-                                        'class' => 'button',
-                                        'value' => $this->_name));
+                'class' => 'button',
+                'value' => $this->_name));
             if ($button_position == 'left') {
                 $form->pushContent($button);
                 $form->pushContent($s);
@@ -147,7 +152,9 @@ extends WikiPlugin
         }
         return $form;
     }
-};
+}
+
+;
 
 // Local Variables:
 // mode: php
diff --git a/lib/plugin/FacebookLike.php b/lib/plugin/FacebookLike.php
index fcab70813..1fbfc8ac2 100644
--- a/lib/plugin/FacebookLike.php
+++ b/lib/plugin/FacebookLike.php
@@ -21,57 +21,62 @@
  */
 
 /**
- Optional opengraph page meta data to be added to head.tmpl:
-  og:title - The title of your page; if not specified, the title element will be used.
-  og:site_name - The name of your web site, e.g., "CNN" or "IMDb".
-  og:image - The URL of the best picture for this page. The image must be at least
-             50px by 50px and have a maximum aspect ratio of 3:1.
-*/
+Optional opengraph page meta data to be added to head.tmpl:
+og:title - The title of your page; if not specified, the title element will be used.
+og:site_name - The name of your web site, e.g., "CNN" or "IMDb".
+og:image - The URL of the best picture for this page. The image must be at least
+50px by 50px and have a maximum aspect ratio of 3:1.
+ */
 
 class WikiPlugin_FacebookLike
-extends WikiPlugin
+    extends WikiPlugin
 {
-    function getDescription() {
+    function getDescription()
+    {
         return _("Display a Facebook Like button. See http://developers.facebook.com/docs/reference/plugins/like");
     }
 
-    function getDefaultArguments() {
-        return array('width'       => 450,
-                     'height'      => 35,
-                     //'title'       => '',    // override $TITLE (i.e. pagename)
-                     'colorscheme' => 'light', // or "dark"
-                     'show_faces'  => "false",
-                     'layout'      => "standard", // or "button_count"
-                     'action'      => "like",   // or "recommend"
-                     );
+    function getDefaultArguments()
+    {
+        return array('width' => 450,
+            'height' => 35,
+            //'title'       => '',    // override $TITLE (i.e. pagename)
+            'colorscheme' => 'light', // or "dark"
+            'show_faces' => "false",
+            'layout' => "standard", // or "button_count"
+            'action' => "like", // or "recommend"
+        );
     }
 
-    function run($dbi, $argstr, &$request, $basepage) {
+    function run($dbi, $argstr, &$request, $basepage)
+    {
         $args = $this->getArgs($argstr, $request);
         extract($args);
 
         //$iframe = "";
         $urlargs = array(
-                         "layout"     => $layout,
-                         "show_faces" => $show_faces,
-                         "width"      => $width,
-                         "action"     => "like", // or "recommend"
-                         "colorscheme"=> $colorscheme,
-                         "height"     => $height
-                         );
+            "layout" => $layout,
+            "show_faces" => $show_faces,
+            "width" => $width,
+            "action" => "like", // or "recommend"
+            "colorscheme" => $colorscheme,
+            "height" => $height
+        );
         $pagename = $request->getArg('pagename');
         $url = "http://www.facebook.com/plugins/like.php?"
-             . "href=" . urlencode(WikiUrl($pagename,$urlargs,true));
-        $url = str_replace("%3D","=",$url);
-        $params = array("src"               => $url,
-                        "scrolling"         => 'no',
-                        "frameborder"       => '0',
-                        "style"             => "border:none; overflow:hidden; "
-                                             . "width:$width"."px; height:$height"."px;",
-                        "allowtransparency" => "true");
+            . "href=" . urlencode(WikiUrl($pagename, $urlargs, true));
+        $url = str_replace("%3D", "=", $url);
+        $params = array("src" => $url,
+            "scrolling" => 'no',
+            "frameborder" => '0',
+            "style" => "border:none; overflow:hidden; "
+                . "width:$width" . "px; height:$height" . "px;",
+            "allowtransparency" => "true");
         return HTML::iframe($params);
     }
-};
+}
+
+;
 
 // Local Variables:
 // mode: php
diff --git a/lib/plugin/FileInfo.php b/lib/plugin/FileInfo.php
index bd9f0148e..ecced82fd 100644
--- a/lib/plugin/FileInfo.php
+++ b/lib/plugin/FileInfo.php
@@ -34,27 +34,31 @@
  */
 
 class WikiPlugin_FileInfo
-extends WikiPlugin
+    extends WikiPlugin
 {
-    function getName () {
+    function getName()
+    {
         return _("FileInfo");
     }
 
-    function getDescription () {
+    function getDescription()
+    {
         return _("Display file information like version, size, date... of uploaded files.");
     }
 
-    function getDefaultArguments() {
+    function getDefaultArguments()
+    {
         return array(
-                     'file'      => false, // relative path from PHPWIKI_DIR. (required)
-                     'display'   => false, // version,phonysize,size,date,mtime,owner,name,path,dirname,link.  (required)
-                     'format'    => false, // printf format string with %s only, all display modes
-                     'quiet'     => false  // print no error if file not found
-                                           // from above vars return strings (optional)
-                    );
+            'file' => false, // relative path from PHPWIKI_DIR. (required)
+            'display' => false, // version,phonysize,size,date,mtime,owner,name,path,dirname,link.  (required)
+            'format' => false, // printf format string with %s only, all display modes
+            'quiet' => false // print no error if file not found
+            // from above vars return strings (optional)
+        );
     }
 
-    function run($dbi, $argstr, &$request, $basepage) {
+    function run($dbi, $argstr, &$request, $basepage)
+    {
         $args = $this->getArgs($argstr, $request);
         extract($args);
         if (!$file) {
@@ -64,7 +68,7 @@ extends WikiPlugin
             return $this->error(sprintf(_("A required argument '%s' is missing."), 'display'));
         }
         if (string_starts_with($file, "Upload:")) {
-            $file = preg_replace("/^Upload:(.*)$/", getUploadFilePath()."\\1", $file);
+            $file = preg_replace("/^Upload:(.*)$/", getUploadFilePath() . "\\1", $file);
             $is_Upload = 1;
         }
         $dir = getcwd();
@@ -90,7 +94,7 @@ extends WikiPlugin
                 // For convenience we warn the admin
                 if ($quiet and $user->isAdmin())
                     return HTML::span(array('title' => _("Output suppressed. FileInfoPlugin with local files require a locked page.")),
-                                      HTML::em(_("page not locked")));
+                        HTML::em(_("page not locked")));
                 else
                     return $this->error("Invalid path \"$file\". Only ADMIN can allow local paths, and the page must be locked.");
             }
@@ -99,41 +103,69 @@ extends WikiPlugin
         $modes = explode(",", $display);
         foreach ($modes as $mode) {
             switch ($mode) {
-            case 'version':  $s[] = $this->exeversion($file); break;
-            case 'size':     $s[] = filesize($file); break;
-            case 'phonysize':$s[] = $this->phonysize(filesize($file)); break;
-            case 'date':     $s[] = strftime("%x %X", filemtime($file)); break;
-            case 'mtime':    $s[] = filemtime($file); break;
-            case 'owner':    $o = posix_getpwuid(fileowner($file)); $s[] = $o['name']; break;
-            case 'group':    $o = posix_getgrgid(filegroup($file)); $s[] = $o['name']; break;
-            case 'name':     $s[] = basename($file); break;
-            case 'path':     $s[] = $file; break;
-            case 'dirname':  $s[] = dirname($file); break;
-            case 'magic':    $s[] = $this->magic($file); break;
-            case 'mime-typ': $s[] = $this->mime_type($file); break;
-            case 'link':
-                if ($is_Upload) {
-                    $s[] = " [".$args['file'] . "]";
-                } elseif ($isuploaded) {
-                    // will fail with user uploads
-                    $s[] = " [Upload:".basename($file)."]";
-                } else {
-                    $s[] = " [".basename($file)."] ";
-                }
-                break;
-            default:
-                if (!$quiet) {
-                    return $this->error(sprintf(_("Unsupported argument: %s=%s"), 'display', $mode));
-                } else {
-                    return HTML::raw('');
-                }
-                break;
+                case 'version':
+                    $s[] = $this->exeversion($file);
+                    break;
+                case 'size':
+                    $s[] = filesize($file);
+                    break;
+                case 'phonysize':
+                    $s[] = $this->phonysize(filesize($file));
+                    break;
+                case 'date':
+                    $s[] = strftime("%x %X", filemtime($file));
+                    break;
+                case 'mtime':
+                    $s[] = filemtime($file);
+                    break;
+                case 'owner':
+                    $o = posix_getpwuid(fileowner($file));
+                    $s[] = $o['name'];
+                    break;
+                case 'group':
+                    $o = posix_getgrgid(filegroup($file));
+                    $s[] = $o['name'];
+                    break;
+                case 'name':
+                    $s[] = basename($file);
+                    break;
+                case 'path':
+                    $s[] = $file;
+                    break;
+                case 'dirname':
+                    $s[] = dirname($file);
+                    break;
+                case 'magic':
+                    $s[] = $this->magic($file);
+                    break;
+                case 'mime-typ':
+                    $s[] = $this->mime_type($file);
+                    break;
+                case 'link':
+                    if ($is_Upload) {
+                        $s[] = " [" . $args['file'] . "]";
+                    } elseif ($isuploaded) {
+                        // will fail with user uploads
+                        $s[] = " [Upload:" . basename($file) . "]";
+                    } else {
+                        $s[] = " [" . basename($file) . "] ";
+                    }
+                    break;
+                default:
+                    if (!$quiet) {
+                        return $this->error(sprintf(_("Unsupported argument: %s=%s"), 'display', $mode));
+                    } else {
+                        return HTML::raw('');
+                    }
+                    break;
             }
         }
         chdir($dir);
         if (!$format) {
             $format = '';
-            foreach ($s as $x) { $format .= " %s"; }
+            foreach ($s as $x) {
+                $format .= " %s";
+            }
         }
         array_unshift($s, $format);
         // $x, array($i,$j) => sprintf($x, $i, $j)
@@ -146,12 +178,13 @@ extends WikiPlugin
         }
     }
 
-    function magic($file) {
+    function magic($file)
+    {
         if (function_exists('finfo_file') or loadPhpExtension('fileinfo')) {
             // Valid finfo_open (i.e. libmagic) options:
             // FILEINFO_NONE | FILEINFO_SYMLINK | FILEINFO_MIME | FILEINFO_COMPRESS | FILEINFO_DEVICES |
             // FILEINFO_CONTINUE | FILEINFO_PRESERVE_ATIME | FILEINFO_RAW
-            $f = finfo_open(/*FILEINFO_MIME*/);
+            $f = finfo_open( /*FILEINFO_MIME*/);
             $result = finfo_file(realpath($file));
             finfo_close($res);
             return $result;
@@ -159,18 +192,22 @@ extends WikiPlugin
         return '';
     }
 
-    function mime_type($file) {
+    function mime_type($file)
+    {
         return '';
     }
 
-    function _formatsize ($n, $factor, $suffix = '') {
+    function _formatsize($n, $factor, $suffix = '')
+    {
         if ($n > $factor) {
             $b = $n / $factor;
             $n -= floor($factor * $b);
-            return number_format($b, $n ? 3 : 0). $suffix;
+            return number_format($b, $n ? 3 : 0) . $suffix;
         }
     }
-    function phonysize ($a) {
+
+    function phonysize($a)
+    {
         $factor = 1024 * 1024 * 1000;
         if ($a > $factor)
             return $this->_formatsize($a, $factor, ' GB');
@@ -186,8 +223,9 @@ extends WikiPlugin
             return $a;
     }
 
-    function exeversion($file) {
-            if (!isWindows()) return "?";
+    function exeversion($file)
+    {
+        if (!isWindows()) return "?";
         if (class_exists('ffi') or loadPhpExtension('ffi'))
             return $this->exeversion_ffi($file);
         if (function_exists('res_list_type') or loadPhpExtension('win32std'))
@@ -197,13 +235,15 @@ extends WikiPlugin
     }
 
     // http://www.codeproject.com/dll/showver.asp
-    function exeversion_showver($file) {
+    function exeversion_showver($file)
+    {
         $path = realpath($file);
         $result = `showver $path`;
-            return "?";
+        return "?";
     }
 
-    function exeversion_ffi($file) {
+    function exeversion_ffi($file)
+    {
         if (!DEBUG)
             return "?"; // not yet stable
 
@@ -239,35 +279,36 @@ struct VS_VERSIONINFO { struct VS_VERSIONINFO
 ";
             $ffi = new ffi($win32_idl);
             $dummy = 0; // &DWORD
-             $size = $ffi->GetFileVersionInfoSizeA($file, $dummy);
+            $size = $ffi->GetFileVersionInfoSizeA($file, $dummy);
             //$pVer = str_repeat($size+1);
             $pVer = new ffi_struct($ffi, "VS_VERSIONINFO");
             if ($ffi->GetFileVersionInfoA($file, 0, $size, $pVer)
-                and $pVer->wValueLength) {
+                and $pVer->wValueLength
+            ) {
                 // analyze the VS_FIXEDFILEINFO(Value);
                 // $pValue = new ffi_struct($ffi, "VS_FIXEDFILEINFO");
                 $pValue =& $pVer->Value;
                 return sprintf("%d.%d.%d.%d",
-                               $pValue->dwFileVersionMS >> 16,
-                               $pValue->dwFileVersionMS & 0xFFFF,
-                               $pValue->dwFileVersionLS >> 16,
-                               $pValue->dwFileVersionLS & 0xFFFF);
+                    $pValue->dwFileVersionMS >> 16,
+                    $pValue->dwFileVersionMS & 0xFFFF,
+                    $pValue->dwFileVersionLS >> 16,
+                    $pValue->dwFileVersionLS & 0xFFFF);
             }
         }
     }
 
     // Read "RT_VERSION/VERSIONINFO" exe/dll resource info for MSWin32 binaries
     // The "win32std" extension is not ready yet to pass back a VERSIONINFO struct
-    function exeversion_resopen($file) {
+    function exeversion_resopen($file)
+    {
         if (function_exists('res_list_type') or loadPhpExtension('win32std')) {
             // See http://msdn.microsoft.com/workshop/networking/predefined/res.asp
-            $v = file_get_contents('res://'.realpath($file).urlencode('/RT_VERSION/#1'));
+            $v = file_get_contents('res://' . realpath($file) . urlencode('/RT_VERSION/#1'));
             if ($v) {
-                    // This is really a binary VERSIONINFO block, with lots of
-                    // nul bytes (widechar) which cannot be transported as string.
-                    return "$v";
-            }
-            else {
+                // This is really a binary VERSIONINFO block, with lots of
+                // nul bytes (widechar) which cannot be transported as string.
+                return "$v";
+            } else {
                 $h = res_open(realpath($file));
                 $v = res_get($h, 'RT_VERSION', 'FileVersion');
                 res_close($h);
@@ -282,23 +323,23 @@ struct VS_VERSIONINFO { struct VS_VERSIONINFO
             /* The version consists of two 32-bit integers, defined by four 16-bit integers.
                For example, "FILEVERSION 3,10,0,61" is translated into two doublewords:
                0x0003000a and 0x0000003d, in that order. */
-/*
-        $h = res_open(realpath($file));
+            /*
+                    $h = res_open(realpath($file));
 
-        echo "Res list of '$file': \n";
-        $list= res_list_type($h, true);
-        if( $list===FALSE ) err( "Can't list type" );
+                    echo "Res list of '$file': \n";
+                    $list= res_list_type($h, true);
+                    if( $list===FALSE ) err( "Can't list type" );
 
-        for( $i= 0; $iheavily based on an example file distributed with XML_FOAF 0.2
-* HTTP GET vars:
-* foaf=uri - Used to determine the URI of a FOAF file.
-* original=true - Simply dumps contents of $foaf
-*
-* @author Daniel O'Connor 
-* @author Davey Shafik 
-* @date 2004-06-07
-* @version 0.0.2
-* @bug XML_FOAF 0.2 has problems with named RDF nodes (ie, http://www.ahsonline.com.au/dod/FOAF.rdf).
-*      Davey knows, will be fixing this soon.
-* @todo "Friends" component
-* @todo Named URLs (DC metadata)
-* @todo "View in FOAFNAUT/foafexplorer/other"
-* @bug Full name !available incorrectly handled.
-*/
+ * Basic FoafViewPlugin for PHPWiki.
+ *
+ * Please note; this is heavily based on an example file distributed with XML_FOAF 0.2
+ * HTTP GET vars:
+ * foaf=uri - Used to determine the URI of a FOAF file.
+ * original=true - Simply dumps contents of $foaf
+ *
+ * @author Daniel O'Connor 
+ * @author Davey Shafik 
+ * @date 2004-06-07
+ * @version 0.0.2
+ * @bug XML_FOAF 0.2 has problems with named RDF nodes (ie, http://www.ahsonline.com.au/dod/FOAF.rdf).
+ *      Davey knows, will be fixing this soon.
+ * @todo "Friends" component
+ * @todo Named URLs (DC metadata)
+ * @todo "View in FOAFNAUT/foafexplorer/other"
+ * @bug Full name !available incorrectly handled.
+ */
 
 /**
  * FoafViewer:  Parse an RDF FOAF file and extract information to render as HTML
@@ -53,34 +53,39 @@
  *  - fix the pear FOAF Parser or we'll write our own (based on our XmlParser)
  */
 class WikiPlugin_FoafViewer
-extends WikiPlugin
+    extends WikiPlugin
 {
     // The handler is handled okay. The only problem is that it still
     // throws a fatal.
-    function _error_handler($error) {
-        if (strstr($error->errstr,"Failed opening required 'XML/FOAF/Parser.php'"))
+    function _error_handler($error)
+    {
+        if (strstr($error->errstr, "Failed opening required 'XML/FOAF/Parser.php'"))
             return true;
-        elseif (strstr($error->errstr,'No such file or directory'))
+        elseif (strstr($error->errstr, 'No such file or directory'))
             return true;
         return false;
     }
 
-    function getName() {
+    function getName()
+    {
         return _("FoafViewer");
     }
 
-    function getDescription() {
+    function getDescription()
+    {
         return _("Parse an RDF FOAF file and extract information to render as HTML");
     }
 
-    function getDefaultArguments() {
-        return array( 'foaf'     => false, // the URI to parse
-                      //'userid'   => false,
-                      'original' => false
-                      );
+    function getDefaultArguments()
+    {
+        return array('foaf' => false, // the URI to parse
+            //'userid'   => false,
+            'original' => false
+        );
     }
 
-    function run($dbi, $argstr, &$request, $basepage) {
+    function run($dbi, $argstr, &$request, $basepage)
+    {
 
         /* ignore fatal on loading */
         /*
@@ -89,7 +94,7 @@ extends WikiPlugin
         */
         // Require the XML_FOAF_Parser class. This is a pear library not included with phpwiki.
         // see doc/README.foaf
-        if (findFile('XML/FOAF/Parser.php','missing_ok'))
+        if (findFile('XML/FOAF/Parser.php', 'missing_ok'))
             require_once 'XML/FOAF/Parser.php';
         //$ErrorManager->popErrorHandler();
         if (!class_exists('XML_FOAF_Parser'))
@@ -98,31 +103,29 @@ extends WikiPlugin
         extract($this->getArgs($argstr, $request));
         // Get our FOAF File from the foaf plugin argument or $_GET['foaf']
         if (empty($foaf)) $foaf = $request->getArg('foaf');
-        $chooser = HTML::form(array('method'=>'get','action'=>$request->getURLtoSelf()),
-                              HTML::h4(_("FOAF File URI")),
-                              HTML::input(array('id'=>'foaf','name'=>'foaf','type'=>'text','size'=>'80','value'=>$foaf)),
-                              HTML::br(),
-                              //HTML::p("Pretty HTML"),
-                              HTML::input(array('id'=>'pretty','name'=>'pretty','type'=>'radio','checked'=>'checked'),_("Pretty HTML")),
-                              //HTML::p("Original URL (Redirect)"),
-                              HTML::input(array('id'=>'original','name'=>'original','type'=>'radio'),_("Original URL (Redirect)")),
-                              HTML::br(),
-                              HTML::input(array('type'=>'submit','value'=>_("Parse FOAF")))
-                              //HTML::label(array('for'=>'foaf'),"FOAF File URI"),
-                              );
+        $chooser = HTML::form(array('method' => 'get', 'action' => $request->getURLtoSelf()),
+            HTML::h4(_("FOAF File URI")),
+            HTML::input(array('id' => 'foaf', 'name' => 'foaf', 'type' => 'text', 'size' => '80', 'value' => $foaf)),
+            HTML::br(),
+            //HTML::p("Pretty HTML"),
+            HTML::input(array('id' => 'pretty', 'name' => 'pretty', 'type' => 'radio', 'checked' => 'checked'), _("Pretty HTML")),
+            //HTML::p("Original URL (Redirect)"),
+            HTML::input(array('id' => 'original', 'name' => 'original', 'type' => 'radio'), _("Original URL (Redirect)")),
+            HTML::br(),
+            HTML::input(array('type' => 'submit', 'value' => _("Parse FOAF")))
+        //HTML::label(array('for'=>'foaf'),"FOAF File URI"),
+        );
         if (empty($foaf)) {
             return $chooser;
-        }
-        else {
+        } else {
             //Error Checking
-            if (substr($foaf,0,7) != "http://") {
+            if (substr($foaf, 0, 7) != "http://") {
                 return $this->error(_("foaf must be a URI starting with http://"));
             }
             // Start of output
-               if (!empty($original)) {
+            if (!empty($original)) {
                 $request->redirect($foaf);
-            }
-            else {
+            } else {
                 $foaffile = url_get_contents($foaf);
                 if (!$foaffile) {
                     //TODO: get errormsg
@@ -135,51 +138,51 @@ extends WikiPlugin
                 $a = $parser->toArray();
 
                 $html = HTML(HTML::h1(@$a[0]["name"]),
-                            HTML::table(
-                                        HTML::thead(),
-                                        HTML::tbody(
-                                                    @$a[0]["title"] ?
-                                                        HTML::tr(HTML::td(_("Title")),
-                                                                 HTML::td($a[0]["title"])) : null,
-                                                    (@$a[0]["homepage"][0]) ?
-                                                        $this->iterateHTML($a[0],"homepage",$a["dc"]) : null,
-                                                    (@$a[0]["weblog"][0]) ?
-                                                        $this->iterateHTML($a[0],"weblog",$a["dc"]) : null,
-                                                    //This seems broken?
-                                                    /*
-                                                     HTML::tr(HTML::td("Full Name"),
-                                                                       (@$a[0]["name"][0]) ?
-                                                                       HTML::td(@$a[0]["name"]) :
-                                                                       (@$a[0]["firstname"][0] && @$a[0]["surname"][0]) ?
-                                                                       HTML::td(@$a[0]["firstname"][0] . " " . @$a[0]["surname"][0])
-                                                                       : null
-                                                    */
-                                                    HTML::tr(HTML::td("Full Name"),
-                                                             (@$a[0]["name"][0]) ?
-                                                             HTML::td(@$a[0]["name"]) : null
-                                                             ),
-                                                    (@$a[0]["nick"][0]) ?
-                                                    $this->iterateHTML($a[0],"nick",$a["dc"])
-                                                    : null,
-                                                    (@$a[0]["mboxsha1sum"][0]) ?
-                                                    $this->iterateHTML($a[0],"mboxsha1sum",$a["dc"])
-                                                    : null,
-                                                    (@$a[0]["depiction"][0]) ?
-                                                    $this->iterateHTML($a[0],"depiction",$a["dc"])
-                                                    : null,
-                                                    (@$a[0]["seealso"][0]) ?
-                                                    $this->iterateHTML($a[0],"seealso",$a["dc"])
-                                                    : null,
-                                                    HTML::tr(HTML::td("Source"),
-                                                             HTML::td(
-                                                                      HTML::a(array('href'=>@$foaf),"RDF")
-                                                                      )
-                                                             )
-                                                    )
-                                        )
-                             );
+                    HTML::table(
+                        HTML::thead(),
+                        HTML::tbody(
+                            @$a[0]["title"] ?
+                                HTML::tr(HTML::td(_("Title")),
+                                    HTML::td($a[0]["title"])) : null,
+                            (@$a[0]["homepage"][0]) ?
+                                $this->iterateHTML($a[0], "homepage", $a["dc"]) : null,
+                            (@$a[0]["weblog"][0]) ?
+                                $this->iterateHTML($a[0], "weblog", $a["dc"]) : null,
+                            //This seems broken?
+                            /*
+                             HTML::tr(HTML::td("Full Name"),
+                                               (@$a[0]["name"][0]) ?
+                                               HTML::td(@$a[0]["name"]) :
+                                               (@$a[0]["firstname"][0] && @$a[0]["surname"][0]) ?
+                                               HTML::td(@$a[0]["firstname"][0] . " " . @$a[0]["surname"][0])
+                                               : null
+                            */
+                            HTML::tr(HTML::td("Full Name"),
+                                (@$a[0]["name"][0]) ?
+                                    HTML::td(@$a[0]["name"]) : null
+                            ),
+                            (@$a[0]["nick"][0]) ?
+                                $this->iterateHTML($a[0], "nick", $a["dc"])
+                                : null,
+                            (@$a[0]["mboxsha1sum"][0]) ?
+                                $this->iterateHTML($a[0], "mboxsha1sum", $a["dc"])
+                                : null,
+                            (@$a[0]["depiction"][0]) ?
+                                $this->iterateHTML($a[0], "depiction", $a["dc"])
+                                : null,
+                            (@$a[0]["seealso"][0]) ?
+                                $this->iterateHTML($a[0], "seealso", $a["dc"])
+                                : null,
+                            HTML::tr(HTML::td("Source"),
+                                HTML::td(
+                                    HTML::a(array('href' => @$foaf), "RDF")
+                                )
+                            )
+                        )
+                    )
+                );
                 if (DEBUG) {
-                    $html->pushContent(HTML::hr(),$chooser);
+                    $html->pushContent(HTML::hr(), $chooser);
                 }
                 return $html;
             }
@@ -194,19 +197,18 @@ extends WikiPlugin
      * @todo Make sure it can look more than 1 layer deep
      * @todo Pass in dublincore metadata
      */
-    function iterateHTML($array,$index,$dc=NULL) {
-        for ($i=0;$i'
-                    .'Plink - ' . $array[$index][$i] . '';
-            }
-            else if ($index == "depiction") {
+                    . 'Plink - ' . $array[$index][$i] . '';
+            } else if ($index == "depiction") {
                 $string = '';
-            }
-            else if ((substr($array[$index][$i],0,7) == "http://") || (substr($array[$index][$i],0,7) == "mailto:")) {
+            } else if ((substr($array[$index][$i], 0, 7) == "http://") || (substr($array[$index][$i], 0, 7) == "mailto:")) {
                 $string = ' false,       // the src url to include
-                      'page'        => false,
-                      'name'        => 'content',   // name of our frame
-                      'title'       => false,
-                      'rows'        => '18%,*,15%', // names: top, $name, bottom
-                      'cols'        => '20%,*',     // names: left, $name
-                                                    // only useful on WikiTheme "Sidebar"
-                      'frameborder' => 1,
-                      'marginwidth'  => false,
-                      'marginheight' => false,
-                      'noresize'    => false,
-                      'scrolling'   => 'auto',  // '[ yes | no | auto ]'
-                    );
+    function getDefaultArguments()
+    {
+        return array('src' => false, // the src url to include
+            'page' => false,
+            'name' => 'content', // name of our frame
+            'title' => false,
+            'rows' => '18%,*,15%', // names: top, $name, bottom
+            'cols' => '20%,*', // names: left, $name
+            // only useful on WikiTheme "Sidebar"
+            'frameborder' => 1,
+            'marginwidth' => false,
+            'marginheight' => false,
+            'noresize' => false,
+            'scrolling' => 'auto', // '[ yes | no | auto ]'
+        );
     }
 
-    function run($dbi, $argstr, &$request, $basepage) {
+    function run($dbi, $argstr, &$request, $basepage)
+    {
 
         $args = ($this->getArgs($argstr, $request));
         extract($args);
@@ -80,33 +84,33 @@ extends WikiPlugin
         if ($request->getArg('action') != 'browse') {
             return $this->disabled(_("Plugin not run: not in browse mode"));
         }
-        if (! $request->isGetOrHead()) {
+        if (!$request->isGetOrHead()) {
             return $this->disabled("(method != 'GET')");
         }
 
         if (!$src and $page) {
             if ($page == $request->get('pagename')) {
                 return $this->error(sprintf(_("Recursive inclusion of page %s"),
-                                            $page));
+                    $page));
             }
             $src = WikiURL($page);
         }
         if (!$src) {
             return $this->error(sprintf(_("%s or %s parameter missing"),
-                                        'src', 'page'));
+                'src', 'page'));
         }
 
         // FIXME: How to normalize url's to compare against recursion?
-        if ($src == $request->getURLtoSelf() ) {
+        if ($src == $request->getURLtoSelf()) {
             return $this->error(sprintf(_("Recursive inclusion of url %s"),
-                                        $src));
+                $src));
         }
 
         static $noframes = false;
         if ($noframes) {
             // Content for noframes version of page.
             return HTML::p(fmt("See %s",
-                               HTML::a(array('href' => $src), $src)));
+                HTML::a(array('href' => $src), $src)));
         }
         $noframes = true;
 
@@ -119,12 +123,12 @@ extends WikiPlugin
 
         // Generate the outer frameset
         $frame = HTML::frame(array('name' => $name,
-                                   'src' => $src,
-                                   'title' => $title,
-                                   'frameborder' => (int)$frameborder,
-                                   'scrolling' => (string)$scrolling,
-                                   'noresize' => (bool)$noresize,
-                                   ));
+            'src' => $src,
+            'title' => $title,
+            'frameborder' => (int)$frameborder,
+            'scrolling' => (string)$scrolling,
+            'noresize' => (bool)$noresize,
+        ));
 
         if ($marginwidth)
             $frame->setArg('marginwidth', $marginwidth);
@@ -132,17 +136,19 @@ extends WikiPlugin
             $frame->setArg('marginheight', $marginheight);
 
         $tokens = array('CONTENT_FRAME' => $frame,
-                        'ROWS' => $rows,
-                        'COLS' => $cols,
-                        'FRAMEARGS' => sprintf('frameborder="%d"', $frameborder),
-                        );
+            'ROWS' => $rows,
+            'COLS' => $cols,
+            'FRAMEARGS' => sprintf('frameborder="%d"', $frameborder),
+        );
 
         // Produce the frameset.
         $request->discardOutput();
         displayPage($request, new Template('frameset', $request, $tokens));
         $request->finish(); //noreturn
     }
-};
+}
+
+;
 
 // Local Variables:
 // mode: php
diff --git a/lib/plugin/FullTextSearch.php b/lib/plugin/FullTextSearch.php
index ac24fcf4f..a1a6e7e1e 100644
--- a/lib/plugin/FullTextSearch.php
+++ b/lib/plugin/FullTextSearch.php
@@ -40,31 +40,35 @@ require_once 'lib/PageList.php';
  *   php.ini: memory_limit = 32 MB
  */
 class WikiPlugin_FullTextSearch
-extends WikiPlugin
+    extends WikiPlugin
 {
-    function getName() {
+    function getName()
+    {
         return _("FullTextSearch");
     }
 
-    function getDescription() {
+    function getDescription()
+    {
         return _("Search the content of all pages in this wiki.");
     }
 
-    function getDefaultArguments() {
+    function getDefaultArguments()
+    {
         return array_merge
-            (
-             PageList::supportedArgs(), // paging and more.
-             array('s'        => false,
-                   'hilight'  => true,
-                   'case_exact' => false,
-                   'regex'    => 'auto',
-                   'sortby'   => '-hi_content',
-                   'noheader' => false,
-                   'exclude'  => false,   // comma-seperated list of glob
-                   'quiet'    => true));  // be less verbose
+        (
+            PageList::supportedArgs(), // paging and more.
+            array('s' => false,
+                'hilight' => true,
+                'case_exact' => false,
+                'regex' => 'auto',
+                'sortby' => '-hi_content',
+                'noheader' => false,
+                'exclude' => false, // comma-seperated list of glob
+                'quiet' => true)); // be less verbose
     }
 
-    function run($dbi, $argstr, &$request, $basepage) {
+    function run($dbi, $argstr, &$request, $basepage)
+    {
 
         $args = $this->getArgs($argstr, $request);
 
@@ -83,11 +87,11 @@ extends WikiPlugin
             unset($args['info']);
             $args['listtype'] = 'dl';
             $args['types'] = array(new _PageList_Column_content
-              ('rev:hi_content', _("Content"), "left", $s, $hilight_re));
+            ('rev:hi_content', _("Content"), "left", $s, $hilight_re));
             $list = new PageList(false, $exclude, $args);
             $list->setCaption(fmt("Full text search results for '%s'", $s));
             while ($page = $pages->next()) {
-                $list->addPage( $page );
+                $list->addPage($page);
             }
             return $list;
         }
@@ -102,7 +106,7 @@ extends WikiPlugin
         if ($exclude) $exclude = explodePageList($exclude);
         while ($page = $pages->next() and (!$limit or ($count < $limit))) {
             $name = $page->getName();
-            if ($exclude and in_array($name,$exclude)) continue;
+            if ($exclude and in_array($name, $exclude)) continue;
             $count++;
             $list->pushContent(HTML::dt(WikiLink($page)));
             if ($hilight_re)
@@ -110,57 +114,65 @@ extends WikiPlugin
             unset($page);
         }
         if ($limit and $count >= $limit) //todo: pager link to list of next matches
-            $list->pushContent(HTML::dd(fmt("only %d pages displayed",$limit)));
+            $list->pushContent(HTML::dd(fmt("only %d pages displayed", $limit)));
         if (!$list->getContent())
             $list->pushContent(HTML::dd(_("")));
 
         if (!empty($pages->stoplisted))
             $list = HTML(HTML::p(fmt(_("Ignored stoplist words '%s'"),
-                                     join(', ', $pages->stoplisted))),
-                         $list);
+                    join(', ', $pages->stoplisted))),
+                $list);
         if ($noheader)
             return $list;
         return HTML(HTML::p(fmt("Full text search results for '%s'", $s)),
-                    $list);
+            $list);
     }
 
-    function showhits($page, $hilight_re) {
+    function showhits($page, $hilight_re)
+    {
         $current = $page->getCurrentRevision();
         $matches = preg_grep("/$hilight_re/i", $current->getContent());
         $html = array();
         foreach ($matches as $line) {
             $line = $this->highlight_line($line, $hilight_re);
             $html[] = HTML::dd(HTML::small(array('class' => 'search-context'),
-                                           $line));
+                $line));
         }
         return $html;
     }
 
-    function highlight_line ($line, $hilight_re) {
+    function highlight_line($line, $hilight_re)
+    {
         while (preg_match("/^(.*?)($hilight_re)/i", $line, $m)) {
             $line = substr($line, strlen($m[0]));
-            $html[] = $m[1];    // prematch
+            $html[] = $m[1]; // prematch
             $html[] = HTML::strong(array('class' => 'search-term'), $m[2]); // match
         }
-        $html[] = $line;        // postmatch
+        $html[] = $line; // postmatch
         return $html;
     }
-};
+}
+
+;
 
 /*
  * List of Links and link to ListLinks
  */
-class _PageList_Column_hilight extends _PageList_Column {
-    function _PageList_Column_WantedPages_links (&$params) {
+class _PageList_Column_hilight extends _PageList_Column
+{
+    function _PageList_Column_WantedPages_links(&$params)
+    {
         $this->parentobj =& $params[3];
-        $this->_PageList_Column($params[0],$params[1],$params[2]);
+        $this->_PageList_Column($params[0], $params[1], $params[2]);
     }
-    function _getValue(&$page, $revision_handle) {
-            $html = false;
+
+    function _getValue(&$page, $revision_handle)
+    {
+        $html = false;
         $pagename = $page->getName();
         $count = count($this->parentobj->_wpagelist[$pagename]);
         return LinkURL(WikiURL($page, array('action' => 'BackLinks'), false),
-                        fmt("(%d Links)", $count));
+            fmt("(%d Links)", $count));
     }
 }
 
diff --git a/lib/plugin/FuzzyPages.php b/lib/plugin/FuzzyPages.php
index 46225eb4e..c68764b86 100644
--- a/lib/plugin/FuzzyPages.php
+++ b/lib/plugin/FuzzyPages.php
@@ -33,43 +33,50 @@
  * http://www.php.net/manual/en/function.metaphone.php
  */
 class WikiPlugin_FuzzyPages
-extends WikiPlugin
+    extends WikiPlugin
 {
-    function getName() {
+    function getName()
+    {
         return _("FuzzyPages");
     }
 
-    function getDescription() {
+    function getDescription()
+    {
         return sprintf(_("Search for page titles similar to %s."),
-                       '[pagename]');
+            '[pagename]');
     }
 
-    function getDefaultArguments() {
-        return array('s'     => false,
-                     'debug' => false);
+    function getDefaultArguments()
+    {
+        return array('s' => false,
+            'debug' => false);
     }
 
-    function spelling_similarity($subject) {
+    function spelling_similarity($subject)
+    {
         $spelling_similarity_score = 0;
         similar_text($subject, $this->_searchterm,
-                     $spelling_similarity_score);
+            $spelling_similarity_score);
         return $spelling_similarity_score;
     }
 
-    function sound_similarity($subject) {
+    function sound_similarity($subject)
+    {
         $sound_similarity_score = 0;
         similar_text(metaphone($subject), $this->_searchterm_metaphone,
-                     $sound_similarity_score);
+            $sound_similarity_score);
         return $sound_similarity_score;
     }
 
-    function averageSimilarities($subject) {
+    function averageSimilarities($subject)
+    {
         return ($this->spelling_similarity($subject)
-                + $this->sound_similarity($subject)) / 2;
+            + $this->sound_similarity($subject)) / 2;
     }
 
-    function collectSimilarPages(&$list, &$dbi) {
-        if (! defined('MIN_SCORE_CUTOFF'))
+    function collectSimilarPages(&$list, &$dbi)
+    {
+        if (!defined('MIN_SCORE_CUTOFF'))
             define('MIN_SCORE_CUTOFF', 33);
 
         $this->_searchterm_metaphone = metaphone($this->_searchterm);
@@ -84,22 +91,25 @@ extends WikiPlugin
         }
     }
 
-    function sortCollectedPages(&$list) {
+    function sortCollectedPages(&$list)
+    {
         arsort($list, SORT_NUMERIC);
     }
 
-    function addTableCaption(&$table, &$dbi) {
+    function addTableCaption(&$table, &$dbi)
+    {
         if ($dbi->isWikiPage($this->_searchterm))
             $link = WikiLink($this->_searchterm, 'auto');
         else
             $link = $this->_searchterm;
         $caption = fmt("These page titles match fuzzy with '%s'", $link);
-        $table->pushContent(HTML::caption(array('align'=>'top'), $caption));
+        $table->pushContent(HTML::caption(array('align' => 'top'), $caption));
     }
 
-    function addTableHead(&$table) {
+    function addTableHead(&$table)
+    {
         $row = HTML::tr(HTML::th(_("Name")),
-                        HTML::th(array('align' => 'right'), _("Score")));
+            HTML::th(array('align' => 'right'), _("Score")));
 
         if (defined('DEBUG') && DEBUG && $this->debug) {
             $this->_pushDebugHeadingTDinto($row);
@@ -108,18 +118,19 @@ extends WikiPlugin
         $table->pushContent(HTML::thead($row));
     }
 
-    function addTableBody(&$list, &$table) {
-        if (! defined('HIGHLIGHT_ROWS_CUTOFF_SCORE'))
+    function addTableBody(&$list, &$table)
+    {
+        if (!defined('HIGHLIGHT_ROWS_CUTOFF_SCORE'))
             define('HIGHLIGHT_ROWS_CUTOFF_SCORE', 60);
 
         $tbody = HTML::tbody();
         foreach ($list as $found_pagename => $score) {
             $row = HTML::tr(array('class' =>
-                                  $score > HIGHLIGHT_ROWS_CUTOFF_SCORE
-                                  ? 'evenrow' : 'oddrow'),
-                            HTML::td(WikiLink($found_pagename)),
-                            HTML::td(array('align' => 'right'),
-                                     round($score)));
+                $score > HIGHLIGHT_ROWS_CUTOFF_SCORE
+                    ? 'evenrow' : 'oddrow'),
+                HTML::td(WikiLink($found_pagename)),
+                HTML::td(array('align' => 'right'),
+                    round($score)));
 
             if (defined('DEBUG') && DEBUG && $this->debug) {
                 $this->_pushDebugTDinto($row, $found_pagename);
@@ -130,15 +141,16 @@ extends WikiPlugin
         $table->pushContent($tbody);
     }
 
-    function formatTable(&$list, &$dbi) {
+    function formatTable(&$list, &$dbi)
+    {
 
         if (empty($list)) {
-           return HTML::p(fmt("No fuzzy matches with '%s'", $this->_searchterm));
+            return HTML::p(fmt("No fuzzy matches with '%s'", $this->_searchterm));
         }
         $table = HTML::table(array('cellpadding' => 2,
-                                   'cellspacing' => 1,
-                                   'border'      => 0,
-                                   'class' => 'pagelist'));
+            'cellspacing' => 1,
+            'border' => 0,
+            'class' => 'pagelist'));
         $this->addTableCaption($table, $dbi);
         $this->addTableHead($table);
         $this->addTableBody($list, $table);
@@ -146,7 +158,8 @@ extends WikiPlugin
     }
 
 
-    function run($dbi, $argstr, &$request, $basepage) {
+    function run($dbi, $argstr, &$request, $basepage)
+    {
         $args = $this->getArgs($argstr, $request);
         extract($args);
         if (empty($s)) {
@@ -165,25 +178,29 @@ extends WikiPlugin
         return $this->formatTable($this->_list, $dbi);
     }
 
-    function _pushDebugHeadingTDinto(&$row) {
+    function _pushDebugHeadingTDinto(&$row)
+    {
         $row->pushContent(HTML::td(_("Spelling Score")),
-                          HTML::td(_("Sound Score")),
-                          HTML::td('Metaphones'));
+            HTML::td(_("Sound Score")),
+            HTML::td('Metaphones'));
     }
 
-    function _pushDebugTDinto(&$row, $pagename) {
+    function _pushDebugTDinto(&$row, $pagename)
+    {
         // This actually calculates everything a second time for each pagename
         // so the individual scores can be displayed separately for debugging.
         $debug_spelling = round($this->spelling_similarity($pagename), 1);
         $debug_sound = round($this->sound_similarity($pagename), 1);
         $debug_metaphone = sprintf("(%s, %s)", metaphone($pagename),
-                                   $this->_searchterm_metaphone);
+            $this->_searchterm_metaphone);
 
         $row->pushcontent(HTML::td(array('align' => 'center'), $debug_spelling),
-                          HTML::td(array('align' => 'center'), $debug_sound),
-                          HTML::td($debug_metaphone));
+            HTML::td(array('align' => 'center'), $debug_sound),
+            HTML::td($debug_metaphone));
     }
-};
+}
+
+;
 
 // Local Variables:
 // mode: php
diff --git a/lib/plugin/GoTo.php b/lib/plugin/GoTo.php
index a83a7e091..03f1ea185 100644
--- a/lib/plugin/GoTo.php
+++ b/lib/plugin/GoTo.php
@@ -27,26 +27,30 @@
  *  Note: pagenames are absolute, not relative to the actual subpage.
  *
  *  Usage: <>
- *  @author: Michael van Dam
+ * @author: Michael van Dam
  */
 
 class WikiPlugin_GoTo
-extends WikiPlugin
+    extends WikiPlugin
 {
-    function getName () {
+    function getName()
+    {
         return _("GoTo");
     }
 
-    function getDescription () {
+    function getDescription()
+    {
         return _("Go to or create page.");
     }
 
-    function getDefaultArguments() {
+    function getDefaultArguments()
+    {
         return array('size' => 32);
     }
 
-    function run($dbi, $argstr, &$request, $basepage) {
-        $request->setArg('action',false);
+    function run($dbi, $argstr, &$request, $basepage)
+    {
+        $request->setArg('action', false);
         $args = $this->getArgs($argstr, $request);
         extract($args);
 
@@ -55,9 +59,9 @@ extends WikiPlugin
             $request->setArg('goto', false);
             $target = $goto['target'];
             if ($dbi->isWikiPage($target))
-                $url = WikiURL($target,0,1);
+                $url = WikiURL($target, 0, 1);
             else
-                $url = WikiURL($target, array('action'=>'edit'),1);
+                $url = WikiURL($target, array('action' => 'edit'), 1);
 
             $request->redirect($url);
             // User should see nothing after redirect
@@ -65,15 +69,15 @@ extends WikiPlugin
         }
 
         $action = $request->getURLtoSelf();
-        $form = HTML::form(array('action'=>$action,
-                                 'method'=>'post'
-                          ));
+        $form = HTML::form(array('action' => $action,
+            'method' => 'post'
+        ));
 
         $form->pushContent(HiddenInputs($request->getArgs()));
 
         $textfield = HTML::input(array('type' => 'text',
-                                       'size' => $size,
-                                       'name' => 'goto[target]'));
+            'size' => $size,
+            'name' => 'goto[target]'));
 
         $button = Button('submit:goto[go]', _("Go"), false);
 
@@ -82,7 +86,9 @@ extends WikiPlugin
         return $form;
 
     }
-};
+}
+
+;
 
 // Local Variables:
 // mode: php
diff --git a/lib/plugin/GoogleMaps.php b/lib/plugin/GoogleMaps.php
index 2575de223..27dba99d4 100644
--- a/lib/plugin/GoogleMaps.php
+++ b/lib/plugin/GoogleMaps.php
@@ -24,7 +24,6 @@
  * Uses Google Maps as a Map Server
  *
  * This plugin displays a marker with further infos (when clicking) on given coordinates.
-
  * Hint: You need to sign up for a Google Maps API key!
  *         http://www.google.com/apis/maps/signup.html
  *       Then enter the key in config/config.ini under GOOGLE_LICENSE_KEY=
@@ -57,31 +56,35 @@
  *   Automatic route following
  */
 class WikiPlugin_GoogleMaps
-extends WikiPlugin
+    extends WikiPlugin
 {
-    function getName() {
+    function getName()
+    {
         return _("GoogleMaps");
     }
 
-    function getDescription() {
-      return _("Displays a marker with further infos (when clicking) on given coordinates");
+    function getDescription()
+    {
+        return _("Displays a marker with further infos (when clicking) on given coordinates");
     }
 
-    function getDefaultArguments() {
+    function getDefaultArguments()
+    {
         return array(
-                     'Longitude' =>         '',
-                     'Latitude'  =>         '',
-                     'ZoomFactor'=>        5,
-                     'Marker'    =>        true,
-                     'InfoText'  =>         '',
-                     'MapType'   =>          'Hybrid', // Map|Satellite|Hybrid,
-                     'SmallMapControl' => false,  // large or small
-                     'width'     =>        '500px',
-                     'height'    =>        '400px',
-                    );
+            'Longitude' => '',
+            'Latitude' => '',
+            'ZoomFactor' => 5,
+            'Marker' => true,
+            'InfoText' => '',
+            'MapType' => 'Hybrid', // Map|Satellite|Hybrid,
+            'SmallMapControl' => false, // large or small
+            'width' => '500px',
+            'height' => '400px',
+        );
     }
 
-    function run($dbi, $argstr, &$request, $basepage) {
+    function run($dbi, $argstr, &$request, $basepage)
+    {
 
         $args = $this->getArgs($argstr, $request);
         extract($args);
@@ -93,15 +96,22 @@ extends WikiPlugin
             return $this->error(sprintf(_("A required argument '%s' is missing."), 'Latitude'));
         }
 
-        $maps = JavaScript('',array('src'=>"http://maps.google.com/maps?file=api&v=1&key=" . GOOGLE_LICENSE_KEY));
+        $maps = JavaScript('', array('src' => "http://maps.google.com/maps?file=api&v=1&key=" . GOOGLE_LICENSE_KEY));
         $id = GenerateId("googlemap");
         switch ($MapType) {
-        case "Satellite": $type = "_SATELLITE_TYPE"; break;
-        case "Map":       $type = "_MAP_TYPE"; break;
-        case "Hybrid":    $type = "_HYBRID_TYPE"; break;
-        default: return $this->error(sprintf(_("Invalid argument %s"), $MapType));
+            case "Satellite":
+                $type = "_SATELLITE_TYPE";
+                break;
+            case "Map":
+                $type = "_MAP_TYPE";
+                break;
+            case "Hybrid":
+                $type = "_HYBRID_TYPE";
+                break;
+            default:
+                return $this->error(sprintf(_("Invalid argument %s"), $MapType));
         }
-        $div = HTML::div(array('id'=>$id,'style'=>'width: '.$width.'; height: '.$height));
+        $div = HTML::div(array('id' => $id, 'style' => 'width: ' . $width . '; height: ' . $height));
 
         // TODO: Check for multiple markers or polygons
         if (!$InfoText)
@@ -111,7 +121,7 @@ extends WikiPlugin
             if ($InfoText) {
                 include_once 'lib/BlockParser.php';
                 $page = $dbi->getPage($request->getArg('pagename'));
-                $rev  = $page->getCurrentRevision(false);
+                $rev = $page->getCurrentRevision(false);
                 $markup = $rev->get('markup');
                 $markertext = TransformText($InfoText, $markup, $basepage);
             }
@@ -119,33 +129,35 @@ extends WikiPlugin
 function createMarker(point, text) {
   var marker = new GMarker(point);
   var html = text + \"

[" . - _("new window") . - "]\"; + _("new window") . + "]\"; GEvent.addListener(marker, \"click\", function() {marker.openInfoWindowHtml(html);}); return marker; }"); } $run = JavaScript(" -var map = new GMap(document.getElementById('".$id."'));\n" . -($SmallMapControl - ? "map.addControl(new GSmallMapControl());\n" - : "map.addControl(new GLargeMapControl());\n") . " +var map = new GMap(document.getElementById('" . $id . "'));\n" . + ($SmallMapControl + ? "map.addControl(new GSmallMapControl());\n" + : "map.addControl(new GLargeMapControl());\n") . " map.addControl(new GMapTypeControl()); -map.centerAndZoom(new GPoint(".$Longitude.", ".$Latitude."), ".$ZoomFactor."); -map.setMapType(".$type.");" . -($Marker - ? " -var point = new GPoint(".$Longitude.",".$Latitude."); -var marker = createMarker(point, '".$markertext->asXml()."'); map.addOverlay(marker);" - : "") -); +map.centerAndZoom(new GPoint(" . $Longitude . ", " . $Latitude . "), " . $ZoomFactor . "); +map.setMapType(" . $type . ");" . + ($Marker + ? " +var point = new GPoint(" . $Longitude . "," . $Latitude . "); +var marker = createMarker(point, '" . $markertext->asXml() . "'); map.addOverlay(marker);" + : "") + ); if ($Marker) - return HTML($markerjs,$maps,$div,$run); + return HTML($markerjs, $maps, $div, $run); else - return HTML($maps,$div,$run); + return HTML($maps, $div, $run); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/GooglePlugin.php b/lib/plugin/GooglePlugin.php index 72083f7ad..be9b6b30f 100644 --- a/lib/plugin/GooglePlugin.php +++ b/lib/plugin/GooglePlugin.php @@ -37,28 +37,32 @@ require_once 'lib/Google.php'; * Add Google's spell-checking to an application */ class WikiPlugin_GooglePlugin -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("GooglePlugin"); } - function getDescription () { + function getDescription() + { return _("Make use of the Google API"); } - function getDefaultArguments() { - return array('q' => '', - 'mode' => 'search', // or 'cache' or 'spell' - 'startIndex' => 1, - 'maxResults' => 10, // fixed to 10 for now by google - 'formsize' => 30, - // 'language' => `?? - //'license_key' => false, - ); + function getDefaultArguments() + { + return array('q' => '', + 'mode' => 'search', // or 'cache' or 'spell' + 'startIndex' => 1, + 'maxResults' => 10, // fixed to 10 for now by google + 'formsize' => 30, + // 'language' => `?? + //'license_key' => false, + ); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); // if (empty($args['s'])) // return ''; @@ -70,26 +74,31 @@ extends WikiPlugin $google = new Google(); if (!$google) return ''; switch ($mode) { - case 'search': $result = $google->doGoogleSearch($q); break; - case 'cache': $result = $google->doGetCachedPage($q); break; - case 'spell': $result = $google->doSpellingSuggestion($q); break; + case 'search': + $result = $google->doGoogleSearch($q); + break; + case 'cache': + $result = $google->doGetCachedPage($q); + break; + case 'spell': + $result = $google->doSpellingSuggestion($q); + break; default: - trigger_error("Invalid mode"); + trigger_error("Invalid mode"); } - if (isa($result,'HTML')) + if (isa($result, 'HTML')) $html->pushContent($result); - if (isa($result,'GoogleSearchResults')) { + if (isa($result, 'GoogleSearchResults')) { //TODO: result template if (!empty($result->resultElements)) { $list = HTML::ol(); foreach ($result->resultElements as $res) { - $li = HTML::li(LinkURL($res['URL'],$res['directoryTitle']),HTML::br(), - $res['directoryTitle'] ? HTML(HTML::raw('  '),HTML::em($res['summary']),' -- ',LinkURL($res['URL'])) : ''); + $li = HTML::li(LinkURL($res['URL'], $res['directoryTitle']), HTML::br(), + $res['directoryTitle'] ? HTML(HTML::raw('  '), HTML::em($res['summary']), ' -- ', LinkURL($res['URL'])) : ''); $list->pushContent($li); } $html->pushContent($list); - } - else + } else return _("Nothing found"); } if (is_string($result)) { @@ -97,25 +106,27 @@ extends WikiPlugin $html->pushContent(HTML::blockquote(HTML::raw($result))); } } - if ($formsize < 1) $formsize = 30; + if ($formsize < 1) $formsize = 30; // todo: template $form = HTML::form(array('action' => $request->getPostURL(), - 'method' => 'post', - //'class' => 'class', //fixme - 'accept-charset' => $GLOBALS['charset']), - HiddenInputs(array('pagename' => $basepage, - 'mode' => $mode))); + 'method' => 'post', + //'class' => 'class', //fixme + 'accept-charset' => $GLOBALS['charset']), + HiddenInputs(array('pagename' => $basepage, + 'mode' => $mode))); $form->pushContent(HTML::input(array('type' => 'text', - 'value' => $q, - 'name' => 'q', - 'size' => $formsize))); + 'value' => $q, + 'name' => 'q', + 'size' => $formsize))); $form->pushContent(HTML::input(array('type' => 'submit', - 'class' => 'button', - 'value' => gettext($mode) - ))); - return HTML($html,$form); + 'class' => 'button', + 'value' => gettext($mode) + ))); + return HTML($html, $form); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/GraphViz.php b/lib/plugin/GraphViz.php index be3eb1405..2f29ba3a8 100644 --- a/lib/plugin/GraphViz.php +++ b/lib/plugin/GraphViz.php @@ -32,9 +32,8 @@ * * Usage: <> - * See also: VisualWiki, which depends on GraphViz and WikiPluginCached. * * TODO: @@ -51,20 +50,19 @@ if (PHP_OS == "Darwin") { // Mac OS X // The default font paths do not find your fonts, set the path here: $fontpath = "/System/Library/Frameworks/JavaVM.framework/Versions/1.3.1/Home/lib/fonts/"; //$fontpath = "/usr/X11R6/lib/X11/fonts/TTF/"; -} -elseif (isWindows()) { +} elseif (isWindows()) { if (!defined("GRAPHVIZ_EXE")) - define('GRAPHVIZ_EXE','dot.exe'); + define('GRAPHVIZ_EXE', 'dot.exe'); if (!defined('VISUALWIKIFONT')) define('VISUALWIKIFONT', 'Arial'); } elseif ($_SERVER["SERVER_NAME"] == 'phpwiki.sourceforge.net') { // sf.net hack if (!defined("GRAPHVIZ_EXE")) - define('GRAPHVIZ_EXE','/home/groups/p/ph/phpwiki/bin/dot'); + define('GRAPHVIZ_EXE', '/home/groups/p/ph/phpwiki/bin/dot'); if (!defined('VISUALWIKIFONT')) define('VISUALWIKIFONT', 'luximr'); } else { // other os if (!defined("GRAPHVIZ_EXE")) - define('GRAPHVIZ_EXE','/usr/local/bin/dot'); + define('GRAPHVIZ_EXE', '/usr/local/bin/dot'); // Name of the Truetypefont - Helvetica is probably easier to read if (!defined('VISUALWIKIFONT')) define('VISUALWIKIFONT', 'Helvetica'); @@ -78,11 +76,12 @@ elseif (isWindows()) { require_once 'lib/WikiPluginCached.php'; class WikiPlugin_GraphViz -extends WikiPluginCached + extends WikiPluginCached { - function _mapTypes() { - return array("imap", "cmapx", "ismap", "cmap"); + function _mapTypes() + { + return array("imap", "cmapx", "ismap", "cmap"); } /** @@ -90,58 +89,70 @@ extends WikiPluginCached * or HTML if the imagetype is not supported by GD (EPS, SVG, SVGZ) (not yet) * or IMG_INLINE if device = png, gif or jpeg */ - function getPluginType() { + function getPluginType() + { $type = $this->decideImgType($this->_args['imgtype']); if ($type == $this->_args['imgtype']) return PLUGIN_CACHED_IMG_INLINE; $device = strtolower($this->_args['imgtype']); - if (in_array($device, $this->_mapTypes())) - return PLUGIN_CACHED_MAP; - if (in_array($device, array('svg','swf','svgz','eps','ps'))) { + if (in_array($device, $this->_mapTypes())) + return PLUGIN_CACHED_MAP; + if (in_array($device, array('svg', 'swf', 'svgz', 'eps', 'ps'))) { switch ($this->_args['imgtype']) { - case 'svg': - case 'svgz': - return PLUGIN_CACHED_STATIC | PLUGIN_CACHED_SVG_PNG; - case 'swf': - return PLUGIN_CACHED_STATIC | PLUGIN_CACHED_SWF; + case 'svg': + case 'svgz': + return PLUGIN_CACHED_STATIC | PLUGIN_CACHED_SVG_PNG; + case 'swf': + return PLUGIN_CACHED_STATIC | PLUGIN_CACHED_SWF; default: - return PLUGIN_CACHED_STATIC | PLUGIN_CACHED_HTML; + return PLUGIN_CACHED_STATIC | PLUGIN_CACHED_HTML; } - } - else + } else return PLUGIN_CACHED_IMG_INLINE; // normal cached libgd image handles } - function getName () { + + function getName() + { return _("GraphViz"); } - function getDescription () { + + function getDescription() + { return _("GraphViz image or imagemap creation of directed graphs"); } - function managesValidators() { + + function managesValidators() + { return true; } - function getDefaultArguments() { + + function getDefaultArguments() + { return array( - 'imgtype' => 'png', // png,gif,svgz,svg,... - 'alt' => false, - 'pages' => false, // support - 'exclude' => false, - 'help' => false, - 'debug' => false, - ); + 'imgtype' => 'png', // png,gif,svgz,svg,... + 'alt' => false, + 'pages' => false, // support + 'exclude' => false, + 'help' => false, + 'debug' => false, + ); } - function handle_plugin_args_cruft(&$argstr, &$args) { + + function handle_plugin_args_cruft(&$argstr, &$args) + { $this->source = $argstr; } + /** * Sets the expire time to one day (so the image producing * functions are called seldomly) or to about two minutes * if a help screen is created. */ - function getExpire($dbi, $argarray, $request) { + function getExpire($dbi, $argarray, $request) + { if (!empty($argarray['help'])) return '+120'; // 2 minutes - return sprintf('+%d', 3*86000); // approx 3 days + return sprintf('+%d', 3 * 86000); // approx 3 days } /** @@ -150,7 +161,8 @@ extends WikiPluginCached * formats. * @return string 'png', 'jpeg', 'gif' */ - function getImageType($dbi, $argarray, $request) { + function getImageType($dbi, $argarray, $request) + { return $argarray['imgtype']; } @@ -158,9 +170,10 @@ extends WikiPluginCached * This gives an alternative text description of * the image. */ - function getAlt($dbi, $argstr, $request) { + function getAlt($dbi, $argstr, $request) + { return (!empty($this->_args['alt'])) ? $this->_args['alt'] - : $this->getDescription(); + : $this->getDescription(); } /** @@ -169,7 +182,8 @@ extends WikiPluginCached * TODO: *map features. * @return string image handle */ - function helpImage() { + function helpImage() + { $def = $this->defaultArguments(); //$other_imgtypes = $GLOBALS['PLUGIN_CACHED_IMGTYPES']; //unset ($other_imgtypes[$def['imgtype']]); @@ -177,40 +191,41 @@ extends WikiPluginCached $imgtypes = array_merge($imgtypes, array("svg", "svgz", "ps"), $this->_mapTypes()); $helparr = array( '< ' = "' . $def['imgtype'] . "(default)|" . join('|',$imgtypes).'"', - 'alt' => ' = "alternate image text"', - 'pages' => ' = "pagenames,*" or pagelist as input', - 'exclude' => ' = "pagenames,*" or pagelist as input', - 'help' => ' bool: displays this screen', - '...' => ' all further lines below the first plugin line ', - '' => ' and inside the tags are the dot script.', + 'imgtype' => ' = "' . $def['imgtype'] . "(default)|" . join('|', $imgtypes) . '"', + 'alt' => ' = "alternate image text"', + 'pages' => ' = "pagenames,*" or pagelist as input', + 'exclude' => ' = "pagenames,*" or pagelist as input', + 'help' => ' bool: displays this screen', + '...' => ' all further lines below the first plugin line ', + '' => ' and inside the tags are the dot script.', "\n ?>" - ); + ); $length = 0; - foreach($helparr as $alignright => $alignleft) { + foreach ($helparr as $alignright => $alignleft) { $length = max($length, strlen($alignright)); } - $helptext =''; - foreach($helparr as $alignright => $alignleft) { + $helptext = ''; + foreach ($helparr as $alignright => $alignleft) { $helptext .= substr(' ' - . $alignright, -$length).$alignleft."\n"; + . $alignright, -$length) . $alignleft . "\n"; } return $this->text2img($helptext, 4, array(1, 0, 0), - array(255, 255, 255)); + array(255, 255, 255)); } - function processSource($argarray=false) { + function processSource($argarray = false) + { if (empty($this->source)) { // create digraph from pages if (empty($argarray['pages'])) { trigger_error(sprintf(_("%s is empty"), 'GraphViz argument source'), E_USER_WARNING); return ''; } - $source = "digraph GraphViz {\n"; // } + $source = "digraph GraphViz {\n"; // } foreach ($argarray['pages'] as $name) { // support pagelists // allow Page/SubPage $url = str_replace(urlencode(SUBPAGE_SEPARATOR), SUBPAGE_SEPARATOR, - rawurlencode($name)); + rawurlencode($name)); $source .= " \"$name\" [URL=\"$url\"];\n"; } // { @@ -233,22 +248,24 @@ extends WikiPluginCached return $source; } - function createDotFile($tempfile='', $argarray=false) { + function createDotFile($tempfile = '', $argarray = false) + { $this->source = $this->processSource($argarray); if (!$this->source) return false; if (!$tempfile) { - $tempfile = $this->tempnam($this->getName().".dot"); + $tempfile = $this->tempnam($this->getName() . ".dot"); @unlink($tempfile); } if (!$fp = fopen($tempfile, 'w')) return false; $ok = fwrite($fp, $this->source); - $ok = fclose($fp) && $ok; // close anyway + $ok = fclose($fp) && $ok; // close anyway return $ok ? $tempfile : false; } - function getImage($dbi, $argarray, $request) { + function getImage($dbi, $argarray, $request) + { $dotbin = GRAPHVIZ_EXE; $tempfiles = $this->tempnam($this->getName()); $gif = $argarray['imgtype']; @@ -259,7 +276,7 @@ extends WikiPluginCached } $ImageCreateFromFunc = "ImageCreateFrom$gif"; - $outfile = $tempfiles.".".$gif; + $outfile = $tempfiles . "." . $gif; $debug = $request->getArg('debug'); if ($debug) { $tempdir = dirname($tempfiles); @@ -269,37 +286,37 @@ extends WikiPluginCached if (empty($source)) return $this->error(fmt("No dot graph given")); if (isWindows()) { - $ok = $tempfiles; - $dotfile = $this->createDotFile($tempfiles.'.dot', $argarray); - $args = "-T$gif $dotfile -o $outfile"; - $cmdline = "$dotbin $args"; - $code = $this->execute($cmdline, $outfile); - if (!$code) - $this->complain(sprintf(_("Couldn't start commandline '%s'"), $cmdline)); + $ok = $tempfiles; + $dotfile = $this->createDotFile($tempfiles . '.dot', $argarray); + $args = "-T$gif $dotfile -o $outfile"; + $cmdline = "$dotbin $args"; + $code = $this->execute($cmdline, $outfile); + if (!$code) + $this->complain(sprintf(_("Couldn't start commandline '%s'"), $cmdline)); } else { - $args = "-T$gif -o $outfile"; - $cmdline = "$dotbin $args"; - if ($debug) $cmdline .= " > $tempout"; - //if (!isWindows()) $cmdline .= " 2>&1"; - $code = $this->filterThroughCmd($source, $cmdline); - if ($code) - $this->complain(sprintf(_("Couldn't start commandline '%s'"), $cmdline)); - sleep(0.1); + $args = "-T$gif -o $outfile"; + $cmdline = "$dotbin $args"; + if ($debug) $cmdline .= " > $tempout"; + //if (!isWindows()) $cmdline .= " 2>&1"; + $code = $this->filterThroughCmd($source, $cmdline); + if ($code) + $this->complain(sprintf(_("Couldn't start commandline '%s'"), $cmdline)); + sleep(0.1); } - if (! file_exists($outfile) ) { + if (!file_exists($outfile)) { $this->complain(sprintf(_("%s error: outputfile '%s' not created"), - "GraphViz", $outfile)); + "GraphViz", $outfile)); $this->complain("\ncmd-line: $cmdline"); return false; } if (function_exists($ImageCreateFromFunc)) { - $img = $ImageCreateFromFunc( $outfile ); + $img = $ImageCreateFromFunc($outfile); // clean up tempfiles @unlink($tempfiles); if (empty($argarray['debug'])) - foreach (array(".$gif",'.dot') as $ext) { + foreach (array(".$gif", '.dot') as $ext) { //if (file_exists($tempfiles.$ext)) - @unlink($tempfiles.$ext); + @unlink($tempfiles . $ext); } return $img; } @@ -308,18 +325,20 @@ extends WikiPluginCached // which argument must be set to 'png', for the fallback image when svg will fail on the client. // type: SVG_PNG - function pngArg() { - return 'imgtype'; + function pngArg() + { + return 'imgtype'; } - function getMap($dbi, $argarray, $request) { - $result = $this->invokeDot($argarray); + function getMap($dbi, $argarray, $request) + { + $result = $this->invokeDot($argarray); if (isa($result, 'HtmlElement')) return array(false, $result); else return $result; // $img = $this->getImage($dbi, $argarray, $request); - //return array($this->_mapfile, $img); + //return array($this->_mapfile, $img); } /** @@ -334,12 +353,13 @@ extends WikiPluginCached * @param shape string node shape; 'ellipse', 'box', 'circle', 'point' * @param label string not used anymore */ - function invokeDot($argarray) { + function invokeDot($argarray) + { $dotbin = GRAPHVIZ_EXE; $tempfiles = $this->tempnam($this->getName()); $gif = $argarray['imgtype']; $ImageCreateFromFunc = "ImageCreateFrom$gif"; - $outfile = $tempfiles.".".$gif; + $outfile = $tempfiles . "." . $gif; $debug = $GLOBALS['request']->getArg('debug'); if ($debug) { $tempdir = dirname($tempfiles); @@ -366,10 +386,10 @@ extends WikiPluginCached $ok = $ok and $this->filterThroughCmd($source, $cmdline2); // $this->execute("$dotbin -Timap $tempfiles.dot -o ".$tempfiles.".map" . // ($debug ? " > $tempout 2>&1" : " 2>&1"), $tempfiles.".map") - $ok = $ok and file_exists( $outfile ); - $ok = $ok and file_exists( $tempfiles.'.map' ); + $ok = $ok and file_exists($outfile); + $ok = $ok and file_exists($tempfiles . '.map'); $ok = $ok and ($img = $ImageCreateFromFunc($outfile)); - $ok = $ok and ($fp = fopen($tempfiles.'.map', 'r')); + $ok = $ok and ($fp = fopen($tempfiles . '.map', 'r')); $map = HTML(); if ($debug == 'static') { @@ -378,11 +398,11 @@ extends WikiPluginCached if (file_exists($outfile) and filesize($outfile) > 900) $img = $outfile; else - $img = $tempdir . "/".$this->getName().".".$gif; - if (file_exists( $tempfiles.".map") and filesize($tempfiles.".map") > 20) - $map = $tempfiles.".map"; + $img = $tempdir . "/" . $this->getName() . "." . $gif; + if (file_exists($tempfiles . ".map") and filesize($tempfiles . ".map") > 20) + $map = $tempfiles . ".map"; else - $map = $tempdir . "/".$this->getName().".map"; + $map = $tempdir . "/" . $this->getName() . ".map"; $img = $ImageCreateFromFunc($img); $fp = fopen($map, 'r'); $map = HTML(); @@ -394,7 +414,7 @@ extends WikiPluginCached if (substr($line, 0, 1) == '#') continue; list($shape, $url, $e1, $e2, $e3, $e4) = sscanf($line, - "%s %s %d,%d %d,%d"); + "%s %s %d,%d %d,%d"); if ($shape != 'rect') continue; @@ -405,20 +425,20 @@ extends WikiPluginCached $y1 = min($e2, $e4); $y2 = max($e2, $e4); $map->pushContent(HTML::area(array( - 'shape' => 'rect', - 'coords' => "$x1,$y1,$x2,$y2", - 'href' => $url, - 'title' => rawurldecode($url), - 'alt' => $url))); + 'shape' => 'rect', + 'coords' => "$x1,$y1,$x2,$y2", + 'href' => $url, + 'title' => rawurldecode($url), + 'alt' => $url))); } fclose($fp); //trigger_error("url=".$url); } else { $this->complain("$outfile: " - . (file_exists($outfile) ? filesize($outfile):'missing') - ."\n" - . "$tempfiles.map: " - . (file_exists("$tempfiles.map") ? filesize("$tempfiles.map"):'missing')); + . (file_exists($outfile) ? filesize($outfile) : 'missing') + . "\n" + . "$tempfiles.map: " + . (file_exists("$tempfiles.map") ? filesize("$tempfiles.map") : 'missing')); $this->complain("\ncmd-line: $cmdline1"); $this->complain("\ncmd-line: $cmdline2"); //trigger_error($this->GetError(), E_USER_WARNING); @@ -428,8 +448,8 @@ extends WikiPluginCached // clean up tempfiles @unlink($tempfiles); if ($ok and !$argarray['debug']) - foreach (array('',".$gif",'.map','.dot') as $ext) { - @unlink($tempfiles.$ext); + foreach (array('', ".$gif", '.map', '.dot') as $ext) { + @unlink($tempfiles . $ext); } if ($ok) @@ -438,7 +458,9 @@ extends WikiPluginCached return array(false, $this->GetError()); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/HelloWorld.php b/lib/plugin/HelloWorld.php index 6c58aa103..b9dfe4c32 100644 --- a/lib/plugin/HelloWorld.php +++ b/lib/plugin/HelloWorld.php @@ -38,35 +38,41 @@ if (!defined('THE_END')) define('THE_END', "!"); class WikiPlugin_HelloWorld -extends WikiPlugin + extends WikiPlugin { // Four required functions in a WikiPlugin. - function getName () { + function getName() + { return _("HelloWorld"); } - function getDescription () { + function getDescription() + { return _("Simple Sample Plugin"); } // Establish default values for each of this plugin's arguments. - function getDefaultArguments() { + function getDefaultArguments() + { return array('salutation' => "Hello,", - 'name' => "World"); + 'name' => "World"); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { extract($this->getArgs($argstr, $request)); // Any text that is returned will not be further transformed, // so use html where necessary. $html = HTML::tt(fmt('%s: %s', $salutation, WikiLink($name, 'auto')), - THE_END); + THE_END); return $html; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/HtmlConverter.php b/lib/plugin/HtmlConverter.php index 1c3d65f94..cc7614ac9 100644 --- a/lib/plugin/HtmlConverter.php +++ b/lib/plugin/HtmlConverter.php @@ -33,19 +33,23 @@ class WikiPlugin_HtmlConverter extends WikiPlugin { - function getName () { + function getName() + { return "HtmlConverter"; } - function getDescription () { + function getDescription() + { return _("Convert HTML markup into wiki markup."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array(); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { /* plugin not yet has arguments - save for later (copied from UpLoad) $args = $this->getArgs($argstr, $request); @@ -53,18 +57,18 @@ class WikiPlugin_HtmlConverter extends WikiPlugin */ $form = HTML::form(array('action' => $request->getPostURL(), - 'enctype' => 'multipart/form-data', - 'method' => 'post')); + 'enctype' => 'multipart/form-data', + 'method' => 'post')); $contents = HTML::div(array('class' => 'wikiaction')); $contents->pushContent(HTML::input(array('type' => 'hidden', - 'name' => 'MAX_FILE_SIZE', - 'value' => MAX_UPLOAD_SIZE))); + 'name' => 'MAX_FILE_SIZE', + 'value' => MAX_UPLOAD_SIZE))); $contents->pushContent(HTML::input(array('name' => 'userfile', - 'type' => 'file', - 'size' => '50'))); + 'type' => 'file', + 'size' => '50'))); $contents->pushContent(HTML::raw(" ")); $contents->pushContent(HTML::input(array('value' => _("Convert"), - 'type' => 'submit'))); + 'type' => 'submit'))); $form->pushContent($contents); $message = HTML(); @@ -74,15 +78,15 @@ class WikiPlugin_HtmlConverter extends WikiPlugin $userfile_name = basename($userfile_name); $userfile_tmpname = $userfile->getTmpName(); - if ( !preg_match("/(\.html|\.htm)$/i", $userfile_name)) { - $message->pushContent(_("Only files with extension HTML are allowed"),HTML::br(),HTML::br()); + if (!preg_match("/(\.html|\.htm)$/i", $userfile_name)) { + $message->pushContent(_("Only files with extension HTML are allowed"), HTML::br(), HTML::br()); } else { - $message->pushContent( _("Processed $userfile_name"), HTML::br(), HTML::br()); - $message->pushContent( _("Copy the output below and paste it into your Wiki page."), HTML::br()); - $message->pushContent( $this->_process( $userfile_tmpname)); + $message->pushContent(_("Processed $userfile_name"), HTML::br(), HTML::br()); + $message->pushContent(_("Copy the output below and paste it into your Wiki page."), HTML::br()); + $message->pushContent($this->_process($userfile_tmpname)); } } else { - $message->pushContent(HTML::br(),HTML::br()); + $message->pushContent(HTML::br(), HTML::br()); } $result = HTML(); @@ -91,101 +95,105 @@ class WikiPlugin_HtmlConverter extends WikiPlugin return $result; } - function _processA(&$file) { + function _processA(&$file) + { - $file = eregi_replace( + $file = eregi_replace( "]*)>", "{{\\4}}", $file); - $file = eregi_replace("{{([-/a-zA-Z0-9._~#@%$?&=:\200-\377\(\)[:space:]]+)}}([^<]+)
", "[ \\2 | \\1 ]", $file); - } + $file = eregi_replace("{{([-/a-zA-Z0-9._~#@%$?&=:\200-\377\(\)[:space:]]+)}}([^<]+)", "[ \\2 | \\1 ]", $file); + } - function _processIMG(&$file) { + function _processIMG(&$file) + { - $img_regexp = "_]*>_"; + $img_regexp = "_]*>_"; - $file = preg_replace( $img_regexp, "\n\n[Upload:\\1]", $file); - } + $file = preg_replace($img_regexp, "\n\n[Upload:\\1]", $file); + } - function _processUL( &$file) { - - // put any
  • -Tag in a new line to indent correctly and strip trailing white space (including new-lines) - $file = str_replace( "\s*/", "
  • ", $file); - - $enclosing_regexp = "_(.*)]*>((?U).*)(.*)_is"; - $indent_tag = " is inserted instead of the erased
      tags to have a paragraph generated at the end of the script - $file = $embedded_fragment_array[1] . "

      " . $indented . $embedded_fragment_array[3]; - $found = preg_match( $enclosing_regexp, $file, $embedded_fragment_array); - } + function _processUL(&$file) + { + + // put any

    • -Tag in a new line to indent correctly and strip trailing white space (including new-lines) + $file = str_replace("\s*/", "
    • ", $file); + + $enclosing_regexp = "_(.*)]*>((?U).*)
    (.*)_is"; + $indent_tag = " is inserted instead of the erased
      tags to have a paragraph generated at the end of the script + $file = $embedded_fragment_array[1] . "

      " . $indented . $embedded_fragment_array[3]; + $found = preg_match($enclosing_regexp, $file, $embedded_fragment_array); } + } - function _process( $file_name) { - $result = HTML(); - $file = file_get_contents( $file_name); - $file = html_entity_decode( $file); + function _process($file_name) + { + $result = HTML(); + $file = file_get_contents($file_name); + $file = html_entity_decode($file); - $ascii = '[\x00-\x7F]'; - $euc = '[\xA1-\xFE][\xA1-\xFE]'; - $character = "$ascii|$euc"; + $ascii = '[\x00-\x7F]'; + $euc = '[\xA1-\xFE][\xA1-\xFE]'; + $character = "$ascii|$euc"; - $this->_processA( $file); - $this->_processIMG( $file); - $this->_processUL( $file); + $this->_processA($file); + $this->_processIMG($file); + $this->_processUL($file); - $file = str_replace ("\r\n", "\n", $file); + $file = str_replace("\r\n", "\n", $file); - $file = eregi_replace ("]*>", "\n\n!!!!", $file); + $file = eregi_replace("]*>", "\n\n!!!!", $file); - $file = eregi_replace ("]*>", "\n\n!!!", $file); + $file = eregi_replace("]*>", "\n\n!!!", $file); - $file = eregi_replace ("]*>", "\n\n!!", $file); + $file = eregi_replace("]*>", "\n\n!!", $file); - $file = eregi_replace ("]*>", "\n\n!", $file); + $file = eregi_replace("]*>", "\n\n!", $file); - $file = eregi_replace ("]*>", "\n\n__", $file); + $file = eregi_replace("]*>", "\n\n__", $file); - $file = eregi_replace ("", "\n\n", $file); + $file = eregi_replace("", "\n\n", $file); - $file = eregi_replace ("", "\n\n", $file); + $file = eregi_replace("", "\n\n", $file); - $file = eregi_replace ("", "\n\n", $file); + $file = eregi_replace("", "\n\n", $file); - $file = eregi_replace ("", "\n\n", $file); + $file = eregi_replace("", "\n\n", $file); - $file = eregi_replace ("", "__\n\n", $file); + $file = eregi_replace("", "__\n\n", $file); - $file = eregi_replace ("]*>", "\n----\n", $file); + $file = eregi_replace("]*>", "\n----\n", $file); - $file = eregi_replace ("]*>", "* ", $file); + $file = eregi_replace("]*>", "* ", $file); - // strip all tags, except for

      , which is supported by wiki
      -                // and 

      's which will be converted after compression. - $file = strip_tags($file, "

      "); - // strip

      end tags with trailing white space - $file = preg_replace ("_

      \s*_i", "", $file); + // strip all tags, except for
      , which is supported by wiki
      +        // and 

      's which will be converted after compression. + $file = strip_tags($file, "

      "); + // strip

      end tags with trailing white space + $file = preg_replace("_

      \s*_i", "", $file); - // get rid of all blank lines - $file = preg_replace( "/\n\s*\n/", "\n", $file); + // get rid of all blank lines + $file = preg_replace("/\n\s*\n/", "\n", $file); - // finally only add paragraphs where defined by inserting double new-lines - // be sure to only catch

      or and not

      !
      -                // Actually 

      tags with all white space and one new-line before - // and after around are replaced - $file = preg_replace ("_\n?[^\S\n]*]*|)>[^\S\n]*\n?_i", "\n\n", $file); + // finally only add paragraphs where defined by inserting double new-lines + // be sure to only catch

      or and not

      !
      +        // Actually 

      tags with all white space and one new-line before + // and after around are replaced + $file = preg_replace("_\n?[^\S\n]*]*|)>[^\S\n]*\n?_i", "\n\n", $file); - // strip attributes from

      -Tags and add a new-line before
      -                $file = preg_replace ("_]*|)>_iU", "\n
      ", $file);
      +        // strip attributes from 
      -Tags and add a new-line before
      +        $file = preg_replace("_]*|)>_iU", "\n
      ", $file);
       
               $outputArea = HTML::textarea(array('rows' => '30', 'cols' => '80'));
       
      -                $outputArea->pushContent( _($file));
      -                $result->pushContent( $outputArea);
      -                return $result;
      -        }
      +        $outputArea->pushContent(_($file));
      +        $result->pushContent($outputArea);
      +        return $result;
      +    }
       }
      diff --git a/lib/plugin/Imdb.php b/lib/plugin/Imdb.php
      index 4ab62c648..1dc612c25 100644
      --- a/lib/plugin/Imdb.php
      +++ b/lib/plugin/Imdb.php
      @@ -49,29 +49,33 @@
       include_once 'lib/plugin/SqlResult.php';
       
       class WikiPlugin_Imdb
      -extends WikiPlugin_SqlResult
      +    extends WikiPlugin_SqlResult
       {
      -    function getName () {
      +    function getName()
      +    {
               return _("Imdb");
           }
       
      -    function getDescription () {
      +    function getDescription()
      +    {
               return _("Query a local imdb database");
           }
       
      -    function getDefaultArguments() {
      +    function getDefaultArguments()
      +    {
               return array(
      -                     'query'       => false, // what
      -                     'template'    => false, // TODO: use a custom /template.tmpl for the result
      -                     'where'       => false, // custom filter for the query
      -                     'title'       => false, // custom filter for the query
      -                     'name'        => false, // custom filter for the query
      -                     'sortby'      => false, // for paging, default none
      -                     'limit'       => false, // for paging, default: only the first 50
      -                    );
      +            'query' => false, // what
      +            'template' => false, // TODO: use a custom /template.tmpl for the result
      +            'where' => false, // custom filter for the query
      +            'title' => false, // custom filter for the query
      +            'name' => false, // custom filter for the query
      +            'sortby' => false, // for paging, default none
      +            'limit' => false, // for paging, default: only the first 50
      +        );
           }
       
      -    function run($dbi, $argstr, &$request, $basepage) {
      +    function run($dbi, $argstr, &$request, $basepage)
      +    {
               $args = $this->getArgs($argstr, $request);
               extract($args);
               include_once 'lib/imdb.php';
      @@ -85,15 +89,15 @@ extends WikiPlugin_SqlResult
       
               // if ($limit) ; // TODO: fill paging vars (see PageList)
               if ($ordered) {
      -            $html = HTML::ol(array('class'=>'sqlresult'));
      +            $html = HTML::ol(array('class' => 'sqlresult'));
                   foreach ($SqlResult as $row) {
      -                $html->pushContent(HTML::li(array('class'=> $i++ % 2 ? 'evenrow' : 'oddrow'), $row[0]));
      +                $html->pushContent(HTML::li(array('class' => $i++ % 2 ? 'evenrow' : 'oddrow'), $row[0]));
                   }
               } else {
      -            $html = HTML::table(array('class'=>'sqlresult'));
      +            $html = HTML::table(array('class' => 'sqlresult'));
                   $i = 0;
                   foreach ($SqlResult as $row) {
      -                $tr = HTML::tr(array('class'=> $i++ % 2 ? 'evenrow' : 'oddrow'));
      +                $tr = HTML::tr(array('class' => $i++ % 2 ? 'evenrow' : 'oddrow'));
                       foreach ($row as $col) {
                           $tr->pushContent(HTML::td($col));
                       }
      @@ -103,7 +107,9 @@ extends WikiPlugin_SqlResult
               // if ($limit) ; // do paging via pagelink template
               return $html;
           }
      -};
      +}
      +
      +;
       
       // Local Variables:
       // mode: php
      diff --git a/lib/plugin/IncludePage.php b/lib/plugin/IncludePage.php
      index 82b9a440f..d2e836184 100644
      --- a/lib/plugin/IncludePage.php
      +++ b/lib/plugin/IncludePage.php
      @@ -28,30 +28,34 @@
        */
       
       class WikiPlugin_IncludePage
      -extends WikiPlugin
      +    extends WikiPlugin
       {
      -    function getName() {
      +    function getName()
      +    {
               return _("IncludePage");
           }
       
      -    function getDescription() {
      +    function getDescription()
      +    {
               return _("Include text from another wiki page.");
           }
       
      -    function getDefaultArguments() {
      -        return array( 'page'    => false, // the page to include
      -                      'rev'     => false, // the revision (defaults to most recent)
      -                      'quiet'   => false, // if set, inclusion appears as normal content
      -                      'bytes'   => false, // maximum number of bytes to include
      -                      'words'   => false, // maximum number of words to include
      -                      'lines'   => false, // maximum number of lines to include
      -                      'sections' => false, // maximum number of sections to include
      -                      'section' => false, // include a named section
      -                      'sectionhead' => false // when including a named section show the heading
      -                      );
      +    function getDefaultArguments()
      +    {
      +        return array('page' => false, // the page to include
      +            'rev' => false, // the revision (defaults to most recent)
      +            'quiet' => false, // if set, inclusion appears as normal content
      +            'bytes' => false, // maximum number of bytes to include
      +            'words' => false, // maximum number of words to include
      +            'lines' => false, // maximum number of lines to include
      +            'sections' => false, // maximum number of sections to include
      +            'section' => false, // include a named section
      +            'sectionhead' => false // when including a named section show the heading
      +        );
           }
       
      -    function getWikiPageLinks($argstr, $basepage) {
      +    function getWikiPageLinks($argstr, $basepage)
      +    {
               extract($this->getArgs($argstr));
       
               if (!isset($page))
      @@ -65,7 +69,8 @@ extends WikiPlugin
               return array(array('linkto' => $page->name, 'relation' => 0));
           }
       
      -    function run($dbi, $argstr, &$request, $basepage) {
      +    function run($dbi, $argstr, &$request, $basepage)
      +    {
               $args = $this->getArgs($argstr, $request);
               extract($args);
       
      @@ -83,7 +88,7 @@ extends WikiPlugin
               static $included_pages = array();
               if (in_array($page, $included_pages)) {
                   return $this->error(sprintf(_("Recursive inclusion of page %s ignored"),
      -                                        $page));
      +                $page));
               }
       
               // Check if page exists
      @@ -92,20 +97,20 @@ extends WikiPlugin
               }
       
               // Check if user is allowed to get the Page.
      -        if (!mayAccessPage ('view', $page)) {
      +        if (!mayAccessPage('view', $page)) {
                   return $this->error(sprintf(_("Illegal inclusion of page %s: no read access"),
      -                                        $page));
      +                $page));
               }
       
               $p = $dbi->getPage($page);
               if ($rev) {
      -            if (!is_whole_number($rev) or !($rev>0)) {
      +            if (!is_whole_number($rev) or !($rev > 0)) {
                       return $this->error(_("Error: rev must be a positive integer."));
                   }
                   $r = $p->getRevision($rev);
                   if ((!$r) || ($r->hasDefaultContents())) {
                       return $this->error(sprintf(_("%s: no such revision %d."),
      -                                            $page, $rev));
      +                    $page, $rev));
                   }
               } else {
                   $r = $p->getCurrentRevision();
      @@ -113,28 +118,29 @@ extends WikiPlugin
               $c = $r->getContent();
       
               // follow redirects
      -        if ((preg_match('/<'.'\?plugin\s+RedirectTo\s+page=(\S+)\s*\?'.'>/', implode("\n", $c), $m))
      -          or (preg_match('/<'.'\?plugin\s+RedirectTo\s+page=(.*?)\s*\?'.'>/', implode("\n", $c), $m))
      -          or (preg_match('/<<\s*RedirectTo\s+page=(\S+)\s*>>/', implode("\n", $c), $m))
      -          or (preg_match('/<<\s*RedirectTo\s+page="(.*?)"\s*>>/', implode("\n", $c), $m)))
      -        {
      +        if ((preg_match('/<' . '\?plugin\s+RedirectTo\s+page=(\S+)\s*\?' . '>/', implode("\n", $c), $m))
      +            or (preg_match('/<' . '\?plugin\s+RedirectTo\s+page=(.*?)\s*\?' . '>/', implode("\n", $c), $m))
      +            or (preg_match('/<<\s*RedirectTo\s+page=(\S+)\s*>>/', implode("\n", $c), $m))
      +            or (preg_match('/<<\s*RedirectTo\s+page="(.*?)"\s*>>/', implode("\n", $c), $m))
      +        ) {
                   // Strip quotes (simple or double) from page name if any
                   if ((string_starts_with($m[1], "'"))
      -              or (string_starts_with($m[1], "\""))) {
      +                or (string_starts_with($m[1], "\""))
      +            ) {
                       $m[1] = substr($m[1], 1, -1);
                   }
                   // trap recursive redirects
                   if (in_array($m[1], $included_pages)) {
                       return $this->error(sprintf(_("Recursive inclusion of page %s ignored"),
      -                                                $page.' => '.$m[1]));
      +                    $page . ' => ' . $m[1]));
                   }
                   $page = $m[1];
                   $p = $dbi->getPage($page);
                   $r = $p->getCurrentRevision();
      -            $c = $r->getContent();   // array of lines
      +            $c = $r->getContent(); // array of lines
               }
       
      -        $ct = $this->extractParts ($c, $page, $args);
      +        $ct = $this->extractParts($c, $page, $args);
       
               // exclude from expansion
               if (preg_match('/.+<\/noinclude>/s', $ct)) {
      @@ -159,14 +165,15 @@ extends WikiPlugin
                   $transclusion_title = fmt("Included from %s", WikiLink($page));
               }
               return HTML(HTML::p(array('class' => 'transclusion-title'), $transclusion_title),
      -                    HTML::div(array('class' => 'transclusion'), false, $content));
      +            HTML::div(array('class' => 'transclusion'), false, $content));
           }
       
           /**
            * handles the arguments: section, sectionhead, lines, words, bytes,
            * for UnfoldSubpages, IncludePage, ...
            */
      -    function extractParts ($c, $pagename, $args) {
      +    function extractParts($c, $pagename, $args)
      +    {
               extract($args);
       
               if ($section) {
      @@ -196,7 +203,9 @@ extends WikiPlugin
               $ct = implode("\n", $c); // one string
               return $ct;
           }
      -};
      +}
      +
      +;
       
       // Local Variables:
       // mode: php
      diff --git a/lib/plugin/IncludePages.php b/lib/plugin/IncludePages.php
      index 2ace94e88..42e45f53a 100644
      --- a/lib/plugin/IncludePages.php
      +++ b/lib/plugin/IncludePages.php
      @@ -29,24 +29,28 @@
       include_once 'lib/plugin/IncludePage.php';
       
       class WikiPlugin_IncludePages
      -extends WikiPlugin_IncludePage
      +    extends WikiPlugin_IncludePage
       {
      -    function getName() {
      +    function getName()
      +    {
               return _("IncludePages");
           }
       
      -    function getDescription() {
      +    function getDescription()
      +    {
               return _("Include multiple pages.");
           }
       
      -    function getDefaultArguments() {
      -        return array_merge(array( 'pages'   => false,  // the pages to include
      -                                  'exclude' => false), // the pages to exclude
      -                           WikiPlugin_IncludePage::getDefaultArguments()
      -                          );
      +    function getDefaultArguments()
      +    {
      +        return array_merge(array('pages' => false, // the pages to include
      +                'exclude' => false), // the pages to exclude
      +            WikiPlugin_IncludePage::getDefaultArguments()
      +        );
           }
       
      -    function run($dbi, $argstr, &$request, $basepage) {
      +    function run($dbi, $argstr, &$request, $basepage)
      +    {
               $args = $this->getArgs($argstr, $request);
               $html = HTML();
               if (empty($args['pages'])) {
      @@ -75,12 +79,14 @@ extends WikiPlugin_IncludePage
       
               foreach ($args['pages'] as $page) {
                   if (empty($args['exclude']) or !in_array($page, $args['exclude'])) {
      -                $html = HTML($html, $include->run($dbi, "page='$page' ".$argstr, $request, $basepage));
      +                $html = HTML($html, $include->run($dbi, "page='$page' " . $argstr, $request, $basepage));
                   }
               }
               return $html;
           }
      -};
      +}
      +
      +;
       
       // Local Variables:
       // mode: php
      diff --git a/lib/plugin/IncludeSiteMap.php b/lib/plugin/IncludeSiteMap.php
      index 3418e9034..932fc905d 100644
      --- a/lib/plugin/IncludeSiteMap.php
      +++ b/lib/plugin/IncludeSiteMap.php
      @@ -46,34 +46,38 @@ require_once 'lib/PageList.php';
       require_once 'lib/plugin/SiteMap.php';
       
       class WikiPlugin_IncludeSiteMap
      -extends WikiPlugin_SiteMap
      +    extends WikiPlugin_SiteMap
       {
      -  function getName () {
      -    return _("IncludeSiteMap");
      -  }
      +    function getName()
      +    {
      +        return _("IncludeSiteMap");
      +    }
       
      -  function getDescription () {
      -    return sprintf(_("Include recursively all linked pages starting at %s"),
      -                   $this->_pagename);
      -  }
      +    function getDescription()
      +    {
      +        return sprintf(_("Include recursively all linked pages starting at %s"),
      +            $this->_pagename);
      +    }
       
      -  function getDefaultArguments() {
      -      return array('exclude'        => '',
      -                   'include_self'   => 0,
      -                   'noheader'       => 0,
      -                   'page'           => '[pagename]',
      -                   'description'    => $this->getDescription(),
      -                   'reclimit'       => 2,
      -                   'info'           => false,
      -                   'direction'      => 'back',
      -                   'firstreversed'  => false,
      -                   'excludeunknown' => true,
      -                   'includepages'   => 'words=50'
      -                   );
      +    function getDefaultArguments()
      +    {
      +        return array('exclude' => '',
      +            'include_self' => 0,
      +            'noheader' => 0,
      +            'page' => '[pagename]',
      +            'description' => $this->getDescription(),
      +            'reclimit' => 2,
      +            'info' => false,
      +            'direction' => 'back',
      +            'firstreversed' => false,
      +            'excludeunknown' => true,
      +            'includepages' => 'words=50'
      +        );
           }
       
      -    function run($dbi, $argstr, &$request, $basepage) {
      -      return WikiPlugin_SiteMap::run($dbi, $argstr, $request, $basepage);
      +    function run($dbi, $argstr, &$request, $basepage)
      +    {
      +        return WikiPlugin_SiteMap::run($dbi, $argstr, $request, $basepage);
           }
       }
       
      diff --git a/lib/plugin/IncludeTree.php b/lib/plugin/IncludeTree.php
      index 08112c240..1716feabe 100644
      --- a/lib/plugin/IncludeTree.php
      +++ b/lib/plugin/IncludeTree.php
      @@ -33,35 +33,39 @@ require_once 'lib/PageList.php';
       require_once 'lib/plugin/SiteMap.php';
       
       class WikiPlugin_IncludeTree
      -extends WikiPlugin_SiteMap
      +    extends WikiPlugin_SiteMap
       {
      -  function getName () {
      -    return _("IncludeTree");
      -  }
      +    function getName()
      +    {
      +        return _("IncludeTree");
      +    }
       
      -  function getDescription () {
      -    return _("Dynamic Category Tree");
      -  }
      +    function getDescription()
      +    {
      +        return _("Dynamic Category Tree");
      +    }
       
      -  function getDefaultArguments() {
      -      return array('exclude'        => '',
      -                   'include_self'   => 0,
      -                   'noheader'       => 0,
      -                   'page'           => '[pagename]',
      -                   'description'    => $this->getDescription(),
      -                   'reclimit'       => 2,
      -                   'info'           => false,
      -                   'direction'      => 'back',
      -                   'firstreversed'  => false,
      -                   'excludeunknown' => true,
      -                   'includepages'   => 'words=100',
      -                   'category'       => '',
      -                   'dtree'          => true,
      -                   );
      +    function getDefaultArguments()
      +    {
      +        return array('exclude' => '',
      +            'include_self' => 0,
      +            'noheader' => 0,
      +            'page' => '[pagename]',
      +            'description' => $this->getDescription(),
      +            'reclimit' => 2,
      +            'info' => false,
      +            'direction' => 'back',
      +            'firstreversed' => false,
      +            'excludeunknown' => true,
      +            'includepages' => 'words=100',
      +            'category' => '',
      +            'dtree' => true,
      +        );
           }
       
      -    function run($dbi, $argstr, &$request, $basepage) {
      -      return WikiPlugin_SiteMap::run($dbi, $argstr, $request, $basepage);
      +    function run($dbi, $argstr, &$request, $basepage)
      +    {
      +        return WikiPlugin_SiteMap::run($dbi, $argstr, $request, $basepage);
           }
       }
       
      diff --git a/lib/plugin/InterWikiSearch.php b/lib/plugin/InterWikiSearch.php
      index dd1afae7f..f3aa82258 100644
      --- a/lib/plugin/InterWikiSearch.php
      +++ b/lib/plugin/InterWikiSearch.php
      @@ -25,23 +25,27 @@
       require_once 'lib/PageType.php';
       
       class WikiPlugin_InterWikiSearch
      -extends WikiPlugin
      +    extends WikiPlugin
       {
      -    function getName() {
      +    function getName()
      +    {
               return _("InterWikiSearch");
           }
       
      -    function getDescription() {
      +    function getDescription()
      +    {
               return _("Perform searches on InterWiki sites listed in InterWikiMap.");
           }
       
      -    function getDefaultArguments() {
      +    function getDefaultArguments()
      +    {
               return array('s' => '',
      -                     'formsize' => 30,
      -                    );
      +            'formsize' => 30,
      +        );
           }
       
      -    function run($dbi, $argstr, &$request, $basepage) {
      +    function run($dbi, $argstr, &$request, $basepage)
      +    {
               $args = $this->getArgs($argstr, $request);
               extract($args);
       
      @@ -49,8 +53,8 @@ extends WikiPlugin
                   return $this->disabled("Sorry, this plugin is currently out of order.");
       
               $page = $dbi->getPage($request->getArg('pagename'));
      -        return new TransformedText($page,_('InterWikiMap'),array('markup' => 2),
      -                                   'searchableInterWikiMap');
      +        return new TransformedText($page, _('InterWikiMap'), array('markup' => 2),
      +            'searchableInterWikiMap');
               /*
               return new PageType($pagerevisionhandle,
                                   $pagename = _('InterWikiMap'),
      @@ -58,61 +62,70 @@ extends WikiPlugin
                                   $overridePageType = 'PageType_searchableInterWikiMap');
               */
           }
      -};
      +}
      +
      +;
       
       /**
        * @desc
        */
       if (defined('DEBUG') && DEBUG) {
      -class PageFormatter_searchableInterWikiMap
      -extends PageFormatter_interwikimap {}
      -
      -class PageType_searchableInterWikiMap
      -extends PageType_interwikimap
      -{
      -    function format($text) {
      -        return HTML::div(array('class' => 'wikitext'),
      -                         $this->_transform($this->_getHeader($text)),
      -                         $this->_formatMap(),
      -                         $this->_transform($this->_getFooter($text)));
      +    class PageFormatter_searchableInterWikiMap
      +        extends PageFormatter_interwikimap
      +    {
           }
       
      -    function _formatMap() {
      -        return $this->_arrayToTable ($this->_getMap(), $GLOBALS['request']);
      -    }
      +    class PageType_searchableInterWikiMap
      +        extends PageType_interwikimap
      +    {
      +        function format($text)
      +        {
      +            return HTML::div(array('class' => 'wikitext'),
      +                $this->_transform($this->_getHeader($text)),
      +                $this->_formatMap(),
      +                $this->_transform($this->_getFooter($text)));
      +        }
       
      -    function _arrayToTable ($array, &$request) {
      -        $thead = HTML::thead();
      -        $label[0] = _("Wiki Name");
      -        $label[1] = _("Search");
      -        $thead->pushContent(HTML::tr(HTML::th($label[0]),
      -                                     HTML::th($label[1])));
      -
      -        $tbody = HTML::tbody();
      -        $dbi = $request->getDbh();
      -        if ($array) {
      -            foreach ($array as $moniker => $interurl) {
      -                $monikertd = HTML::td(array('class' => 'interwiki-moniker'),
      -                                      $dbi->isWikiPage($moniker)
      -                                      ? WikiLink($moniker)
      -                                      : $moniker);
      -
      -                $w = new WikiPluginLoader;
      -                $p = $w->getPlugin('ExternalSearch');
      -                $argstr = sprintf('url="%s"', addslashes($interurl));
      -                $searchtd = HTML::td($p->run($dbi, $argstr, $request, $basepage));
      -
      -                $tbody->pushContent(HTML::tr($monikertd, $searchtd));
      -            }
      +        function _formatMap()
      +        {
      +            return $this->_arrayToTable($this->_getMap(), $GLOBALS['request']);
               }
      -        $table = HTML::table();
      -        $table->setAttr('class', 'interwiki-map');
      -        $table->pushContent($thead);
      -        $table->pushContent($tbody);
       
      -        return $table;
      +        function _arrayToTable($array, &$request)
      +        {
      +            $thead = HTML::thead();
      +            $label[0] = _("Wiki Name");
      +            $label[1] = _("Search");
      +            $thead->pushContent(HTML::tr(HTML::th($label[0]),
      +                HTML::th($label[1])));
      +
      +            $tbody = HTML::tbody();
      +            $dbi = $request->getDbh();
      +            if ($array) {
      +                foreach ($array as $moniker => $interurl) {
      +                    $monikertd = HTML::td(array('class' => 'interwiki-moniker'),
      +                        $dbi->isWikiPage($moniker)
      +                            ? WikiLink($moniker)
      +                            : $moniker);
      +
      +                    $w = new WikiPluginLoader;
      +                    $p = $w->getPlugin('ExternalSearch');
      +                    $argstr = sprintf('url="%s"', addslashes($interurl));
      +                    $searchtd = HTML::td($p->run($dbi, $argstr, $request, $basepage));
      +
      +                    $tbody->pushContent(HTML::tr($monikertd, $searchtd));
      +                }
      +            }
      +            $table = HTML::table();
      +            $table->setAttr('class', 'interwiki-map');
      +            $table->pushContent($thead);
      +            $table->pushContent($tbody);
      +
      +            return $table;
      +        }
           }
      -};
      +
      +    ;
       }
       
       // Local Variables:
      diff --git a/lib/plugin/JabberPresence.php b/lib/plugin/JabberPresence.php
      index 9700bbfab..2ff50ef22 100644
      --- a/lib/plugin/JabberPresence.php
      +++ b/lib/plugin/JabberPresence.php
      @@ -33,42 +33,48 @@
        */
       
       if (!defined('MY_JABBER_ID'))
      -    define('MY_JABBER_ID', $GLOBALS['request']->_user->UserName()."@jabber.com"); // or "@netflint.net"
      +    define('MY_JABBER_ID', $GLOBALS['request']->_user->UserName() . "@jabber.com"); // or "@netflint.net"
       
       class WikiPlugin_JabberPresence
      -extends WikiPlugin
      +    extends WikiPlugin
       {
      -    function getName () {
      +    function getName()
      +    {
               return _("JabberPresence");
           }
       
      -    function getDescription () {
      +    function getDescription()
      +    {
               return _("Simple jabber presence plugin");
           }
       
           // Establish default values for each of this plugin's arguments.
      -    function getDefaultArguments() {
      +    function getDefaultArguments()
      +    {
               return array('scripturl' => "http://edgar.netflint.net/status.php",
      -                     'jid'       => MY_JABBER_ID,
      -                     'type'      => 'image',
      -                     'iconset'   => "gabber");
      +            'jid' => MY_JABBER_ID,
      +            'type' => 'image',
      +            'iconset' => "gabber");
           }
       
      -    function run($dbi, $argstr, $request) {
      +    function run($dbi, $argstr, $request)
      +    {
               extract($this->getArgs($argstr, $request));
               // Any text that is returned will not be further transformed,
               // so use html where necessary.
               if (empty($jid))
                   $html = HTML();
               else
      -          $html = HTML::img(array('src' => urlencode($scripturl).
      -                                  '&jid='.urlencode($jid).
      -                                  '&type='.urlencode($type).
      -                                  '&iconset='.($iconset),
      -                                  'alt' =>""));
      +            $html = HTML::img(array('src' => urlencode($scripturl) .
      +                '&jid=' . urlencode($jid) .
      +                '&type=' . urlencode($type) .
      +                '&iconset=' . ($iconset),
      +                'alt' => ""));
               return $html;
           }
      -};
      +}
      +
      +;
       
       // Local Variables:
       // mode: php
      diff --git a/lib/plugin/LdapSearch.php b/lib/plugin/LdapSearch.php
      index ea203f0f0..d9a1f1584 100644
      --- a/lib/plugin/LdapSearch.php
      +++ b/lib/plugin/LdapSearch.php
      @@ -28,49 +28,54 @@
        * TODO: Return a pagelist on certain attributes
        *
        * Usage Samples:
      -  <>
      -  <>
      -  <>
      -  <>
      -  <>
      -  <>
      -
      +<>
      +<>
      +<>
      +<>
      +<>
      +<>
        * @author John Lines
        */
       
       class WikiPlugin_LdapSearch
      -extends WikiPlugin
      +    extends WikiPlugin
       {
      -    function getName () {
      +    function getName()
      +    {
               return _("LdapSearch");
           }
      -    function getDescription () {
      +
      +    function getDescription()
      +    {
               return _("Search an LDAP directory");
           }
      -    function getDefaultArguments() {
      -        return array('host'         => "",                 // default: LDAP_AUTH_HOST
      -                     'port'         => 389,                // ignored if host = full uri
      -                     'basedn'         => "",                // LDAP_BASE_DN
      -                     'filter'   => "(cn=*)",
      -                     'attributes' => "",
      -                     'user'     => '',
      -                     'password' => '',
      -                     'options'   => "",
      -                     );
      +
      +    function getDefaultArguments()
      +    {
      +        return array('host' => "", // default: LDAP_AUTH_HOST
      +            'port' => 389, // ignored if host = full uri
      +            'basedn' => "", // LDAP_BASE_DN
      +            'filter' => "(cn=*)",
      +            'attributes' => "",
      +            'user' => '',
      +            'password' => '',
      +            'options' => "",
      +        );
           }
       
           // I ought to require the ldap extension, but fail sanely, if I cant get it.
           // - however at the moment this seems to work as is
      -    function run($dbi, $argstr, $request) {
      +    function run($dbi, $argstr, $request)
      +    {
               if (!function_exists('ldap_connect')) {
                   if (!loadPhpExtension('ldap'))
                       return $this->error(_("Missing ldap extension"));
      @@ -142,25 +147,27 @@ extends WikiPlugin
       
               // If we were given attributes then we return them in the order given
               // else take all
      -        if ( !$attributes ) {
      +        if (!$attributes) {
                   $attr_array = array();
      -            for ($ii=0; $ii < $entries[0]["count"]; $ii++) {
      -                    $data = $entries[0][$ii];
      -                    $attr_array[] = $data;
      +            for ($ii = 0; $ii < $entries[0]["count"]; $ii++) {
      +                $data = $entries[0][$ii];
      +                $attr_array[] = $data;
                   }
               }
      -        for ($i=0; $i < count($attr_array) ; $i++) { $attrcols[$i] = 0; }
      +        for ($i = 0; $i < count($attr_array); $i++) {
      +            $attrcols[$i] = 0;
      +        }
               // Work out how many columns we need for each attribute. objectclass has more
      -        for ($i=0; $i<$entries[0]["count"]; $i++) {
      -                $data = $entries[0][$i];
      -                $datalen = $entries[0][$data]["count"];
      -                if ($attrcols[$i] < $datalen) {
      -                    $attrcols[$i] = $datalen;
      -                }
      +        for ($i = 0; $i < $entries[0]["count"]; $i++) {
      +            $data = $entries[0][$i];
      +            $datalen = $entries[0][$data]["count"];
      +            if ($attrcols[$i] < $datalen) {
      +                $attrcols[$i] = $datalen;
      +            }
               }
               // Print the headers
               $row = HTML::tr();
      -        for ($i=0; $i < count($attr_array) ; $i++) {
      +        for ($i = 0; $i < count($attr_array); $i++) {
                   // span subcolumns, like objectclass
                   if ($attrcols[$i] > 1)
                       $row->pushContent(HTML::th(array('colspan' => $attrcols[$i]), $attr_array[$i]));
      @@ -171,18 +178,21 @@ extends WikiPlugin
       
               // Print the data rows
               for ($currow = 0; $currow < $entries["count"]; $currow++) {
      -            $row = HTML::tr(); $nc=0;
      +            $row = HTML::tr();
      +            $nc = 0;
                   // columns
      -            for ($i=0; $i < count($attr_array); $i++){
      -                    $colname = $attr_array[$i];
      +            for ($i = 0; $i < count($attr_array); $i++) {
      +                $colname = $attr_array[$i];
                       $data = @$entries[$currow][$colname];
                       if ($data and $data["count"] > 0) {
                           // subcolumns, e.g. for objectclass
      -                    for ($iii=0; $iii < $data["count"]; $iii++) {
      -                      $row->pushContent(HTML::td($data[$iii])); $nc++;
      +                    for ($iii = 0; $iii < $data["count"]; $iii++) {
      +                        $row->pushContent(HTML::td($data[$iii]));
      +                        $nc++;
                           }
                       } else {
      -                    $row->pushContent(HTML::td("")); $nc++;
      +                    $row->pushContent(HTML::td(""));
      +                    $nc++;
                       }
                       // Make up some blank cells if required to pad this row
                       /*for ( $j=0 ; $j < ($attrcols[$ii] - $nc); $j++ ) {
      @@ -191,9 +201,11 @@ extends WikiPlugin
                   }
                   $html->pushContent($row);
               }
      -        return HTML::table(array('cellpadding' => 1,'cellspacing' => 1, 'border' => 1), $html);
      +        return HTML::table(array('cellpadding' => 1, 'cellspacing' => 1, 'border' => 1), $html);
           }
      -};
      +}
      +
      +;
       
       // Local Variables:
       // mode: php
      diff --git a/lib/plugin/LikePages.php b/lib/plugin/LikePages.php
      index 4823ae9d7..c9b919e1d 100644
      --- a/lib/plugin/LikePages.php
      +++ b/lib/plugin/LikePages.php
      @@ -24,32 +24,37 @@ require_once 'lib/TextSearchQuery.php';
       require_once 'lib/PageList.php';
       
       class WikiPlugin_LikePages
      -extends WikiPlugin
      +    extends WikiPlugin
       {
      -    function getName() {
      +    function getName()
      +    {
               return _("LikePages");
           }
       
      -    function getDescription() {
      +    function getDescription()
      +    {
               return sprintf(_("List page names which share an initial or final title word with '%s'."),
      -                       '[pagename]');
      +            '[pagename]');
           }
       
      -    function getDefaultArguments() {
      +    function getDefaultArguments()
      +    {
               return array_merge
      -            (
      -             PageList::supportedArgs(),
      -             array('page'     => '[pagename]',
      -                   'prefix'   => false,
      -                   'suffix'   => false,
      -                   'noheader' => false,
      -                   ));
      +        (
      +            PageList::supportedArgs(),
      +            array('page' => '[pagename]',
      +                'prefix' => false,
      +                'suffix' => false,
      +                'noheader' => false,
      +            ));
           }
      +
           // info arg allows multiple columns
           // info=mtime,hits,summary,version,author,locked,minor
           // exclude arg allows multiple pagenames exclude=HomePage,RecentChanges
       
      -    function run($dbi, $argstr, &$request, $basepage) {
      +    function run($dbi, $argstr, &$request, $basepage)
      +    {
               $args = $this->getArgs($argstr, $request);
       
               extract($args);
      @@ -59,31 +64,29 @@ extends WikiPlugin
               if ($prefix) {
                   $suffix = false;
                   $descrip = fmt("Page names with prefix '%s'", $prefix);
      -        }
      -        elseif ($suffix) {
      +        } elseif ($suffix) {
                   $descrip = fmt("Page names with suffix '%s'", $suffix);
      -        }
      -        elseif ($page) {
      +        } elseif ($page) {
                   $words = preg_split('/[\s:-;.,]+/',
      -                                SplitPagename($page));
      +                SplitPagename($page));
                   $words = preg_grep('/\S/', $words);
       
                   $prefix = reset($words);
                   $suffix = end($words);
       
                   $descrip = fmt("These pages share an initial or final title word with '%s'",
      -                           WikiLink($page, 'auto'));
      +                WikiLink($page, 'auto'));
               }
       
               // Search for pages containing either the suffix or the prefix.
               $search = $match = array();
               if (!empty($prefix)) {
                   $search[] = $this->_quote($prefix);
      -            $match[]  = '^' . preg_quote($prefix, '/');
      +            $match[] = '^' . preg_quote($prefix, '/');
               }
               if (!empty($suffix)) {
                   $search[] = $this->_quote($suffix);
      -            $match[]  = preg_quote($suffix, '/') . '$';
      +            $match[] = preg_quote($suffix, '/') . '$';
               }
       
               if ($search)
      @@ -107,10 +110,13 @@ extends WikiPlugin
               return $pagelist;
           }
       
      -    function _quote($str) {
      +    function _quote($str)
      +    {
               return "'" . str_replace("'", "''", $str) . "'";
           }
      -};
      +}
      +
      +;
       
       // Local Variables:
       // mode: php
      diff --git a/lib/plugin/LinkDatabase.php b/lib/plugin/LinkDatabase.php
      index 026ef1c7c..b8874e676 100644
      --- a/lib/plugin/LinkDatabase.php
      +++ b/lib/plugin/LinkDatabase.php
      @@ -36,72 +36,82 @@ require_once 'lib/WikiPluginCached.php';
        * DONE: Convert " " to %20
        */
       class WikiPlugin_LinkDatabase
      -extends WikiPluginCached
      +    extends WikiPluginCached
       {
      -    function getName () {
      +    function getName()
      +    {
               return _("LinkDatabase");
           }
      -    function getPluginType() {
      +
      +    function getPluginType()
      +    {
               return PLUGIN_CACHED_HTML;
           }
      -    function getDescription () {
      +
      +    function getDescription()
      +    {
               return _("List all pages with all links in various formats for some Java Visualization tools");
           }
      -    function getExpire($dbi, $argarray, $request) {
      +
      +    function getExpire($dbi, $argarray, $request)
      +    {
               return '+900'; // 15 minutes
           }
       
      -    function getDefaultArguments() {
      +    function getDefaultArguments()
      +    {
               return array_merge
      -            (
      -             PageList::supportedArgs(),
      -             array(
      -                   'format'        => 'html', // 'html', 'text', 'xml'
      -                   'noheader'      => false,
      -                   'include_empty' => false,
      -                   'exclude_from'  => false,
      -                   'info'          => '',
      -                   ));
      +        (
      +            PageList::supportedArgs(),
      +            array(
      +                'format' => 'html', // 'html', 'text', 'xml'
      +                'noheader' => false,
      +                'include_empty' => false,
      +                'exclude_from' => false,
      +                'info' => '',
      +            ));
           }
       
      -    function getHtml($dbi, $argarray, $request, $basepage) {
      +    function getHtml($dbi, $argarray, $request, $basepage)
      +    {
               $this->run($dbi, WikiPluginCached::glueArgs($argarray), $request, $basepage);
           }
       
      -    function run($dbi, $argstr, $request, $basepage) {
      +    function run($dbi, $argstr, $request, $basepage)
      +    {
               global $WikiTheme;
               $args = $this->getArgs($argstr, $request);
       
               $caption = _("All pages with all links in this wiki (%d total):");
       
      -        if ( !empty($args['owner']) ) {
      -            $pages = PageList::allPagesByOwner($args['owner'],$args['include_empty'],
      -                                               $args['sortby'],$args['limit']);
      +        if (!empty($args['owner'])) {
      +            $pages = PageList::allPagesByOwner($args['owner'], $args['include_empty'],
      +                $args['sortby'], $args['limit']);
                   if ($args['owner'])
                       $caption = fmt("List of pages owned by [%s] (%d total):",
      -                               WikiLink($args['owner'], 'if_known'),
      -                               count($pages));
      -        } elseif ( !empty($args['author']) ) {
      -            $pages = PageList::allPagesByAuthor($args['author'],$args['include_empty'],
      -                                                $args['sortby'],$args['limit']);
      +                    WikiLink($args['owner'], 'if_known'),
      +                    count($pages));
      +        } elseif (!empty($args['author'])) {
      +            $pages = PageList::allPagesByAuthor($args['author'], $args['include_empty'],
      +                $args['sortby'], $args['limit']);
                   if ($args['author'])
                       $caption = fmt("List of pages last edited by [%s] (%d total):",
      -                               WikiLink($args['author'], 'if_known'),
      -                               count($pages));
      -        } elseif ( !empty($args['creator']) ) {
      -            $pages = PageList::allPagesByCreator($args['creator'],$args['include_empty'],
      -                                                 $args['sortby'],$args['limit']);
      +                    WikiLink($args['author'], 'if_known'),
      +                    count($pages));
      +        } elseif (!empty($args['creator'])) {
      +            $pages = PageList::allPagesByCreator($args['creator'], $args['include_empty'],
      +                $args['sortby'], $args['limit']);
                   if ($args['creator'])
                       $caption = fmt("List of pages created by [%s] (%d total):",
      -                               WikiLink($args['creator'], 'if_known'),
      -                               count($pages));
      +                    WikiLink($args['creator'], 'if_known'),
      +                    count($pages));
               } else {
      -            if (! $request->getArg('count'))
      +            if (!$request->getArg('count'))
                       $args['count'] = $dbi->numPages($args['include_empty'], $args['exclude_from']);
                   else
                       $args['count'] = $request->getArg('count');
                   $pages = $dbi->getAllPages($args['include_empty'], $args['sortby'],
      -                                       $args['limit'], $args['exclude_from']);
      +                $args['limit'], $args['exclude_from']);
               }
               if ($args['format'] == 'html') {
                   $args['types']['links'] =
      @@ -118,11 +128,11 @@ extends WikiPluginCached
                       header("Content-Type: text/plain");
                   $request->checkValidators();
                   while ($page = $pages->next()) {
      -                echo preg_replace("/ /","%20",$page->getName());
      +                echo preg_replace("/ /", "%20", $page->getName());
                       $links = $page->getPageLinks(false, $args['sortby'], $args['limit'],
      -                                             $args['exclude']);
      +                    $args['exclude']);
                       while ($link = $links->next()) {
      -                    echo " ", preg_replace("/ /","%20",$link->getName());
      +                    echo " ", preg_replace("/ /", "%20", $link->getName());
                       }
                       echo "\n";
                   }
      @@ -144,15 +154,15 @@ extends WikiPluginCached
                   $dtd = $WikiTheme->_findData("GraphXML.dtd");
                   echo "\n";
                   echo "\n";
      -            echo "\n";
      -            echo '',"\n\n";
      +            echo "\n";
      +            echo '', "\n\n";
                   while ($page = $pages->next()) {
      -                    $pageid = MangleXmlIdentifier($page->getName());
      -                    $pagename = $page->getName();
      +                $pageid = MangleXmlIdentifier($page->getName());
      +                $pagename = $page->getName();
                       echo "";
      -                echo "\n";
      +                echo "\n";
                       $links = $page->getPageLinks(false, $args['sortby'], $args['limit'], $args['exclude']);
                       while ($link = $links->next()) {
                           $edge = MangleXmlIdentifier($link->getName());
      @@ -170,10 +180,14 @@ extends WikiPluginCached
                   return $this->error(fmt("Unsupported format argument %s", $args['format']));
               }
           }
      -};
      +}
      +
      +;
       
      -class _PageList_Column_LinkDatabase_links extends _PageList_Column {
      -    function _getValue($page, &$revision_handle) {
      +class _PageList_Column_LinkDatabase_links extends _PageList_Column
      +{
      +    function _getValue($page, &$revision_handle)
      +    {
               $out = HTML();
               $links = $page->getPageLinks();
               while ($link = $links->next()) {
      diff --git a/lib/plugin/LinkSearch.php b/lib/plugin/LinkSearch.php
      index 48b912a28..79c0c0905 100644
      --- a/lib/plugin/LinkSearch.php
      +++ b/lib/plugin/LinkSearch.php
      @@ -29,51 +29,57 @@ require_once 'lib/PageList.php';
        * @author: Reini Urban
        */
       class WikiPlugin_LinkSearch
      -extends WikiPlugin
      +    extends WikiPlugin
       {
      -    function getName() {
      +    function getName()
      +    {
               return _("LinkSearch");
           }
      -    function getDescription() {
      +
      +    function getDescription()
      +    {
               return _("Search page and link names");
           }
      -    function getDefaultArguments() {
      +
      +    function getDefaultArguments()
      +    {
               return array_merge
      -            (
      -             PageList::supportedArgs(), // paging and more.
      -             array(
      -                   's'          => "", // linkvalue query string
      -                   'page'       => "*", // which pages (glob allowed), default: all
      -                   'direction'  => "out", // or in
      -                   'case_exact' => false,
      -                   'regex'      => 'auto',
      -                   'noform'     => false, // don't show form with results.
      -                   'noheader'   => false  // no caption
      -                   ));
      +        (
      +            PageList::supportedArgs(), // paging and more.
      +            array(
      +                's' => "", // linkvalue query string
      +                'page' => "*", // which pages (glob allowed), default: all
      +                'direction' => "out", // or in
      +                'case_exact' => false,
      +                'regex' => 'auto',
      +                'noform' => false, // don't show form with results.
      +                'noheader' => false // no caption
      +            ));
           }
       
      -    function showForm (&$dbi, &$request, $args) {
      +    function showForm(&$dbi, &$request, $args)
      +    {
               $action = $request->getPostURL();
      -        $hiddenfield = HiddenInputs($request->getArgs(),'',
      -                                    array('action','page','s','direction'));
      +        $hiddenfield = HiddenInputs($request->getArgs(), '',
      +            array('action', 'page', 's', 'direction'));
               $pagefilter = HTML::input(array('name' => 'page',
      -                                        'value' => $args['page'],
      -                                        'title' => _("Search only in these pages. With autocompletion."),
      -                                        'class' => 'dropdown',
      -                                        'acdropdown' => 'true',
      -                                        'autocomplete_complete' => 'true',
      -                                        'autocomplete_matchsubstring' => 'false',
      -                                        'autocomplete_list' => 'xmlrpc:wiki.titleSearch ^[S] 4'
      -                                        ), '');
      +            'value' => $args['page'],
      +            'title' => _("Search only in these pages. With autocompletion."),
      +            'class' => 'dropdown',
      +            'acdropdown' => 'true',
      +            'autocomplete_complete' => 'true',
      +            'autocomplete_matchsubstring' => 'false',
      +            'autocomplete_list' => 'xmlrpc:wiki.titleSearch ^[S] 4'
      +        ), '');
               $query = HTML::input(array('name' => 's',
      -                                   'value' => $args['s'],
      -                                   'title' => _("Filter by this link. These are pagenames. With autocompletion."),
      -                                   'class' => 'dropdown',
      -                                   'acdropdown' => 'true',
      -                                   'autocomplete_complete' => 'true',
      -                                   'autocomplete_matchsubstring' => 'true',
      -                                   'autocomplete_list' => 'xmlrpc:wiki.titleSearch ^[S] 4'
      -                                   ), '');
      +            'value' => $args['s'],
      +            'title' => _("Filter by this link. These are pagenames. With autocompletion."),
      +            'class' => 'dropdown',
      +            'acdropdown' => 'true',
      +            'autocomplete_complete' => 'true',
      +            'autocomplete_matchsubstring' => 'true',
      +            'autocomplete_list' => 'xmlrpc:wiki.titleSearch ^[S] 4'
      +        ), '');
               $dirsign_switch = JavaScript("
       function dirsign_switch() {
         var d = document.getElementById('dirsign')
      @@ -81,18 +87,18 @@ function dirsign_switch() {
       }
       ");
               $dirsign = " => ";
      -        $in = $out = array('name' => 'direction', 'type'=>'radio', 'onChange' => 'dirsign_switch()');
      +        $in = $out = array('name' => 'direction', 'type' => 'radio', 'onChange' => 'dirsign_switch()');
               $out['value'] = 'out';
               $out['id'] = 'dir_out';
      -        if ($args['direction']=='out') $out['checked'] = 'checked';
      +        if ($args['direction'] == 'out') $out['checked'] = 'checked';
               $in['value'] = 'in';
               $in['id'] = 'dir_in';
      -        if ($args['direction']=='in') {
      +        if ($args['direction'] == 'in') {
                   $in['checked'] = 'checked';
                   $dirsign = " <= ";
               }
      -        $direction = HTML(HTML::input($out), HTML::label(array('for'=>'dir_out'),_("outgoing")),
      -                          HTML::input($in), HTML::label(array('for'=>'dir_in'),_("incoming")));
      +        $direction = HTML(HTML::input($out), HTML::label(array('for' => 'dir_out'), _("outgoing")),
      +            HTML::input($in), HTML::label(array('for' => 'dir_in'), _("incoming")));
               /*
               $direction = HTML::select(array('name'=>'direction',
                                               'onChange' => 'dirsign_switch()'));
      @@ -106,23 +112,24 @@ function dirsign_switch() {
               $direction->pushContent(HTML::option($out, _("outgoing")));
               $direction->pushContent(HTML::option($in, _("incoming")));
               */
      -        $submit = Button('submit:search',  _("LinkSearch"), false);
      +        $submit = Button('submit:search', _("LinkSearch"), false);
               $instructions = _("Search in pages for links with the matching name.");
               $form = HTML::form(array('action' => $action,
      -                                 'method' => 'GET',
      -                                 'accept-charset' => $GLOBALS['charset']),
      -                           $dirsign_switch,
      -                           $hiddenfield,
      -                           $instructions, HTML::br(),
      -                           $pagefilter,
      -                           HTML::strong(HTML::tt(array('id'=>'dirsign'), $dirsign)),
      -                           $query,
      -                           HTML::raw(' '), $direction,
      -                           HTML::raw(' '), $submit);
      +                'method' => 'GET',
      +                'accept-charset' => $GLOBALS['charset']),
      +            $dirsign_switch,
      +            $hiddenfield,
      +            $instructions, HTML::br(),
      +            $pagefilter,
      +            HTML::strong(HTML::tt(array('id' => 'dirsign'), $dirsign)),
      +            $query,
      +            HTML::raw(' '), $direction,
      +            HTML::raw(' '), $submit);
               return $form;
           }
       
      -    function run ($dbi, $argstr, &$request, $basepage) {
      +    function run($dbi, $argstr, &$request, $basepage)
      +    {
               global $WikiTheme;
               $args = $this->getArgs($argstr, $request);
       
      @@ -142,7 +149,7 @@ function dirsign_switch() {
                   $pagelist->_links[] = $link;
               }
               $pagelist->addColumnObject
      -            (new _PageList_Column_LinkSearch_link('link', _("Link"), $pagelist));
      +        (new _PageList_Column_LinkSearch_link('link', _("Link"), $pagelist));
       
               if (!$noheader) {
                   // We put the form into the caption just to be able to return one pagelist object,
      @@ -150,30 +157,35 @@ function dirsign_switch() {
                   // putting the form as WikiFormRich into the actionpage. but thid doesnt look as
                   // nice as this here.
                   $pagelist->setCaption
      -            (   // on mozilla the form doesn't fit into the caption very well.
      -                HTML($noform ? '' : HTML($form,HTML::hr()),
      -                     fmt("LinkSearch result for \"%s\" in pages \"%s\", direction %s", $s, $page, $direction)));
      +            ( // on mozilla the form doesn't fit into the caption very well.
      +                HTML($noform ? '' : HTML($form, HTML::hr()),
      +                    fmt("LinkSearch result for \"%s\" in pages \"%s\", direction %s", $s, $page, $direction)));
               }
               return $pagelist;
           }
      -};
      +}
      +
      +;
       
       // FIXME: sortby errors with this column
       class _PageList_Column_LinkSearch_link
      -extends _PageList_Column
      +    extends _PageList_Column
       {
      -    function _PageList_Column_LinkSearch_link ($field, $heading, &$pagelist) {
      +    function _PageList_Column_LinkSearch_link($field, $heading, &$pagelist)
      +    {
               $this->_field = $field;
               $this->_heading = $heading;
               $this->_need_rev = false;
               $this->_iscustom = true;
               $this->_pagelist =& $pagelist;
           }
      -    function _getValue(&$page, $revision_handle) {
      +
      +    function _getValue(&$page, $revision_handle)
      +    {
               if (is_object($page)) $text = $page->getName();
               else $text = $page;
               $link = $this->_pagelist->_links[$this->current_row];
      -        return WikiLink($link['linkvalue'],'if_known');
      +        return WikiLink($link['linkvalue'], 'if_known');
           }
       }
       
      diff --git a/lib/plugin/ListPages.php b/lib/plugin/ListPages.php
      index 6d31f5255..0ad689c2a 100644
      --- a/lib/plugin/ListPages.php
      +++ b/lib/plugin/ListPages.php
      @@ -32,25 +32,28 @@ require_once 'lib/PageList.php';
        * @author: Dan Frankowski
        */
       class WikiPlugin_ListPages
      -extends WikiPlugin
      +    extends WikiPlugin
       {
      -    function getName() {
      +    function getName()
      +    {
               return _("ListPages");
           }
       
      -    function getDescription() {
      +    function getDescription()
      +    {
               return _("List pages that are explicitly given as the pages argument.");
           }
       
      -    function getDefaultArguments() {
      +    function getDefaultArguments()
      +    {
               return array_merge
      -            (
      -             PageList::supportedArgs(),
      -             array('pages'    => false,
      -                   //'exclude'  => false,
      -                   'info'     => 'pagename',
      -                   'dimension' => 0,
      -                   ));
      +        (
      +            PageList::supportedArgs(),
      +            array('pages' => false,
      +                //'exclude'  => false,
      +                'info' => 'pagename',
      +                'dimension' => 0,
      +            ));
           }
       
           // info arg allows multiple columns
      @@ -60,7 +63,8 @@ extends WikiPlugin
           //   numbacklinks  : number of backlinks (links to the given page)
           //   numpagelinks  : number of forward links (links at the given page)
       
      -    function run($dbi, $argstr, &$request, $basepage) {
      +    function run($dbi, $argstr, &$request, $basepage)
      +    {
               $args = $this->getArgs($argstr, $request);
       
               extract($args);
      @@ -77,7 +81,7 @@ extends WikiPlugin
                   require_once 'lib/wikilens/Buddy.php';
                   require_once 'lib/wikilens/PageListColumns.php';
       
      -            $active_user   = $request->getUser();
      +            $active_user = $request->getUser();
                   $active_userid = $active_user->_userid;
       
                   // if userids is null or empty, fill it with just the active user
      @@ -86,8 +90,8 @@ extends WikiPlugin
                       // causing the userids[] parameter to be ignored
                       if (is_string($active_userid)
                           and strlen($active_userid)
      -                    and $active_user->isSignedIn())
      -                {
      +                        and $active_user->isSignedIn()
      +                ) {
                           $userids = getBuddies($active_userid, $dbi);
                       } else {
                           $userids = array();
      @@ -108,7 +112,7 @@ extends WikiPlugin
                       unset($user);
                   }
                   $options = array('dimension' => $dimension,
      -                             'users' => $allowed_users);
      +                'users' => $allowed_users);
                   $args = array_merge($options, $args);
               }
               if (empty($pages) and $pages != '0')
      @@ -126,15 +130,21 @@ extends WikiPlugin
               $pagelist->addPageList($pages_array);
               return $pagelist;
           }
      -};
      +}
      +
      +;
       
       // how many back-/forwardlinks for this page
      -class _PageList_Column_ListPages_count extends _PageList_Column {
      -    function _PageList_Column_ListPages_count($field, $display, $backwards = false) {
      +class _PageList_Column_ListPages_count extends _PageList_Column
      +{
      +    function _PageList_Column_ListPages_count($field, $display, $backwards = false)
      +    {
               $this->_direction = $backwards;
               return $this->_PageList_Column($field, $display, 'center');
           }
      -    function _getValue($page, &$revision_handle) {
      +
      +    function _getValue($page, &$revision_handle)
      +    {
               $iter = $page->getLinks($this->_direction);
               $count = $iter->count();
               return $count;
      diff --git a/lib/plugin/ListRelations.php b/lib/plugin/ListRelations.php
      index a41748839..93b40df47 100644
      --- a/lib/plugin/ListRelations.php
      +++ b/lib/plugin/ListRelations.php
      @@ -28,23 +28,30 @@ require_once 'lib/PageList.php';
        * @author: Reini Urban
        */
       class WikiPlugin_ListRelations
      -extends WikiPlugin
      +    extends WikiPlugin
       {
      -    function getName() {
      +    function getName()
      +    {
               return _("ListRelations");
           }
      -    function getDescription() {
      +
      +    function getDescription()
      +    {
               return _("Display the list of all defined relations and optionnally attributes in this entire wiki");
           }
      -    function getDefaultArguments() {
      +
      +    function getDefaultArguments()
      +    {
               return array_merge
      -            (
      -             PageList::supportedArgs(), // paging and more.
      -             array(
      -                   'mode' => "relations" // or "attributes" or "all"
      -                   ));
      +        (
      +            PageList::supportedArgs(), // paging and more.
      +            array(
      +                'mode' => "relations" // or "attributes" or "all"
      +            ));
           }
      -    function run ($dbi, $argstr, &$request, $basepage) {
      +
      +    function run($dbi, $argstr, &$request, $basepage)
      +    {
               $args = $this->getArgs($argstr, $request);
               extract($args);
               $pagelist = new PageList($info, $exclude, $args);
      @@ -53,7 +60,9 @@ extends WikiPlugin
               return $pagelist;
           }
       
      -};
      +}
      +
      +;
       
       // Local Variables:
       // mode: php
      diff --git a/lib/plugin/ListSubpages.php b/lib/plugin/ListSubpages.php
      index 58016dad6..70739d9d4 100644
      --- a/lib/plugin/ListSubpages.php
      +++ b/lib/plugin/ListSubpages.php
      @@ -28,33 +28,38 @@
       require_once 'lib/PageList.php';
       
       class WikiPlugin_ListSubpages
      -extends WikiPlugin
      +    extends WikiPlugin
       {
      -    function getName() {
      +    function getName()
      +    {
               return _("ListSubpages");
           }
       
      -    function getDescription () {
      +    function getDescription()
      +    {
               return _("Lists the names of all SubPages of the current page.");
           }
       
      -    function getDefaultArguments() {
      +    function getDefaultArguments()
      +    {
               return array_merge
      -            (
      -             PageList::supportedArgs(),
      -               array('noheader' => false, // no header
      -                     'basepage' => false, // subpages of which page, default: current
      -                     'maxpages' => '',    // maximum number of pages to include, change that to limit
      -                     //'exclude'  => '',
      -                     /*'relative' => false, */
      -                     'info'     => ''
      -                     ));
      +        (
      +            PageList::supportedArgs(),
      +            array('noheader' => false, // no header
      +                'basepage' => false, // subpages of which page, default: current
      +                'maxpages' => '', // maximum number of pages to include, change that to limit
      +                //'exclude'  => '',
      +                /*'relative' => false, */
      +                'info' => ''
      +            ));
           }
      +
           // info arg allows multiple columns
           // info=mtime,hits,summary,version,author,locked,minor,count
           // exclude arg allows multiple pagenames exclude=HomePage,RecentChanges
       
      -    function run($dbi, $argstr, &$request, $basepage) {
      +    function run($dbi, $argstr, &$request, $basepage)
      +    {
               $args = $this->getArgs($argstr, $request);
               if ($args['basepage'])
                   $pagename = $args['basepage'];
      @@ -65,7 +70,7 @@ extends WikiPlugin
               // expected when there are no subpages. (see also
               // UnfoldSubPages plugin)
               $subpages = explodePageList($pagename . SUBPAGE_SEPARATOR . '*');
      -        if (! $subpages) {
      +        if (!$subpages) {
                   return $this->error(_("The current page has no subpages defined."));
               }
               extract($args);
      @@ -73,14 +78,14 @@ extends WikiPlugin
               $content = HTML();
               //$subpages = array_reverse($subpages); // TODO: why?
               if ($maxpages) {
      -            $subpages = array_slice ($subpages, 0, $maxpages);
      +            $subpages = array_slice($subpages, 0, $maxpages);
               }
       
               $descrip = fmt("SubPages of %s:",
      -                       WikiLink($pagename, 'auto'));
      +            WikiLink($pagename, 'auto'));
               if ($info) {
                   $info = explode(",", $info);
      -            if (in_array('count',$info))
      +            if (in_array('count', $info))
                       $args['types']['count'] = new _PageList_Column_ListSubpages_count('count', _("#"), 'center');
               }
               $pagelist = new PageList($info, $exclude, $args);
      @@ -92,7 +97,7 @@ extends WikiPlugin
                   static $included_pages = array();
                   if (in_array($page, $included_pages)) {
                       $content->pushContent(HTML::p(sprintf(_("Recursive inclusion of page %s ignored"),
      -                                                      $page)));
      +                    $page)));
                       continue;
                   }
                   array_push($included_pages, $page);
      @@ -106,11 +111,15 @@ extends WikiPlugin
               $content->pushContent($pagelist);
               return $content;
           }
      -};
      +}
      +
      +;
       
       // how many backlinks for this subpage
      -class _PageList_Column_ListSubpages_count extends _PageList_Column {
      -    function _getValue($page, &$revision_handle) {
      +class _PageList_Column_ListSubpages_count extends _PageList_Column
      +{
      +    function _getValue($page, &$revision_handle)
      +    {
               $iter = $page->getBackLinks();
               $count = $iter->count();
               return $count;
      diff --git a/lib/plugin/MediawikiTable.php b/lib/plugin/MediawikiTable.php
      index 2ad5ea8d0..9bec71326 100644
      --- a/lib/plugin/MediawikiTable.php
      +++ b/lib/plugin/MediawikiTable.php
      @@ -48,23 +48,27 @@
        * MediawikiTablePlugin
        * A PhpWiki plugin that allows insertion of tables using a Mediawiki-like
        * syntax.
      -*/
      + */
       class WikiPlugin_MediawikiTable
      -extends WikiPlugin
      +    extends WikiPlugin
       {
      -    function getName() {
      +    function getName()
      +    {
               return _("MediawikiTable");
           }
       
      -    function getDescription() {
      -      return _("Layout tables using a Mediawiki-like markup style.");
      +    function getDescription()
      +    {
      +        return _("Layout tables using a Mediawiki-like markup style.");
           }
       
      -    function getDefaultArguments() {
      +    function getDefaultArguments()
      +    {
               return array();
           }
       
      -    function run($dbi, $argstr, &$request, $basepage) {
      +    function run($dbi, $argstr, &$request, $basepage)
      +    {
               include_once 'lib/BlockParser.php';
               // MediawikiTablePlugin markup is new.
               $markup = 2.0;
      @@ -94,18 +98,19 @@ extends WikiPlugin
               // If user provides an Id, the generated Id will be overwritten below.
               $table->setAttr("id", GenerateId("MediawikiTable"));
       
      -        if (substr($lines[0],0,2) == "{|") {
      +        if (substr($lines[0], 0, 2) == "{|") {
                   // Start of table
      -            $lines[0] = substr($lines[0],2);
      +            $lines[0] = substr($lines[0], 2);
               }
               if (($lines[0][0] != '|') and ($lines[0][0] != '!')) {
                   $line = array_shift($lines);
                   $attrs = parse_attributes($line);
                   foreach ($attrs as $key => $value) {
      -                if (in_array ($key, array("id", "class", "title", "style",
      -                                          "bgcolor", "frame", "rules", "border",
      -                                          "cellspacing", "cellpadding",
      -                                          "summary", "align", "width"))) {
      +                if (in_array($key, array("id", "class", "title", "style",
      +                    "bgcolor", "frame", "rules", "border",
      +                    "cellspacing", "cellpadding",
      +                    "summary", "align", "width"))
      +                ) {
                           $table->setAttr($key, $value);
                       }
                   }
      @@ -116,11 +121,11 @@ extends WikiPlugin
               }
       
               foreach ($lines as $line) {
      -            if (substr($line,0,2) == "|}") {
      +            if (substr($line, 0, 2) == "|}") {
                       // End of table
                       continue;
                   }
      -            if (substr($line,0,2) == "|-") {
      +            if (substr($line, 0, 2) == "|-") {
                       if (isset($row)) {
                           if (isset($cell)) {
                               if (isset($content)) {
      @@ -144,10 +149,11 @@ extends WikiPlugin
                           }
                       }
                       $row = HTML::tr();
      -                $attrs = parse_attributes(substr($line,2));
      +                $attrs = parse_attributes(substr($line, 2));
                       foreach ($attrs as $key => $value) {
      -                    if (in_array ($key, array("id", "class", "title", "style",
      -                                              "bgcolor", "align", "valign"))) {
      +                    if (in_array($key, array("id", "class", "title", "style",
      +                        "bgcolor", "align", "valign"))
      +                    ) {
                               $row->setAttr($key, $value);
                           }
                       }
      @@ -155,32 +161,33 @@ extends WikiPlugin
                   }
       
                   // Table summary
      -            if (substr($line,0,2) == "|=") {
      -                $line = substr($line,2);
      +            if (substr($line, 0, 2) == "|=") {
      +                $line = substr($line, 2);
                       $table->setAttr("summary", trim($line));
                   }
       
                   // Table caption
      -            if (substr($line,0,2) == "|+") {
      +            if (substr($line, 0, 2) == "|+") {
       
      -                $line = substr($line,2);
      +                $line = substr($line, 2);
                       $pospipe = strpos($line, "|");
                       $posbracket = strpos($line, "[");
                       if (($pospipe !== false) && (($posbracket === false) || ($posbracket > $pospipe))) {
                           $attrs = parse_attributes(substr($line, 0, $pospipe));
                           foreach ($attrs as $key => $value) {
      -                        if (in_array ($key, array("id", "class", "title", "style",
      -                                                  "align", "lang"))) {
      +                        if (in_array($key, array("id", "class", "title", "style",
      +                            "align", "lang"))
      +                        ) {
                                   $caption->setAttr($key, $value);
                               }
                           }
      -                    $line=substr($line, $pospipe+1);
      +                    $line = substr($line, $pospipe + 1);
                       }
       
                       $caption->setContent(TransformInline(trim($line)));
                   }
       
      -            if (((substr($line,0,1) == "|") or (substr($line,0,1) == "!")) and isset($row)) {
      +            if (((substr($line, 0, 1) == "|") or (substr($line, 0, 1) == "!")) and isset($row)) {
                       if (isset($cell)) {
                           if (isset ($content)) {
                               if (is_numeric(trim($content))) {
      @@ -192,11 +199,11 @@ extends WikiPlugin
                           }
                           $row->pushContent($cell);
                       }
      -                if (substr($line,0,1) == "!") {
      +                if (substr($line, 0, 1) == "!") {
                           if ($theadstatus == 0) { // unknown
                               $theadstatus = 1; // inside
                           }
      -                    $cell = HTML::th();   // Header
      +                    $cell = HTML::th(); // Header
                       } else {
                           if ($theadstatus == 1) { // inside
                               $theadstatus = 2; // false
      @@ -224,13 +231,14 @@ extends WikiPlugin
                       if (($pospipe !== false) && (($posbracket === false) || ($posbracket > $pospipe)) && (($poscurly === false) || ($poscurly > $pospipe))) {
                           $attrs = parse_attributes(substr($line, 0, $pospipe));
                           foreach ($attrs as $key => $value) {
      -                        if (in_array ($key, array("id", "class", "title", "style", "scope",
      -                                                  "colspan", "rowspan", "width", "height",
      -                                                  "bgcolor", "align", "valign"))) {
      +                        if (in_array($key, array("id", "class", "title", "style", "scope",
      +                            "colspan", "rowspan", "width", "height",
      +                            "bgcolor", "align", "valign"))
      +                        ) {
                                   $cell->setAttr($key, $value);
                               }
                           }
      -                    $line=substr($line, $pospipe+1);
      +                    $line = substr($line, $pospipe + 1);
                           if (is_numeric(trim($line))) {
                               $cell->pushContent(HTML::p(array('style' => "text-align:right"), trim($line)));
                           } else {
      diff --git a/lib/plugin/ModeratedPage.php b/lib/plugin/ModeratedPage.php
      index dc60b17d5..5522da83d 100644
      --- a/lib/plugin/ModeratedPage.php
      +++ b/lib/plugin/ModeratedPage.php
      @@ -36,25 +36,31 @@
       require_once 'lib/WikiPlugin.php';
       
       class WikiPlugin_ModeratedPage
      -extends WikiPlugin
      +    extends WikiPlugin
       {
      -    function getName () {
      +    function getName()
      +    {
               return _("ModeratedPage");
           }
      -    function getDescription () {
      +
      +    function getDescription()
      +    {
               return _("Support moderated pages");
           }
      -    function getDefaultArguments() {
      -        return array('page'          => '[pagename]',
      -                     'moderators'    => false,
      -                     'require_level' => false,   // 1=bogo
      -                     'require_access' => 'edit,remove,change',
      -                     'id'   => '',
      -                     'pass' => '',
      -                    );
      +
      +    function getDefaultArguments()
      +    {
      +        return array('page' => '[pagename]',
      +            'moderators' => false,
      +            'require_level' => false, // 1=bogo
      +            'require_access' => 'edit,remove,change',
      +            'id' => '',
      +            'pass' => '',
      +        );
           }
       
      -    function run($dbi, $argstr, &$request, $basepage) {
      +    function run($dbi, $argstr, &$request, $basepage)
      +    {
               $args = $this->getArgs($argstr, $request);
       
               // Handle moderation request from urls sent by email
      @@ -69,22 +75,20 @@ extends WikiPlugin
                           // handle defaults:
                           //   approve or reject
                           if ($request->isPost()) {
      -                            $button = $request->getArg('ModeratedPage');
      -                            if (isset($button['reject']))
      -                                return $this->reject($request, $args, $moderation);
      -                            elseif (isset($button['approve']))
      -                                return $this->approve($request, $args, $moderation);
      -                            else
      -                                return $this->error("Wrong button pressed");
      +                        $button = $request->getArg('ModeratedPage');
      +                        if (isset($button['reject']))
      +                            return $this->reject($request, $args, $moderation);
      +                        elseif (isset($button['approve']))
      +                            return $this->approve($request, $args, $moderation); else
      +                            return $this->error("Wrong button pressed");
                           }
                           if ($args['pass'] == 'approve')
                               return $this->approve($request, $args, $moderation);
                           elseif ($args['pass'] == 'reject')
      -                        return $this->reject($request, $args, $moderation);
      -                    else
      -                        return $this->error("Wrong pass ".$args['pass']);
      +                        return $this->reject($request, $args, $moderation); else
      +                        return $this->error("Wrong pass " . $args['pass']);
                       } else {
      -                    return $this->error("Wrong id ".htmlentities($args['id']));
      +                    return $this->error("Wrong id " . htmlentities($args['id']));
                       }
                   }
               }
      @@ -94,7 +98,8 @@ extends WikiPlugin
           /**
            * resolve moderators and require_access (not yet) from actionpage plugin argstr
            */
      -    function resolve_argstr(&$request, $argstr) {
      +    function resolve_argstr(&$request, $argstr)
      +    {
               $args = $this->getArgs($argstr);
               $group = $request->getGroup();
               if (empty($args['moderators'])) {
      @@ -104,7 +109,7 @@ extends WikiPlugin
               } else {
                   // resolve possible group names
                   $moderators = explode(',', $args['moderators']);
      -            for ($i=0; $i < count($moderators); $i++) {
      +            for ($i = 0; $i < count($moderators); $i++) {
                       $members = $group->getMembersOf($moderators[$i]);
                       if (!empty($members)) {
                           array_splice($moderators, $i, 1, $members);
      @@ -131,7 +136,7 @@ extends WikiPlugin
                       unset($args['require_access']);
               }
               if ($args['require_level'] !== false) {
      -            $args['require_level'] = (integer) $args['require_level'];
      +            $args['require_level'] = (integer)$args['require_level'];
               }
               unset($args['id']);
               unset($args['page']);
      @@ -143,23 +148,24 @@ extends WikiPlugin
            * Handle client-side moderation change request.
            * Hook called on the lock action, if moderation metadata already exists.
            */
      -    function lock_check(&$request, &$page, $moderated) {
      +    function lock_check(&$request, &$page, $moderated)
      +    {
               $action_page = $request->getPage(_("ModeratedPage"));
               $status = $this->getSiteStatus($request, $action_page);
               if (is_array($status)) {
                   if (empty($status['emails'])) {
                       trigger_error(_("ModeratedPage: No emails for the moderators defined"),
      -                              E_USER_WARNING);
      +                    E_USER_WARNING);
                       return false;
                   }
                   $page->set('moderation', array('status' => $status));
                   return $this->notice(
      -                       fmt("ModeratedPage status update:\n  Moderators: '%s'\n  require_access: '%s'",
      -                       join(',', $status['moderators']), $status['require_access']));
      +                fmt("ModeratedPage status update:\n  Moderators: '%s'\n  require_access: '%s'",
      +                    join(',', $status['moderators']), $status['require_access']));
               } else {
                   $page->set('moderation', false);
                   return $this->notice(HTML($status,
      -                        fmt("'%s' is no ModeratedPage anymore.", $page->getName())));
      +                fmt("'%s' is no ModeratedPage anymore.", $page->getName())));
               }
           }
       
      @@ -168,38 +174,40 @@ extends WikiPlugin
            * Hook called on the lock action, if moderation metadata should be added.
            * Need to store the the plugin args (who, when) in the page meta-data
            */
      -    function lock_add(&$request, &$page, &$action_page) {
      +    function lock_add(&$request, &$page, &$action_page)
      +    {
               $status = $this->getSiteStatus($request, $action_page);
               if (is_array($status)) {
                   if (empty($status['emails'])) {
      -                    // We really should present such warnings prominently.
      +                // We really should present such warnings prominently.
                       trigger_error(_("ModeratedPage: No emails for the moderators defined"),
      -                              E_USER_WARNING);
      +                    E_USER_WARNING);
                       return false;
                   }
                   $page->set('moderation', array('status' => $status));
                   return $this->notice(
      -                       fmt("ModeratedPage status update: '%s' is now a ModeratedPage.\n  Moderators: '%s'\n  require_access: '%s'",
      -                       $page->getName(), join(',', $status['moderators']), $status['require_access']));
      -        }
      -        else { // error
      +                fmt("ModeratedPage status update: '%s' is now a ModeratedPage.\n  Moderators: '%s'\n  require_access: '%s'",
      +                    $page->getName(), join(',', $status['moderators']), $status['require_access']));
      +        } else { // error
                   return $status;
               }
           }
       
      -    function notice($msg) {
      -            return HTML::div(array('class' => 'wiki-edithelp'), $msg);
      +    function notice($msg)
      +    {
      +        return HTML::div(array('class' => 'wiki-edithelp'), $msg);
           }
       
      -    function generateId() {
      +    function generateId()
      +    {
               better_srand();
               $s = "";
               for ($i = 1; $i <= 25; $i++) {
                   $r = function_exists('mt_rand') ? mt_rand(55, 90) : rand(55, 90);
      -            $s .= chr(($r < 65) ? ($r-17) : $r);
      +            $s .= chr(($r < 65) ? ($r - 17) : $r);
               }
      -        $len = $r = function_exists('mt_rand') ? mt_rand(15, 25) : rand(15,25);
      -        return substr(base64_encode($s),3,$len);
      +        $len = $r = function_exists('mt_rand') ? mt_rand(15, 25) : rand(15, 25);
      +        return substr(base64_encode($s), 3, $len);
           }
       
           /**
      @@ -207,62 +215,65 @@ extends WikiPlugin
            *   if ($page->get('moderation')) WikiPlugin_ModeratedPage::handler(...);
            * return false if not handled (pass through), true if handled and displayed.
            */
      -    function handler(&$request, &$page) {
      -            $action = $request->getArg('action');
      -            $moderated = $page->get('moderated');
      -            // cached version, need re-lock of each page to update moderators
      -            if (!empty($moderated['status']))
      -                $status = $moderated['status'];
      -            else {
      +    function handler(&$request, &$page)
      +    {
      +        $action = $request->getArg('action');
      +        $moderated = $page->get('moderated');
      +        // cached version, need re-lock of each page to update moderators
      +        if (!empty($moderated['status']))
      +            $status = $moderated['status'];
      +        else {
                   $action_page = $request->getPage(_("ModeratedPage"));
                   $status = $this->getSiteStatus($request, $action_page);
                   $moderated['status'] = $status;
      -            }
      +        }
               if (empty($status['emails'])) {
                   trigger_error(_("ModeratedPage: No emails for the moderators defined"),
      -                          E_USER_WARNING);
      +                E_USER_WARNING);
                   return true;
               }
               // which action?
               if (!empty($status['require_access'])
      -            and !in_array(action2access($action), $status['require_access']))
      +            and !in_array(action2access($action), $status['require_access'])
      +        )
                   return false; // allow and fall through, not moderated
               if (!empty($status['require_level'])
      -            and $request->_user->_level >= $status['require_level'])
      +            and $request->_user->_level >= $status['require_level']
      +        )
                   return false; // allow and fall through, not moderated
               // else all post actions are moderated by default
      -            if (1) /* or in_array($action, array('edit','remove','rename')*/ {
      -                $id = $this->generateId();
      -                while (!empty($moderated['data'][$id])) $id = $this->generateId(); // avoid duplicates
      -                $moderated['id'] = $id;                 // overwrite current id
      -                $tempuser = $request->_user;
      +        if (1) /* or in_array($action, array('edit','remove','rename')*/ {
      +            $id = $this->generateId();
      +            while (!empty($moderated['data'][$id])) $id = $this->generateId(); // avoid duplicates
      +            $moderated['id'] = $id; // overwrite current id
      +            $tempuser = $request->_user;
                   if (isset($tempuser->_HomePagehandle))
                       unset($tempuser->_HomePagehandle);
      -                $moderated['data'][$id] = array(         // add current request
      -                                                'timestamp' => time(),
      -                                                      'userid' => $request->_user->getId(),
      -                                            'args'   => $request->getArgs(),
      -                                            'user'   => serialize( $tempuser ),
      -                                            );
      +            $moderated['data'][$id] = array( // add current request
      +                'timestamp' => time(),
      +                'userid' => $request->_user->getId(),
      +                'args' => $request->getArgs(),
      +                'user' => serialize($tempuser),
      +            );
                   $this->_tokens['CONTENT'] =
                       HTML::div(array('class' => 'wikitext'),
      -                          fmt("%s: action forwarded to moderator %s",
      -                              $action,
      -                              join(", ", $status['moderators'])
      -                              ));
      +                    fmt("%s: action forwarded to moderator %s",
      +                        $action,
      +                        join(", ", $status['moderators'])
      +                    ));
                   // Send email
                   require_once 'lib/MailNotify.php';
                   $pagename = $page->getName();
                   $mailer = new MailNotify($pagename);
      -            $subject = "[".WIKI_NAME.'] '.$action._(": ")._("ModeratedPage").' '.$pagename;
      -            $content =         "You are approved as Moderator of the ".WIKI_NAME. " wiki.\n".
      -                     "Someone wanted to edit a moderated page, which you have to approve or reject.\n\n".
      -                     $action._(": ")._("ModeratedPage").' '.$pagename."\n"
      -                     //. serialize($moderated['data'][$id])
      -                     ."\n<".WikiURL($pagename, array('action' => _("ModeratedPage"),
      -                                                     'id' => $id, 'pass' => 'approve'), 1).">"
      -                     ."\n<".WikiURL($pagename, array('action' => _("ModeratedPage"),
      -                                                     'id' => $id, 'pass' => 'reject'), 1).">\n";
      +            $subject = "[" . WIKI_NAME . '] ' . $action . _(": ") . _("ModeratedPage") . ' ' . $pagename;
      +            $content = "You are approved as Moderator of the " . WIKI_NAME . " wiki.\n" .
      +                "Someone wanted to edit a moderated page, which you have to approve or reject.\n\n" .
      +                $action . _(": ") . _("ModeratedPage") . ' ' . $pagename . "\n"
      +                //. serialize($moderated['data'][$id])
      +                . "\n<" . WikiURL($pagename, array('action' => _("ModeratedPage"),
      +                'id' => $id, 'pass' => 'approve'), 1) . ">"
      +                . "\n<" . WikiURL($pagename, array('action' => _("ModeratedPage"),
      +                'id' => $id, 'pass' => 'reject'), 1) . ">\n";
                   $mailer->emails = $mailer->userids = $status['emails'];
                   $mailer->from = $request->_user->_userid;
                   if ($mailer->sendMail($subject, $content, "Moderation notice")) {
      @@ -271,12 +282,12 @@ extends WikiPlugin
                   } else {
                       //DELETEME!
                       $page->set('moderated', $moderated);
      -                    //FIXME: This msg gets lost on the edit redirect
      +                //FIXME: This msg gets lost on the edit redirect
                       trigger_error(_("ModeratedPage Notification Error: Couldn't send email"),
      -                              E_USER_ERROR);
      +                    E_USER_ERROR);
                       return true;
                   }
      -            }
      +        }
               return false;
           }
       
      @@ -286,7 +297,8 @@ extends WikiPlugin
            * with the left-over stored request.
            * Better we display a post form for verification.
            */
      -    function approve(&$request, $args, &$moderation) {
      +    function approve(&$request, $args, &$moderation)
      +    {
               if ($request->isPost()) {
                   // this is unsafe because we dont know if it will succeed. but we tried.
                   $this->cleanup_and_notify($request, $args, $moderation);
      @@ -301,11 +313,9 @@ extends WikiPlugin
                   $method = "action_$action";
                   if (method_exists($request, $method)) {
                       $request->{$method}();
      -            }
      -            elseif ($page = $this->findActionPage($action)) {
      +            } elseif ($page = $this->findActionPage($action)) {
                       $this->actionpage($page);
      -            }
      -            else {
      +            } else {
                       $this->finish(fmt("%s: Bad action", $action));
                   }
                   // now we are gone and nobody brings us back here.
      @@ -321,7 +331,8 @@ extends WikiPlugin
           /**
            * Handle admin-side moderation resolve.
            */
      -    function reject(&$request, $args, &$moderation) {
      +    function reject(&$request, $args, &$moderation)
      +    {
               // check id, delete action
               if ($request->isPost()) {
                   // clean up and notify the requestor. Mabye: store and revert to have a diff later on?
      @@ -331,10 +342,11 @@ extends WikiPlugin
               }
           }
       
      -    function cleanup_and_notify (&$request, $args, &$moderation) {
      +    function cleanup_and_notify(&$request, $args, &$moderation)
      +    {
               $pagename = $moderation['args']['pagename'];
               $page = $request->_dbi->getPage($pagename);
      -        $pass = $args['pass'];     // accept or reject
      +        $pass = $args['pass']; // accept or reject
               $reason = $args['reason']; // summary why
               $user = $moderation['args']['user'];
               $action = $moderation['args']['action'];
      @@ -349,27 +361,28 @@ extends WikiPlugin
                   $status = $this->getSiteStatus($request, $action_page);
                   require_once 'lib/MailNotify.php';
                   $mailer = new MailNotify($pagename);
      -            $subject = "[".WIKI_NAME."] $pass $action "._("ModeratedPage")._(": ").$pagename;
      +            $subject = "[" . WIKI_NAME . "] $pass $action " . _("ModeratedPage") . _(": ") . $pagename;
                   $mailer->from = $request->_user->UserFrom();
                   $content = sprintf(_("%s approved your wiki action from %s"),
      -                                 $mailer->from,CTime($moderation['timestamp']))
      -                ."\n\n"
      -                ."Decision: ".$pass
      -                ."Reason: ".$reason
      -                ."\n<".WikiURL($pagename).">\n";
      +                $mailer->from, CTime($moderation['timestamp']))
      +                . "\n\n"
      +                . "Decision: " . $pass
      +                . "Reason: " . $reason
      +                . "\n<" . WikiURL($pagename) . ">\n";
                   $mailer->emails = $mailer->userids = $email;
                   $mailer->sendMail($subject, $content, "Approval notice");
               }
           }
       
      -    function _approval_form(&$request, $args, $moderation, $pass='approve') {
      +    function _approval_form(&$request, $args, $moderation, $pass = 'approve')
      +    {
               $header = HTML::h3(_("Please approve or reject this request:"));
       
               $loader = new WikiPluginLoader();
               $BackendInfo = $loader->getPlugin("_BackendInfo");
               $table = HTML::table(array('border' => 1,
      -                                     'cellpadding' => 2,
      -                                     'cellspacing' => 0));
      +            'cellpadding' => 2,
      +            'cellspacing' => 0));
               $content = $table;
               $diff = '';
               if ($moderation['args']['action'] == 'edit') {
      @@ -380,49 +393,50 @@ extends WikiPlugin
                   $new_content = $moderation['args']['edit']['content'];
                   include_once 'lib/difflib.php';
                   $diff2 = new Diff($curr_content, $new_content);
      -            $fmt = new UnifiedDiffFormatter(/*$context_lines*/);
      -            $diff  = $pagename . " Current Version " .
      +            $fmt = new UnifiedDiffFormatter( /*$context_lines*/);
      +            $diff = $pagename . " Current Version " .
                       Iso8601DateTime($p->get('mtime')) . "\n";
                   $diff .= $pagename . " Edited Version " .
                       Iso8601DateTime($moderation['timestamp']) . "\n";
                   $diff .= $fmt->format($diff2);
               }
               $content->pushContent($BackendInfo->_showhash("Request",
      -                        array('User'      => $moderation['userid'],
      -                              'When'      => CTime($moderation['timestamp']),
      -                              'Pagename'  => $pagename,
      -                              'Action'    => $moderation['args']['action'],
      -                              'Diff'      => HTML::pre($diff))));
      +            array('User' => $moderation['userid'],
      +                'When' => CTime($moderation['timestamp']),
      +                'Pagename' => $pagename,
      +                'Action' => $moderation['args']['action'],
      +                'Diff' => HTML::pre($diff))));
               $content_dbg = $table;
      -        $myargs  = $args;
      +        $myargs = $args;
               $BackendInfo->_fixupData($myargs);
               $content_dbg->pushContent($BackendInfo->_showhash("raw request args", $myargs));
               $BackendInfo->_fixupData($moderation);
               $content_dbg->pushContent($BackendInfo->_showhash("raw moderation data", $moderation));
               $reason = HTML::div(_("Reason: "), HTML::textarea(array('name' => 'reason')));
               $approve = Button('submit:ModeratedPage[approve]', _("Approve"),
      -                          $pass == 'approve' ? 'wikiadmin' : 'button');
      -        $reject  = Button('submit:ModeratedPage[reject]', _("Reject"),
      -                          $pass == 'reject' ? 'wikiadmin' : 'button');
      +            $pass == 'approve' ? 'wikiadmin' : 'button');
      +        $reject = Button('submit:ModeratedPage[reject]', _("Reject"),
      +            $pass == 'reject' ? 'wikiadmin' : 'button');
               $args['action'] = _("ModeratedPage");
               return HTML::form(array('action' => $request->getPostURL(),
      -                                'method' => 'post'),
      -                          $header,
      -                          $content, HTML::p(""), $content_dbg,
      -                          $reason,
      -                          ENABLE_PAGEPERM
      -                            ? ''
      -                            : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN)),
      -                          HiddenInputs($args),
      -                          $pass == 'approve' ? HTML::p($approve, $reject)
      -                                               : HTML::p($reject, $approve));
      +                'method' => 'post'),
      +            $header,
      +            $content, HTML::p(""), $content_dbg,
      +            $reason,
      +            ENABLE_PAGEPERM
      +                ? ''
      +                : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN)),
      +            HiddenInputs($args),
      +            $pass == 'approve' ? HTML::p($approve, $reject)
      +                : HTML::p($reject, $approve));
           }
       
           /**
            * Get the side-wide ModeratedPage status, reading the action-page args.
            * Who are the moderators? What actions should be moderated?
            */
      -    function getSiteStatus(&$request, &$action_page) {
      +    function getSiteStatus(&$request, &$action_page)
      +    {
               $loader = new WikiPluginLoader();
               $rev = $action_page->getCurrentRevision();
               $content = $rev->getPackedContent();
      @@ -431,18 +445,20 @@ extends WikiPlugin
                   $plugin =& $parsed[1];
                   if ($plugin->getName() != _("ModeratedPage"))
                       return $this->error(sprintf(_("<> not found in first line of %s"),
      -                                            $action_page->getName()));
      +                    $action_page->getName()));
                   if (!$action_page->get('locked'))
                       return $this->error(sprintf(_("%s is not locked!"),
      -                                            $action_page->getName()));
      +                    $action_page->getName()));
                   return $plugin->resolve_argstr($request, $parsed[2]);
               } else {
                   return $this->error(sprintf(_("<> not found in first line of %s"),
      -                                        $action_page->getName()));
      +                $action_page->getName()));
               }
           }
       
      -};
      +}
      +
      +;
       
       // Local Variables:
       // mode: php
      diff --git a/lib/plugin/MostPopular.php b/lib/plugin/MostPopular.php
      index ad740ab80..cf4e1011a 100644
      --- a/lib/plugin/MostPopular.php
      +++ b/lib/plugin/MostPopular.php
      @@ -24,28 +24,31 @@
       require_once 'lib/PageList.php';
       
       class WikiPlugin_MostPopular
      -extends WikiPlugin
      +    extends WikiPlugin
       {
      -    function getName () {
      +    function getName()
      +    {
               return _("MostPopular");
           }
       
      -    function getDescription () {
      +    function getDescription()
      +    {
               return _("List the most popular pages.");
           }
       
      -    function getDefaultArguments() {
      +    function getDefaultArguments()
      +    {
               return array_merge
      -            (
      -             PageList::supportedArgs(),
      -             array('pagename' => '[pagename]', // hackish
      -                   //'exclude'  => '',
      -                   'limit'    => 20, // limit <0 returns least popular pages
      -                   'noheader' => 0,
      -                   'sortby'   => '-hits',
      -                   'info'     => false,
      -                   //'paging'   => 'auto'
      -                   ));
      +        (
      +            PageList::supportedArgs(),
      +            array('pagename' => '[pagename]', // hackish
      +                //'exclude'  => '',
      +                'limit' => 20, // limit <0 returns least popular pages
      +                'noheader' => 0,
      +                'sortby' => '-hits',
      +                'info' => false,
      +                //'paging'   => 'auto'
      +            ));
           }
       
           // info arg allows multiple columns
      @@ -53,18 +56,19 @@ extends WikiPlugin
           // exclude arg allows multiple pagenames exclude=HomePage,RecentChanges
           // sortby: only pagename or hits. mtime not!
       
      -    function run($dbi, $argstr, &$request, $basepage) {
      -            $args = $this->getArgs($argstr, $request);
      +    function run($dbi, $argstr, &$request, $basepage)
      +    {
      +        $args = $this->getArgs($argstr, $request);
               extract($args);
      -        if (strstr($sortby,'mtime')) {
      +        if (strstr($sortby, 'mtime')) {
                   trigger_error(_("sortby=mtime not supported with MostPopular"),
      -                          E_USER_WARNING);
      +                E_USER_WARNING);
                   $sortby = '';
               }
               $columns = $info ? explode(",", $info) : array();
               array_unshift($columns, 'hits');
       
      -        if (! $request->getArg('count')) {
      +        if (!$request->getArg('count')) {
                   //$args['count'] = $dbi->numPages(false,$exclude);
                   $allpages = $dbi->mostPopular(0, $sortby);
                   $args['count'] = $allpages->count();
      @@ -84,7 +88,7 @@ extends WikiPlugin
               }
               $pages->free();
       
      -        if (! $noheader) {
      +        if (!$noheader) {
                   if ($limit > 0) {
                       $pagelist->setCaption(fmt("The %d most popular pages of this wiki:", $limit));
                   } elseif ($limit < 0) {
      @@ -96,7 +100,9 @@ extends WikiPlugin
       
               return $pagelist;
           }
      -};
      +}
      +
      +;
       
       // Local Variables:
       // mode: php
      diff --git a/lib/plugin/NewPagesPerUser.php b/lib/plugin/NewPagesPerUser.php
      index eebfbd6e8..4f6092df1 100644
      --- a/lib/plugin/NewPagesPerUser.php
      +++ b/lib/plugin/NewPagesPerUser.php
      @@ -29,41 +29,45 @@
        */
       
       class WikiPlugin_NewPagesPerUser
      -extends WikiPlugin
      +    extends WikiPlugin
       {
      -    function getName () {
      +    function getName()
      +    {
               return _("NewPagesPerUser");
           }
       
      -    function getDescription () {
      +    function getDescription()
      +    {
               return _("List all new pages per month per user");
           }
       
      -    function getDefaultArguments() {
      -        return array('userid'   => '',
      -                     'month'    => 0,
      -                     'since'    => 0,
      -                     'until'    => 0,
      -                     'comments' => 0,
      -                     'links'    => 1,
      -                     'debug'    => 0,
      -                   );
      +    function getDefaultArguments()
      +    {
      +        return array('userid' => '',
      +            'month' => 0,
      +            'since' => 0,
      +            'until' => 0,
      +            'comments' => 0,
      +            'links' => 1,
      +            'debug' => 0,
      +        );
           }
       
      -    function run($dbi, $argstr, &$request, $basepage) {
      -            global $WikiTheme;
      -            $args = $this->getArgs($argstr, $request);
      +    function run($dbi, $argstr, &$request, $basepage)
      +    {
      +        global $WikiTheme;
      +        $args = $this->getArgs($argstr, $request);
               extract($args);
               if ($since)
                   $since = strtotime($since);
               if ($month) {
                   $since = strtotime($month);
      -            $since = mktime(0,0,0,date("m",$since),1,date("Y",$since));
      -            $until = mktime(23,59,59,date("m",$since)+1,0,date("Y",$since));
      +            $since = mktime(0, 0, 0, date("m", $since), 1, date("Y", $since));
      +            $until = mktime(23, 59, 59, date("m", $since) + 1, 0, date("Y", $since));
               } else
                   $until = 0;
       
      -        $iter = $dbi->getAllPages(false,'-mtime');
      +        $iter = $dbi->getAllPages(false, '-mtime');
               $pages = array();
       
               while ($page = $iter->next()) {
      @@ -74,63 +78,65 @@ extends WikiPlugin
                   //$author = $rev->get('author_id');
                   $author = $page->getOwner();
                   if (defined('DEBUG') && DEBUG && $debug) {
      -                echo "$pagename, ",strftime("%Y-%m-%d %h:%m:%s", $date),", $author
      \n"; + echo "$pagename, ", strftime("%Y-%m-%d %h:%m:%s", $date), ", $author
      \n"; } - if ($userid and (!preg_match("/".$userid."/", $author))) continue; + if ($userid and (!preg_match("/" . $userid . "/", $author))) continue; if ($since and $date < $since) continue; if ($until and $date > $until) continue; if (!$comments and preg_match("/\/Comment/", $pagename)) continue; $monthnum = strftime("%Y%m", $date); if (!isset($pages[$monthnum])) $pages[$monthnum] = array('author' => array(), - 'month' => strftime("%B, %Y", $date)); + 'month' => strftime("%B, %Y", $date)); if (!isset($pages[$monthnum]['author'][$author])) $pages[$monthnum]['author'][$author] = array('count' => 0, - 'pages' => array()); + 'pages' => array()); $pages[$monthnum]['author'][$author]['count']++; $pages[$monthnum]['author'][$author]['pages'][] = $pagename; } $iter->free(); - $html = HTML::table(HTML::col(array('span' => 2,'align'=> 'left'))); + $html = HTML::table(HTML::col(array('span' => 2, 'align' => 'left'))); $nbsp = HTML::raw(' '); krsort($pages); foreach ($pages as $monthname => $parr) { - $html->pushContent(HTML::tr(HTML::td(array('colspan' => 2), - HTML::strong($parr['month'])))); - uasort($parr['author'], 'cmp_by_count'); - foreach ($parr['author'] as $user => $authorarr) { - $count = $authorarr['count']; - $id = preg_replace("/ /","_",'pages-'.$monthname.'-'.$user); - $html->pushContent - (HTML::tr(HTML::td($nbsp,$nbsp, - HTML::img(array('id' => "$id-img", - 'src' => $WikiTheme->_findData("images/folderArrowClosed.png"), - 'onclick'=> "showHideFolder('$id')", - 'alt' => _("Click to hide/show"), - 'title' => _("Click to hide/show"))), - $nbsp, - $user), - HTML::td($count) - )); - if ($links) { - $pagelist = HTML(); - foreach ($authorarr['pages'] as $p) - $pagelist->pushContent(WikiLink($p),', '); - } else { - $pagelist = join(', ',$authorarr['pages']); - } - $html->pushContent - (HTML::tr(array('id' => $id.'-body', - 'style'=>'display:none; background-color: #eee;'), - HTML::td(array('colspan' => 2, - 'style' => 'font-size:smaller'), - $pagelist - ))); - } + $html->pushContent(HTML::tr(HTML::td(array('colspan' => 2), + HTML::strong($parr['month'])))); + uasort($parr['author'], 'cmp_by_count'); + foreach ($parr['author'] as $user => $authorarr) { + $count = $authorarr['count']; + $id = preg_replace("/ /", "_", 'pages-' . $monthname . '-' . $user); + $html->pushContent + (HTML::tr(HTML::td($nbsp, $nbsp, + HTML::img(array('id' => "$id-img", + 'src' => $WikiTheme->_findData("images/folderArrowClosed.png"), + 'onclick' => "showHideFolder('$id')", + 'alt' => _("Click to hide/show"), + 'title' => _("Click to hide/show"))), + $nbsp, + $user), + HTML::td($count) + )); + if ($links) { + $pagelist = HTML(); + foreach ($authorarr['pages'] as $p) + $pagelist->pushContent(WikiLink($p), ', '); + } else { + $pagelist = join(', ', $authorarr['pages']); + } + $html->pushContent + (HTML::tr(array('id' => $id . '-body', + 'style' => 'display:none; background-color: #eee;'), + HTML::td(array('colspan' => 2, + 'style' => 'font-size:smaller'), + $pagelist + ))); + } } return $html; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/NoCache.php b/lib/plugin/NoCache.php index 5e6d4dab0..92dc2b2f9 100644 --- a/lib/plugin/NoCache.php +++ b/lib/plugin/NoCache.php @@ -34,28 +34,34 @@ * */ class WikiPlugin_NoCache -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("NoCache"); } - function getDescription() { + function getDescription() + { return _("Don't cache this page."); } - function getDefaultArguments() { - return array( 'nocache' => 1 ); + function getDefaultArguments() + { + return array('nocache' => 1); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); // works regardless of WIKIDB_NOCACHE_MARKUP // if WIKIDB_NOCACHE_MARKUP is false it doesn't hurt $request->setArg('nocache', $args['nocache']); return HTML::raw(''); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/OldStyleTable.php b/lib/plugin/OldStyleTable.php index 44a6abe3e..57424086a 100644 --- a/lib/plugin/OldStyleTable.php +++ b/lib/plugin/OldStyleTable.php @@ -44,36 +44,41 @@ */ class WikiPlugin_OldStyleTable -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("OldStyleTable"); } - function getDescription() { - return _("Layout tables using the old markup style."); + function getDescription() + { + return _("Layout tables using the old markup style."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array( - 'caption' => '', - 'cellpadding' => '1', - 'cellspacing' => '1', - 'border' => '1', - 'summary' => '', - ); + 'caption' => '', + 'cellpadding' => '1', + 'cellspacing' => '1', + 'border' => '1', + 'summary' => '', + ); } - function handle_plugin_args_cruft($argstr, $args) { + function handle_plugin_args_cruft($argstr, $args) + { return; } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { include_once 'lib/InlineParser.php'; $args = $this->getArgs($argstr, $request); $default = $this->getDefaultArguments(); - foreach (array('cellpadding','cellspacing','border') as $arg) { + foreach (array('cellpadding', 'cellspacing', 'border') as $arg) { if (!is_numeric($args[$arg])) { $args[$arg] = $default[$arg]; } @@ -83,7 +88,7 @@ extends WikiPlugin $default_args = array_keys($default); foreach ($default_args as $arg) { if ($args[$arg] == '' and $default[$arg] == '') - continue; // ignore '' arguments + continue; // ignore '' arguments if ($arg == 'caption') $caption = $args[$arg]; else @@ -97,13 +102,13 @@ extends WikiPlugin foreach ($lines as $line) { if (!$line) continue; - if (strstr($line,"=")) { - $tmp = explode("=",$line); - if (in_array(trim($tmp[0]),$default_args)) + if (strstr($line, "=")) { + $tmp = explode("=", $line); + if (in_array(trim($tmp[0]), $default_args)) continue; } if ($line[0] != '|') { - // bogus error if argument + // bogus error if argument trigger_error(sprintf(_("Line %s does not begin with a '|'."), $line), E_USER_WARNING); } else { $table->pushContent($this->_parse_row($line, $basepage)); @@ -113,12 +118,13 @@ extends WikiPlugin return $table; } - function _parse_row ($line, $basepage) { + function _parse_row($line, $basepage) + { $brkt_link = "\\[ .*? [^]\s] .*? \\]"; - $cell_content = "(?: [^[] | ".ESCAPE_CHAR."\\[ | $brkt_link )*?"; + $cell_content = "(?: [^[] | " . ESCAPE_CHAR . "\\[ | $brkt_link )*?"; preg_match_all("/(\\|+) (v*) ([<>^]?) \s* ($cell_content) \s* (?=\\||\$)/x", - $line, $matches, PREG_SET_ORDER); + $line, $matches, PREG_SET_ORDER); $row = HTML::tr(); @@ -141,11 +147,13 @@ extends WikiPlugin $content = TransformInline($m[4], 2.0, $basepage); $row->pushContent(HTML::td($attr, HTML::raw(' '), - $content, HTML::raw(' '))); + $content, HTML::raw(' '))); } return $row; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/OrphanedPages.php b/lib/plugin/OrphanedPages.php index cb878a108..1761eab7a 100644 --- a/lib/plugin/OrphanedPages.php +++ b/lib/plugin/OrphanedPages.php @@ -28,31 +28,36 @@ require_once 'lib/PageList.php'; class WikiPlugin_OrphanedPages -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("OrphanedPages"); } - function getDescription () { + function getDescription() + { return _("List pages which are not linked to by any other page."); } - function getDefaultArguments() { - return array('noheader' => false, - 'include_empty' => false, - 'exclude' => '', - 'info' => '', - 'sortby' => false, - 'limit' => 0, - 'paging' => 'auto', - ); + function getDefaultArguments() + { + return array('noheader' => false, + 'include_empty' => false, + 'exclude' => '', + 'info' => '', + 'sortby' => false, + 'limit' => 0, + 'paging' => 'auto', + ); } + // info arg allows multiple columns // info=mtime,hits,summary,version,author,locked,minor,markup or all // exclude arg allows multiple pagenames exclude=HomePage,RecentChanges - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); extract($args); @@ -66,9 +71,10 @@ extends WikiPlugin // Test for absence of backlinks. If a page is linked to // only by itself, it is still an orphan $parent = $links_iter->next(); - if (!$parent // page has no parents + if (!$parent // page has no parents or (($parent->getName() == $page->getName()) - and !$links_iter->next())) // or page has only itself as a parent + and !$links_iter->next()) + ) // or page has only itself as a parent { $pages[] = $page; } @@ -80,17 +86,19 @@ extends WikiPlugin // deleted pages show up as version 0. if ($include_empty) $pagelist->_addColumn('version'); - list($offset,$pagesize) = $pagelist->limit($args['limit']); + list($offset, $pagesize) = $pagelist->limit($args['limit']); if (!$pagesize) $pagelist->addPageList($pages); else { - for ($i=$offset; $i < $offset + $pagesize - 1; $i++) { - if ($i >= $args['count']) break; + for ($i = $offset; $i < $offset + $pagesize - 1; $i++) { + if ($i >= $args['count']) break; $pagelist->addPage($pages[$i]); } } return $pagelist; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/PageDump.php b/lib/plugin/PageDump.php index 41cedd983..d84c6226a 100644 --- a/lib/plugin/PageDump.php +++ b/lib/plugin/PageDump.php @@ -48,42 +48,47 @@ */ class WikiPlugin_PageDump -extends WikiPlugin + extends WikiPlugin { var $MessageId; - function getName() { + function getName() + { return _("PageDump"); } - function getDescription() { + + function getDescription() + { return _("View a single page dump online."); } - function getDefaultArguments() { - return array('s' => false, - 'page' => '[pagename]', - //'encoding' => 'binary', // 'binary', 'quoted-printable' - 'format' => false, // 'normal', 'forsvn', 'forcvs', 'backup' - // display within WikiPage or give a downloadable - // raw pgsrc? - 'download' => false); + function getDefaultArguments() + { + return array('s' => false, + 'page' => '[pagename]', + //'encoding' => 'binary', // 'binary', 'quoted-printable' + 'format' => false, // 'normal', 'forsvn', 'forcvs', 'backup' + // display within WikiPage or give a downloadable + // raw pgsrc? + 'download' => false); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { extract($this->getArgs($argstr, $request)); // allow plugin-form if (!empty($s)) $page = $s; if (!$page) return ''; - if (! $dbi->isWikiPage($page) ) + if (!$dbi->isWikiPage($page)) return fmt("Page %s not found.", - WikiLink($page, 'unknown')); + WikiLink($page, 'unknown')); // Check if user is allowed to get the Page. - if (!mayAccessPage ('view', $page)) { - return $this->error(sprintf(_("Illegal access to page %s: no read access"), - $page)); + if (!mayAccessPage('view', $page)) { + return $this->error(sprintf(_("Illegal access to page %s: no read access"), + $page)); } $p = $dbi->getPage($page); @@ -111,11 +116,11 @@ extends WikiPlugin // TODO: we need a way to hook into the generated headers, to override // Content-Type, Set-Cookie, Cache-control, ... $request->discardOutput(); // Hijack the http request from PhpWiki. - ob_end_clean(); // clean up after hijacking $request + ob_end_clean(); // clean up after hijacking $request //while (@ob_end_flush()); //debugging $filename = FilenameForPage($page); Header("Content-disposition: attachment; filename=\"" - . $filename . "\""); + . $filename . "\""); // Read charset from generated page itself. // Inconsequential at the moment, since loadsave.php // always generates headers. @@ -125,8 +130,8 @@ extends WikiPlugin // then here and the mimified string $mailified also has it! // This one is correct and overwrites the others. Header("Content-Type: application/octet-stream; name=\"" - . $filename . "\"; charset=\"" . $charset - . "\""); + . $filename . "\"; charset=\"" . $charset + . "\""); $request->checkValidators(); // let $request provide last modified & etag Header("Content-Id: <" . $this->MessageId . ">"); @@ -142,26 +147,26 @@ extends WikiPlugin // text if it is too long--unless quoted-printable (TODO). $mailified = wordwrap($mailified, 70); - $dlsvn = Button(array(//'page' => $page, - 'action' => $this->getName(), - 'format'=> 'forsvn', - 'download'=> true), - _("Download for Subversion"), - $page); - $dl = Button(array(//'page' => $page, - 'action' => $this->getName(), - 'download'=> true), - _("Download for backup"), - $page); - $dlall = Button(array(//'page' => $page, - 'action' => $this->getName(), - 'format'=> 'backup', - 'download'=> true), - _("Download all revisions for backup"), - $page); + $dlsvn = Button(array( //'page' => $page, + 'action' => $this->getName(), + 'format' => 'forsvn', + 'download' => true), + _("Download for Subversion"), + $page); + $dl = Button(array( //'page' => $page, + 'action' => $this->getName(), + 'download' => true), + _("Download for backup"), + $page); + $dlall = Button(array( //'page' => $page, + 'action' => $this->getName(), + 'format' => 'backup', + 'download' => true), + _("Download all revisions for backup"), + $page); $h2 = HTML::h2(fmt("Preview: Page dump of %s", - WikiLink($page, 'auto'))); + WikiLink($page, 'auto'))); global $WikiTheme; if (!$Sep = $WikiTheme->getButtonSeparator()) $Sep = " "; @@ -169,67 +174,67 @@ extends WikiPlugin if ($format == 'forsvn') { $desc = _("(formatted for PhpWiki developers as pgsrc template, not for backing up)"); $altpreviewbuttons = HTML( - Button(array('action' => $this->getName()), - _("Preview as normal format"), - $page), - $Sep, - Button(array( - 'action' => $this->getName(), - 'format'=> 'backup'), - _("Preview as backup format"), - $page)); - } - elseif ($format == 'backup') { + Button(array('action' => $this->getName()), + _("Preview as normal format"), + $page), + $Sep, + Button(array( + 'action' => $this->getName(), + 'format' => 'backup'), + _("Preview as backup format"), + $page)); + } elseif ($format == 'backup') { $desc = _("(formatted for backing up: all revisions)"); // all revisions $altpreviewbuttons = HTML( - Button(array('action' => $this->getName(), - 'format'=> 'forsvn'), - _("Preview as developer format"), - $page), - $Sep, - Button(array( - 'action' => $this->getName(), - 'format'=> ''), - _("Preview as normal format"), - $page)); + Button(array('action' => $this->getName(), + 'format' => 'forsvn'), + _("Preview as developer format"), + $page), + $Sep, + Button(array( + 'action' => $this->getName(), + 'format' => ''), + _("Preview as normal format"), + $page)); } else { $desc = _("(normal formatting: latest revision only)"); $altpreviewbuttons = HTML( - Button(array('action' => $this->getName(), - 'format'=> 'forsvn'), - _("Preview as developer format"), - $page), - $Sep, - Button(array( - 'action' => $this->getName(), - 'format'=> 'backup'), - _("Preview as backup format"), - $page)); + Button(array('action' => $this->getName(), + 'format' => 'forsvn'), + _("Preview as developer format"), + $page), + $Sep, + Button(array( + 'action' => $this->getName(), + 'format' => 'backup'), + _("Preview as backup format"), + $page)); } $warning = HTML( -_("Please use one of the downloadable versions rather than copying and pasting from the above preview.") -. " " . -_("The wordwrap of the preview doesn't take nested markup or list indentation into consideration!") -. " ", -HTML::em( -_("PhpWiki developers should manually inspect the downloaded file for nested markup before rewrapping with emacs and checking into Subversion.") - ) - ); + _("Please use one of the downloadable versions rather than copying and pasting from the above preview.") + . " " . + _("The wordwrap of the preview doesn't take nested markup or list indentation into consideration!") + . " ", + HTML::em( + _("PhpWiki developers should manually inspect the downloaded file for nested markup before rewrapping with emacs and checking into Subversion.") + ) + ); return HTML($h2, HTML::em($desc), - HTML::pre($mailified), - $altpreviewbuttons, - HTML::div(array('class' => 'error'), - HTML::strong(_("Warning:")), - " ", $warning), - $dl, $Sep, $dlall, $Sep, $dlsvn - ); + HTML::pre($mailified), + $altpreviewbuttons, + HTML::div(array('class' => 'error'), + HTML::strong(_("Warning:")), + " ", $warning), + $dl, $Sep, $dlall, $Sep, $dlsvn + ); } // function handle_plugin_args_cruft(&$argstr, &$args) { // } - function generateMessageId($mailified) { + function generateMessageId($mailified) + { $array = explode("\n", $mailified); // Extract lastmodifed from mailified document for Content-Id // and/or Message-Id header, NOT from DB (page could have been @@ -238,7 +243,7 @@ _("PhpWiki developers should manually inspect the downloaded file for nested mar $m1 = array_values($m1); //reset resulting keys unset($array); $m2 = preg_split("/(^\s+lastmodified\=)|(;)/", $m1[0], 2, - PREG_SPLIT_NO_EMPTY); + PREG_SPLIT_NO_EMPTY); // insert message id into actual message when appropriate, NOT // into http header should be part of fixup_headers, in the @@ -252,38 +257,40 @@ _("PhpWiki developers should manually inspect the downloaded file for nested mar $this->MessageId = implode('', explode('.', PHPWIKI_VERSION)) . "-" . $m2[0] . date("O") //. "-". rawurlencode(WIKI_NAME.":" . $request->getURLtoSelf()) - . "-". rawurlencode(WIKI_NAME.":" . $this->pagename) - . "@". rawurlencode(SERVER_NAME); + . "-" . rawurlencode(WIKI_NAME . ":" . $this->pagename) + . "@" . rawurlencode(SERVER_NAME); } - function fixup_headers(&$mailified) { + function fixup_headers(&$mailified) + { $return = explode("\n", $mailified); // Leave message intact for backing up, just add Message-Id header before transmitting. - $item_to_insert = "Message-Id: <" . $this->MessageId .">"; + $item_to_insert = "Message-Id: <" . $this->MessageId . ">"; $insert_into_key_position = 2; $returnval_ignored = array_splice($return, - $insert_into_key_position, - 0, $item_to_insert); + $insert_into_key_position, + 0, $item_to_insert); $mailified = implode("\n", array_values($return)); } - function fixup_headers_forsvn(&$mailified) { + function fixup_headers_forsvn(&$mailified) + { $array = explode("\n", $mailified); // Massage headers to prepare for developer checkin to Subversion. $item_to_insert = "X-Rcs-Id: \$Id\$"; $insert_into_key_position = 2; $returnval_ignored = array_splice($array, - $insert_into_key_position, - 0, $item_to_insert); + $insert_into_key_position, + 0, $item_to_insert); $item_to_insert = " pgsrc_version=\"2 \$Revision\$\";"; $insert_into_key_position = 5; $returnval_ignored = array_splice($array, - $insert_into_key_position, - 0, $item_to_insert); + $insert_into_key_position, + 0, $item_to_insert); /* Strip out all this junk: author=MeMe; @@ -293,23 +300,26 @@ _("PhpWiki developers should manually inspect the downloaded file for nested mar hits=146; */ $killme = array("author", "version", "lastmodified", - "author_id", "hits", "owner", "acl"); + "author_id", "hits", "owner", "acl"); // UltraNasty, fixme: foreach ($killme as $pattern) { $array = preg_replace("/^\s\s$pattern\=.*;/", - /*$replacement =*/"zzzjunk", $array); + /*$replacement =*/ + "zzzjunk", $array); } // remove deleted values from array - for ($i = 0; $i < count($array); $i++ ) { - if(trim($array[$i]) != "zzzjunk") { //nasty, fixme - //trigger_error("'$array[$i]'");//debugging + for ($i = 0; $i < count($array); $i++) { + if (trim($array[$i]) != "zzzjunk") { //nasty, fixme + //trigger_error("'$array[$i]'");//debugging $return[] = $array[$i]; } } $mailified = implode("\n", $return); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/PageGroup.php b/lib/plugin/PageGroup.php index 2cf9178fa..5a1a9dd52 100644 --- a/lib/plugin/PageGroup.php +++ b/lib/plugin/PageGroup.php @@ -39,39 +39,44 @@ * Updated to use new HTML(). It mostly works, but it's still a giant hackish mess. */ class WikiPlugin_PageGroup -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("PageGroup"); } - function getDescription() { - return sprintf(_("PageGroup for %s"),'[pagename]'); + function getDescription() + { + return sprintf(_("PageGroup for %s"), '[pagename]'); } - function getDefaultArguments() { + function getDefaultArguments() + { return array( - 'parent' => '', - 'rev' => false, - 'section' => _("Contents"), - 'label' => '', - 'loop' => false, - ); + 'parent' => '', + 'rev' => false, + 'section' => _("Contents"), + 'label' => '', + 'loop' => false, + ); } // Stolen from IncludePage.php - function extractGroupSection ($section, $content, $page) { + function extractGroupSection($section, $content, $page) + { $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/')); if (preg_match("/ ^(!{1,})\\s*$qsection" // section header - . " \\s*$\\n?" // possible blank lines - . " ( (?: ^.*\\n? )*? )" // some lines - . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF) - implode("\n", $content), - $match)) { + . " \\s*$\\n?" // possible blank lines + . " ( (?: ^.*\\n? )*? )" // some lines + . " (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF) + implode("\n", $content), + $match) + ) { $result = array(); //FIXME: return list of Wiki_Pagename objects foreach (explode("\n", $match[2]) as $line) { - $text = trim($line); + $text = trim($line); // Strip trailing blanks lines and ----
      s $text = preg_replace("/\\s*^-{4,}\\s*$/", "", $text); // Strip leading list chars: * or # @@ -84,22 +89,23 @@ extends WikiPlugin } return $result; } - return array(sprintf(_("<%s: no such section>"), $page ." ". $section)); + return array(sprintf(_("<%s: no such section>"), $page . " " . $section)); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); extract($args); if (empty($parent)) { return $this->error(sprintf(_("A required argument '%s' is missing."), 'parent')); } - $directions = array ('next' => _("Next"), - 'previous' => _("Previous"), - 'contents' => _("Contents"), - 'first' => _("First"), - 'last' => _("Last") - ); + $directions = array('next' => _("Next"), + 'previous' => _("Previous"), + 'contents' => _("Contents"), + 'first' => _("First"), + 'last' => _("Last") + ); global $WikiTheme; $sep = $WikiTheme->getButtonSeparator(); @@ -118,7 +124,7 @@ extends WikiPlugin $r = $p->getRevision($rev); if ((!$r) || ($r->hasDefaultContents())) { return $this->error(sprintf(_("%s: no such revision %d."), - $parent, $rev)); + $parent, $rev)); } } else { $r = $p->getCurrentRevision(); @@ -135,58 +141,58 @@ extends WikiPlugin $thispage = array_search($pagename, $c); - $go = array ('previous','next'); + $go = array('previous', 'next'); $links = HTML(); $links->pushcontent($label); $links->pushcontent(" [ "); // an experiment $lastindex = count($c) - 1; // array is 0-based, count is 1-based! - foreach ( $go as $go_item ) { + foreach ($go as $go_item) { //yuck this smells, needs optimization. if ($go_item == 'previous') { if ($loop) { if ($thispage == 0) { - $linkpage = $c[$lastindex]; + $linkpage = $c[$lastindex]; } else { - $linkpage = $c[$thispage - 1]; + $linkpage = $c[$thispage - 1]; } // mind the French : punctuation $text = fmt("%s: %s", $directions[$go_item], - $WikiTheme->makeLinkButton($linkpage)); + $WikiTheme->makeLinkButton($linkpage)); $links->pushcontent($text); $links->pushcontent($sep); // this works because - // there are only 2 go - // items, previous,next + // there are only 2 go + // items, previous,next } else { if ($thispage == 0) { // skip it } else { - $linkpage = $c[$thispage - 1]; + $linkpage = $c[$thispage - 1]; $text = fmt("%s: %s", $directions[$go_item], - $WikiTheme->makeLinkButton($linkpage)); + $WikiTheme->makeLinkButton($linkpage)); $links->pushcontent($text); $links->pushcontent($sep); //this works - //because there are - //only 2 go items, - //previous,next + //because there are + //only 2 go items, + //previous,next } } } elseif ($go_item == 'next') { if ($loop) { if ($thispage == $lastindex) { - $linkpage = $c[1]; + $linkpage = $c[1]; } else { - $linkpage = $c[$thispage + 1]; + $linkpage = $c[$thispage + 1]; } $text = fmt("%s: %s", $directions[$go_item], - $WikiTheme->makeLinkButton($linkpage)); + $WikiTheme->makeLinkButton($linkpage)); } else { if ($thispage == $lastindex) { // skip it } else { $linkpage = $c[$thispage + 1]; $text = fmt("%s: %s", $directions[$go_item], - $WikiTheme->makeLinkButton($linkpage)); + $WikiTheme->makeLinkButton($linkpage)); } } $links->pushcontent($text); @@ -195,7 +201,9 @@ extends WikiPlugin $links->pushcontent(" ] "); // an experiment return $links; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/PageHistory.php b/lib/plugin/PageHistory.php index 48b111029..754c28449 100644 --- a/lib/plugin/PageHistory.php +++ b/lib/plugin/PageHistory.php @@ -23,9 +23,10 @@ require_once 'lib/plugin/RecentChanges.php'; class _PageHistory_PageRevisionIter -extends WikiDB_PageRevisionIterator + extends WikiDB_PageRevisionIterator { - function _PageHistory_PageRevisionIter($rev_iter, $params) { + function _PageHistory_PageRevisionIter($rev_iter, $params) + { $this->_iter = $rev_iter; @@ -35,7 +36,7 @@ extends WikiDB_PageRevisionIterator $this->_since = $since; $this->_include_major = empty($exclude_major_revisions); - if (! $this->_include_major) + if (!$this->_include_major) $this->_include_minor = true; else $this->_include_minor = !empty($include_minor_revisions); @@ -46,7 +47,8 @@ extends WikiDB_PageRevisionIterator $this->_limit = $limit; } - function next() { + function next() + { if (!$this->_iter) return false; @@ -58,7 +60,7 @@ extends WikiDB_PageRevisionIterator $this->_limit--; } - while ( ($rev = $this->_iter->next()) ) { + while (($rev = $this->_iter->next())) { if (isset($this->_since) && $rev->get('mtime') < $this->_since) { $this->free(); return false; @@ -69,7 +71,8 @@ extends WikiDB_PageRevisionIterator return false; } - function free() { + function free() + { if ($this->_iter) $this->_iter->free(); $this->_iter = false; @@ -77,34 +80,39 @@ extends WikiDB_PageRevisionIterator } class _PageHistory_HtmlFormatter -extends _RecentChanges_HtmlFormatter + extends _RecentChanges_HtmlFormatter { - function include_versions_in_URLs() { + function include_versions_in_URLs() + { return true; } - function headline() { + function headline() + { return HTML(fmt("PageHistory for %s", - WikiLink($this->_args['page'])), - "\n", - $this->rss_icon(), - $this->rss2_icon(), - $this->atom_icon(), - $this->rdf_icon()); + WikiLink($this->_args['page'])), + "\n", + $this->rss_icon(), + $this->rss2_icon(), + $this->atom_icon(), + $this->rdf_icon()); } - function title() { - return "PageHistory:".$this->_args['page']; + function title() + { + return "PageHistory:" . $this->_args['page']; } - function empty_message () { + function empty_message() + { return _("No revisions found"); } - function description() { - $button = HTML::input(array('type' => 'submit', - 'value' => _("compare revisions"), - 'class' => 'wikiaction')); + function description() + { + $button = HTML::input(array('type' => 'submit', + 'value' => _("compare revisions"), + 'class' => 'wikiaction')); $js_desc = $no_js_desc = _RecentChanges_HtmlFormatter::description(); @@ -114,7 +122,8 @@ extends _RecentChanges_HtmlFormatter return IfJavaScript($js_desc, $no_js_desc); } - function format ($changes) { + function format($changes) + { $this->_itemcount = 0; $pagename = $this->_args['page']; @@ -123,25 +132,24 @@ extends _RecentChanges_HtmlFormatter $fmt->action = _("PageHistory"); $html[] = $fmt; - $html[] = HTML::input(array('type' => 'hidden', - 'name' => 'action', - 'value' => 'diff')); + $html[] = HTML::input(array('type' => 'hidden', + 'name' => 'action', + 'value' => 'diff')); if (USE_PATH_INFO) { $action = WikiURL($pagename); - } - else { + } else { $action = SCRIPT_NAME; - $html[] = HTML::input(array('type' => 'hidden', - 'name' => 'pagename', - 'value' => $pagename)); + $html[] = HTML::input(array('type' => 'hidden', + 'name' => 'pagename', + 'value' => $pagename)); } return HTML(HTML::form(array('method' => 'get', - 'action' => $action, - 'id' => 'diff-select'), - $html), - "\n", - JavaScript(' + 'action' => $action, + 'id' => 'diff-select'), + $html), + "\n", + JavaScript(' var diffCkBoxes = document.forms["diff-select"].elements["versions[]"]; function diffCkBox_onclick() { @@ -160,134 +168,147 @@ extends _RecentChanges_HtmlFormatter diffCkBoxes[i].onclick = diffCkBox_onclick;')); } - function diffLink ($rev) { - return HTML::input(array('type' => 'checkbox', - 'name' => 'versions[]', - 'value' => $rev->getVersion())); + function diffLink($rev) + { + return HTML::input(array('type' => 'checkbox', + 'name' => 'versions[]', + 'value' => $rev->getVersion())); } - function pageLink ($rev) { + function pageLink($rev) + { $text = fmt("Version %d", $rev->getVersion()); return _RecentChanges_HtmlFormatter::pageLink($rev, $text); } - function format_revision ($rev) { + function format_revision($rev) + { global $WikiTheme; $class = 'rc-' . $this->importance($rev); $time = $this->time($rev); if ($rev->get('is_minor_edit')) { $minor_flag = HTML(" ", - HTML::span(array('class' => 'pageinfo-minoredit'), - "(" . _("minor edit") . ")")); - } - else { + HTML::span(array('class' => 'pageinfo-minoredit'), + "(" . _("minor edit") . ")")); + } else { $time = HTML::span(array('class' => 'pageinfo-majoredit'), $time); $minor_flag = ''; } $line = HTML::li(array('class' => $class)); - if (isa($WikiTheme,'WikiTheme_MonoBook')) { + if (isa($WikiTheme, 'WikiTheme_MonoBook')) { $line->pushContent( - $this->diffLink($rev), ' ', - $this->pageLink($rev), ' ', - $time,' ',$this->date($rev), ' . . ', - $this->authorLink($rev),' ', - $this->authorContribs($rev),' ', - $this->summaryAsHTML($rev),' ', - $minor_flag); + $this->diffLink($rev), ' ', + $this->pageLink($rev), ' ', + $time, ' ', $this->date($rev), ' . . ', + $this->authorLink($rev), ' ', + $this->authorContribs($rev), ' ', + $this->summaryAsHTML($rev), ' ', + $minor_flag); } else { $line->pushContent( - $this->diffLink($rev), ' ', - $this->pageLink($rev), ' ', - $time, ' ', - $this->summaryAsHTML($rev), - ' ... ', - $this->authorLink($rev), - $minor_flag); + $this->diffLink($rev), ' ', + $this->pageLink($rev), ' ', + $time, ' ', + $this->summaryAsHTML($rev), + ' ... ', + $this->authorLink($rev), + $minor_flag); } return $line; } } class _PageHistory_RssFormatter -extends _RecentChanges_RssFormatter + extends _RecentChanges_RssFormatter { - function include_versions_in_URLs() { + function include_versions_in_URLs() + { return true; } - function image_properties () { + function image_properties() + { return false; } - function textinput_properties () { + function textinput_properties() + { return false; } - function channel_properties () { + function channel_properties() + { global $request; $rc_url = WikiURL($request->getArg('pagename'), false, 'absurl'); $title = sprintf(_("%s: %s"), - WIKI_NAME, - SplitPagename($this->_args['page'])); + WIKI_NAME, + SplitPagename($this->_args['page'])); - return array('title' => $title, - 'dc:description' => _("History of changes."), - 'link' => $rc_url, - 'dc:date' => Iso8601DateTime(time())); + return array('title' => $title, + 'dc:description' => _("History of changes."), + 'link' => $rc_url, + 'dc:date' => Iso8601DateTime(time())); } - function item_properties ($rev) { + function item_properties($rev) + { if (!($title = $this->summary($rev))) $title = sprintf(_("Version %d"), $rev->getVersion()); - return array( 'title' => $title, - 'link' => $this->pageURL($rev), - 'dc:date' => $this->time($rev), - 'dc:contributor' => $rev->get('author'), - 'wiki:version' => $rev->getVersion(), - 'wiki:importance' => $this->importance($rev), - 'wiki:status' => $this->status($rev), - 'wiki:diff' => $this->diffURL($rev), - ); + return array('title' => $title, + 'link' => $this->pageURL($rev), + 'dc:date' => $this->time($rev), + 'dc:contributor' => $rev->get('author'), + 'wiki:version' => $rev->getVersion(), + 'wiki:importance' => $this->importance($rev), + 'wiki:status' => $this->status($rev), + 'wiki:diff' => $this->diffURL($rev), + ); } } class WikiPlugin_PageHistory -extends WikiPlugin_RecentChanges + extends WikiPlugin_RecentChanges { - function getName () { + function getName() + { return _("PageHistory"); } - function getDescription () { - return sprintf(_("List PageHistory for %s"),'[pagename]'); + function getDescription() + { + return sprintf(_("List PageHistory for %s"), '[pagename]'); } - function getDefaultArguments() { - return array('days' => false, - 'show_minor' => true, - 'show_major' => true, - 'limit' => false, - 'page' => '[pagename]', - 'format' => false); + function getDefaultArguments() + { + return array('days' => false, + 'show_minor' => true, + 'show_major' => true, + 'limit' => false, + 'page' => '[pagename]', + 'format' => false); } - function getDefaultFormArguments() { + function getDefaultFormArguments() + { $dflts = WikiPlugin_RecentChanges::getDefaultFormArguments(); $dflts['textinput'] = 'page'; return $dflts; } - function getMostRecentParams ($args) { + function getMostRecentParams($args) + { $params = WikiPlugin_RecentChanges::getMostRecentParams($args); $params['include_all_revisions'] = true; return $params; } - function getChanges ($dbi, $args) { + function getChanges($dbi, $args) + { $page = $dbi->getPage($args['page']); $iter = $page->getAllRevisions(); $params = $this->getMostRecentParams($args); @@ -295,7 +316,8 @@ extends WikiPlugin_RecentChanges return new _PageHistory_PageRevisionIter($iter, $params); } - function format ($changes, $args) { + function format($changes, $args) + { global $WikiTheme; $format = $args['format']; @@ -312,7 +334,8 @@ extends WikiPlugin_RecentChanges return $fmt->format($changes); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); $pagename = $args['page']; if (empty($pagename)) @@ -322,13 +345,15 @@ extends WikiPlugin_RecentChanges $current = $page->getCurrentRevision(); if ($current->getVersion() < 1) { return HTML(HTML::p(fmt("I'm sorry, there is no such page as %s.", - WikiLink($pagename, 'unknown'))), - $this->makeForm("", $request)); + WikiLink($pagename, 'unknown'))), + $this->makeForm("", $request)); } // Hack alert: format() is a NORETURN for rss formatters. return $this->format($this->getChanges($dbi, $args), $args); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/PageInfo.php b/lib/plugin/PageInfo.php index 4827f9433..1eee360f8 100644 --- a/lib/plugin/PageInfo.php +++ b/lib/plugin/PageInfo.php @@ -26,23 +26,27 @@ * 'info.tmpl', which does all the real work. */ class WikiPlugin_PageInfo -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("PageInfo"); } - function getDescription () { + function getDescription() + { return sprintf(_("Show extra page Info and statistics for %s."), - '[pagename]'); + '[pagename]'); } - function getDefaultArguments() { + function getDefaultArguments() + { return array('page' => '[pagename]', - 'version' => '[version]'); + 'version' => '[version]'); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); extract($args); @@ -52,21 +56,22 @@ extends WikiPlugin if ($current->getVersion() < 1) return fmt("I'm sorry, there is no such page as %s.", - WikiLink($pagename, 'unknown')); + WikiLink($pagename, 'unknown')); if (!empty($version)) { if (!($revision = $page->getRevision($version))) NoSuchRevision($request, $page, $version); - } - else { + } else { $revision = $current; } $template = new Template('info', $request, - array('revision' => $revision)); + array('revision' => $revision)); return $template; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/PageTrail.php b/lib/plugin/PageTrail.php index 9cfbfb93b..51d5ae87d 100644 --- a/lib/plugin/PageTrail.php +++ b/lib/plugin/PageTrail.php @@ -36,28 +36,32 @@ if (!defined('PAGETRAIL_ARROW')) define('PAGETRAIL_ARROW', " => "); class WikiPlugin_PageTrail -extends WikiPlugin + extends WikiPlugin { // Four required functions in a WikiPlugin. var $def_numberlinks = 5; - function getName () { + function getName() + { return _("PageTrail"); } - function getDescription () { + function getDescription() + { return _("PageTrail Plugin"); } // default values - function getDefaultArguments() { + function getDefaultArguments() + { return array('numberlinks' => $this->def_numberlinks, - 'invisible' => false, - 'duplicates' => false, - ); + 'invisible' => false, + 'duplicates' => false, + ); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { extract($this->getArgs($argstr, $request)); if ($numberlinks > 10 || $numberlinks < 0) { @@ -75,19 +79,21 @@ extends WikiPlugin } $numberlinks = min(count($Pages), $numberlinks); - if (! $invisible and $numberlinks) { + if (!$invisible and $numberlinks) { $html = HTML::div(array('class' => 'pagetrail')); - $html->pushContent(WikiLink($Pages[$numberlinks-1], 'auto')); + $html->pushContent(WikiLink($Pages[$numberlinks - 1], 'auto')); for ($i = $numberlinks - 2; $i >= 0; $i--) { if (!empty($Pages[$i])) $html->pushContent(PAGETRAIL_ARROW, - WikiLink($Pages[$i], 'auto')); + WikiLink($Pages[$i], 'auto')); } return $html; } else return HTML(); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/PasswordReset.php b/lib/plugin/PasswordReset.php index 96ea51709..12d751fba 100644 --- a/lib/plugin/PasswordReset.php +++ b/lib/plugin/PasswordReset.php @@ -36,85 +36,93 @@ * => action=reset&user=username */ class WikiPlugin_PasswordReset -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("PasswordReset"); } - function getDescription () { + function getDescription() + { return _("Allow admin to reset any users password, allow user to request his password by e-mail."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array('user' => ''); } /* reset password, verified */ - function doReset($userid) { + function doReset($userid) + { $user = WikiUser($userid); $prefs = $user->getPreferences(); - $prefs->set('passwd',''); + $prefs->set('passwd', ''); if ($user->setPreferences($prefs)) { $alert = new Alert(_("Message"), - fmt("The password for user %s has been deleted.", $userid)); + fmt("The password for user %s has been deleted.", $userid)); } else { $alert = new Alert(_("Error"), - fmt("The password for user %s could not be deleted.", $userid)); + fmt("The password for user %s could not be deleted.", $userid)); } $alert->show(); } - function doEmail(&$request, $userid) { + function doEmail(&$request, $userid) + { $thisuser = WikiUser($userid); $prefs = $thisuser->getPreferences(); $email = $prefs->get('email'); $passwd = $prefs->get('passwd'); // plain? - $from = $request->_user->getId() . '@' . $request->get('REMOTE_HOST'); + $from = $request->_user->getId() . '@' . $request->get('REMOTE_HOST'); if (mail($email, - "[".WIKI_NAME."] PasswortReset", - "PasswortReset requested by $from\r\n". - "Password for ".WIKI_NAME.": $passwd", - "From: $from")) + "[" . WIKI_NAME . "] PasswortReset", + "PasswortReset requested by $from\r\n" . + "Password for " . WIKI_NAME . ": $passwd", + "From: $from") + ) $alert = new Alert(_("Message"), - fmt("Email sent to the stored email address for user %s", $userid)); + fmt("Email sent to the stored email address for user %s", $userid)); else $alert = new Alert(_("Error"), - fmt("Error sending email with password for user %s.", $userid)); + fmt("Error sending email with password for user %s.", $userid)); $alert->show(); } - function doForm(&$request, $userid='', $header = '', $footer = '') { + function doForm(&$request, $userid = '', $header = '', $footer = '') + { $post_args = $request->getArg('admin_reset'); if (!$header) { $header = HTML::p(_("Reset password of user: "), - HTML::Raw(' '), - HTML::input(array('type' => 'text', - 'name' => "user", - 'value' => $userid)) - ); + HTML::Raw(' '), + HTML::input(array('type' => 'text', + 'name' => "user", + 'value' => $userid)) + ); } if (!$footer) { $isadmin = $request->_user->isAdmin(); $footer = HTML::p(Button('submit:admin_reset[reset]', - $isadmin ? _("Yes") : _("Send email"), - $isadmin ? 'wikiadmin' : 'button'), - HTML::Raw(' '), - Button('submit:admin_reset[cancel]', _("Cancel"), 'button')); + $isadmin ? _("Yes") : _("Send email"), + $isadmin ? 'wikiadmin' : 'button'), + HTML::Raw(' '), + Button('submit:admin_reset[cancel]', _("Cancel"), 'button')); } return HTML::form(array('action' => $request->getPostURL(), - 'method' => 'post'), - $header, - HiddenInputs($request->getArgs(), false, array('admin_reset', 'user')), - ENABLE_PAGEPERM ? '' : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN)), - $footer ); + 'method' => 'post'), + $header, + HiddenInputs($request->getArgs(), false, array('admin_reset', 'user')), + ENABLE_PAGEPERM ? '' : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN)), + $footer); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); - if (isa($request,'MockRequest')) + if (isa($request, 'MockRequest')) return ''; $user =& $request->_user; @@ -128,7 +136,7 @@ extends WikiPlugin return $this->doForm($request, $userid); if (!$userid) { $alert = new Alert(_("Warning:"), - _("You need to specify the userid!")); + _("You need to specify the userid!")); $alert->show(); return $this->doForm($request); } @@ -142,16 +150,16 @@ extends WikiPlugin //TODO: verify should check if the user exists, his prefs can be read/safed // and the email is verified, even if admin. $buttons = HTML::p(Button('submit:admin_reset[reset]', - $isadmin ? _("Yes") : _("Send email"), - $isadmin ? 'wikiadmin' : 'button'), - HTML::Raw(' '), - Button('submit:admin_reset[cancel]', _("Cancel"), 'button')); + $isadmin ? _("Yes") : _("Send email"), + $isadmin ? 'wikiadmin' : 'button'), + HTML::Raw(' '), + Button('submit:admin_reset[cancel]', _("Cancel"), 'button')); $header = HTML::strong("Verify"); if (!$user->isAdmin()) { // check for email if ($userid == $user->UserName() and $user->isAuthenticated()) { $alert = new Alert(_("Already logged in"), - HTML(fmt("Changing passwords is done at "), WikiLink(_("UserPreferences")))); + HTML(fmt("Changing passwords is done at "), WikiLink(_("UserPreferences")))); $alert->show(); return; } @@ -160,10 +168,10 @@ extends WikiPlugin $email = $prefs->get('email'); if (!$email) { $alert = new Alert(_("Error"), - HTML(fmt("No email stored for user %s.", $userid), - HTML::br(), - fmt("You need to ask an Administrator to reset this password. See below: "), - HTML::br(), WikiLink(ADMIN_USER))); + HTML(fmt("No email stored for user %s.", $userid), + HTML::br(), + fmt("You need to ask an Administrator to reset this password. See below: "), + HTML::br(), WikiLink(ADMIN_USER))); $alert->show(); return; } @@ -172,12 +180,12 @@ extends WikiPlugin $header->pushContent(HTML::br(), "Warning: This users email address is unverified!"); } return $this->doForm($request, $userid, - $header, - HTML(HTML::hr(), - fmt("Do you really want to reset the password of user %s?", $userid), - $isadmin ? '' : _("An email will be sent."), - HiddenInputs(array('admin_reset[verify]' => 1, 'user' => $userid)), - $buttons)); + $header, + HTML(HTML::hr(), + fmt("Do you really want to reset the password of user %s?", $userid), + $isadmin ? '' : _("An email will be sent."), + HiddenInputs(array('admin_reset[verify]' => 1, 'user' => $userid)), + $buttons)); } else { // verify ok, but no userid return $this->doForm($request, $userid); } @@ -185,7 +193,9 @@ extends WikiPlugin return $this->doForm($request, $userid); } } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/PhotoAlbum.php b/lib/plugin/PhotoAlbum.php index 20585ab13..b56b63c52 100644 --- a/lib/plugin/PhotoAlbum.php +++ b/lib/plugin/PhotoAlbum.php @@ -72,11 +72,12 @@ class ImageTile extends HtmlElement { // go away, hack! - function image_tile (/*...*/) { + function image_tile( /*...*/) + { $el = new HTML ('img'); $tag = func_get_args(); $path = DATA_PATH . "/ImageTile.php"; - $params = "' . $tag[0]['alt'] . ''; - return $el->raw ($params); + return $el->raw($params); } } class WikiPlugin_PhotoAlbum -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("PhotoAlbum"); } - function getDescription () { + function getDescription() + { return _("Displays a set of photos listed in a text file with optional descriptions"); } @@ -108,53 +111,56 @@ extends WikiPlugin // define('album_default_extension', '.jpg'); // define('desc_separator', ';'); - function getDefaultArguments() { - return array('src' => '', // textfile of image list, or local dir. - 'url' => '', // if src=localfs, url prefix (webroot for the links) - 'mode' => 'normal', // normal|thumbs|tiles|list - // "normal" - Normal table which shows photos full-size - // "thumbs" - WinXP thumbnail style - // "tiles" - WinXP tiles style - // "list" - WinXP list style - // "row" - inline thumbnails - // "column" - photos full-size, displayed in 1 column - // "slide" - slideshow mode, needs javascript on client - 'numcols' => 3, // photos per row, columns - 'showdesc' => 'both', // none|name|desc|both - // "none" - No descriptions next to photos - // "name" - Only filename shown - // "desc" - Only description (from textfile) shown - // "both" - If no description found, then filename will be used - 'link' => true, // show link to original sized photo - // If true, each image will be hyperlinked to a page where the single - // photo will be shown full-size. Only works when mode != 'normal' - 'attrib' => '', // 'sort, nowrap, alt' - // attrib arg allows multiple attributes: attrib=sort,nowrap,alt - // 'sort' sorts alphabetically, 'nowrap' for cells, 'alt' to use - // descs instead of filenames in image ALT-tags - 'bgcolor' => '#eae8e8', // cell bgcolor (lightgrey) - 'hlcolor' => '#c0c0ff', // highlight color (lightblue) - 'align' => 'center', // alignment of table - 'height' => 'auto', // image height (auto|75|100%) - 'width' => 'auto', // image width (auto|75|100%) - // Size of shown photos. Either absolute value (e.g. "50") or - // HTML style percentage (e.g. "75%") or "auto" for no special - // action. - 'cellwidth'=> 'image', // cell (auto|equal|image|75|100%) - // Width of cells in table. Either absolute value in pixels, HTML - // style percentage, "auto" (no special action), "equal" (where - // all columns are equally sized) or "image" (take height and - // width of the photo in that cell). - 'tablewidth'=> false, // table (75|100%) - 'p' => false, // "displaythissinglephoto.jpg" - 'h' => false, // "highlightcolorofthisphoto.jpg" - 'duration' => 6, // in slide mode, in seconds - 'thumbswidth' => 80 //width of thumbnails - ); + function getDefaultArguments() + { + return array('src' => '', // textfile of image list, or local dir. + 'url' => '', // if src=localfs, url prefix (webroot for the links) + 'mode' => 'normal', // normal|thumbs|tiles|list + // "normal" - Normal table which shows photos full-size + // "thumbs" - WinXP thumbnail style + // "tiles" - WinXP tiles style + // "list" - WinXP list style + // "row" - inline thumbnails + // "column" - photos full-size, displayed in 1 column + // "slide" - slideshow mode, needs javascript on client + 'numcols' => 3, // photos per row, columns + 'showdesc' => 'both', // none|name|desc|both + // "none" - No descriptions next to photos + // "name" - Only filename shown + // "desc" - Only description (from textfile) shown + // "both" - If no description found, then filename will be used + 'link' => true, // show link to original sized photo + // If true, each image will be hyperlinked to a page where the single + // photo will be shown full-size. Only works when mode != 'normal' + 'attrib' => '', // 'sort, nowrap, alt' + // attrib arg allows multiple attributes: attrib=sort,nowrap,alt + // 'sort' sorts alphabetically, 'nowrap' for cells, 'alt' to use + // descs instead of filenames in image ALT-tags + 'bgcolor' => '#eae8e8', // cell bgcolor (lightgrey) + 'hlcolor' => '#c0c0ff', // highlight color (lightblue) + 'align' => 'center', // alignment of table + 'height' => 'auto', // image height (auto|75|100%) + 'width' => 'auto', // image width (auto|75|100%) + // Size of shown photos. Either absolute value (e.g. "50") or + // HTML style percentage (e.g. "75%") or "auto" for no special + // action. + 'cellwidth' => 'image', // cell (auto|equal|image|75|100%) + // Width of cells in table. Either absolute value in pixels, HTML + // style percentage, "auto" (no special action), "equal" (where + // all columns are equally sized) or "image" (take height and + // width of the photo in that cell). + 'tablewidth' => false, // table (75|100%) + 'p' => false, // "displaythissinglephoto.jpg" + 'h' => false, // "highlightcolorofthisphoto.jpg" + 'duration' => 6, // in slide mode, in seconds + 'thumbswidth' => 80 //width of thumbnails + ); } + // descriptions (instead of filenames) for image alt-tags - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { extract($this->getArgs($argstr, $request)); @@ -165,8 +171,8 @@ extends WikiPlugin // check all parameters // what type do we have? if (!$src) { - $showdesc = 'none'; - $src = $request->getArg('pagename'); + $showdesc = 'none'; + $src = $request->getArg('pagename'); $error = $this->fromLocation($src, $photos); } else { $error = $this->fromFile($src, $photos, $url); @@ -189,27 +195,27 @@ extends WikiPlugin } if ($mode == "column") { - $mode="normal"; - $numcols="1"; + $mode = "normal"; + $numcols = "1"; } // set some fixed properties for each $mode if ($mode == 'thumbs' || $mode == 'tiles') { $attributes = array_merge($attributes, "alt"); $attributes = array_merge($attributes, "nowrap"); - $cellwidth = 'auto'; // else cell won't nowrap + $cellwidth = 'auto'; // else cell won't nowrap if ($width == 'auto') $width = 70; } elseif ($mode == 'list') { - $numcols = 1; - $cellwidth = "auto"; + $numcols = 1; + $cellwidth = "auto"; if ($width == 'auto') $width = 50; - } elseif ($mode == 'slide' ) { + } elseif ($mode == 'slide') { $tableheight = 0; $cell_width = 0; $numcols = count($photos); $keep = $photos; while (list($key, $value) = each($photos)) { - list($x,$y,$s,$t) = @getimagesize($value['src']); + list($x, $y, $s, $t) = @getimagesize($value['src']); if ($height != 'auto') $y = $this->newSize($y, $height); if ($width != 'auto') $y = round($y * $this->newSize($x, $width) / $x); if ($x > $cell_width) $cell_width = $x; @@ -217,7 +223,7 @@ extends WikiPlugin } $tableheight += 50; $photos = $keep; - unset ($x,$y,$s,$t,$key,$value,$keep); + unset ($x, $y, $s, $t, $key, $value, $keep); } $row = HTML(); @@ -239,7 +245,7 @@ function display_slides() { } display_slides();")); - while (list($key, $value) = each($photos)) { + while (list($key, $value) = each($photos)) { if ($p && basename($value["name"]) != "$p") { continue; } @@ -249,26 +255,26 @@ display_slides();")); $color = $bgcolor; } // $params will be used for each tag - $params = array('src' => $value["name"], - 'src_tile' => $value["name_tile"], - 'alt' => ($value["desc"] != "" and in_array("alt", $attributes)) - ? $value["desc"] - : basename($value["name"])); + $params = array('src' => $value["name"], + 'src_tile' => $value["name_tile"], + 'alt' => ($value["desc"] != "" and in_array("alt", $attributes)) + ? $value["desc"] + : basename($value["name"])); if (!@empty($value['location'])) $params = array_merge($params, array("location" => $value['location'])); // check description switch ($showdesc) { - case 'none': - $value["desc"] = ''; - break; - case 'name': - $value["desc"] = basename($value["name"]); - break; - case 'desc': - break; - default: // 'both' - if (!$value["desc"]) $value["desc"] = basename($value["name"]); - break; + case 'none': + $value["desc"] = ''; + break; + case 'name': + $value["desc"] = basename($value["name"]); + break; + case 'desc': + break; + default: // 'both' + if (!$value["desc"]) $value["desc"] = basename($value["name"]); + break; } // FIXME: get getimagesize to work with names with spaces in it. @@ -277,8 +283,8 @@ display_slides();")); if (!$size and !empty($value["src"])) { $size = @getimagesize($value["src"]); if (!$size) { - trigger_error("Unable to getimagesize(".$value["name"].")", - E_USER_NOTICE); + trigger_error("Unable to getimagesize(" . $value["name"] . ")", + E_USER_NOTICE); } } $newwidth = $this->newSize($size[0], $width); @@ -287,13 +293,12 @@ display_slides();")); } if (($mode == 'thumbs' || $mode == 'tiles' || $mode == 'list')) { if (!empty($size[0])) { - $newheight = round ($newwidth * $size[1] / $size[0]); + $newheight = round($newwidth * $size[1] / $size[0]); $params['width'] = $newwidth; $params['height'] = $newheight; } else $newheight = ''; - if ($height == 'auto') $height=150; - } - else { + if ($height == 'auto') $height = 150; + } else { $newheight = $this->newSize($size[1], $height); if ($height != 'auto' && $newheight > 0) { $params = array_merge($params, array("height" => $newheight)); @@ -301,13 +306,13 @@ display_slides();")); } // cell operations - $cell = array('align' => "center", - 'valign' => "top", - 'class' => 'photoalbum cell', - 'bgcolor' => "$color"); + $cell = array('align' => "center", + 'valign' => "top", + 'class' => 'photoalbum cell', + 'bgcolor' => "$color"); if ($cellwidth != 'auto') { if ($cellwidth == 'equal') { - $newcellwidth = round(100/$numcols)."%"; + $newcellwidth = round(100 / $numcols) . "%"; } elseif ($cellwidth == 'image') { $newcellwidth = $newwidth; } else { @@ -320,185 +325,186 @@ display_slides();")); } //create url to display single larger version of image on page $url = WikiURL($request->getPage(), - array("p" => basename($value["name"]))) + array("p" => basename($value["name"]))) . "#" . basename($value["name"]); $b_url = WikiURL($request->getPage(), - array("h" => basename($value["name"]))) + array("h" => basename($value["name"]))) . "#" . basename($value["name"]); $url_text = $link ? HTML::a(array("href" => "$url"), basename($value["desc"])) : basename($value["name"]); - if (! $p) { + if (!$p) { if ($mode == 'normal' || $mode == 'slide') { - if(!@empty($params['location'])) $params['src'] = $params['location']; - unset ($params['location'],$params['src_tile']); + if (!@empty($params['location'])) $params['src'] = $params['location']; + unset ($params['location'], $params['src_tile']); $url_image = $link ? HTML::a(array("id" => basename($value["name"]), - "href" => "$url"), HTML::img($params)) - : HTML::img($params); + "href" => "$url"), HTML::img($params)) + : HTML::img($params); } else { $keep = $params; if (!@empty ($params['src_tile'])) - $params['src'] = $params['src_tile'] ; - unset ($params['location'],$params['src_tile']); + $params['src'] = $params['src_tile']; + unset ($params['location'], $params['src_tile']); $url_image = $link ? HTML::a(array("id" => basename($value["name"]), - "href" => "$url"), - ImageTile::image_tile($params)) - : HTML::img($params); + "href" => "$url"), + ImageTile::image_tile($params)) + : HTML::img($params); $params = $keep; unset ($keep); } } else { - if(!@empty($params['location'])) $params['src'] = $params['location']; - unset ($params['location'],$params['src_tile']); - $url_image = $link ? HTML::a(array("id" => basename($value["name"]), - "href" => "$b_url"), HTML::img($params)) - : HTML::img($params); + if (!@empty($params['location'])) $params['src'] = $params['location']; + unset ($params['location'], $params['src_tile']); + $url_image = $link ? HTML::a(array("id" => basename($value["name"]), + "href" => "$b_url"), HTML::img($params)) + : HTML::img($params); } if ($mode == 'list') $url_text = HTML::a(array("id" => basename($value["name"])), - $url_text); + $url_text); // here we use different modes if ($mode == 'tiles') { $row->pushContent( HTML::td($cell, - HTML::div(array('valign' => 'top'), $url_image), - HTML::div(array('valign' => 'bottom'), - HTML::div(array('class'=>'boldsmall'), - ($url_text)), - HTML::br(), - HTML::div(array('class'=>'gensmall'), - ($size[0]. - " x ". - $size[1]. - " pixels")))) - ); + HTML::div(array('valign' => 'top'), $url_image), + HTML::div(array('valign' => 'bottom'), + HTML::div(array('class' => 'boldsmall'), + ($url_text)), + HTML::br(), + HTML::div(array('class' => 'gensmall'), + ($size[0] . + " x " . + $size[1] . + " pixels")))) + ); } elseif ($mode == 'list') { $desc = ($showdesc != 'none') ? $value["desc"] : ''; $row->pushContent( - HTML::td(array("valign" => "top", - "nowrap" => 0, - "bgcolor" => $color), - HTML::div(array('class'=>'boldsmall'),($url_text)))); + HTML::td(array("valign" => "top", + "nowrap" => 0, + "bgcolor" => $color), + HTML::div(array('class' => 'boldsmall'), ($url_text)))); $row->pushContent( - HTML::td(array("valign" => "top", - "nowrap" => 0, - "bgcolor" => $color), - HTML::div(array('class'=>'gensmall'), - ($size[0]. - " x ". - $size[1]. - " pixels")))); + HTML::td(array("valign" => "top", + "nowrap" => 0, + "bgcolor" => $color), + HTML::div(array('class' => 'gensmall'), + ($size[0] . + " x " . + $size[1] . + " pixels")))); if ($desc != '') $row->pushContent( - HTML::td(array("valign" => "top", - "nowrap" => 0, - "bgcolor" => $color), - HTML::div(array('class'=>'gensmall'),$desc))); + HTML::td(array("valign" => "top", + "nowrap" => 0, + "bgcolor" => $color), + HTML::div(array('class' => 'gensmall'), $desc))); } elseif ($mode == 'thumbs') { $desc = ($showdesc != 'none') ? - HTML::p(HTML::a(array("href" => "$url"), - $url_text)) : ''; + HTML::p(HTML::a(array("href" => "$url"), + $url_text)) : ''; $row->pushContent( - (HTML::td($cell, - $url_image, - // FIXME: no HtmlElement for fontsizes? - // rurban: use ->setAttr("style","font-size:small;") - // but better use a css class - HTML::div(array('class'=>'gensmall'),$desc) - ))); + (HTML::td($cell, + $url_image, + // FIXME: no HtmlElement for fontsizes? + // rurban: use ->setAttr("style","font-size:small;") + // but better use a css class + HTML::div(array('class' => 'gensmall'), $desc) + ))); } elseif ($mode == 'normal') { $desc = ($showdesc != 'none') ? HTML::p($value["desc"]) : ''; $row->pushContent( - (HTML::td($cell, - $url_image, - // FIXME: no HtmlElement for fontsizes? - HTML::div(array('class'=>'gensmall'),$desc) - ))); + (HTML::td($cell, + $url_image, + // FIXME: no HtmlElement for fontsizes? + HTML::div(array('class' => 'gensmall'), $desc) + ))); } elseif ($mode == 'slide') { if ($newwidth == 'auto' || !$newwidth) - $newwidth = $this->newSize($size[0],$width); + $newwidth = $this->newSize($size[0], $width); if ($newwidth == 'auto' || !$newwidth) $newwidth = $size[0]; - if ($newheight != 'auto') $newwidth = round($size[0] * $newheight / $size[1]); + if ($newheight != 'auto') $newwidth = round($size[0] * $newheight / $size[1]); $desc = ($showdesc != 'none') ? HTML::p($value["desc"]) : ''; if ($count == 0) - $cell=array('style' => 'display: block; ' - . 'position: absolute; ' - . 'left: 50% ; ' - . 'margin-left: -'.round($newwidth / 2).'px;' - . 'text-align: center; ' - . 'vertical-align: top', - 'name' => "wikislide".$count); + $cell = array('style' => 'display: block; ' + . 'position: absolute; ' + . 'left: 50% ; ' + . 'margin-left: -' . round($newwidth / 2) . 'px;' + . 'text-align: center; ' + . 'vertical-align: top', + 'name' => "wikislide" . $count); else - $cell=array('style' => 'display: none; ' - . 'position: absolute ;' - . 'left: 50% ;' - . 'margin-left: -'.round($newwidth / 2).'px;' - . 'text-align: center; ' - . 'vertical-align: top', - 'name' => "wikislide".$count); + $cell = array('style' => 'display: none; ' + . 'position: absolute ;' + . 'left: 50% ;' + . 'margin-left: -' . round($newwidth / 2) . 'px;' + . 'text-align: center; ' + . 'vertical-align: top', + 'name' => "wikislide" . $count); if ($align == 'left' || $align == 'right') { if ($count == 0) - $cell=array('style' => 'display: block; ' - .'position: absolute; ' - . $align.': 50px; ' - .'vertical-align: top', - 'name' => "wikislide".$count); + $cell = array('style' => 'display: block; ' + . 'position: absolute; ' + . $align . ': 50px; ' + . 'vertical-align: top', + 'name' => "wikislide" . $count); else - $cell=array('style' => 'display: none; ' - .'position: absolute; ' - . $align.': 50px; ' - .'vertical-align: top', - 'name' => "wikislide".$count); - } + $cell = array('style' => 'display: none; ' + . 'position: absolute; ' + . $align . ': 50px; ' + . 'vertical-align: top', + 'name' => "wikislide" . $count); + } $row->pushContent( - (HTML::td($cell, - $url_image, - HTML::div(array('class'=>'gensmall'), $desc) - ))); - $count ++; + (HTML::td($cell, + $url_image, + HTML::div(array('class' => 'gensmall'), $desc) + ))); + $count++; } elseif ($mode == 'row') { $desc = ($showdesc != 'none') ? HTML::p($value["desc"]) : ''; $row->pushContent( - HTML::table(array("style" => "display: inline", - 'class' > "photoalbum row"), - HTML::tr(HTML::td($url_image)), - HTML::tr(HTML::td(array("class" => "gensmall", - "style" => "text-align: center; " - ."background-color: $color"), - $desc)) - )); + HTML::table(array("style" => "display: inline", + 'class' > "photoalbum row"), + HTML::tr(HTML::td($url_image)), + HTML::tr(HTML::td(array("class" => "gensmall", + "style" => "text-align: center; " + . "background-color: $color"), + $desc)) + )); } else { return $this->error(fmt("Invalid argument: %s=%s", 'mode', $mode)); } // no more images in one row as defined by $numcols - if ( ($key + 1) % $numcols == 0 || - ($key + 1) == count($photos) || - $p) { - if ($mode == 'row') - $html->pushcontent(HTML::div($row)); - else - $html->pushcontent(HTML::tr($row)); - $row->setContent(''); + if (($key + 1) % $numcols == 0 || + ($key + 1) == count($photos) || + $p + ) { + if ($mode == 'row') + $html->pushcontent(HTML::div($row)); + else + $html->pushcontent(HTML::tr($row)); + $row->setContent(''); } } //create main table - $table_attributes = array("border" => 0, - "cellpadding" => 5, - "cellspacing" => 2, - "class" => "photoalbum", - "width" => $tablewidth ? $tablewidth : "100%"); + $table_attributes = array("border" => 0, + "cellpadding" => 5, + "cellspacing" => 2, + "class" => "photoalbum", + "width" => $tablewidth ? $tablewidth : "100%"); if (!empty($tableheight)) $table_attributes = array_merge($table_attributes, - array("height" => $tableheight)); + array("height" => $tableheight)); if ($mode != 'row') $html = HTML::table($table_attributes, $html); // align all @@ -513,32 +519,34 @@ display_slides();")); * @param mixed $value Either absolute no. or HTML percentage e.g. '50%' * @return integer New size in pixels */ - function newSize($oldSize, $value) { - if (trim(substr($value,strlen($value)-1)) != "%") { + function newSize($oldSize, $value) + { + if (trim(substr($value, strlen($value) - 1)) != "%") { return $value; } $value = str_replace("%", "", $value); - return round(($oldSize*$value)/100); + return round(($oldSize * $value) / 100); } /** - * fromLocation - read only one picture from fixed album_location - * and return it in array $photos - * - * @param string $src Name of page - * @param array $photos - * @return string Error if fixed location is not allowed - */ - function fromLocation($src, &$photos) { - /*if (!allow_album_location) { - return $this->error(_("Fixed album location is not allowed. Please specify parameter src.")); - }*/ + * fromLocation - read only one picture from fixed album_location + * and return it in array $photos + * + * @param string $src Name of page + * @param array $photos + * @return string Error if fixed location is not allowed + */ + function fromLocation($src, &$photos) + { + /*if (!allow_album_location) { + return $this->error(_("Fixed album location is not allowed. Please specify parameter src.")); + }*/ //FIXME! - if (! IsSafeURL($src)) { + if (!IsSafeURL($src)) { return $this->error(_("Bad url in src: remove all of <, >, \"")); } - $photos[] = array ("name" => $src, //album_location."/$src".album_default_extension, - "desc" => ""); + $photos[] = array("name" => $src, //album_location."/$src".album_default_extension, + "desc" => ""); } /** @@ -549,17 +557,18 @@ display_slides();")); * @param array $photos * @return string Error when bad url or file couldn't be opened */ - function fromFile($src, &$photos, $webpath='') { + function fromFile($src, &$photos, $webpath = '') + { $src_bak = $src; if (preg_match("/^Upload:(.*)$/", $src, $m)) { $src = getUploadFilePath() . $m[1]; $webpath = getUploadDataPath() . $m[1]; } //there has a big security hole... as loading config/config.ini ! - if (!preg_match('/(\.csv|\.jpg|\.jpeg|\.png|\.gif|\/)$/',$src)) { - return $this->error(_("File extension for csv file has to be '.csv'")); + if (!preg_match('/(\.csv|\.jpg|\.jpeg|\.png|\.gif|\/)$/', $src)) { + return $this->error(_("File extension for csv file has to be '.csv'")); } - if (! IsSafeURL($src)) { + if (!IsSafeURL($src)) { return $this->error(_("Bad url in src: remove all of <, >, \"")); } if (preg_match('/^(http|ftp|https):\/\//i', $src)) { @@ -567,8 +576,8 @@ display_slides();")); $web_location = 1; } else { $web_location = 0; - if (string_ends_with($src,"/")) - $src = substr($src,0,-1); + if (string_ends_with($src, "/")) + $src = substr($src, 0, -1); } if (!file_exists($src) and @file_exists(PHPWIKI_DIR . "/$src")) { $src = PHPWIKI_DIR . "/$src"; @@ -577,46 +586,46 @@ display_slides();")); if (file_exists($src) and filetype($src) == 'dir') { //all images $list = array(); - foreach (array('jpeg','jpg','png','gif') as $ext) { + foreach (array('jpeg', 'jpg', 'png', 'gif') as $ext) { $fileset = new fileSet($src, "*.$ext"); $list = array_merge($list, $fileset->getFiles()); } // convert dirname($src) (local fs path) to web path natcasesort($list); - if (! $webpath ) { + if (!$webpath) { // assume relative src. default: "themes/Hawaiian/images/pictures" $webpath = DATA_PATH . '/' . $src_bak; } foreach ($list as $file) { // convert local path to webpath - $photos[] = array ("src" => $file, - "name" => $webpath . "/$file", - "name_tile" => $src . "/$file", - "src" => $src . "/$file", - "desc" => ""); + $photos[] = array("src" => $file, + "name" => $webpath . "/$file", + "name_tile" => $src . "/$file", + "src" => $src . "/$file", + "desc" => ""); } return; } // check if $src is an image - foreach (array('jpeg','jpg','png','gif') as $ext) { + foreach (array('jpeg', 'jpg', 'png', 'gif') as $ext) { if (preg_match("/\.$ext$/", $src)) { if (!file_exists($src) and @file_exists(PHPWIKI_DIR . "/$src")) $src = PHPWIKI_DIR . "/$src"; if ($web_location == 1 and !empty($contents)) { - $photos[] = array ("src" => $src, - "name" => $src, - "name_tile" => $src, - "src" => $src, - "desc" => ""); + $photos[] = array("src" => $src, + "name" => $src, + "name_tile" => $src, + "src" => $src, + "desc" => ""); return; } if (!file_exists($src)) return $this->error(fmt("Unable to find src='%s'", $src)); - $photos[] = array ("src" => $src, - "name" => "../".$src, - "name_tile" => $src, - "src" => $src, - "desc" => ""); + $photos[] = array("src" => $src, + "name" => "../" . $src, + "name_tile" => $src, + "src" => $src, + "desc" => ""); return; } } @@ -627,35 +636,39 @@ display_slides();")); } while ($data = fgetcsv($fp, 1024, ';')) { if (count($data) == 0 || empty($data[0]) - || preg_match('/^#/',$data[0]) - || preg_match('/^[[:space:]]*$/',$data[0])) + || preg_match('/^#/', $data[0]) + || preg_match('/^[[:space:]]*$/', $data[0]) + ) continue; if (empty($data[1])) $data[1] = ''; - $photos[] = array ("name" => dirname($src)."/".trim($data[0]), - "location" => "../".dirname($src)."/".trim($data[0]), - "desc" => trim($data[1]), - "name_tile" => dirname($src)."/".trim($data[0])); + $photos[] = array("name" => dirname($src) . "/" . trim($data[0]), + "location" => "../" . dirname($src) . "/" . trim($data[0]), + "desc" => trim($data[1]), + "name_tile" => dirname($src) . "/" . trim($data[0])); } - fclose ($fp); + fclose($fp); } elseif ($web_location == 1) { //TODO: check if the file is an image - $contents = preg_split('/\n/',$contents); - while (list($key,$value) = each($contents)) { - $data = preg_split('/\;/',$value); + $contents = preg_split('/\n/', $contents); + while (list($key, $value) = each($contents)) { + $data = preg_split('/\;/', $value); if (count($data) == 0 || empty($data[0]) - || preg_match('/^#/',$data[0]) - || preg_match('/^[[:space:]]*$/',$data[0])) + || preg_match('/^#/', $data[0]) + || preg_match('/^[[:space:]]*$/', $data[0]) + ) continue; if (empty($data[1])) $data[1] = ''; - $photos[] = array ("name" => dirname($src)."/".trim($data[0]), - "src" => dirname($src)."/".trim($data[0]), - "desc" => trim($data[1]), - "name_tile" => dirname($src)."/".trim($data[0])); + $photos[] = array("name" => dirname($src) . "/" . trim($data[0]), + "src" => dirname($src) . "/" . trim($data[0]), + "desc" => trim($data[1]), + "name_tile" => dirname($src) . "/" . trim($data[0])); } } } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/PhpHighlight.php b/lib/plugin/PhpHighlight.php index 049fea6f8..69ac3c934 100644 --- a/lib/plugin/PhpHighlight.php +++ b/lib/plugin/PhpHighlight.php @@ -52,33 +52,37 @@ */ class WikiPlugin_PhpHighlight -extends WikiPlugin + extends WikiPlugin { // Four required functions in a WikiPlugin. - function getName () { + function getName() + { return _("PhpHighlight"); } - function getDescription () { + function getDescription() + { return _("PHP syntax highlighting"); } // Establish default values for each of this plugin's arguments. - function getDefaultArguments() { + function getDefaultArguments() + { // TODO: results of ini_get() should be static for multiple // invocations of plugin on one WikiPage - return array('wrap' => true, - 'string' => ini_get("highlight.string"), //'#00CC00', - 'comment' => ini_get("highlight.comment"), //'#FF9900', - 'keyword' => ini_get("highlight.keyword"), //'#006600', - 'bg' => ini_get("highlight.bg"), //'#FFFFFF', - 'default' => ini_get("highlight.default"), //'#0000CC', - 'html' => ini_get("highlight.html") //'#000000' - ); + return array('wrap' => true, + 'string' => ini_get("highlight.string"), //'#00CC00', + 'comment' => ini_get("highlight.comment"), //'#FF9900', + 'keyword' => ini_get("highlight.keyword"), //'#006600', + 'bg' => ini_get("highlight.bg"), //'#FFFFFF', + 'default' => ini_get("highlight.default"), //'#0000CC', + 'html' => ini_get("highlight.html") //'#000000' + ); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { extract($this->getArgs($argstr, $request)); $source =& $this->source; @@ -92,7 +96,7 @@ extends WikiPlugin $source = ""; } else { $source = str_replace(array('< ?php', '? >'), - array(''), $source); + array(''), $source); } $str = highlight_string($source, true); @@ -118,7 +122,8 @@ extends WikiPlugin return new RawXml($str); } - function handle_plugin_args_cruft(&$argstr, &$args) { + function handle_plugin_args_cruft(&$argstr, &$args) + { $this->source = $argstr; } @@ -126,19 +131,20 @@ extends WikiPlugin * Make sure color argument is valid * See http://www.w3.org/TR/REC-html40/types.html#h-6.5 */ - function sanify_colors($string, $comment, $keyword, $bg, $default, $html) { + function sanify_colors($string, $comment, $keyword, $bg, $default, $html) + { static $html4colors = array("black", "silver", "gray", "white", - "maroon", "red", "purple", "fuchsia", - "green", "lime", "olive", "yellow", - "navy", "blue", "teal", "aqua"); + "maroon", "red", "purple", "fuchsia", + "green", "lime", "olive", "yellow", + "navy", "blue", "teal", "aqua"); /* max(strlen("fuchsia"), strlen("#00FF00"), ... ) = 7 */ static $MAXLEN = 7; foreach (array($string, $comment, $keyword, $bg, $default, $html) as $color) { $length = strlen($color); //trigger_error(sprintf(_("DEBUG: color '%s' is length %d."), $color, $length), E_USER_NOTICE); if (($length == 7 || $length == 4) && substr($color, 0, 1) == "#" - && "#" == preg_replace("/[a-fA-F0-9]/", "", $color) - ) { + && "#" == preg_replace("/[a-fA-F0-9]/", "", $color) + ) { //trigger_error(sprintf(_("DEBUG: color '%s' appears to be hex."), $color), E_USER_NOTICE); // stop checking, ok to go } elseif (($length < $MAXLEN + 1) && in_array($color, $html4colors)) { @@ -146,13 +152,14 @@ extends WikiPlugin // stop checking, ok to go } else { trigger_error(sprintf(_("Invalid color: %s"), - $color), E_USER_NOTICE); + $color), E_USER_NOTICE); // FIXME: also change color to something valid like "black" or ini_get("highlight.xxx") } } } - function set_colors($string, $comment, $keyword, $bg, $default, $html) { + function set_colors($string, $comment, $keyword, $bg, $default, $html) + { // set highlight colors $this->oldstring = ini_set('highlight.string', $string); $this->oldcomment = ini_set('highlight.comment', $comment); @@ -162,7 +169,8 @@ extends WikiPlugin $this->oldhtml = ini_set('highlight.html', $html); } - function restore_colors() { + function restore_colors() + { // restore previous default highlight colors ini_set('highlight.string', $this->oldstring); ini_set('highlight.comment', $this->oldcomment); @@ -172,7 +180,9 @@ extends WikiPlugin ini_set('highlight.html', $this->oldhtml); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/PhpWeather.php b/lib/plugin/PhpWeather.php index 05d6e3dd8..005d87ab9 100644 --- a/lib/plugin/PhpWeather.php +++ b/lib/plugin/PhpWeather.php @@ -57,26 +57,30 @@ if (!defined('PHPWEATHER_BASE_DIR')) { } class WikiPlugin_PhpWeather -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("PhpWeather"); } - function getDescription () { + function getDescription() + { return _("The PhpWeather plugin provides weather reports from the Internet."); } - function getDefaultArguments() { + function getDefaultArguments() + { global $LANG; - return array('icao' => 'EKAH', - 'cc' => 'DK', - 'language' => 'en', - 'menu' => false, - 'units' => 'both_metric'); + return array('icao' => 'EKAH', + 'cc' => 'DK', + 'language' => 'en', + 'menu' => false, + 'units' => 'both_metric'); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { // When 'phpweather/phpweather.php' is not installed then // PHPWEATHER_BASE_DIR will be undefined. if (!defined('PHPWEATHER_BASE_DIR')) @@ -97,7 +101,7 @@ extends WikiPlugin /* The country code couldn't be resolved, so we * shouldn't use the ICAO: */ trigger_error(sprintf(_("The ICAO '%s' wasn't recognized."), - $icao), E_USER_NOTICE); + $icao), E_USER_NOTICE); $icao = ''; } } @@ -108,8 +112,8 @@ extends WikiPlugin //if (!in_array($language, array_keys($w->get_languages('text')))) { if (!in_array($language, array_keys(get_languages('text')))) { trigger_error(sprintf(_("%s does not know about the language '%s', using 'en' instead."), - $this->getName(), $language), - E_USER_NOTICE); + $this->getName(), $language), + E_USER_NOTICE); $language = 'en'; } @@ -122,7 +126,7 @@ extends WikiPlugin $i_temp = HTML::img(array('src' => $i->get_temp_image())); $i_wind = HTML::img(array('src' => $i->get_winddir_image())); - $i_sky = HTML::img(array('src' => $i->get_sky_image())); + $i_sky = HTML::img(array('src' => $i->get_sky_image())); $m = $t->print_pretty(); @@ -134,7 +138,7 @@ extends WikiPlugin $i_table = HTML::table($i_tr); $i_table->pushContent(HTML::tr(HTML::td(array('colspan' => '2'), - $i_sky))); + $i_sky))); $tr = HTML::tr(); $tr->pushContent($m_td); @@ -148,23 +152,23 @@ extends WikiPlugin if ($menu || empty($icao)) { $form_arg = array('action' => $request->getURLtoSelf(), - 'method' => 'get'); + 'method' => 'get'); /* The country box is always part of the menu: */ $p1 = HTML::p(new RawXml(get_countries_select($w, $cc))); /* We want to save the language: */ - $p1->pushContent(HTML::input(array('type' => 'hidden', - 'name' => 'language', - 'value' => $language))); + $p1->pushContent(HTML::input(array('type' => 'hidden', + 'name' => 'language', + 'value' => $language))); /* And also the ICAO: */ - $p1->pushContent(HTML::input(array('type' => 'hidden', - 'name' => 'icao', - 'value' => $icao))); + $p1->pushContent(HTML::input(array('type' => 'hidden', + 'name' => 'icao', + 'value' => $icao))); $caption = (empty($cc) ? _("Submit country") : _("Change country")); - $p1->pushContent(HTML::input(array('type' => 'submit', - 'value' => $caption))); + $p1->pushContent(HTML::input(array('type' => 'submit', + 'value' => $caption))); $html->pushContent(HTML::form($form_arg, $p1)); @@ -174,14 +178,14 @@ extends WikiPlugin $p2 = HTML::p(); /* We need the country code after the form is submitted: */ - $p2->pushContent(HTML::input(array('type' => 'hidden', - 'name' => 'cc', - 'value' => $cc))); + $p2->pushContent(HTML::input(array('type' => 'hidden', + 'name' => 'cc', + 'value' => $cc))); $p2->pushContent(new RawXml(get_stations_select($w, $cc, $icao))); $p2->pushContent(new RawXml(get_languages_select($language))); - $p2->pushContent(HTML::input(array('type' => 'submit', - 'value' => _("Submit location")))); + $p2->pushContent(HTML::input(array('type' => 'submit', + 'value' => _("Submit location")))); $html->pushContent(HTML::form($form_arg, $p2)); @@ -191,7 +195,9 @@ extends WikiPlugin return $html; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/Ploticus.php b/lib/plugin/Ploticus.php index 91a7ffe1a..26cbac475 100644 --- a/lib/plugin/Ploticus.php +++ b/lib/plugin/Ploticus.php @@ -38,7 +38,7 @@ * * Usage: <> * or without any script: (not tested) <> @@ -49,25 +49,26 @@ */ if (!defined("PLOTICUS_EXE")) - if (isWindows()) - define('PLOTICUS_EXE','pl.exe'); - else - define('PLOTICUS_EXE','/usr/local/bin/pl'); + if (isWindows()) + define('PLOTICUS_EXE', 'pl.exe'); + else + define('PLOTICUS_EXE', '/usr/local/bin/pl'); //TODO: check $_ENV['PLOTICUS_PREFABS'] and default directory require_once 'lib/WikiPluginCached.php'; class WikiPlugin_Ploticus -extends WikiPluginCached + extends WikiPluginCached { /** * Sets plugin type to MAP if -csmap (-map or -mapdemo or -csmapdemo not supported) * or HTML if the imagetype is not supported by GD (EPS, SVG, SVGZ) (not yet) * or IMG_INLINE if device = png, gif or jpeg */ - function getPluginType() { - if (!empty($this->_args['-csmap'])) - return PLUGIN_CACHED_MAP; // not yet tested + function getPluginType() + { + if (!empty($this->_args['-csmap'])) + return PLUGIN_CACHED_MAP; // not yet tested // produce these on-demand so far, uncached. // will get better support in WikiPluginCached soon. // FIXME: html also? what about ''? @@ -75,51 +76,62 @@ extends WikiPluginCached if ($type == $this->_args['device']) return PLUGIN_CACHED_IMG_INLINE; $device = strtolower($this->_args['device']); - if (in_array($device, array('svg','swf','svgz','eps','ps','pdf','html'))) { + if (in_array($device, array('svg', 'swf', 'svgz', 'eps', 'ps', 'pdf', 'html'))) { switch ($this->_args['device']) { - case 'svg': - case 'svgz': - return PLUGIN_CACHED_STATIC | PLUGIN_CACHED_SVG_PNG; - case 'swf': - return PLUGIN_CACHED_STATIC | PLUGIN_CACHED_SWF; + case 'svg': + case 'svgz': + return PLUGIN_CACHED_STATIC | PLUGIN_CACHED_SVG_PNG; + case 'swf': + return PLUGIN_CACHED_STATIC | PLUGIN_CACHED_SWF; default: - return PLUGIN_CACHED_STATIC | PLUGIN_CACHED_HTML; + return PLUGIN_CACHED_STATIC | PLUGIN_CACHED_HTML; } - } - else + } else return PLUGIN_CACHED_IMG_INLINE; // normal cached libgd image handles } - function getName () { + + function getName() + { return _("Ploticus"); } - function getDescription () { + + function getDescription() + { return _("Ploticus image creation"); } - function managesValidators() { + + function managesValidators() + { return true; } - function getDefaultArguments() { + + function getDefaultArguments() + { return array( - 'device' => 'png', // png,gif,svgz,svg,... - '-prefab' => '', - '-csmap' => false, - 'data' => false, // support - 'alt' => false, - 'help' => false, - ); + 'device' => 'png', // png,gif,svgz,svg,... + '-prefab' => '', + '-csmap' => false, + 'data' => false, // support + 'alt' => false, + 'help' => false, + ); } - function handle_plugin_args_cruft(&$argstr, &$args) { + + function handle_plugin_args_cruft(&$argstr, &$args) + { $this->source = $argstr; } + /** * Sets the expire time to one day (so the image producing * functions are called seldomly) or to about two minutes * if a help screen is created. */ - function getExpire($dbi, $argarray, $request) { + function getExpire($dbi, $argarray, $request) + { if (!empty($argarray['help'])) return '+120'; // 2 minutes - return sprintf('+%d', 3*86000); // approx 3 days + return sprintf('+%d', 3 * 86000); // approx 3 days } /** @@ -132,7 +144,8 @@ extends WikiPluginCached * * @return string 'png', 'jpeg', 'gif' */ - function getImageType($dbi, $argarray, $request) { + function getImageType($dbi, $argarray, $request) + { return $argarray['device']; } @@ -140,9 +153,10 @@ extends WikiPluginCached * This gives an alternative text description of * the image. */ - function getAlt($dbi, $argstr, $request) { + function getAlt($dbi, $argstr, $request) + { return (!empty($this->_args['alt'])) ? $this->_args['alt'] - : $this->getDescription(); + : $this->getDescription(); } /** @@ -151,44 +165,47 @@ extends WikiPluginCached * TODO: -csmap pointing to the Ploticus documentation at sf.net. * @return string image handle */ - function helpImage() { + function helpImage() + { $def = $this->defaultArguments(); //$other_imgtypes = $GLOBALS['PLUGIN_CACHED_IMGTYPES']; //unset ($other_imgtypes[$def['imgtype']]); $helparr = array( '< ' = "' . $def['device'] . "(default)|" - . join('|',$GLOBALS['PLUGIN_CACHED_IMGTYPES']).'"', - 'data' => ' : pagelist as input', - 'alt' => ' = "alternate text"', - '-csmap' => ' bool: clickable map?', - 'help' => ' bool: displays this screen', - '...' => ' all further lines below the first plugin line ', - '' => ' and inside the tags are the ploticus script.', + 'device' => ' = "' . $def['device'] . "(default)|" + . join('|', $GLOBALS['PLUGIN_CACHED_IMGTYPES']) . '"', + 'data' => ' : pagelist as input', + 'alt' => ' = "alternate text"', + '-csmap' => ' bool: clickable map?', + 'help' => ' bool: displays this screen', + '...' => ' all further lines below the first plugin line ', + '' => ' and inside the tags are the ploticus script.', "\n >>" - ); + ); $length = 0; - foreach($helparr as $alignright => $alignleft) { + foreach ($helparr as $alignright => $alignleft) { $length = max($length, strlen($alignright)); } - $helptext =''; - foreach($helparr as $alignright => $alignleft) { + $helptext = ''; + foreach ($helparr as $alignright => $alignleft) { $helptext .= substr(' ' - . $alignright, -$length).$alignleft."\n"; + . $alignright, -$length) . $alignleft . "\n"; } return $this->text2img($helptext, 4, array(1, 0, 0), - array(255, 255, 255)); + array(255, 255, 255)); } - function withShellCommand($script) { - $findme = 'shell'; + function withShellCommand($script) + { + $findme = 'shell'; $pos = strpos($script, $findme); // uppercase? if ($pos === false) return 0; return 1; } - function getImage($dbi, $argarray, $request) { + function getImage($dbi, $argarray, $request) + { //extract($this->getArgs($argstr, $request)); //extract($argarray); $source =& $this->source; @@ -210,16 +227,16 @@ extends WikiPluginCached $src .= $source; $source = $src; } - $tempfile = $this->tempnam('Ploticus','plo'); + $tempfile = $this->tempnam('Ploticus', 'plo'); @unlink($tempfile); $gif = $argarray['device']; $args = "-$gif -o $tempfile.$gif"; if (!empty($argarray['-csmap'])) { - $args .= " -csmap -mapfile $tempfile.map"; - $this->_mapfile = "$tempfile.map"; + $args .= " -csmap -mapfile $tempfile.map"; + $this->_mapfile = "$tempfile.map"; } if (!empty($argarray['-prefab'])) { - //check $_ENV['PLOTICUS_PREFABS'] and default directory + //check $_ENV['PLOTICUS_PREFABS'] and default directory global $HTTP_ENV_VARS; if (empty($HTTP_ENV_VARS['PLOTICUS_PREFABS'])) { if (file_exists("/usr/share/ploticus")) @@ -227,33 +244,33 @@ extends WikiPluginCached elseif (defined('PLOTICUS_PREFABS')) $HTTP_ENV_VARS['PLOTICUS_PREFABS'] = constant('PLOTICUS_PREFABS'); } - $args .= (" -prefab " . $argarray['-prefab']); + $args .= (" -prefab " . $argarray['-prefab']); } if (isWindows()) { $fp = fopen("$tempfile.plo", "w"); - fwrite ($fp, $source); + fwrite($fp, $source); fclose($fp); - $code = $this->execute(PLOTICUS_EXE . " $tempfile.plo $args", $tempfile.".$gif"); + $code = $this->execute(PLOTICUS_EXE . " $tempfile.plo $args", $tempfile . ".$gif"); } else { $code = $this->filterThroughCmd($source, PLOTICUS_EXE . " -stdin $args"); sleep(1); } //if (empty($code)) // return $this->error(fmt("Couldn't start commandline '%s'", $commandLine)); - if (! file_exists($tempfile.".$gif") ) { + if (!file_exists($tempfile . ".$gif")) { $this->_errortext .= sprintf(_("%s error: outputfile '%s' not created"), - "Ploticus", "$tempfile.$gif"); + "Ploticus", "$tempfile.$gif"); if (isWindows()) - $this->_errortext .= ("\ncmd-line: " .PLOTICUS_EXE . " $tempfile.plo $args"); + $this->_errortext .= ("\ncmd-line: " . PLOTICUS_EXE . " $tempfile.plo $args"); else - $this->_errortext .= ("\ncmd-line: cat script | ".PLOTICUS_EXE . " $args"); + $this->_errortext .= ("\ncmd-line: cat script | " . PLOTICUS_EXE . " $args"); @unlink("$tempfile.pl"); @unlink("$tempfile"); return false; } $ImageCreateFromFunc = "ImageCreateFrom$gif"; if (function_exists($ImageCreateFromFunc)) { - $handle = $ImageCreateFromFunc( "$tempfile.$gif" ); + $handle = $ImageCreateFromFunc("$tempfile.$gif"); if ($handle) { @unlink("$tempfile.$gif"); @unlink("$tempfile.plo"); @@ -269,15 +286,19 @@ extends WikiPluginCached // which argument must be set to 'png', for the fallback image when svg will fail on the client. // type: SVG_PNG - function pngArg() { - return 'device'; + function pngArg() + { + return 'device'; } - function getMap($dbi, $argarray, $request) { - $img = $this->getImage($dbi, $argarray, $request); - return array($this->_mapfile, $img); + function getMap($dbi, $argarray, $request) + { + $img = $this->getImage($dbi, $argarray, $request); + return array($this->_mapfile, $img); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/PluginManager.php b/lib/plugin/PluginManager.php index f136deb45..9d18ee29a 100644 --- a/lib/plugin/PluginManager.php +++ b/lib/plugin/PluginManager.php @@ -26,58 +26,64 @@ define('REQUIRE_ADMIN', false); class WikiPlugin_PluginManager -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("PluginManager"); } - function getDescription () { + function getDescription() + { return _("List of plugins on this wiki"); } - function getDefaultArguments() { + function getDefaultArguments() + { return array('info' => 'args'); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { extract($this->getArgs($argstr, $request)); $h = HTML(); $this->_generatePageheader($info, $h); - if (! REQUIRE_ADMIN || $request->_user->isadmin()) { + if (!REQUIRE_ADMIN || $request->_user->isadmin()) { $h->pushContent(HTML::h2(_("Plugins"))); $table = HTML::table(array('class' => "pagelist")); $this->_generateColheadings($info, $table); $this->_generateTableBody($info, $dbi, $request, $table); $h->pushContent($table); - } - else { + } else { $h->pushContent(fmt("You must be an administrator to %s.", - _("use this plugin"))); + _("use this plugin"))); } return $h; } - function _generatePageheader(&$info, &$html) { + function _generatePageheader(&$info, &$html) + { $html->pushContent(HTML::p($this->getDescription())); } - function _generateColheadings(&$info, &$table) { + function _generateColheadings(&$info, &$table) + { // table headings $tr = HTML::tr(); $headings = array(_("Plugin"), _("Description")); if ($info == 'args') - $headings []= _("Arguments"); + $headings [] = _("Arguments"); foreach ($headings as $title) { $tr->pushContent(HTML::th($title)); } $table->pushContent(HTML::thead($tr)); } - function _generateTableBody(&$info, &$dbi, &$request, &$table) { + function _generateTableBody(&$info, &$dbi, &$request, &$table) + { global $AllAllowedPlugins; @@ -101,7 +107,7 @@ extends WikiPlugin continue; } // instantiate a plugin - $temppluginclass = '<'."? plugin $pluginName ?>"; // hackish + $temppluginclass = '<' . "? plugin $pluginName ?>"; // hackish $p = $w->getPlugin($pluginName, false); // second arg? // trap php files which aren't WikiPlugin~s if (!strtolower(substr(get_parent_class($p), 0, 10)) == 'wikiplugin') { @@ -109,7 +115,7 @@ extends WikiPlugin // plugin dir from non-admins. if ($request->_user->isAdmin()) trigger_error(sprintf(_("%s does not appear to be a WikiPlugin."), - $pluginName . ".php")); + $pluginName . ".php")); continue; // skip this non WikiPlugin file } $desc = $p->getDescription(); @@ -119,33 +125,33 @@ extends WikiPlugin // This section was largely improved by Pierrick Meignen: // make a link if an actionpage exists $pluginNamelink = $pluginName; - $pluginDocPageName = _("Help")."/" . $pluginName . "Plugin"; + $pluginDocPageName = _("Help") . "/" . $pluginName . "Plugin"; if (defined('FUSIONFORGE') and FUSIONFORGE) { - $pluginDocPageName = _("Help").":" . $pluginName . "Plugin"; + $pluginDocPageName = _("Help") . ":" . $pluginName . "Plugin"; } $pluginDocPageNamelink = false; $localizedPluginName = ''; $localizedPluginDocPageName = ''; - if($GLOBALS['LANG'] != "en"){ + if ($GLOBALS['LANG'] != "en") { if (_($pluginName) != $pluginName) $localizedPluginName = _($pluginName); - if($localizedPluginName && $dbi->isWikiPage($localizedPluginName)) - $pluginDocPageNamelink = WikiLink($localizedPluginName,'if_known'); + if ($localizedPluginName && $dbi->isWikiPage($localizedPluginName)) + $pluginDocPageNamelink = WikiLink($localizedPluginName, 'if_known'); if (_($pluginDocPageName) != $pluginDocPageName) $localizedPluginDocPageName = _($pluginDocPageName); - if($localizedPluginDocPageName && - $dbi->isWikiPage($localizedPluginDocPageName)) + if ($localizedPluginDocPageName && + $dbi->isWikiPage($localizedPluginDocPageName) + ) $pluginDocPageNamelink = WikiLink($localizedPluginDocPageName, 'if_known'); - } - else { + } else { $pluginNamelink = WikiLink($pluginName, 'if_known'); if ($dbi->isWikiPage($pluginDocPageName)) - $pluginDocPageNamelink = WikiLink($pluginDocPageName,'if_known'); + $pluginDocPageNamelink = WikiLink($pluginDocPageName, 'if_known'); } if (defined('FUSIONFORGE') and FUSIONFORGE) { @@ -161,10 +167,9 @@ extends WikiPlugin if ($pluginDocPageNamelink) { // plugin has a description page 'Help/' . 'PluginName' . 'Plugin' $tr->pushContent(HTML::td($pluginNamelink, HTML::br(), - $pluginDocPageNamelink)); + $pluginDocPageNamelink)); $pluginDocPageNamelink = false; - } - else { + } else { // plugin just has an actionpage $tr->pushContent(HTML::td($pluginNamelink)); } @@ -172,14 +177,16 @@ extends WikiPlugin if ($info == 'args') { // add Arguments column $style = array('style' - => 'font-family:monospace;font-size:smaller'); + => 'font-family:monospace;font-size:smaller'); $tr->pushContent(HTML::td($style, $arguments)); } $tbody->pushContent($tr); } $table->pushContent($tbody); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/PopUp.php b/lib/plugin/PopUp.php index d2e963904..31ed99122 100644 --- a/lib/plugin/PopUp.php +++ b/lib/plugin/PopUp.php @@ -44,55 +44,63 @@ */ class WikiPlugin_PopUp -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("PopUp"); } - function getDescription () { + + function getDescription() + { return _("Used to create a clickable popup link."); } - function getDefaultArguments() { - return array('link' => "HomePage", - 'title' => "", - 'text' => "", - 'width' => "500", - 'height' => "400", - 'resizable' => "no", - 'scrollbars' => "no", - 'toolbar' => "no", - 'location' => "no", - 'directories' => "no", - 'status' => "no", - 'menubar' => "no", - 'copyhistory' => "no", - 'close' => "no", - ); + + function getDefaultArguments() + { + return array('link' => "HomePage", + 'title' => "", + 'text' => "", + 'width' => "500", + 'height' => "400", + 'resizable' => "no", + 'scrollbars' => "no", + 'toolbar' => "no", + 'location' => "no", + 'directories' => "no", + 'status' => "no", + 'menubar' => "no", + 'copyhistory' => "no", + 'close' => "no", + ); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { extract($this->getArgs($argstr, $request)); return HTML::a(array('href' => WikiURL($link), - 'target' => "_blank", - 'onclick' => ($close == "yes" ? "window.close()" : ("window.open('" . - WikiURL($link) . "', '" . - ($title == "" ? ($text == "" ? $link : $text) : $title) . "', '" . - "width=$width," . - "height=$height," . - "resizable=$resizable," . - "scrollbars=$scrollbars," . - "toolbar=$toolbar," . - "location=$location," . - "directories=$directories," . - "status=$status," . - "menubar=$menubar," . - "copyhistory=$copyhistory')" - )) . ";return false;" - ), - ($text == "" ? ($close == "yes" ? "Close window" : $link) : $text) - ); + 'target' => "_blank", + 'onclick' => ($close == "yes" ? "window.close()" : ("window.open('" . + WikiURL($link) . "', '" . + ($title == "" ? ($text == "" ? $link : $text) : $title) . "', '" . + "width=$width," . + "height=$height," . + "resizable=$resizable," . + "scrollbars=$scrollbars," . + "toolbar=$toolbar," . + "location=$location," . + "directories=$directories," . + "status=$status," . + "menubar=$menubar," . + "copyhistory=$copyhistory')" + )) . ";return false;" + ), + ($text == "" ? ($close == "yes" ? "Close window" : $link) : $text) + ); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/PopularNearby.php b/lib/plugin/PopularNearby.php index bab1a8d08..990a3628b 100644 --- a/lib/plugin/PopularNearby.php +++ b/lib/plugin/PopularNearby.php @@ -37,55 +37,59 @@ require_once 'lib/PageList.php'; class WikiPlugin_PopularNearby -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("PopularNearby"); } - function getDescription () { + function getDescription() + { return _("List the most popular pages nearby."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array('pagename' => '[pagename]', - 'mode' => 'nearby', // or 'incoming' or 'outgoing' - //'exclude' => false, // not yet - 'limit' => 5, - 'noheader' => 0, - ); + 'mode' => 'nearby', // or 'incoming' or 'outgoing' + //'exclude' => false, // not yet + 'limit' => 5, + 'noheader' => 0, + ); } - function run($dbi, $argstr, &$request, $basepage) { - $args = $this->getArgs($argstr, $request); + function run($dbi, $argstr, &$request, $basepage) + { + $args = $this->getArgs($argstr, $request); extract($args); $header = ''; $page = $dbi->getPage($pagename); switch ($mode) { - case 'incoming': // not the hits, but the number of links - if (! $noheader ) - $header = sprintf(_("%d best incoming links: "),$limit); - $links = $this->sortedLinks($page->getLinks("reversed"),"reversed",$limit); - break; - case 'outgoing': // not the hits, but the number of links - if (! $noheader ) - $header = sprintf(_("%d best outgoing links: "),$limit); - $links = $this->sortedLinks($page->getLinks(),false,$limit); - break; - case 'nearby': // all linksfrom and linksto, sorted by hits - if (! $noheader ) - $header = sprintf(_("%d most popular nearby: "),$limit); - $inlinks = $page->getLinks(); - $outlinks = $page->getLinks('reversed'); - // array_merge doesn't sort out duplicate page objects here. - $links = $this->sortedLinks(array_merge($inlinks->asArray(), - $outlinks->asArray()), - false, $limit); - break; + case 'incoming': // not the hits, but the number of links + if (!$noheader) + $header = sprintf(_("%d best incoming links: "), $limit); + $links = $this->sortedLinks($page->getLinks("reversed"), "reversed", $limit); + break; + case 'outgoing': // not the hits, but the number of links + if (!$noheader) + $header = sprintf(_("%d best outgoing links: "), $limit); + $links = $this->sortedLinks($page->getLinks(), false, $limit); + break; + case 'nearby': // all linksfrom and linksto, sorted by hits + if (!$noheader) + $header = sprintf(_("%d most popular nearby: "), $limit); + $inlinks = $page->getLinks(); + $outlinks = $page->getLinks('reversed'); + // array_merge doesn't sort out duplicate page objects here. + $links = $this->sortedLinks(array_merge($inlinks->asArray(), + $outlinks->asArray()), + false, $limit); + break; } $html = HTML($header); - for ($i=0; $ipushContent($links[$i]['format'],$ipushContent($links[$i]['format'], $i < count($links) - 1 ? ', ' : ''); } return $html; } @@ -103,8 +107,9 @@ extends WikiPlugin * * @return Array of sorted links */ - function sortedLinks($pages, $direction=false, $limit=5) { - $links = array(); + function sortedLinks($pages, $direction = false, $limit = 5) + { + $links = array(); if (is_array($pages)) { $already = array(); // need special duplicate check foreach ($pages as $page) { @@ -114,8 +119,8 @@ extends WikiPlugin $hits = $page->get('hits'); if (!$hits) continue; $links[] = array('hits' => $hits, - 'pagename' => $page->_pagename, - 'format' => HTML(WikiLink($page->_pagename),' (' . $hits . ')')); + 'pagename' => $page->_pagename, + 'format' => HTML(WikiLink($page->_pagename), ' (' . $hits . ')')); } } else { while ($page = $pages->next()) { @@ -126,8 +131,8 @@ extends WikiPlugin if (!$score) continue; $name = $page->_pagename; $links[] = array('hits' => $score, - 'pagename' => $name, - 'format' => HTML(WikiLink($name),' (' . $score . ')')); + 'pagename' => $name, + 'format' => HTML(WikiLink($name), ' (' . $score . ')')); } $pages->free(); } @@ -136,17 +141,21 @@ extends WikiPlugin return $this->sortByHits($links); } - function sortByHits($links) { + function sortByHits($links) + { if (!$links) return array(); - usort($links,'cmp_by_hits'); // php-4.0.6 cannot use methods + usort($links, 'cmp_by_hits'); // php-4.0.6 cannot use methods reset($links); return $links; } -}; +} + +; -function cmp_by_hits($a, $b) { - if ($a['hits'] == $b['hits']) return 0; - return $a['hits'] < $b['hits'] ? 1 : -1; +function cmp_by_hits($a, $b) +{ + if ($a['hits'] == $b['hits']) return 0; + return $a['hits'] < $b['hits'] ? 1 : -1; } // Local Variables: diff --git a/lib/plugin/PopularTags.php b/lib/plugin/PopularTags.php index da92547c5..2192c339e 100644 --- a/lib/plugin/PopularTags.php +++ b/lib/plugin/PopularTags.php @@ -27,26 +27,30 @@ require_once 'lib/PageList.php'; class WikiPlugin_PopularTags -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("PopularTags"); } - function getDescription () { + function getDescription() + { return _("List the most popular tags."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array('pagename' => '[pagename]', - 'limit' => 10, - 'mincount' => 5, - 'noheader' => 0, - ); + 'limit' => 10, + 'mincount' => 5, + 'noheader' => 0, + ); } - function run($dbi, $argstr, &$request, $basepage) { - $args = $this->getArgs($argstr, $request); + function run($dbi, $argstr, &$request, $basepage) + { + $args = $this->getArgs($argstr, $request); extract($args); $maincat = $dbi->getPage(_("CategoryCategory")); @@ -54,23 +58,24 @@ extends WikiPlugin $bl = array(); while ($b = $bi->next()) { $name = $b->getName(); - if (preg_match("/^"._("Template")."/", $name)) continue; + if (preg_match("/^" . _("Template") . "/", $name)) continue; $pages = $b->getBackLinks(false); $bl[] = array('name' => $name, - 'count' => $pages->count()); + 'count' => $pages->count()); } usort($bl, 'cmp_by_count'); - $html = HTML::ul(); $i = 0; + $html = HTML::ul(); + $i = 0; foreach ($bl as $b) { $i++; - $name = $b['name']; + $name = $b['name']; $count = $b['count']; if ($count < $mincount) break; if ($i > $limit) break; - $wo = preg_replace("/^("._("Category")."|" - ._("Topic").")/", "", $name); - $wo = HTML(HTML::span($wo),HTML::raw(" "),HTML::small("(".$count.")")); + $wo = preg_replace("/^(" . _("Category") . "|" + . _("Topic") . ")/", "", $name); + $wo = HTML(HTML::span($wo), HTML::raw(" "), HTML::small("(" . $count . ")")); $link = WikiLink($name, 'auto', $wo); $html->pushContent(HTML::li($link)); } @@ -79,9 +84,10 @@ extends WikiPlugin } // get list of categories sorted by number of backlinks -function cmp_by_count($a, $b) { - if ($a['count'] == $b['count']) return 0; - return $a['count'] < $b['count'] ? 1 : -1; +function cmp_by_count($a, $b) +{ + if ($a['count'] == $b['count']) return 0; + return $a['count'] < $b['count'] ? 1 : -1; } // Local Variables: diff --git a/lib/plugin/PreferenceApp.php b/lib/plugin/PreferenceApp.php index 8819d32d7..1218f0ca4 100644 --- a/lib/plugin/PreferenceApp.php +++ b/lib/plugin/PreferenceApp.php @@ -47,38 +47,43 @@ require_once 'lib/wikilens/Buddy.php'; require_once 'lib/wikilens/RatingsDb.php'; class WikiPlugin_PreferenceApp -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("PreferenceApp"); } - function getDescription () { + function getDescription() + { return _("Analyzes preferences based on voting budget and ratings."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array( - 'category' => null, - 'lockedBudget' => null, - 'pageTextLabel' => null, - 'group' => null, - 'roundCalc' => "true", - 'neutralRating' => "3", - 'declareBudget' => "true"); + 'category' => null, + 'lockedBudget' => null, + 'pageTextLabel' => null, + 'group' => null, + 'roundCalc' => "true", + 'neutralRating' => "3", + 'declareBudget' => "true"); } + // info arg allows multiple columns // info=mtime,hits,summary,version,author,locked,minor // exclude arg allows multiple pagenames exclude=HomePage,RecentChanges - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { extract($this->getArgs($argstr, $request)); - if($pageTextLabel == null && $category != null && $group == null){ + if ($pageTextLabel == null && $category != null && $group == null) { $group = $category; } - if($category == null || $pageTextLabel == null){ - return HTML::div(array('class' => "error"), "PreferencesApp Error: You must declare at least parameters category and pageTextLabel."); + if ($category == null || $pageTextLabel == null) { + return HTML::div(array('class' => "error"), "PreferencesApp Error: You must declare at least parameters category and pageTextLabel."); } $dbi = $request->getDbh(); @@ -88,28 +93,28 @@ extends WikiPlugin $PAGE_TEXT_LABEL = $pageTextLabel; $NEUTRAL_RATING = (int)$neutralRating; - $active_user = $request->getUser(); + $active_user = $request->getUser(); $active_userid = $active_user->_userid; $html = HTML(); $html->pushContent(""); //Load participating Users $users_array = array(); - if($group != null){ + if ($group != null) { $users_array = getMembers($group, $rdbi); } else { $people_iter = $rdbi->sql_get_users_rated(); - while($people_array = $people_iter->next()){ + while ($people_array = $people_iter->next()) { $users_array[] = $people_array['pagename']; } } $people = array(); - foreach($users_array as $person_indv){ - if($declareBudget == "true"){ + foreach ($users_array as $person_indv) { + if ($declareBudget == "true") { $get_array = getPageTextData($person_indv, $dbi, $PAGE_TEXT_LABEL, "cans"); - if(count($get_array) == 1){ + if (count($get_array) == 1) { $cans_text = $get_array[0]; - if(is_numeric($cans_text) && $cans_text >= 0){ + if (is_numeric($cans_text) && $cans_text >= 0) { $canBudget[$person_indv] = $cans_text; //Load the persons budget } else { $canBudget[$person_indv] = 0; @@ -121,47 +126,47 @@ extends WikiPlugin $people[] = $person_indv; } } - if(count($people) < 1){ + if (count($people) < 1) { return fmt("Nobody has used %s on their homepage", $PAGE_TEXT_LABEL); } //Get all pages from Category $pageids = array(); $category_page = $dbi->getPage($CATEGORY); $iter = $category_page->getLinks(); - while ($item = $iter->next()){ + while ($item = $iter->next()) { array_push($pageids, $item->getName()); } $ratingTotals = array(); - foreach ($people as $person){ - $ratings_iter = $rdbi->sql_get_rating(0, $person, $pageids); - $ratingTotals[$person] = 0; - while($ratings_array = $ratings_iter->next()){ - $can_rating = $ratings_array['ratingvalue']; - if($can_rating >= $NEUTRAL_RATING){ - $ratingTotals[$person] += $can_rating; - } + foreach ($people as $person) { + $ratings_iter = $rdbi->sql_get_rating(0, $person, $pageids); + $ratingTotals[$person] = 0; + while ($ratings_array = $ratings_iter->next()) { + $can_rating = $ratings_array['ratingvalue']; + if ($can_rating >= $NEUTRAL_RATING) { + $ratingTotals[$person] += $can_rating; } + } } //Generate numbers $canTotals = array(); $peopleTotals = array(); - foreach($pageids as $soda){ + foreach ($pageids as $soda) { $canTotals[$soda] = 0; } - foreach($people as $person){ - foreach($pageids as $soda){ + foreach ($people as $person) { + foreach ($pageids as $soda) { $peopleTotals[$person][$soda] = 0; } } - foreach($people as $person){ - foreach($pageids as $page){ + foreach ($people as $person) { + foreach ($pageids as $page) { $can_rating_iter = $rdbi->sql_get_rating(0, $person, $page); $can_rating_array = $can_rating_iter->next(); $can_rating = $can_rating_array['ratingvalue']; - if($can_rating >= $NEUTRAL_RATING){ + if ($can_rating >= $NEUTRAL_RATING) { $calc = (($can_rating / $ratingTotals[$person]) * $canBudget[$person]); - if($roundCalc == "true"){ + if ($roundCalc == "true") { $adjustedCans = round($calc); } else { $adjustedCans = round($calc, 2); @@ -173,8 +178,8 @@ extends WikiPlugin } } $outputArray = array(); - foreach($people as $person){ - foreach($pageids as $page){ + foreach ($people as $person) { + foreach ($pageids as $page) { $outputArray[$person][$page] = 0; } } @@ -185,12 +190,12 @@ extends WikiPlugin $td->pushContent(" "); $tr->pushContent($td); - foreach($people as $person){ + foreach ($people as $person) { $td = HTML::td(array('bgcolor' => '#FFFFFF')); $td->pushContent(HTML::a(array('href' => WikiURL($person), - 'class' => 'wiki' - ), - SplitPagename($person))); + 'class' => 'wiki' + ), + SplitPagename($person))); //$td->pushContent(WikiLink(" $person ")); $tr->pushContent($td); } @@ -202,9 +207,9 @@ extends WikiPlugin $tr->pushContent($td); $table->pushContent($tr); - for($i = 0; $i < count($pageids); $i++){ + for ($i = 0; $i < count($pageids); $i++) { $total_cans = 0; - for($j = 0; $j < count($people); $j++){ + for ($j = 0; $j < count($people); $j++) { $td = HTML::td(array('align' => 'right')); $cans_per_soda = $peopleTotals[$people[$j]][$pageids[$i]]; $total_cans = $total_cans + $cans_per_soda; @@ -212,38 +217,38 @@ extends WikiPlugin } } - foreach($people as $person){ + foreach ($people as $person) { $min_soda = ""; $min_cans = 9999999; //9 million, serving as "infinity" $total_cans = 0; - foreach($pageids as $page){ + foreach ($pageids as $page) { $cur_soda_cans = $outputArray[$person][$page]; - if($cur_soda_cans < $min_cans && $cur_soda_cans > 0){ + if ($cur_soda_cans < $min_cans && $cur_soda_cans > 0) { $min_cans = $cur_soda_cans; $min_soda = $page; } $total_cans = $total_cans + $cur_soda_cans; } - if($total_cans != $canBudget[$person] && $total_cans > 0){ + if ($total_cans != $canBudget[$person] && $total_cans > 0) { $diff = $canBudget[$person] - $total_cans; $outputArray[$person][$min_soda] = $outputArray[$person][$min_soda] + $diff; } } - for($i = 0; $i < count($pageids); $i++){ + for ($i = 0; $i < count($pageids); $i++) { $tr = HTML::tr(); $td = HTML::td(array('align' => 'left', 'bgcolor' => '#f7f7f7')); $td->pushContent(HTML::a(array('href' => WikiURL($pageids[$i]), - 'class' => 'wiki' - ), - SplitPagename($pageids[$i]))); + 'class' => 'wiki' + ), + SplitPagename($pageids[$i]))); $tr->pushContent($td); $total_cans = 0; $total_voters = 0; - for($j = 0; $j < count($people); $j++){ + for ($j = 0; $j < count($people); $j++) { $td = HTML::td(array('align' => 'right', 'bgcolor' => '#f7f7f7')); $output = $outputArray[$people[$j]][$pageids[$i]]; $total_cans = $total_cans + $output; - if($output == ""){ + if ($output == "") { $output = "-"; } else { $total_voters++; @@ -251,10 +256,10 @@ extends WikiPlugin $td->pushContent($output); $tr->pushContent($td); } - if($total_cans == ""){ + if ($total_cans == "") { $total_cans = "-"; } - if($total_voters == ""){ + if ($total_voters == "") { $total_voters = "-"; } $td = HTML::td(array('align' => 'right')); @@ -272,15 +277,15 @@ extends WikiPlugin $tr->pushContent($td); $cans_total = 0; $total_voters = 0; - for($i = 0; $i < count($people); $i++){ + for ($i = 0; $i < count($people); $i++) { $td = HTML::td(array('align' => 'right')); $cans_for_soda = 0; - foreach($pageids as $page){ + foreach ($pageids as $page) { $cans_for_soda = $cans_for_soda + $outputArray[$people[$i]][$page]; } $cans = $cans_for_soda; $cans_total = $cans_total + $cans; - if($cans == ""){ + if ($cans == "") { $cans = "-"; } else { $total_voters++; @@ -303,7 +308,9 @@ extends WikiPlugin return $html; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/PrevNext.php b/lib/plugin/PrevNext.php index 72deac5d8..053ee54a3 100644 --- a/lib/plugin/PrevNext.php +++ b/lib/plugin/PrevNext.php @@ -27,44 +27,48 @@ * */ class WikiPlugin_PrevNext -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("PrevNext"); } - function getDescription() { - return sprintf(_("Easy navigation buttons for %s"),'[pagename]'); + function getDescription() + { + return sprintf(_("Easy navigation buttons for %s"), '[pagename]'); } - function getDefaultArguments() { + function getDefaultArguments() + { return array( - 'prev' => '', - 'next' => '', - 'contents' => '', - 'index' => '', - 'up' => '', - 'first' => '', - 'last' => '', - 'order' => '', - 'style' => 'button', // or 'text' - 'align' => 'left', // or 'right', or 'center' - 'class' => 'wikiaction' - ); + 'prev' => '', + 'next' => '', + 'contents' => '', + 'index' => '', + 'up' => '', + 'first' => '', + 'last' => '', + 'order' => '', + 'style' => 'button', // or 'text' + 'align' => 'left', // or 'right', or 'center' + 'class' => 'wikiaction' + ); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); extract($args); - $directions = array ('first' => _("First"), - 'prev' => _("Previous"), - 'next' => _("Next"), - 'last' => _("Last"), - 'up' => _("Up"), - 'contents' => _("Contents"), - 'index' => _("Index") - ); + $directions = array('first' => _("First"), + 'prev' => _("Previous"), + 'next' => _("Next"), + 'last' => _("Last"), + 'up' => _("Up"), + 'contents' => _("Contents"), + 'index' => _("Index") + ); if ($order) { // reorder the buttons: comma-delimited $new_directions = array(); foreach (explode(',', $order) as $o) { @@ -144,7 +148,7 @@ extends WikiPlugin } $last_is_text = false; } else { // text only - if (! $this_is_first) { + if (!$this_is_first) { if ($align == 'center') { $tr->pushContent(HTML::td(array('align' => $align), $sep)); } elseif ($align == 'right') { @@ -163,7 +167,7 @@ extends WikiPlugin $last_is_text = true; } } else { - if (! $this_is_first) { + if (!$this_is_first) { if ($align == 'center') { $tr->pushContent(HTML::td(array('align' => $align), $sep)); } elseif ($align == 'right') { diff --git a/lib/plugin/Processing.php b/lib/plugin/Processing.php index 5459b5b7e..d523191c1 100644 --- a/lib/plugin/Processing.php +++ b/lib/plugin/Processing.php @@ -25,28 +25,34 @@ * Syntax: http://ejohn.org/blog/overview-of-processing/ */ class WikiPlugin_Processing -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("Processing"); } - function getDescription() { + function getDescription() + { return _("Render inline Processing"); } - function getDefaultArguments() { - return array('width' => 200, - 'height' => 200, - 'script' => false, // one line script. not very likely - 'onmousemove' => false - ); + function getDefaultArguments() + { + return array('width' => 200, + 'height' => 200, + 'script' => false, // one line script. not very likely + 'onmousemove' => false + ); } - function handle_plugin_args_cruft(&$argstr, &$args) { + + function handle_plugin_args_cruft(&$argstr, &$args) + { $this->source = $argstr; } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { global $WikiTheme; $args = $this->getArgs($argstr, $request); if (empty($this->source)) @@ -54,7 +60,7 @@ extends WikiPlugin $html = HTML(); if (empty($WikiTheme->_asciiSVG)) { $js = JavaScript('', array - ('src' => $WikiTheme->_findData('Processing.js'))); + ('src' => $WikiTheme->_findData('Processing.js'))); if (empty($WikiTheme->_headers_printed)) $WikiTheme->addMoreHeaders($js); else @@ -66,10 +72,10 @@ extends WikiPlugin $this->source = $m[1]; $args['script'] = $m[2]; } - $embedargs = array('width' => $args['width'], - 'height' => $args['height'], - //'src' => "d.svg", - 'script' => $this->source); + $embedargs = array('width' => $args['width'], + 'height' => $args['height'], + //'src' => "d.svg", + 'script' => $this->source); // additional onmousemove argument if ($args['onmousemove']) $embedargs['onmousemove'] = $args['onmousemove']; // we need script='data' and not script="data" @@ -78,10 +84,14 @@ extends WikiPlugin if ($args['script']) $html->pushContent(JavaScript($args['script'])); return $html; } -}; +} -class Processing_HTML extends HtmlElement { - function startTag() { +; + +class Processing_HTML extends HtmlElement +{ + function startTag() + { $start = "<" . $this->_tag; $this->_setClasses(); foreach ($this->_attr as $attr => $val) { diff --git a/lib/plugin/RandomPage.php b/lib/plugin/RandomPage.php index 841b49064..166b1d04e 100644 --- a/lib/plugin/RandomPage.php +++ b/lib/plugin/RandomPage.php @@ -27,29 +27,33 @@ require_once 'lib/PageList.php'; * action=upgrade should deal with pages containing RandomPage modified earlier than 2005-01-24 */ class WikiPlugin_RandomPage -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("RandomPage"); } - function getDescription () { + function getDescription() + { return _("Displays a list of randomly chosen pages or redirects to a random page."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array_merge - ( - PageList::supportedArgs(), - array('numpages' => 20, // was pages - 'pages' => false, // deprecated - 'redirect' => false, - 'hidename' => false, // only for numpages=1 - 'exclude' => $this->default_exclude(), - 'info' => '')); + ( + PageList::supportedArgs(), + array('numpages' => 20, // was pages + 'pages' => false, // deprecated + 'redirect' => false, + 'hidename' => false, // only for numpages=1 + 'exclude' => $this->default_exclude(), + 'info' => '')); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); extract($args); @@ -63,7 +67,7 @@ extends WikiPlugin if (is_integer($pages)) { $numpages = $pages; $pages = false; - // fix new pages handling in arg preprozessor. + // fix new pages handling in arg preprozessor. } elseif (is_array($pages)) { $numpages = (int)$pages[0]; if ($numpages > 0 and !$dbi->isWikiPage($numpages)) $pages = false; @@ -85,20 +89,21 @@ extends WikiPlugin return WikiLink($pagename); } - $numpages = min( max(1, (int) $numpages), 20, count($pagearray)); + $numpages = min(max(1, (int)$numpages), 20, count($pagearray)); $pagelist = new PageList($info, $exclude, $args); $shuffle = array_rand($pagearray, $numpages); if (is_array($shuffle)) { foreach ($shuffle as $i) if (isset($pagearray[$i])) $pagelist->addPage($pagearray[$i]); } else { // if $numpages = 1 - if (isset($pagearray[$shuffle])) - $pagelist->addPage($pagearray[$shuffle]); + if (isset($pagearray[$shuffle])) + $pagelist->addPage($pagearray[$shuffle]); } return $pagelist; } - function default_exclude() { + function default_exclude() + { // Some useful default pages to exclude. $default_exclude = 'RandomPage,HomePage,AllPages,RecentChanges,RecentEdits,FullRecentChanges'; foreach (explode(",", $default_exclude) as $e) { @@ -106,7 +111,9 @@ extends WikiPlugin } return implode(",", $exclude); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/RateIt.php b/lib/plugin/RateIt.php index e4453da73..fa2a6838f 100644 --- a/lib/plugin/RateIt.php +++ b/lib/plugin/RateIt.php @@ -82,36 +82,40 @@ require_once 'lib/WikiPlugin.php'; require_once 'lib/wikilens/RatingsDb.php'; class WikiPlugin_RateIt -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("RateIt"); } - function getDescription() { + + function getDescription() + { return _("Rating system. Store user ratings per page"); } - function RatingWidgetJavascript() { + function RatingWidgetJavascript() + { global $WikiTheme; if (!empty($this->imgPrefix)) $imgPrefix = $this->imgPrefix; elseif (defined("RATEIT_IMGPREFIX")) - $imgPrefix = RATEIT_IMGPREFIX; - else $imgPrefix = ''; - if ($imgPrefix and !$WikiTheme->_findData("images/RateIt".$imgPrefix."Nk0.png",1)) + $imgPrefix = RATEIT_IMGPREFIX; else $imgPrefix = ''; + if ($imgPrefix and !$WikiTheme->_findData("images/RateIt" . $imgPrefix . "Nk0.png", 1)) $imgPrefix = ''; - $img = substr($WikiTheme->_findData("images/RateIt".$imgPrefix."Nk0.png"),0,-7); - $urlprefix = WikiURL("",0,1); // TODO: check actions USE_PATH_INFO=false - $js_globals = "var rateit_imgsrc = '".$img."'; -var rateit_action = '".urlencode("RateIt")."'; + $img = substr($WikiTheme->_findData("images/RateIt" . $imgPrefix . "Nk0.png"), 0, -7); + $urlprefix = WikiURL("", 0, 1); // TODO: check actions USE_PATH_INFO=false + $js_globals = "var rateit_imgsrc = '" . $img . "'; +var rateit_action = '" . urlencode("RateIt") . "'; "; $WikiTheme->addMoreHeaders - (JavaScript('', - array('src' => $WikiTheme->_findData('themes/wikilens/wikilens.js')))); + (JavaScript('', + array('src' => $WikiTheme->_findData('themes/wikilens/wikilens.js')))); return JavaScript($js_globals); } - function actionImgPath() { + function actionImgPath() + { global $WikiTheme; return $WikiTheme->_findFile("images/RateItAction.png", 1); } @@ -120,46 +124,50 @@ var rateit_action = '".urlencode("RateIt")."'; * Take a string and quote it sufficiently to be passed as a Javascript * string between ''s */ - function _javascript_quote_string($s) { + function _javascript_quote_string($s) + { return str_replace("'", "\'", $s); } - function getDefaultArguments() { - return array( 'pagename' => '[pagename]', - 'version' => false, - 'id' => 'rateit', - 'imgPrefix' => '', // '' or BStar or Star - 'dimension' => false, - 'small' => false, - 'show' => false, - 'mode' => false, - ); + function getDefaultArguments() + { + return array('pagename' => '[pagename]', + 'version' => false, + 'id' => 'rateit', + 'imgPrefix' => '', // '' or BStar or Star + 'dimension' => false, + 'small' => false, + 'show' => false, + 'mode' => false, + ); } - function head() { // early side-effects (before body) + function head() + { // early side-effects (before body) global $WikiTheme; static $_already; if (!empty($_already)) return; $_already = 1; $WikiTheme->addMoreHeaders(JavaScript( -"var prediction = new Array; var rating = new Array; + "var prediction = new Array; var rating = new Array; var avg = new Array; var numusers = new Array; -var msg_rating_votes = '"._("Rating: %.1f (%d votes)")."'; -var msg_curr_rating = '"._("Your current rating: ")."'; -var msg_curr_prediction = '"._("Your current prediction: ")."'; -var msg_chg_rating = '"._("Change your rating from ")."'; -var msg_to = '"._(" to ")."'; -var msg_add_rating = '"._("Add your rating: ")."'; -var msg_thanks = '"._("Thanks!")."'; -var msg_rating_deleted = '"._("Rating deleted!")."'; +var msg_rating_votes = '" . _("Rating: %.1f (%d votes)") . "'; +var msg_curr_rating = '" . _("Your current rating: ") . "'; +var msg_curr_prediction = '" . _("Your current prediction: ") . "'; +var msg_chg_rating = '" . _("Change your rating from ") . "'; +var msg_to = '" . _(" to ") . "'; +var msg_add_rating = '" . _("Add your rating: ") . "'; +var msg_thanks = '" . _("Thanks!") . "'; +var msg_rating_deleted = '" . _("Rating deleted!") . "'; ")); $WikiTheme->addMoreHeaders($this->RatingWidgetJavascript()); } - function displayActionImg ($mode) { + function displayActionImg($mode) + { global $WikiTheme, $request; if (!empty($request->_is_buffering_output)) - ob_end_clean(); // discard any previous output + ob_end_clean(); // discard any previous output // delete the cache $page = $request->getPage(); //$page->set('_cached_html', false); @@ -168,7 +176,7 @@ var msg_rating_deleted = '"._("Rating deleted!")."'; $dbi->touch(); //fake validators without args $request->appendValidators(array('wikiname' => WIKI_NAME, - 'args' => wikihash(''))); + 'args' => wikihash(''))); $request->discardOutput(); $actionImg = $WikiTheme->_path . $this->actionImgPath(); if (file_exists($actionImg)) { @@ -177,13 +185,14 @@ var msg_rating_deleted = '"._("Rating deleted!")."'; } else { header('Content-type: image/png'); echo base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAIAAAACAQMAAABIeJ9nAAAAA1BMVEX///' - .'+nxBvIAAAAAXRSTlMAQObYZgAAABNJREFUeF4NwAEBAAAAgJD+r5YGAAQAAXHhfPAAAAAASUVORK5CYII='); + . '+nxBvIAAAAAXRSTlMAQObYZgAAABNJREFUeF4NwAEBAAAAgJD+r5YGAAQAAXHhfPAAAAAASUVORK5CYII='); } exit; } // Only for signed users done in template only yet. - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { global $WikiTheme; //$this->_request = & $request; //$this->_dbi = & $dbi; @@ -227,21 +236,21 @@ var msg_rating_deleted = '"._("Rating deleted!")."'; $rdbi->deleteRating($this->userid, $this->pagename, $this->dimension); unset($this->rating); $this->displayActionImg('delete'); - } elseif (! $args['show'] ) { + } elseif (!$args['show']) { return $this->RatingWidgetHtml($args['pagename'], $args['version'], $args['imgPrefix'], - $args['dimension'], $args['small']); + $args['dimension'], $args['small']); } else { //if (!$user->isSignedIn()) return $this->error(_("You must sign in")); //extract($args); - $this->rating = $rdbi->getRating($this->userid, $this->pagename, $this->dimension); - $this->avg = $rdbi->getAvg($this->pagename, $this->dimension); + $this->rating = $rdbi->getRating($this->userid, $this->pagename, $this->dimension); + $this->avg = $rdbi->getAvg($this->pagename, $this->dimension); $this->numusers = $rdbi->getNumUsers($this->pagename, $this->dimension); // Update this text on rateit in javascript. needed: NumUsers, Avg $html = HTML::div - ( - HTML::span(array('class' => 'rateit'), - sprintf(_("Rating: %.1f (%d votes)"), - $this->avg, $this->numusers))); + ( + HTML::span(array('class' => 'rateit'), + sprintf(_("Rating: %.1f (%d votes)"), + $this->avg, $this->numusers))); if ($args['show'] == 'top') { if (ENABLE_PAGE_PUBLIC) { $page = $dbi->getPage($this->pagename); @@ -250,28 +259,28 @@ var msg_rating_deleted = '"._("Rating deleted!")."'; } $html->setAttr('id', "rateit-widget-top"); $html->pushContent(HTML::br(), - $this->RatingWidgetHtml($args['pagename'], $args['version'], - $args['imgPrefix'], - $args['dimension'], $args['small'])); + $this->RatingWidgetHtml($args['pagename'], $args['version'], + $args['imgPrefix'], + $args['dimension'], $args['small'])); } elseif ($args['show'] == 'text') { if (!$WikiTheme->DUMP_MODE) $html->pushContent(HTML::br(), - sprintf(_("Your rating was %.1f"), - $this->rating)); + sprintf(_("Your rating was %.1f"), + $this->rating)); } elseif ($this->rating) { $html->pushContent(HTML::br(), - sprintf(_("Your rating was %.1f"), - $this->rating)); + sprintf(_("Your rating was %.1f"), + $this->rating)); } else { - $this->pred = $rdbi->getPrediction($this->userid, $this->pagename, $this->dimension); - if (is_string($this->pred)) + $this->pred = $rdbi->getPrediction($this->userid, $this->pagename, $this->dimension); + if (is_string($this->pred)) $html->pushContent(HTML::br(), - sprintf(_("Prediction: %s"), - $this->pred)); + sprintf(_("Prediction: %s"), + $this->pred)); elseif ($this->pred) $html->pushContent(HTML::br(), - sprintf(_("Prediction: %.1f"), - $this->pred)); + sprintf(_("Prediction: %.1f"), + $this->pred)); } //$html->pushContent(HTML::p()); //$html->pushContent(HTML::em("(Experimental: This might be entirely bogus data)")); @@ -280,18 +289,19 @@ var msg_rating_deleted = '"._("Rating deleted!")."'; } // box is used to display a fixed-width, narrow version with common header - function box($args=false, $request=false, $basepage=false) { + function box($args = false, $request = false, $basepage = false) + { if (!$request) $request =& $GLOBALS['request']; if (!$request->_user->isSignedIn()) return; if (!isset($args)) $args = array(); $args['small'] = 1; $argstr = ''; foreach ($args as $key => $value) - $argstr .= $key."=".$value; + $argstr .= $key . "=" . $value; $widget = $this->run($request->_dbi, $argstr, $request, $basepage); - return $this->makeBox(WikiLink(_("RateIt"),'',_("Rate It")), - $widget); + return $this->makeBox(WikiLink(_("RateIt"), '', _("Rate It")), + $widget); } /** @@ -310,34 +320,35 @@ var msg_rating_deleted = '"._("Rating deleted!")."'; * Limitations: Currently this can only print the current users ratings. * And only the widget, but no value (for buddies) also. */ - function RatingWidgetHtml($pagename, $version, $imgPrefix, $dimension, $small = false) { + function RatingWidgetHtml($pagename, $version, $imgPrefix, $dimension, $small = false) + { global $WikiTheme, $request; $dbi =& $request->_dbi; $version = $dbi->_backend->get_latest_version($pagename); - $pageid = sprintf("%u",crc32($pagename)); // MangleXmlIdentifier($pagename) + $pageid = sprintf("%u", crc32($pagename)); // MangleXmlIdentifier($pagename) $imgId = 'RateIt' . $pageid; - $actionImgName = 'RateIt'.$pageid.'Action'; + $actionImgName = 'RateIt' . $pageid . 'Action'; //$rdbi =& $this->_rdbi; $rdbi = RatingsDb::getTheRatingsDb(); // check if the imgPrefix icons exist. - if (! $WikiTheme->_findData("images/RateIt".$imgPrefix."Nk0.png", true)) + if (!$WikiTheme->_findData("images/RateIt" . $imgPrefix . "Nk0.png", true)) $imgPrefix = ''; // Protect against \'s, though not \r or \n $reImgPrefix = $this->_javascript_quote_string($imgPrefix); - $reImgId = $this->_javascript_quote_string($imgId); + $reImgId = $this->_javascript_quote_string($imgId); $reActionImgName = $this->_javascript_quote_string($actionImgName); - $rePagename = $this->_javascript_quote_string($pagename); + $rePagename = $this->_javascript_quote_string($pagename); //$dimension = $args['pagename'] . "rat"; $html = HTML::span(array("class" => "rateit-widget", "id" => $imgId)); - for ($i=0; $i < 2; $i++) { - $ok[$i] = $WikiTheme->_findData("images/RateIt".$imgPrefix."Ok".$i.".png"); // empty - $nk[$i] = $WikiTheme->_findData("images/RateIt".$imgPrefix."Nk".$i.".png"); // rated - $rk[$i] = $WikiTheme->_findData("images/RateIt".$imgPrefix."Rk".$i.".png"); // pred + for ($i = 0; $i < 2; $i++) { + $ok[$i] = $WikiTheme->_findData("images/RateIt" . $imgPrefix . "Ok" . $i . ".png"); // empty + $nk[$i] = $WikiTheme->_findData("images/RateIt" . $imgPrefix . "Nk" . $i . ".png"); // rated + $rk[$i] = $WikiTheme->_findData("images/RateIt" . $imgPrefix . "Rk" . $i . ".png"); // pred } if (empty($this->userid)) { @@ -354,22 +365,20 @@ var msg_rating_deleted = '"._("Rating deleted!")."'; for ($i = 1; $i <= 10; $i++) { $j = $i / 2; $a1 = HTML::a(array('href' => "javascript:clickRating('$reImgPrefix','$rePagename','$version'," - ."'$reImgId','$dimension',$j)")); + . "'$reImgId','$dimension',$j)")); $img_attr = array(); - $img_attr['src'] = $nk[$i%2]; + $img_attr['src'] = $nk[$i % 2]; if ($this->rating) { - $img_attr['src'] = $ok[$i%2]; + $img_attr['src'] = $ok[$i % 2]; $img_attr['onmouseover'] = "displayRating('$reImgId','$reImgPrefix',$j,0,1)"; - $img_attr['onmouseout'] = "displayRating('$reImgId','$reImgPrefix',$this->rating,0,1)"; - } - else if (!$this->rating and $this->pred) { - $img_attr['src'] = $rk[$i%2]; + $img_attr['onmouseout'] = "displayRating('$reImgId','$reImgPrefix',$this->rating,0,1)"; + } else if (!$this->rating and $this->pred) { + $img_attr['src'] = $rk[$i % 2]; $img_attr['onmouseover'] = "displayRating('$reImgId','$reImgPrefix',$j,1,1)"; - $img_attr['onmouseout'] = "displayRating('$reImgId','$reImgPrefix',$this->pred,1,1)"; - } - else { + $img_attr['onmouseout'] = "displayRating('$reImgId','$reImgPrefix',$this->pred,1,1)"; + } else { $img_attr['onmouseover'] = "displayRating('$reImgId','$reImgPrefix',$j,0,1)"; - $img_attr['onmouseout'] = "displayRating('$reImgId','$reImgPrefix',0,0,1)"; + $img_attr['onmouseout'] = "displayRating('$reImgId','$reImgPrefix',0,0,1)"; } //$imgName = 'RateIt'.$reImgId.$i; $img_attr['id'] = $imgId . $i; @@ -384,12 +393,12 @@ var msg_rating_deleted = '"._("Rating deleted!")."'; $html->pushContent(HTML::Raw(" ")); $a0 = HTML::a(array('href' => "javascript:clickRating('$reImgPrefix','$rePagename','$version'," - ."'$reImgId','$dimension','X')")); + . "'$reImgId','$dimension','X')")); $msg = _("Cancel your rating"); - $imgprops = array('src' => $WikiTheme->getImageUrl("RateIt".$imgPrefix."Cancel"), - 'id' => $imgId.$imgPrefix.'Cancel', - 'alt' => $msg, - 'title' => $msg); + $imgprops = array('src' => $WikiTheme->getImageUrl("RateIt" . $imgPrefix . "Cancel"), + 'id' => $imgId . $imgPrefix . 'Cancel', + 'alt' => $msg, + 'title' => $msg); if (!$this->rating) $imgprops['style'] = 'display:none'; $a0->pushContent(HTML::img($imgprops)); @@ -421,20 +430,22 @@ var msg_rating_deleted = '"._("Rating deleted!")."'; if ($this->rating) { $js .= "rating['$reImgId']=$this->rating; prediction['$reImgId']=$pred;\n"; $html->pushContent(JavaScript($js - ."displayRating('$reImgId','$reImgPrefix',$this->rating,0,1);")); + . "displayRating('$reImgId','$reImgPrefix',$this->rating,0,1);")); } elseif (!empty($this->pred)) { $js .= "rating['$reImgId']=0; prediction['$reImgId']=$this->pred;\n"; $html->pushContent(JavaScript($js - ."displayRating('$reImgId','$reImgPrefix',$this->pred,1,1);")); + . "displayRating('$reImgId','$reImgPrefix',$this->pred,1,1);")); } else { $js .= "rating['$reImgId']=0; prediction['$reImgId']=0;\n"; $html->pushContent(JavaScript($js - ."displayRating('$reImgId','$reImgPrefix',0,0,1);")); + . "displayRating('$reImgId','$reImgPrefix',0,0,1);")); } return $html; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/RawHtml.php b/lib/plugin/RawHtml.php index e7560b15a..afed48a81 100644 --- a/lib/plugin/RawHtml.php +++ b/lib/plugin/RawHtml.php @@ -47,29 +47,34 @@ if (!defined('ENABLE_RAW_HTML_SAFE')) * A plugin to provide for raw HTML within wiki pages. */ class WikiPlugin_RawHtml -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return "RawHtml"; } - function getDescription () { + function getDescription() + { return _("A plugin to provide for raw HTML within wiki pages."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array(); } - function managesValidators() { + function managesValidators() + { // The plugin output will only change if the plugin // invocation (page text) changes --- so the necessary // validators have already been handled by displayPage. return true; } - function run($dbi, $argstr, &$request, $basepage) { - if (!defined('ENABLE_RAW_HTML') || ! ENABLE_RAW_HTML) { + function run($dbi, $argstr, &$request, $basepage) + { + if (!defined('ENABLE_RAW_HTML') || !ENABLE_RAW_HTML) { return $this->disabled(_("Raw HTML is disabled in this wiki.")); } if (!$basepage) { @@ -78,9 +83,9 @@ extends WikiPlugin $page = $request->getPage($basepage); if (ENABLE_RAW_HTML_LOCKEDONLY) { - if (! $page->get('locked')) { + if (!$page->get('locked')) { return $this->disabled(fmt("%s is only allowed in locked pages.", - _("Raw HTML"))); + _("Raw HTML"))); } } if (ENABLE_RAW_HTML_SAFE) { @@ -103,65 +108,66 @@ extends WikiPlugin // safe_html by Chris Snyder (csnyder@chxo.com) for http://pcoms.net // - Huge thanks to James Wetterau for testing and feedback! -/* -Copyright 2003 Chris Snyder. All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - -THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* - set of functions for sanitizing user input: - keeps "friendly" tags but strips javascript events and style attributes - closes any open comment tags - closes any open HTML tags - results may not be valid HTML, but - at least they will keep the rest of the page from breaking - - treats the following as malicious conditions and returns text stripped - of all html tags: - any instances of ='javascript: - event or style attributes remaining after initial replacement -*/ - - function strip_attributes ($html, $attrs) { + /* + Copyright 2003 Chris Snyder. All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + /* + set of functions for sanitizing user input: + keeps "friendly" tags but strips javascript events and style attributes + closes any open comment tags + closes any open HTML tags - results may not be valid HTML, but + at least they will keep the rest of the page from breaking + + treats the following as malicious conditions and returns text stripped + of all html tags: + any instances of ='javascript: + event or style attributes remaining after initial replacement + */ + + function strip_attributes($html, $attrs) + { if (!is_array($attrs)) { - $array= array( "$attrs" ); + $array = array("$attrs"); unset($attrs); - $attrs= $array; + $attrs = $array; } foreach ($attrs AS $attribute) { // once for ", once for ', s makes the dot match linebreaks, too. - $search[]= "/".$attribute.'\s*=\s*".+"/Uis'; - $search[]= "/".$attribute."\s*=\s*'.+'/Uis"; + $search[] = "/" . $attribute . '\s*=\s*".+"/Uis'; + $search[] = "/" . $attribute . "\s*=\s*'.+'/Uis"; // and once more for unquoted attributes - $search[]= "/".$attribute."\s*=\s*\S+/i"; + $search[] = "/" . $attribute . "\s*=\s*\S+/i"; } - $html= preg_replace($search, "", $html); + $html = preg_replace($search, "", $html); // check for additional matches and strip all tags if found foreach ($search AS $pattern) { if (preg_match($pattern, $html)) { - $html= strip_tags($html); + $html = strip_tags($html); break; } } @@ -169,58 +175,58 @@ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. return $html; } - function safe_html ($html, $allowedtags="") { - $version= "safe_html.php/0.4"; + function safe_html($html, $allowedtags = "") + { + $version = "safe_html.php/0.4"; // anything with ="javascript: is right out -- strip all tags and return if found - $pattern= "/=\s*\S+script:\S+/Ui"; + $pattern = "/=\s*\S+script:\S+/Ui"; if (preg_match($pattern, $html)) { - $html= strip_tags($html); + $html = strip_tags($html); return $html; } // setup -- $allowedtags is an array of $tag=>$closeit pairs, where $tag is an HTML tag to allow and $closeit is 1 if the tag requires a matching, closing tag - if ($allowedtags=="") { - $allowedtags= array ( "p"=>1, "br"=>0, "a"=>1, "img"=>0, "li"=>1, - "ol"=>1, "ul"=>1, "b"=>1, "i"=>1, "em"=>1, "strong"=>1, "del"=>1, "ins"=>1, - "sub"=>1, "sup"=>1, "u"=>1, "blockquote"=>1, "pre"=>1, "hr"=>0, - "table"=>1, "thead"=>1, "tfoot"=>1, "tbody"=>1, "tr"=>1, "td"=>1, "th"=>1, - ); - } - elseif (!is_array($allowedtags)) { - $array= array( "$allowedtags" ); + if ($allowedtags == "") { + $allowedtags = array("p" => 1, "br" => 0, "a" => 1, "img" => 0, "li" => 1, + "ol" => 1, "ul" => 1, "b" => 1, "i" => 1, "em" => 1, "strong" => 1, "del" => 1, "ins" => 1, + "sub" => 1, "sup" => 1, "u" => 1, "blockquote" => 1, "pre" => 1, "hr" => 0, + "table" => 1, "thead" => 1, "tfoot" => 1, "tbody" => 1, "tr" => 1, "td" => 1, "th" => 1, + ); + } elseif (!is_array($allowedtags)) { + $array = array("$allowedtags"); unset($allowedtags); - $allowedtags= $array; + $allowedtags = $array; } // there's some debate about this.. is strip_tags() better than rolling your own regex? // note: a bug in PHP 4.3.1 caused improper handling of ! in tag attributes when using strip_tags() - $stripallowed= ""; - foreach ($allowedtags AS $tag=>$closeit) { - $stripallowed.= "<$tag>"; + $stripallowed = ""; + foreach ($allowedtags AS $tag => $closeit) { + $stripallowed .= "<$tag>"; } //print "Stripallowed: $stripallowed -- ".print_r($allowedtags,1); - $html= strip_tags($html, $stripallowed); + $html = strip_tags($html, $stripallowed); // also, lets get rid of some pesky attributes that may be set on the remaining tags... - $badattrs= array("on\w+", "style"); - $html= $this->strip_attributes($html, $badattrs); + $badattrs = array("on\w+", "style"); + $html = $this->strip_attributes($html, $badattrs); // close html tags if necessary -- note that this WON'T be graceful formatting-wise, it just has to fix any maliciousness - foreach ($allowedtags AS $tag=>$closeit) { + foreach ($allowedtags AS $tag => $closeit) { if (!$closeit) continue; - $patternopen= "/<$tag\b[^>]*>/Ui"; - $patternclose= "/<\/$tag\b[^>]*>/Ui"; - $totalopen= preg_match_all ( $patternopen, $html, $matches ); - $totalclose= preg_match_all ( $patternclose, $html, $matches2 ); - if ($totalopen>$totalclose) { - $html.= str_repeat("", ($totalopen - $totalclose)); + $patternopen = "/<$tag\b[^>]*>/Ui"; + $patternclose = "/<\/$tag\b[^>]*>/Ui"; + $totalopen = preg_match_all($patternopen, $html, $matches); + $totalclose = preg_match_all($patternclose, $html, $matches2); + if ($totalopen > $totalclose) { + $html .= str_repeat("", ($totalopen - $totalclose)); } } // close any open "; + $html .= ""; return $html; } } diff --git a/lib/plugin/RecentChanges.php b/lib/plugin/RecentChanges.php index c4d729a82..59cbcfd18 100644 --- a/lib/plugin/RecentChanges.php +++ b/lib/plugin/RecentChanges.php @@ -28,7 +28,8 @@ class _RecentChanges_Formatter var $_absurls = false; var $action = "RecentChanges"; - function _RecentChanges_Formatter ($rc_args) { + function _RecentChanges_Formatter($rc_args) + { $this->_args = $rc_args; $this->_diffargs = array('action' => 'diff'); @@ -40,7 +41,8 @@ class _RecentChanges_Formatter $this->_args['daylist'] = false; } - function title () { + function title() + { global $request; extract($this->_args); if ($author) { @@ -48,13 +50,13 @@ class _RecentChanges_Formatter if ($title == '[]') { $title = $request->_user->getID(); } - $title = _("UserContribs").": $title"; + $title = _("UserContribs") . ": $title"; } elseif ($owner) { $title = $owner; if ($title == '[]') { $title = $request->_user->getID(); } - $title = _("UserContribs").": $title"; + $title = _("UserContribs") . ": $title"; } elseif ($only_new) { $title = _("RecentNewPages"); } elseif ($show_minor) { @@ -68,21 +70,25 @@ class _RecentChanges_Formatter return $title; } - function include_versions_in_URLs() { - return (bool) $this->_args['show_all']; + function include_versions_in_URLs() + { + return (bool)$this->_args['show_all']; } - function date ($rev) { + function date($rev) + { global $WikiTheme; return $WikiTheme->getDay($rev->get('mtime')); } - function time ($rev) { + function time($rev) + { global $WikiTheme; return $WikiTheme->formatTime($rev->get('mtime')); } - function diffURL ($rev) { + function diffURL($rev) + { $args = $this->_diffargs; if ($this->include_versions_in_URLs()) $args['version'] = $rev->getVersion(); @@ -90,29 +96,34 @@ class _RecentChanges_Formatter return WikiURL($page->getName(), $args, $this->_absurls); } - function historyURL ($rev) { + function historyURL($rev) + { $page = $rev->getPage(); return WikiURL($page, array('action' => _("PageHistory")), - $this->_absurls); + $this->_absurls); } - function pageURL ($rev) { + function pageURL($rev) + { return WikiURL($this->include_versions_in_URLs() ? $rev : $rev->getPage(), - '', $this->_absurls); + '', $this->_absurls); } - function authorHasPage ($author) { + function authorHasPage($author) + { global $WikiNameRegexp, $request; $dbi = $request->getDbh(); return isWikiWord($author) && $dbi->isWikiPage($author); } - function authorURL ($author) { + function authorURL($author) + { return $this->authorHasPage() ? WikiURL($author) : false; } - function status ($rev) { + function status($rev) + { if ($rev->hasDefaultContents()) return 'deleted'; $page = $rev->getPage(); @@ -122,12 +133,14 @@ class _RecentChanges_Formatter return 'updated'; } - function importance ($rev) { + function importance($rev) + { return $rev->get('is_minor_edit') ? 'minor' : 'major'; } - function summary($rev) { - if ( ($summary = $rev->get('summary')) ) + function summary($rev) + { + if (($summary = $rev->get('summary'))) return $summary; switch ($this->status($rev)) { @@ -140,43 +153,48 @@ class _RecentChanges_Formatter } } - function setValidators($most_recent_rev) { + function setValidators($most_recent_rev) + { $rev = $most_recent_rev; $validators = array('RecentChanges-top' => - array($rev->getPageName(), $rev->getVersion()), - '%mtime' => $rev->get('mtime')); + array($rev->getPageName(), $rev->getVersion()), + '%mtime' => $rev->get('mtime')); global $request; $request->appendValidators($validators); } } class _RecentChanges_HtmlFormatter -extends _RecentChanges_Formatter + extends _RecentChanges_Formatter { - function diffLink ($rev) { + function diffLink($rev) + { global $WikiTheme; $button = $WikiTheme->makeButton(_("diff"), $this->diffURL($rev), 'wiki-rc-action'); $button->setAttr('rel', 'nofollow'); - return HTML("(",$button,")"); + return HTML("(", $button, ")"); } /* deletions: red, additions: green */ - function diffSummary ($rev) { + function diffSummary($rev) + { $html = $this->diffURL($rev); return ''; } - function historyLink ($rev) { + function historyLink($rev) + { global $WikiTheme; $button = $WikiTheme->makeButton(_("hist"), $this->historyURL($rev), 'wiki-rc-action'); $button->setAttr('rel', 'nofollow'); - return HTML("(",$button,")"); + return HTML("(", $button, ")"); } - function pageLink ($rev, $link_text=false) { + function pageLink($rev, $link_text = false) + { return WikiLink($this->include_versions_in_URLs() ? $rev : $rev->getPage(), - 'auto', $link_text); + 'auto', $link_text); /* $page = $rev->getPage(); global $WikiTheme; @@ -198,48 +216,52 @@ extends _RecentChanges_Formatter */ } - function authorLink ($rev) { + function authorLink($rev) + { return WikiLink($rev->get('author'), 'if_known'); } /* Link to all users contributions (contribs and owns) */ - function authorContribs ($rev) { + function authorContribs($rev) + { $author = $rev->get('author'); if (preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $author)) return ''; return HTML('(', - Button(array('action' => _("RecentChanges"), - 'format' => 'contribs', - 'author' => $author, - 'days' => 360), - _("contribs"), - $author), - ' | ', - Button(array('action' => _("RecentChanges"), - 'format' => 'contribs', - 'owner' => $author, - 'days' => 360), - _("new pages"), - $author), - ')'); - } - - function summaryAsHTML ($rev) { - if ( !($summary = $this->summary($rev)) ) + Button(array('action' => _("RecentChanges"), + 'format' => 'contribs', + 'author' => $author, + 'days' => 360), + _("contribs"), + $author), + ' | ', + Button(array('action' => _("RecentChanges"), + 'format' => 'contribs', + 'owner' => $author, + 'days' => 360), + _("new pages"), + $author), + ')'); + } + + function summaryAsHTML($rev) + { + if (!($summary = $this->summary($rev))) return ''; - return HTML::span( array('class' => 'wiki-summary'), - "(", - // TransformLinks($summary, $rev->get('markup'), $rev->getPageName()), - // We do parse the summary: - // 1) if the summary contains {{foo}}, the template must no be - // expanded - // 2) if the summary contains camel case, and DISABLE_MARKUP_WIKIWORD - // is true, the camel case must not be linked. - // Side-effect: brackets are not linked. TBD. - $summary, - ")"); - } - - function format_icon ($format, $filter = array()) { + return HTML::span(array('class' => 'wiki-summary'), + "(", + // TransformLinks($summary, $rev->get('markup'), $rev->getPageName()), + // We do parse the summary: + // 1) if the summary contains {{foo}}, the template must no be + // expanded + // 2) if the summary contains camel case, and DISABLE_MARKUP_WIKIWORD + // is true, the camel case must not be linked. + // Side-effect: brackets are not linked. TBD. + $summary, + ")"); + } + + function format_icon($format, $filter = array()) + { global $request, $WikiTheme; $args = $this->_args; // remove links not used for those formats @@ -247,38 +269,62 @@ extends _RecentChanges_Formatter unset($args['difflinks']); unset($args['historylinks']); $rss_url = $request->getURLtoSelf - (array_merge($args, - array('action' => $this->action, 'format' => $format), - $filter)); + (array_merge($args, + array('action' => $this->action, 'format' => $format), + $filter)); return $WikiTheme->makeButton($format, $rss_url, 'rssicon'); } - function rss_icon ($args=array()) { return $this->format_icon("rss", $args); } - function rss2_icon ($args=array()) { return $this->format_icon("rss2", $args); } - function atom_icon ($args=array()) { return $this->format_icon("atom", $args); } - function rdf_icon ($args=array()) { return DEBUG ? $this->format_icon("rdf", $args) : ''; } - function rdfs_icon ($args=array()) { return DEBUG ? $this->format_icon("rdfs", $args) : ''; } - function owl_icon ($args=array()) { return DEBUG ? $this->format_icon("owl", $args) : ''; } + function rss_icon($args = array()) + { + return $this->format_icon("rss", $args); + } + + function rss2_icon($args = array()) + { + return $this->format_icon("rss2", $args); + } + + function atom_icon($args = array()) + { + return $this->format_icon("atom", $args); + } + + function rdf_icon($args = array()) + { + return DEBUG ? $this->format_icon("rdf", $args) : ''; + } + + function rdfs_icon($args = array()) + { + return DEBUG ? $this->format_icon("rdfs", $args) : ''; + } + + function owl_icon($args = array()) + { + return DEBUG ? $this->format_icon("owl", $args) : ''; + } - function grazr_icon ($args = array()) { + function grazr_icon($args = array()) + { global $request, $WikiTheme; if (is_localhost()) return ''; if (SERVER_PROTOCOL == "https") return ''; $our_url = WikiURL($request->getArg('pagename'), - array_merge(array('action' => $this->action, 'format' => 'rss2'), $args), - true); + array_merge(array('action' => $this->action, 'format' => 'rss2'), $args), + true); $rss_url = 'http://grazr.com/gzpanel.html?' . $our_url; return $WikiTheme->makeButton("grazr", $rss_url, 'rssicon'); } - function pre_description () { + function pre_description() + { extract($this->_args); // FIXME: say something about show_all. if ($show_major && $show_minor) $edits = _("edits"); elseif ($show_major) - $edits = _("major edits"); - else + $edits = _("major edits"); else $edits = _("minor edits"); if (isset($caption) and $caption == _("Recent Comments")) $edits = _("comments"); @@ -327,68 +373,69 @@ extends _RecentChanges_Formatter if ($timespan) { if (intval($days) == 1) $desc = fmt("The %d most recent %s during the past day are listed below.", - $limit, $edits); + $limit, $edits); else $desc = fmt("The %d most recent %s during the past %s days are listed below.", - $limit, $edits, $days); + $limit, $edits, $days); } else $desc = fmt("The %d most recent %s are listed below.", - $limit, $edits); - } - elseif ($limit < 0) { //$limit < 0 means we want oldest pages + $limit, $edits); + } elseif ($limit < 0) { //$limit < 0 means we want oldest pages if ($timespan) { if (intval($days) == 1) $desc = fmt("The %d oldest %s during the past day are listed below.", - $lmt, $edits); + $lmt, $edits); else $desc = fmt("The %d oldest %s during the past %s days are listed below.", - $lmt, $edits, $days); + $lmt, $edits, $days); } else $desc = fmt("The %d oldest %s are listed below.", - $lmt, $edits); - } - - else { + $lmt, $edits); + } else { if ($timespan) { if (intval($days) == 1) $desc = fmt("The most recent %s during the past day are listed below.", - $edits); + $edits); else $desc = fmt("The most recent %s during the past %s days are listed below.", - $edits, $days); + $edits, $days); } else $desc = fmt("All %s are listed below.", $edits); } return $desc; } - function description() { + function description() + { return HTML::p(false, $this->pre_description()); } /* was title */ - function headline () { + function headline() + { extract($this->_args); return array($this->title(), - ' ', - $this->rss_icon(), - $this->rss2_icon(), - $this->atom_icon(), - $this->rdf_icon(), - /*$this->rdfs_icon(), - $this->owl_icon(),*/ - $this->grazr_icon(), - $this->sidebar_link()); - } - - function empty_message() { + ' ', + $this->rss_icon(), + $this->rss2_icon(), + $this->atom_icon(), + $this->rdf_icon(), + /*$this->rdfs_icon(), + $this->owl_icon(),*/ + $this->grazr_icon(), + $this->sidebar_link()); + } + + function empty_message() + { if (isset($this->_args['caption']) and $this->_args['caption'] == _("Recent Comments")) return _("No comments found"); else return _("No changes found"); } - function sidebar_link() { + function sidebar_link() + { extract($this->_args); $pagetitle = $show_minor ? _("RecentEdits") : _("RecentChanges"); @@ -397,26 +444,27 @@ extends _RecentChanges_Formatter $addsidebarjsfunc = "function addPanel() {\n" - ." window.sidebar.addPanel (\"" . sprintf("%s - %s", WIKI_NAME, $pagetitle) . "\",\n" - ." \"$sidebarurl\",\"\");\n" - ."}\n"; + . " window.sidebar.addPanel (\"" . sprintf("%s - %s", WIKI_NAME, $pagetitle) . "\",\n" + . " \"$sidebarurl\",\"\");\n" + . "}\n"; $jsf = JavaScript($addsidebarjsfunc); global $WikiTheme; $sidebar_button = $WikiTheme->makeButton("sidebar", 'javascript:addPanel();', 'sidebaricon', - array('title' => _("Click to add this feed to your sidebar"), - 'style' => 'font-size:9pt;font-weight:normal; vertical-align:middle;')); + array('title' => _("Click to add this feed to your sidebar"), + 'style' => 'font-size:9pt;font-weight:normal; vertical-align:middle;')); $addsidebarjsclick = asXML($sidebar_button); $jsc = JavaScript("if ((typeof window.sidebar == 'object') &&\n" - ." (typeof window.sidebar.addPanel == 'function'))\n" - ." {\n" - ." document.write('$addsidebarjsclick');\n" - ." }\n" - ); + . " (typeof window.sidebar.addPanel == 'function'))\n" + . " {\n" + . " document.write('$addsidebarjsclick');\n" + . " }\n" + ); return HTML(new RawXML("\n"), $jsf, new RawXML("\n"), $jsc); } - function format ($changes) { + function format($changes) + { include_once 'lib/InlineParser.php'; $html = HTML(HTML::h2(false, $this->headline())); @@ -454,16 +502,17 @@ extends _RecentChanges_Formatter if ($first) { if ($this->_args['daylist']) $html->pushContent // force display of OptionsButtonBars - (JavaScript - ("document.getElementById('rc-action-body').style.display='block';")); + (JavaScript + ("document.getElementById('rc-action-body').style.display='block';")); $html->pushContent(HTML::p(array('class' => 'rc-empty'), - $this->empty_message())); + $this->empty_message())); } return $html; } - function format_revision ($rev) { + function format_revision($rev) + { global $WikiTheme; $args = &$this->_args; @@ -472,8 +521,8 @@ extends _RecentChanges_Formatter $time = $this->time($rev); if ($rev->get('is_minor_edit')) { $minor_flag = HTML(" ", - HTML::span(array('class' => 'pageinfo-minoredit'), - "(" . _("minor edit") . ")")); + HTML::span(array('class' => 'pageinfo-minoredit'), + "(" . _("minor edit") . ")")); } else { $time = HTML::span(array('class' => 'pageinfo-majoredit'), $time); $minor_flag = ''; @@ -496,19 +545,19 @@ extends _RecentChanges_Formatter if ((isa($WikiTheme, 'WikiTheme_MonoBook')) or (isa($WikiTheme, 'WikiTheme_fusionforge'))) { $line->pushContent( - $args['historylinks'] ? '' : $this->historyLink($rev), - ' . . ', $linkorname, '; ', - $time, ' . . ', - $this->authorLink($rev),' ', - $this->authorContribs($rev),' ', - $this->summaryAsHTML($rev),' ', - $minor_flag); + $args['historylinks'] ? '' : $this->historyLink($rev), + ' . . ', $linkorname, '; ', + $time, ' . . ', + $this->authorLink($rev), ' ', + $this->authorContribs($rev), ' ', + $this->summaryAsHTML($rev), ' ', + $minor_flag); } else { $line->pushContent($linkorname, ' ', - $time, ' ', - $this->summaryAsHTML($rev), - ' ... ', - $this->authorLink($rev)); + $time, ' ', + $this->summaryAsHTML($rev), + ' ... ', + $this->authorLink($rev)); } return $line; } @@ -519,31 +568,34 @@ extends _RecentChanges_Formatter * 14:41, 3 December 2006 (hist) (diff) Talk:PhpWiki (added diff link) (top) */ class _RecentChanges_UserContribsFormatter -extends _RecentChanges_HtmlFormatter + extends _RecentChanges_HtmlFormatter { - function headline () { + function headline() + { global $request; extract($this->_args); if ($author == '[]') $author = $request->_user->getID(); - if ($owner == '[]') $owner = $request->_user->getID(); + if ($owner == '[]') $owner = $request->_user->getID(); $author_args = $owner ? array('owner' => $owner) : array('author' => $author); - return array(_("UserContribs"),":",$owner ? $owner : $author, - ' ', - $this->rss_icon($author_args), - $this->rss2_icon($author_args), - $this->atom_icon($author_args), - $this->rdf_icon($author_args), - $this->grazr_icon($author_args)); + return array(_("UserContribs"), ":", $owner ? $owner : $author, + ' ', + $this->rss_icon($author_args), + $this->rss2_icon($author_args), + $this->atom_icon($author_args), + $this->rdf_icon($author_args), + $this->grazr_icon($author_args)); } - function format ($changes) { + function format($changes) + { include_once 'lib/InlineParser.php'; $html = HTML(HTML::h2(false, $this->headline())); $lines = HTML::ol(); - $first = true; $count = 0; + $first = true; + $count = 0; while ($rev = $changes->next()) { if (mayAccessPage('view', $rev->_pagename)) { $lines->pushContent($this->format_revision($rev)); @@ -561,61 +613,71 @@ extends _RecentChanges_HtmlFormatter } if ($first) $html->pushContent(HTML::p(array('class' => 'rc-empty'), - $this->empty_message())); + $this->empty_message())); else $html->pushContent($lines); return $html; } - function format_revision ($rev) { + function format_revision($rev) + { $args = &$this->_args; $class = 'rc-' . $this->importance($rev); $time = $this->time($rev); - if (! $rev->get('is_minor_edit')) + if (!$rev->get('is_minor_edit')) $time = HTML::span(array('class' => 'pageinfo-majoredit'), $time); $line = HTML::li(array('class' => $class)); - $line->pushContent($this->time($rev),", "); - $line->pushContent($this->date($rev)," "); + $line->pushContent($this->time($rev), ", "); + $line->pushContent($this->date($rev), " "); $line->pushContent($this->diffLink($rev), ' '); $line->pushContent($this->historyLink($rev), ' '); $line->pushContent($this->pageLink($rev), ' ', - $this->summaryAsHTML($rev)); + $this->summaryAsHTML($rev)); return $line; } } class _RecentChanges_SideBarFormatter -extends _RecentChanges_HtmlFormatter + extends _RecentChanges_HtmlFormatter { - function rss_icon () { + function rss_icon() + { //omit rssicon } - function rss2_icon () { } - function headline () { + + function rss2_icon() + { + } + + function headline() + { //title click opens the normal RC or RE page in the main browser frame extract($this->_args); $titlelink = WikiLink($this->title()); $titlelink->setAttr('target', '_content'); return HTML($this->logo(), $titlelink); } - function logo () { + + function logo() + { //logo click opens the HomePage in the main browser frame global $WikiTheme; $img = HTML::img(array('src' => $WikiTheme->getImageURL('logo'), - 'align' => 'right', - 'style' => 'height:2.5ex' - )); + 'align' => 'right', + 'style' => 'height:2.5ex' + )); $linkurl = WikiLink(HOME_PAGE, false, $img); $linkurl->setAttr('target', '_content'); return $linkurl; } - function authorLink ($rev) { + function authorLink($rev) + { $author = $rev->get('author'); - if ( $this->authorHasPage($author) ) { + if ($this->authorHasPage($author)) { $linkurl = WikiLink($author); $linkurl->setAttr('target', '_content'); // way to do this using parent::authorLink ?? return $linkurl; @@ -623,7 +685,8 @@ extends _RecentChanges_HtmlFormatter return $author; } - function diffLink ($rev) { + function diffLink($rev) + { $linkurl = parent::diffLink($rev); $linkurl->setAttr('target', '_content'); $linkurl->setAttr('rel', 'nofollow'); @@ -631,37 +694,45 @@ extends _RecentChanges_HtmlFormatter $linkurl = new RawXML(str_replace('setAttr('target', '_content'); // FIXME: Smelly hack to get smaller history buttons in sidebar $linkurl = new RawXML(str_replace('setAttr('target', '_content'); return $linkurl; } + // Overriding summaryAsHTML, because there is no way yet to // return summary as transformed text with // links setAttr('target', '_content') in Mozilla sidebar. // So for now don't create clickable links inside summary // in the sidebar, or else they target the sidebar and not the // main content window. - function summaryAsHTML ($rev) { - if ( !($summary = $this->summary($rev)) ) + function summaryAsHTML($rev) + { + if (!($summary = $this->summary($rev))) return ''; return HTML::span(array('class' => 'wiki-summary'), - "[", - /*TransformLinks(*/$summary,/* $rev->get('markup')),*/ - "]"); + "[", + /*TransformLinks(*/ + $summary, /* $rev->get('markup')),*/ + "]"); } - function format ($changes) { + function format($changes) + { $this->_args['daylist'] = false; //don't show day buttons in Mozilla sidebar - $html = _RecentChanges_HtmlFormatter::format ($changes); + $html = _RecentChanges_HtmlFormatter::format($changes); $html = HTML::div(array('class' => 'wikitext'), $html); global $request; $request->discardOutput(); @@ -676,8 +747,7 @@ extends _RecentChanges_HtmlFormatter if (!empty($category)) $title = $category; elseif (!empty($pagematch)) - $title = $pagematch; - else + $title = $pagematch; else $title = WIKI_NAME . $show_minor ? _("RecentEdits") : _("RecentChanges"); printf("" . $title . "\n"); global $WikiTheme; @@ -696,25 +766,42 @@ extends _RecentChanges_HtmlFormatter } class _RecentChanges_BoxFormatter -extends _RecentChanges_HtmlFormatter + extends _RecentChanges_HtmlFormatter { - function rss_icon () { + function rss_icon() + { } - function rss2_icon () { + + function rss2_icon() + { } - function headline () { + + function headline() + { } - function authorLink ($rev) { + + function authorLink($rev) + { } - function diffLink ($rev) { + + function diffLink($rev) + { } - function historyLink ($rev) { + + function historyLink($rev) + { } - function summaryAsHTML ($rev) { + + function summaryAsHTML($rev) + { } - function description () { + + function description() + { } - function format ($changes) { + + function format($changes) + { include_once 'lib/InlineParser.php'; $last_date = ''; $first = true; @@ -723,9 +810,9 @@ extends _RecentChanges_HtmlFormatter $sp = HTML::Raw("\n · "); while ($rev = $changes->next()) { // enforce view permission - if (mayAccessPage('view',$rev->_pagename)) { - if ($link = $this->pageLink($rev)) // some entries may be empty - // (/Blog/.. interim pages) + if (mayAccessPage('view', $rev->_pagename)) { + if ($link = $this->pageLink($rev)) // some entries may be empty + // (/Blog/.. interim pages) $html->pushContent($sp, $link, HTML::br()); if ($first) $this->setValidators($rev); @@ -734,25 +821,28 @@ extends _RecentChanges_HtmlFormatter } if ($first) $html->pushContent(HTML::p(array('class' => 'rc-empty'), - $this->empty_message())); + $this->empty_message())); return $html; } } class _RecentChanges_RssFormatter -extends _RecentChanges_Formatter + extends _RecentChanges_Formatter { var $_absurls = true; - function time ($rev) { + function time($rev) + { return Iso8601DateTime($rev->get('mtime')); } - function pageURI ($rev) { + function pageURI($rev) + { return WikiURL($rev, '', 'absurl'); } - function format ($changes) { + function format($changes) + { include_once 'lib/RssWriter.php'; $rss = new RssWriter; @@ -768,7 +858,7 @@ extends _RecentChanges_Formatter // enforce view permission if (mayAccessPage('view', $rev->_pagename)) { $rss->addItem($this->item_properties($rev), - $this->pageURI($rev)); + $this->pageURI($rev)); if ($first) $this->setValidators($rev); $first = false; @@ -786,10 +876,11 @@ extends _RecentChanges_Formatter if (($errors = $ErrorManager->getPostponedErrorsAsHTML())) printf("\n\n", AsXML($errors)); - $request->finish(); // NORETURN!!!! + $request->finish(); // NORETURN!!!! } - function image_properties () { + function image_properties() + { global $WikiTheme; $img_url = AbsoluteURL($WikiTheme->getImageURL('logo')); @@ -797,18 +888,20 @@ extends _RecentChanges_Formatter return false; return array('title' => WIKI_NAME, - 'link' => WikiURL(HOME_PAGE, false, 'absurl'), - 'url' => $img_url); + 'link' => WikiURL(HOME_PAGE, false, 'absurl'), + 'url' => $img_url); } - function textinput_properties () { + function textinput_properties() + { return array('title' => _("Search"), - 'description' => _("Title Search"), - 'name' => 's', - 'link' => WikiURL(_("TitleSearch"), false, 'absurl')); + 'description' => _("Title Search"), + 'name' => 's', + 'link' => WikiURL(_("TitleSearch"), false, 'absurl')); } - function channel_properties () { + function channel_properties() + { global $request; $rc_url = WikiURL($request->getArg('pagename'), false, 'absurl'); @@ -820,10 +913,10 @@ extends _RecentChanges_Formatter elseif ($pagematch) $title = $pagematch; return array('title' => $title, - 'link' => $rc_url, - 'description' => $description, - 'dc:date' => Iso8601DateTime(time()), - 'dc:language' => $GLOBALS['LANG']); + 'link' => $rc_url, + 'description' => $description, + 'dc:date' => Iso8601DateTime(time()), + 'dc:language' => $GLOBALS['LANG']); /* FIXME: other things one might like in : * sy:updateFrequency @@ -841,21 +934,22 @@ extends _RecentChanges_Formatter */ } - function item_properties ($rev) { + function item_properties($rev) + { $page = $rev->getPage(); $pagename = $page->getName(); - return array( 'title' => SplitPagename($pagename), - 'description' => $this->summary($rev), - 'link' => $this->pageURL($rev), - 'dc:date' => $this->time($rev), - 'dc:contributor' => $rev->get('author'), - 'wiki:version' => $rev->getVersion(), - 'wiki:importance' => $this->importance($rev), - 'wiki:status' => $this->status($rev), - 'wiki:diff' => $this->diffURL($rev), - 'wiki:history' => $this->historyURL($rev) - ); + return array('title' => SplitPagename($pagename), + 'description' => $this->summary($rev), + 'link' => $this->pageURL($rev), + 'dc:date' => $this->time($rev), + 'dc:contributor' => $rev->get('author'), + 'wiki:version' => $rev->getVersion(), + 'wiki:importance' => $this->importance($rev), + 'wiki:status' => $this->status($rev), + 'wiki:diff' => $this->diffURL($rev), + 'wiki:history' => $this->historyURL($rev) + ); } } @@ -864,9 +958,11 @@ extends _RecentChanges_Formatter * support for xml-rpc cloud registerProcedure (not yet) */ class _RecentChanges_Rss2Formatter -extends _RecentChanges_RssFormatter { + extends _RecentChanges_RssFormatter +{ - function format ($changes) { + function format($changes) + { include_once 'lib/RssWriter2.php'; $rss = new RssWriter2; @@ -882,7 +978,7 @@ extends _RecentChanges_RssFormatter { // enforce view permission if (mayAccessPage('view', $rev->_pagename)) { $rss->addItem($this->item_properties($rev), - $this->pageURI($rev)); + $this->pageURI($rev)); if ($first) $this->setValidators($rev); $first = false; @@ -899,28 +995,34 @@ extends _RecentChanges_RssFormatter { if (($errors = $ErrorManager->getPostponedErrorsAsHTML())) printf("\n\n", AsXML($errors)); - $request->finish(); // NORETURN!!!! + $request->finish(); // NORETURN!!!! } - function channel_properties () { + function channel_properties() + { $chann_10 = parent::channel_properties(); return array_merge($chann_10, - array('generator' => 'PhpWiki-'.PHPWIKI_VERSION, - //Tue, 10 Jun 2003 04:00:00 GMT - //Tue, 10 Jun 2003 09:41:01 GMT - //http://blogs.law.harvard.edu/tech/rss - 'copyright' => COPYRIGHTPAGE_URL - )); + array('generator' => 'PhpWiki-' . PHPWIKI_VERSION, + //Tue, 10 Jun 2003 04:00:00 GMT + //Tue, 10 Jun 2003 09:41:01 GMT + //http://blogs.law.harvard.edu/tech/rss + 'copyright' => COPYRIGHTPAGE_URL + )); } // xml-rpc registerProcedure not yet implemented - function cloud_properties () { return false; } - function cloud_properties_test () { + function cloud_properties() + { + return false; + } + + function cloud_properties_test() + { return array('protocol' => 'xml-rpc', // xml-rpc or soap or http-post - 'registerProcedure' => 'wiki.rssPleaseNotify', - 'path' => DATA_PATH.'/RPC2.php', - 'port' => !SERVER_PORT ? '80' : (SERVER_PROTOCOL == 'https' ? '443' : '80'), - 'domain' => SERVER_NAME); + 'registerProcedure' => 'wiki.rssPleaseNotify', + 'path' => DATA_PATH . '/RPC2.php', + 'port' => !SERVER_PORT ? '80' : (SERVER_PROTOCOL == 'https' ? '443' : '80'), + 'domain' => SERVER_NAME); } } @@ -928,9 +1030,11 @@ extends _RecentChanges_RssFormatter { * A weird, questionable format */ class _RecentChanges_AtomFormatter -extends _RecentChanges_RssFormatter { + extends _RecentChanges_RssFormatter +{ - function format ($changes) { + function format($changes) + { global $request; include_once 'lib/RssWriter.php'; $rss = new AtomFeed; @@ -945,13 +1049,13 @@ extends _RecentChanges_RssFormatter { elseif ($pagematch) $title = $pagematch; $feed_props = array('title' => $description, - 'link' => array('rel'=>"alternate", - 'type'=>"text/html", - 'href' => $rc_url), - 'id' => md5($rc_url), - 'modified' => Iso8601DateTime(time()), - 'generator' => 'PhpWiki-'.PHPWIKI_VERSION, - 'tagline' => ''); + 'link' => array('rel' => "alternate", + 'type' => "text/html", + 'href' => $rc_url), + 'id' => md5($rc_url), + 'modified' => Iso8601DateTime(time()), + 'generator' => 'PhpWiki-' . PHPWIKI_VERSION, + 'tagline' => ''); $rss->feed($feed_props); $first = true; while ($rev = $changes->next()) { @@ -959,8 +1063,8 @@ extends _RecentChanges_RssFormatter { if (mayAccessPage('view', $rev->_pagename)) { $props = $this->item_properties($rev); $rss->addItem($props, - false, - $this->pageURI($rev)); + false, + $this->pageURI($rev)); if ($first) $this->setValidators($rev); $first = false; @@ -976,22 +1080,23 @@ extends _RecentChanges_RssFormatter { if (($errors = $ErrorManager->getPostponedErrorsAsHTML())) printf("\n\n", AsXML($errors)); - $request->finish(); // NORETURN!!!! + $request->finish(); // NORETURN!!!! } - function item_properties ($rev) { + function item_properties($rev) + { $page = $rev->getPage(); $pagename = $page->getName(); - return array( 'title' => $pagename, - 'link' => array('rel' => 'alternate', - 'type' => 'text/html', - 'href' => $this->pageURL($rev)), - 'summary' => $this->summary($rev), - 'modified' => $this->time($rev)."Z", - 'issued' => $this->time($rev), - 'created' => $this->time($rev)."Z", - 'author' => new XmlElement('author', new XmlElement('name', $rev->get('author'))) - ); + return array('title' => $pagename, + 'link' => array('rel' => 'alternate', + 'type' => 'text/html', + 'href' => $this->pageURL($rev)), + 'summary' => $this->summary($rev), + 'modified' => $this->time($rev) . "Z", + 'issued' => $this->time($rev), + 'created' => $this->time($rev) . "Z", + 'author' => new XmlElement('author', new XmlElement('name', $rev->get('author'))) + ); } } @@ -1004,21 +1109,22 @@ class NonDeletedRevisionIterator extends WikiDB_PageRevisionIterator * * @param $revisions object a WikiDB_PageRevisionIterator. */ - function NonDeletedRevisionIterator ($revisions, $check_current_revision = true) { + function NonDeletedRevisionIterator($revisions, $check_current_revision = true) + { $this->_revisions = $revisions; $this->_check_current_revision = $check_current_revision; } - function next () { + function next() + { while (($rev = $this->_revisions->next())) { if ($this->_check_current_revision) { $page = $rev->getPage(); $check_rev = $page->getCurrentRevision(); - } - else { + } else { $check_rev = $rev; } - if (! $check_rev->hasDefaultContents()) + if (!$check_rev->hasDefaultContents()) return $rev; } $this->free(); @@ -1037,11 +1143,13 @@ class NewPageRevisionIterator extends WikiDB_PageRevisionIterator * * @param $revisions object a WikiDB_PageRevisionIterator. */ - function NewPageRevisionIterator ($revisions) { + function NewPageRevisionIterator($revisions) + { $this->_revisions = $revisions; } - function next () { + function next() + { while (($rev = $this->_revisions->next())) { if ($rev->getVersion() == 1) return $rev; @@ -1056,28 +1164,29 @@ class NewPageRevisionIterator extends WikiDB_PageRevisionIterator */ class LinkRevisionIterator extends WikiDB_PageRevisionIterator { - function LinkRevisionIterator ($revisions, $category) { + function LinkRevisionIterator($revisions, $category) + { $this->_revisions = $revisions; if (preg_match("/[\?\.\*]/", $category)) { - $backlinkiter = $this->_revisions->_wikidb->linkSearch + $backlinkiter = $this->_revisions->_wikidb->linkSearch (new TextSearchQuery("*", true), - new TextSearchQuery($category, true), - "linkfrom"); + new TextSearchQuery($category, true), + "linkfrom"); } else { - $basepage = $GLOBALS['request']->getPage($category); - $backlinkiter = $basepage->getBackLinks(true); + $basepage = $GLOBALS['request']->getPage($category); + $backlinkiter = $basepage->getBackLinks(true); } $this->links = array(); foreach ($backlinkiter->asArray() as $p) { if (is_object($p)) $this->links[] = $p->getName(); - elseif (is_array($p)) $this->links[] = $p['pagename']; - else $this->links[] = $p; + elseif (is_array($p)) $this->links[] = $p['pagename']; else $this->links[] = $p; } $backlinkiter->free(); sort($this->links); } - function next () { + function next() + { while (($rev = $this->_revisions->next())) { if (binary_search($rev->getName(), $this->links) != false) return $rev; @@ -1086,19 +1195,22 @@ class LinkRevisionIterator extends WikiDB_PageRevisionIterator return false; } - function free () { + function free() + { unset ($this->links); } } class PageMatchRevisionIterator extends WikiDB_PageRevisionIterator { - function PageMatchRevisionIterator ($revisions, $match) { + function PageMatchRevisionIterator($revisions, $match) + { $this->_revisions = $revisions; $this->search = new TextSearchQuery($match, true); } - function next () { + function next() + { while (($rev = $this->_revisions->next())) { if ($this->search->match($rev->getName())) return $rev; @@ -1107,7 +1219,8 @@ class PageMatchRevisionIterator extends WikiDB_PageRevisionIterator return false; } - function free () { + function free() + { unset ($this->search); } } @@ -1117,12 +1230,14 @@ class PageMatchRevisionIterator extends WikiDB_PageRevisionIterator */ class AuthorPageRevisionIterator extends WikiDB_PageRevisionIterator { - function AuthorPageRevisionIterator ($revisions, $author) { + function AuthorPageRevisionIterator($revisions, $author) + { $this->_revisions = $revisions; $this->_author = $author; } - function next () { + function next() + { while (($rev = $this->_revisions->next())) { if ($rev->get('author_id') == $this->_author) return $rev; @@ -1137,12 +1252,14 @@ class AuthorPageRevisionIterator extends WikiDB_PageRevisionIterator */ class OwnerPageRevisionIterator extends WikiDB_PageRevisionIterator { - function OwnerPageRevisionIterator ($revisions, $owner) { + function OwnerPageRevisionIterator($revisions, $owner) + { $this->_revisions = $revisions; $this->_owner = $owner; } - function next () { + function next() + { while (($rev = $this->_revisions->next())) { $page = $rev->getPage(); if ($page->getOwner() == $this->_owner) @@ -1154,17 +1271,20 @@ class OwnerPageRevisionIterator extends WikiDB_PageRevisionIterator } class WikiPlugin_RecentChanges -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("RecentChanges"); } - function getDescription () { + function getDescription() + { return _("List all recent changes in this wiki."); } - function managesValidators() { + function managesValidators() + { // Note that this is a bit of a fig. // We set validators based on the most recently changed page, // but this fails when the most-recent page is deleted. @@ -1182,28 +1302,30 @@ extends WikiPlugin return true; } - function getDefaultArguments() { - return array('days' => 2, - 'show_minor' => false, - 'show_major' => true, - 'show_all' => false, - 'show_deleted' => 'sometimes', - 'only_new' => false, - 'author' => false, - 'owner' => false, - 'limit' => false, - 'format' => false, - 'daylist' => false, - 'difflinks' => true, - 'historylinks' => false, - 'caption' => '', - 'category' => '', - 'pagematch' => '' - ); - } - - function getArgs ($argstr, $request, $defaults = false) { - if (!$defaults) $defaults = $this->getDefaultArguments(); + function getDefaultArguments() + { + return array('days' => 2, + 'show_minor' => false, + 'show_major' => true, + 'show_all' => false, + 'show_deleted' => 'sometimes', + 'only_new' => false, + 'author' => false, + 'owner' => false, + 'limit' => false, + 'format' => false, + 'daylist' => false, + 'difflinks' => true, + 'historylinks' => false, + 'caption' => '', + 'category' => '', + 'pagematch' => '' + ); + } + + function getArgs($argstr, $request, $defaults = false) + { + if (!$defaults) $defaults = $this->getDefaultArguments(); $args = WikiPlugin::getArgs($argstr, $request, $defaults); $action = $request->getArg('action'); @@ -1221,14 +1343,17 @@ extends WikiPlugin return $args; } - function getMostRecentParams (&$args) { - $show_all = false; $show_minor = false; $show_major = false; - $limit = false; + function getMostRecentParams(&$args) + { + $show_all = false; + $show_minor = false; + $show_major = false; + $limit = false; extract($args); $params = array('include_minor_revisions' => $show_minor, - 'exclude_major_revisions' => !$show_major, - 'include_all_revisions' => !empty($show_all)); + 'exclude_major_revisions' => !$show_major, + 'include_all_revisions' => !empty($show_all)); if ($limit != 0) $params['limit'] = $limit; if (!empty($args['author'])) { @@ -1244,16 +1369,17 @@ extends WikiPlugin $params['owner'] = $args['owner']; } if (!empty($days)) { - if ($days > 0.0) - $params['since'] = time() - 24 * 3600 * $days; - elseif ($days < 0.0) - $params['since'] = 24 * 3600 * $days - time(); + if ($days > 0.0) + $params['since'] = time() - 24 * 3600 * $days; + elseif ($days < 0.0) + $params['since'] = 24 * 3600 * $days - time(); } return $params; } - function getChanges ($dbi, $args) { + function getChanges($dbi, $args) + { $changes = $dbi->mostRecent($this->getMostRecentParams($args)); $show_deleted = @$args['show_deleted']; @@ -1282,7 +1408,8 @@ extends WikiPlugin return $changes; } - function format ($changes, $args) { + function format($changes, $args) + { global $WikiTheme; $format = $args['format']; @@ -1291,20 +1418,14 @@ extends WikiPlugin if ($format == 'rss') $fmt_class = '_RecentChanges_RssFormatter'; elseif ($format == 'rss2') - $fmt_class = '_RecentChanges_Rss2Formatter'; - elseif ($format == 'atom') - $fmt_class = '_RecentChanges_AtomFormatter'; - elseif ($format == 'rss091') { + $fmt_class = '_RecentChanges_Rss2Formatter'; elseif ($format == 'atom') + $fmt_class = '_RecentChanges_AtomFormatter'; elseif ($format == 'rss091') { include_once 'lib/RSSWriter091.php'; $fmt_class = '_RecentChanges_RssFormatter091'; - } - elseif ($format == 'sidebar') - $fmt_class = '_RecentChanges_SideBarFormatter'; - elseif ($format == 'box') - $fmt_class = '_RecentChanges_BoxFormatter'; - elseif ($format == 'contribs') - $fmt_class = '_RecentChanges_UserContribsFormatter'; - else + } elseif ($format == 'sidebar') + $fmt_class = '_RecentChanges_SideBarFormatter'; elseif ($format == 'box') + $fmt_class = '_RecentChanges_BoxFormatter'; elseif ($format == 'contribs') + $fmt_class = '_RecentChanges_UserContribsFormatter'; else $fmt_class = '_RecentChanges_HtmlFormatter'; } @@ -1312,7 +1433,8 @@ extends WikiPlugin return $fmt->format($changes); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); // HACKish: fix for SF bug #622784 (1000 years of RecentChanges ought @@ -1321,8 +1443,8 @@ extends WikiPlugin // Within Categories just display Category Backlinks if (empty($args['category']) and empty($args['pagematch']) - and preg_match("/^Category/", $request->getArg('pagename'))) - { + and preg_match("/^Category/", $request->getArg('pagename')) + ) { $args['category'] = $request->getArg('pagename'); } @@ -1332,7 +1454,8 @@ extends WikiPlugin // box is used to display a fixed-width, narrow version with common header. // just a numbered list of limit pagenames, without date. - function box($args = false, $request = false, $basepage = false) { + function box($args = false, $request = false, $basepage = false) + { if (!$request) $request =& $GLOBALS['request']; if (!isset($args['limit'])) $args['limit'] = 15; $args['format'] = 'box'; @@ -1341,38 +1464,42 @@ extends WikiPlugin $args['show_deleted'] = 'sometimes'; $args['show_all'] = false; $args['days'] = 90; - return $this->makeBox(WikiLink($this->getName(),'', - SplitPagename($this->getName())), - $this->format - ($this->getChanges($request->_dbi, $args), $args)); + return $this->makeBox(WikiLink($this->getName(), '', + SplitPagename($this->getName())), + $this->format + ($this->getChanges($request->_dbi, $args), $args)); } -}; +} -class OptionsButtonBars extends HtmlElement { +; + +class OptionsButtonBars extends HtmlElement +{ - function OptionsButtonBars ($plugin_args) { + function OptionsButtonBars($plugin_args) + { $this->__construct('fieldset', array('class' => 'wiki-rc-action')); - // Add ShowHideFolder button + // Add ShowHideFolder button $icon = $GLOBALS['WikiTheme']->_findData('images/folderArrowOpen.png'); $img = HTML::img(array('id' => 'rc-action-img', - 'src' => $icon, - 'onclick' => "showHideFolder('rc-action')", - 'alt' => _("Click to hide/show"), - 'title' => _("Click to hide/show"))); + 'src' => $icon, + 'onclick' => "showHideFolder('rc-action')", + 'alt' => _("Click to hide/show"), + 'title' => _("Click to hide/show"))); // Display selection buttons extract($plugin_args); // Custom caption - if (! $caption) { + if (!$caption) { $caption = _("Show changes for:"); } - $this->pushContent(HTML::legend($caption,' ',$img)); + $this->pushContent(HTML::legend($caption, ' ', $img)); $table = HTML::table(array('id' => 'rc-action-body', - 'style' => 'display:block')); + 'style' => 'display:block')); $tr = HTML::tr(); foreach (explode(",", $daylist) as $days_button) { @@ -1408,7 +1535,8 @@ class OptionsButtonBars extends HtmlElement { $this->pushContent($table); } - function _makeDayButton ($days_button, $days) { + function _makeDayButton($days_button, $days) + { global $request; $url = $request->getURLtoSelf(array('action' => $request->getArg('action'), 'days' => $days_button)); @@ -1419,13 +1547,14 @@ class OptionsButtonBars extends HtmlElement { } else { $label = sprintf(_("%s days"), abs($days_button)); } - $selected = HTML::td(array('class'=>'tdselected'), $label); - $unselected = HTML::td(array('class'=>'tdunselected'), - HTML::a(array('href' => $url, 'class' => 'wiki-rc-action'), $label)); + $selected = HTML::td(array('class' => 'tdselected'), $label); + $unselected = HTML::td(array('class' => 'tdunselected'), + HTML::a(array('href' => $url, 'class' => 'wiki-rc-action'), $label)); return ($days_button == $days) ? $selected : $unselected; } - function _makeUsersButton ($users) { + function _makeUsersButton($users) + { global $request; if ($users == 0) { @@ -1439,13 +1568,14 @@ class OptionsButtonBars extends HtmlElement { $selfurl = $request->getURLtoSelf(array('action' => $request->getArg('action'))); $url = $request->getURLtoSelf(array('action' => $request->getArg('action'), 'author' => $author)); if ($url == $selfurl) { - return HTML::td(array('colspan'=>3, 'class'=>'tdselected'), $label); + return HTML::td(array('colspan' => 3, 'class' => 'tdselected'), $label); } - return HTML::td(array('colspan'=>3, 'class'=>'tdunselected'), - HTML::a(array('href' => $url, 'class' => 'wiki-rc-action'), $label)); + return HTML::td(array('colspan' => 3, 'class' => 'tdunselected'), + HTML::a(array('href' => $url, 'class' => 'wiki-rc-action'), $label)); } - function _makePagesButton ($pages) { + function _makePagesButton($pages) + { global $request; if ($pages == 0) { @@ -1459,42 +1589,45 @@ class OptionsButtonBars extends HtmlElement { $selfurl = $request->getURLtoSelf(array('action' => $request->getArg('action'))); $url = $request->getURLtoSelf(array('action' => $request->getArg('action'), 'owner' => $owner)); if ($url == $selfurl) { - return HTML::td(array('colspan'=>3, 'class'=>'tdselected'), $label); + return HTML::td(array('colspan' => 3, 'class' => 'tdselected'), $label); } - return HTML::td(array('colspan'=>3, 'class'=>'tdunselected'), - HTML::a(array('href' => $url, 'class' => 'wiki-rc-action'), $label)); + return HTML::td(array('colspan' => 3, 'class' => 'tdunselected'), + HTML::a(array('href' => $url, 'class' => 'wiki-rc-action'), $label)); } - function _makeMinorButton ($minor_button, $show_minor) { + function _makeMinorButton($minor_button, $show_minor) + { global $request; $url = $request->getURLtoSelf(array('action' => $request->getArg('action'), 'show_minor' => $minor_button)); $label = ($minor_button == 0) ? _("Major modifications only") : _("All modifications"); - $selected = HTML::td(array('colspan'=>3, 'class'=>'tdselected'), $label); - $unselected = HTML::td(array('colspan'=>3, 'class'=>'tdunselected'), - HTML::a(array('href' => $url, 'class' => 'wiki-rc-action'), $label)); + $selected = HTML::td(array('colspan' => 3, 'class' => 'tdselected'), $label); + $unselected = HTML::td(array('colspan' => 3, 'class' => 'tdunselected'), + HTML::a(array('href' => $url, 'class' => 'wiki-rc-action'), $label)); return ($minor_button == $show_minor) ? $selected : $unselected; } - function _makeShowAllButton ($showall_button, $show_all) { + function _makeShowAllButton($showall_button, $show_all) + { global $request; $url = $request->getURLtoSelf(array('action' => $request->getArg('action'), 'show_all' => $showall_button)); $label = ($showall_button == 0) ? _("Page once only") : _("Full changes"); - $selected = HTML::td(array('colspan'=>3, 'class'=>'tdselected'), $label); - $unselected = HTML::td(array('colspan'=>3, 'class'=>'tdunselected'), - HTML::a(array('href' => $url, 'class' => 'wiki-rc-action'), $label)); + $selected = HTML::td(array('colspan' => 3, 'class' => 'tdselected'), $label); + $unselected = HTML::td(array('colspan' => 3, 'class' => 'tdunselected'), + HTML::a(array('href' => $url, 'class' => 'wiki-rc-action'), $label)); return ($showall_button == $show_all) ? $selected : $unselected; } - function _makeNewPagesButton ($newpages_button, $only_new) { + function _makeNewPagesButton($newpages_button, $only_new) + { global $request; $url = $request->getURLtoSelf(array('action' => $request->getArg('action'), 'only_new' => $newpages_button)); $label = ($newpages_button == 0) ? _("Old and new pages") : _("New pages only"); - $selected = HTML::td(array('colspan'=>3, 'class'=>'tdselected'), $label); - $unselected = HTML::td(array('colspan'=>3, 'class'=>'tdunselected'), - HTML::a(array('href' => $url, 'class' => 'wiki-rc-action'), $label)); + $selected = HTML::td(array('colspan' => 3, 'class' => 'tdselected'), $label); + $unselected = HTML::td(array('colspan' => 3, 'class' => 'tdunselected'), + HTML::a(array('href' => $url, 'class' => 'wiki-rc-action'), $label)); return ($newpages_button == $only_new) ? $selected : $unselected; } } diff --git a/lib/plugin/RecentChangesCached.php b/lib/plugin/RecentChangesCached.php index c318874e9..922411ba5 100644 --- a/lib/plugin/RecentChangesCached.php +++ b/lib/plugin/RecentChangesCached.php @@ -32,31 +32,37 @@ require_once 'lib/WikiPluginCached.php'; require_once 'lib/plugin/RecentChanges.php'; class WikiPlugin_RecentChangesCached -extends WikiPluginCached + extends WikiPluginCached { - function getPluginType() { + function getPluginType() + { return PLUGIN_CACHED_HTML; } - function getName() { + function getName() + { return "RecentChangesCached"; } - function getDescription() { + function getDescription() + { return 'Caches output of RecentChanges called with default arguments.'; } - function getDefaultArguments() { + function getDefaultArguments() + { return WikiPlugin_RecentChanges::getDefaultArguments(); } - function getExpire($dbi, $argarray, $request) { + function getExpire($dbi, $argarray, $request) + { return '+900'; // 15 minutes } // We don't go through pi parsing, instead we go directly to the // better plugin methods. - function getHtml($dbi, $args, $request, $basepage) { + function getHtml($dbi, $args, $request, $basepage) + { $plugin = new WikiPlugin_RecentChanges(); $changes = $plugin->getChanges($dbi, $args); return $plugin->format($changes, $args); @@ -71,7 +77,8 @@ extends WikiPluginCached // ->box is used to display a fixed-width, narrow version with common header. // Just a limited list of pagenames, without date. // This does not use ->run, to avoid pi construction and deconstruction - function box($args = false, $request = false, $basepage = false, $do_save = false) { + function box($args = false, $request = false, $basepage = false, $do_save = false) + { if (!$request) $request =& $GLOBALS['request']; if (!isset($args['limit'])) $args['limit'] = 12; $args['format'] = 'box'; @@ -105,8 +112,8 @@ extends WikiPluginCached $title = WikiLink($this->getName(), '', SplitPagename($this->getName())); $changes = $plugin->getChanges($request->_dbi, $args); $content['html'] = - $this->makeBox($title, - $plugin->format($changes, $args)); + $this->makeBox($title, + $plugin->format($changes, $args)); if ($errortext = $this->getError()) { $this->printError($errortext, 'html'); return HTML(); @@ -124,8 +131,9 @@ extends WikiPluginCached } // force box cache update on major changes. - function box_update($args = false, $request = false, $basepage = false) { - $this->box($args, $request, $basepage, true); + function box_update($args = false, $request = false, $basepage = false) + { + $this->box($args, $request, $basepage, true); } } diff --git a/lib/plugin/RecentComments.php b/lib/plugin/RecentComments.php index 01ec9cb0a..5287aa806 100644 --- a/lib/plugin/RecentComments.php +++ b/lib/plugin/RecentComments.php @@ -30,17 +30,20 @@ require_once 'lib/plugin/RecentChanges.php'; require_once 'lib/plugin/WikiBlog.php'; class WikiPlugin_RecentComments -extends WikiPlugin_RecentChanges + extends WikiPlugin_RecentChanges { - function getName () { + function getName() + { return _("RecentComments"); } - function getDescription () { + function getDescription() + { return _("List basepages with recently added comments."); } - function getDefaultArguments() { + function getDefaultArguments() + { $args = parent::getDefaultArguments(); $args['show_minor'] = false; $args['show_all'] = true; @@ -48,13 +51,15 @@ extends WikiPlugin_RecentChanges return $args; } - function format ($changes, $args) { + function format($changes, $args) + { $fmt = new _RecentChanges_CommentFormatter($args); $fmt->action = _("RecentComments"); return $fmt->format($changes); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); // HACKish: fix for SF bug #622784 (1000 years of RecentChanges ought // to be enough for anyone.) @@ -62,7 +67,8 @@ extends WikiPlugin_RecentChanges return $this->format($this->getChanges($request->_dbi, $args), $args); } - function getChanges ($dbi, $args) { + function getChanges($dbi, $args) + { $changes = $dbi->mostRecent($this->getMostRecentParams($args)); $show_deleted = $args['show_deleted']; if ($show_deleted == 'sometimes') @@ -76,24 +82,28 @@ extends WikiPlugin_RecentChanges } class _RecentChanges_CommentFormatter -extends _RecentChanges_HtmlFormatter { + extends _RecentChanges_HtmlFormatter +{ - function empty_message () { + function empty_message() + { return _("No comments found"); } - function title() { + function title() + { return; } - function format_revision ($rev) { - static $doublettes = array(); - if (isset($doublettes[$rev->getPageName()])) return; - $doublettes[$rev->getPageName()] = 1; + function format_revision($rev) + { + static $doublettes = array(); + if (isset($doublettes[$rev->getPageName()])) return; + $doublettes[$rev->getPageName()] = 1; $args = &$this->_args; $class = 'rc-' . $this->importance($rev); $time = $this->time($rev); - if (! $rev->get('is_minor_edit')) + if (!$rev->get('is_minor_edit')) $time = HTML::strong(array('class' => 'pageinfo-majoredit'), $time); $line = HTML::li(array('class' => $class)); if ($args['difflinks']) @@ -103,10 +113,10 @@ extends _RecentChanges_HtmlFormatter { $line->pushContent($this->historyLink($rev), ' '); $line->pushContent($this->pageLink($rev), ' ', - $time, ' ', - ' . . . . ', - _("latest comment by "), - $this->authorLink($rev)); + $time, ' ', + ' . . . . ', + _("latest comment by "), + $this->authorLink($rev)); return $line; } } @@ -117,27 +127,29 @@ extends _RecentChanges_HtmlFormatter { */ class RecentCommentsRevisionIterator extends WikiDB_PageRevisionIterator { - function RecentCommentsRevisionIterator ($revisions, &$dbi) { + function RecentCommentsRevisionIterator($revisions, &$dbi) + { $this->_revisions = $revisions; $this->_wikidb = $dbi; $this->_current = 0; $this->_blog = new WikiPlugin_WikiBlog(); } - function next () { - if (!empty($this->comments) and $this->_current) { + function next() + { + if (!empty($this->comments) and $this->_current) { if (isset($this->comments[$this->_current])) { return $this->comments[$this->_current++]; } else { - $this->_current = 0; - } + $this->_current = 0; } + } while (($rev = $this->_revisions->next())) { $this->comments = $this->_blog->findBlogs($this->_wikidb, $rev->getPageName(), 'comment'); if ($this->comments) { if (count($this->comments) > 2) usort($this->comments, array("WikiPlugin_WikiBlog", - "cmp")); + "cmp")); if (isset($this->comments[$this->_current])) { //$this->_current++; return $this->comments[$this->_current++]; @@ -145,7 +157,7 @@ class RecentCommentsRevisionIterator extends WikiDB_PageRevisionIterator } else { $this->_current = 0; } - } + } $this->free(); return false; } diff --git a/lib/plugin/RecentEdits.php b/lib/plugin/RecentEdits.php index 5403a45b4..6c772ac5f 100644 --- a/lib/plugin/RecentEdits.php +++ b/lib/plugin/RecentEdits.php @@ -23,17 +23,20 @@ require_once 'lib/plugin/RecentChanges.php'; class WikiPlugin_RecentEdits -extends WikiPlugin_RecentChanges + extends WikiPlugin_RecentChanges { - function getName () { + function getName() + { return _("RecentEdits"); } - function getDescription () { + function getDescription() + { return _("List all recent edits in this wiki."); } - function getDefaultArguments() { + function getDefaultArguments() + { $args = parent::getDefaultArguments(); $args['show_minor'] = true; $args['show_all'] = true; @@ -42,7 +45,8 @@ extends WikiPlugin_RecentChanges // box is used to display a fixed-width, narrow version with common header. // just a numbered list of limit pagenames, without date. - function box($args = false, $request = false, $basepage = false) { + function box($args = false, $request = false, $basepage = false) + { if (!$request) $request =& $GLOBALS['request']; if (!isset($args['limit'])) $args['limit'] = 15; $args['format'] = 'box'; @@ -51,8 +55,8 @@ extends WikiPlugin_RecentChanges $args['show_deleted'] = false; $args['show_all'] = true; $args['days'] = 90; - return $this->makeBox(WikiLink(_("RecentEdits"),'',_("Recent Edits")), - $this->format($this->getChanges($request->_dbi, $args), $args)); + return $this->makeBox(WikiLink(_("RecentEdits"), '', _("Recent Edits")), + $this->format($this->getChanges($request->_dbi, $args), $args)); } } diff --git a/lib/plugin/RecentReferrers.php b/lib/plugin/RecentReferrers.php index 93bc4e264..9b757b2b6 100644 --- a/lib/plugin/RecentReferrers.php +++ b/lib/plugin/RecentReferrers.php @@ -29,48 +29,53 @@ include_once 'lib/PageList.php'; class WikiPlugin_RecentReferrers extends WikiPlugin { - function getName () { + function getName() + { return _("RecentReferrers"); } - function getDescription () { + function getDescription() + { return _("Analyse access log."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array_merge - ( - PageList::supportedArgs(), - array( - 'limit' => 15, - 'noheader' => false, - )); + ( + PageList::supportedArgs(), + array( + 'limit' => 15, + 'noheader' => false, + )); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { if (!ACCESS_LOG) { return HTML::div(array('class' => "error"), "Error: no ACCESS_LOG"); } $args = $this->getArgs($argstr, $request); $table = HTML::table(array('cellpadding' => 1, - 'cellspacing' => 2, - 'border' => 0, - 'class' => 'pagelist')); + 'cellspacing' => 2, + 'border' => 0, + 'class' => 'pagelist')); if (!$args['noheader'] and !empty($args['caption'])) - $table->pushContent(HTML::caption(array('align'=>'top'), $args['caption'])); + $table->pushContent(HTML::caption(array('align' => 'top'), $args['caption'])); $logs = array(); $limit = $args['limit']; $accesslog =& $request->_accesslog; if ($logiter = $accesslog->get_referer($limit, "external_only") - and $logiter->count()) { - $table->pushContent(HTML::tr(HTML::th("Target"),HTML::th("Referrer"), - HTML::th("Host"),HTML::th("Date"))); - while($logentry = $logiter->next()) { + and $logiter->count() + ) { + $table->pushContent(HTML::tr(HTML::th("Target"), HTML::th("Referrer"), + HTML::th("Host"), HTML::th("Date"))); + while ($logentry = $logiter->next()) { $table->pushContent(HTML::tr(HTML::td($logentry['request']), - HTML::td($logentry['referer']), - HTML::td($logentry['host']), - HTML::td($logentry['time']) - )); + HTML::td($logentry['referer']), + HTML::td($logentry['host']), + HTML::td($logentry['time']) + )); } return $table; } diff --git a/lib/plugin/RedirectTo.php b/lib/plugin/RedirectTo.php index 99d30e44c..2c9541f83 100644 --- a/lib/plugin/RedirectTo.php +++ b/lib/plugin/RedirectTo.php @@ -37,23 +37,27 @@ */ class WikiPlugin_RedirectTo -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("RedirectTo"); } - function getDescription() { + function getDescription() + { return _("Redirects to another URL or page."); } - function getDefaultArguments() { - return array( 'href' => '', - 'page' => false, - ); + function getDefaultArguments() + { + return array('href' => '', + 'page' => false, + ); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = ($this->getArgs($argstr, $request)); $href = $args['href']; @@ -68,16 +72,14 @@ extends WikiPlugin return $this->disabled(_("Illegal characters in external URL.")); } $thispage = $request->getPage(); - if (! $thispage->get('locked')) { + if (!$thispage->get('locked')) { return $this->disabled(_("Redirect to an external URL is only allowed in locked pages.")); } - } - else if ($page) { + } else if ($page) { $url = WikiURL($page, - array('redirectfrom' => $request->getArg('pagename')), - 'abs_path'); - } - else { + array('redirectfrom' => $request->getArg('pagename')), + 'abs_path'); + } else { return $this->error(_("'href' or 'page' parameter missing.")); } @@ -102,7 +104,9 @@ extends WikiPlugin return $request->redirect($url); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/RelatedChanges.php b/lib/plugin/RelatedChanges.php index 9c4bf320f..a9a36b27a 100644 --- a/lib/plugin/RelatedChanges.php +++ b/lib/plugin/RelatedChanges.php @@ -30,26 +30,30 @@ require_once 'lib/plugin/RecentChanges.php'; class _RelatedChanges_HtmlFormatter -extends _RecentChanges_HtmlFormatter + extends _RecentChanges_HtmlFormatter { - function description() { + function description() + { return HTML::p(false, $this->pre_description(), - fmt(" (to pages linked from \"%s\")",$this->_args['page'])); + fmt(" (to pages linked from \"%s\")", $this->_args['page'])); } } class WikiPlugin_RelatedChanges -extends WikiPlugin_RecentChanges + extends WikiPlugin_RecentChanges { - function getName () { + function getName() + { return _("RecentEdits"); } - function getDescription () { + function getDescription() + { return _("List of changes on all pages which are linked to from this page."); } - function getDefaultArguments() { + function getDefaultArguments() + { $args = parent::getDefaultArguments(); $args['page'] = '[pagename]'; $args['show_minor'] = true; @@ -58,7 +62,8 @@ extends WikiPlugin_RecentChanges return $args; } - function getChanges ($dbi, $args) { + function getChanges($dbi, $args) + { $changes = $dbi->mostRecent($this->getMostRecentParams($args)); $show_deleted = $args['show_deleted']; @@ -74,7 +79,8 @@ extends WikiPlugin_RecentChanges // box is used to display a fixed-width, narrow version with common header. // just a numbered list of limit pagenames, without date. - function box($args = false, $request = false, $basepage = false) { + function box($args = false, $request = false, $basepage = false) + { if (!$request) $request =& $GLOBALS['request']; if (!isset($args['limit'])) $args['limit'] = 15; $args['format'] = 'box'; @@ -83,11 +89,12 @@ extends WikiPlugin_RecentChanges $args['show_deleted'] = false; $args['show_all'] = false; $args['days'] = 90; - return $this->makeBox(WikiLink(_("RelatedChanges"),'',_("Related Changes")), - $this->format($this->getChanges($request->_dbi, $args), $args)); + return $this->makeBox(WikiLink(_("RelatedChanges"), '', _("Related Changes")), + $this->format($this->getChanges($request->_dbi, $args), $args)); } - function format ($changes, $args) { + function format($changes, $args) + { global $WikiTheme; $format = $args['format']; @@ -96,16 +103,12 @@ extends WikiPlugin_RecentChanges if ($format == 'rss') $fmt_class = '_RecentChanges_RssFormatter'; elseif ($format == 'rss2') - $fmt_class = '_RecentChanges_Rss2Formatter'; - elseif ($format == 'rss091') { + $fmt_class = '_RecentChanges_Rss2Formatter'; elseif ($format == 'rss091') { include_once 'lib/RSSWriter091.php'; $fmt_class = '_RecentChanges_RssFormatter091'; - } - elseif ($format == 'sidebar') - $fmt_class = '_RecentChanges_SideBarFormatter'; - elseif ($format == 'box') - $fmt_class = '_RecentChanges_BoxFormatter'; - else + } elseif ($format == 'sidebar') + $fmt_class = '_RecentChanges_SideBarFormatter'; elseif ($format == 'box') + $fmt_class = '_RecentChanges_BoxFormatter'; else $fmt_class = '_RelatedChanges_HtmlFormatter'; } @@ -120,7 +123,8 @@ extends WikiPlugin_RecentChanges */ class RelatedChangesRevisionIterator extends WikiDB_PageRevisionIterator { - function RelatedChangesRevisionIterator ($revisions, &$dbi, $pagename) { + function RelatedChangesRevisionIterator($revisions, &$dbi, $pagename) + { $this->_revisions = $revisions; $this->_wikidb = $dbi; $page = $dbi->getPage($pagename); @@ -132,7 +136,8 @@ class RelatedChangesRevisionIterator extends WikiDB_PageRevisionIterator $links->free(); } - function next () { + function next() + { while (($rev = $this->_revisions->next())) { if (isset($this->_links[$rev->_pagename])) return $rev; diff --git a/lib/plugin/RichTable.php b/lib/plugin/RichTable.php index 4ccbbb527..e33a08d95 100644 --- a/lib/plugin/RichTable.php +++ b/lib/plugin/RichTable.php @@ -25,24 +25,28 @@ /** * RichTablePlugin * A PhpWiki plugin that allows insertion of tables using a richer syntax. -*/ + */ class WikiPlugin_RichTable -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("RichTable"); } - function getDescription() { - return _("Layout tables using a very rich markup style."); + function getDescription() + { + return _("Layout tables using a very rich markup style."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array(); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { include_once 'lib/BlockParser.php'; // RichTablePlugin markup is new. $markup = 2.0; @@ -51,20 +55,21 @@ extends WikiPlugin $table = HTML::table(); if ($lines[0][0] == '*') { - $line = substr(array_shift($lines),1); + $line = substr(array_shift($lines), 1); $attrs = parse_attributes($line); foreach ($attrs as $key => $value) { - if (in_array ($key, array("id", "class", "title", "style", - "bgcolor", "frame", "rules", "border", - "cellspacing", "cellpadding", - "summary", "align", "width"))) { + if (in_array($key, array("id", "class", "title", "style", + "bgcolor", "frame", "rules", "border", + "cellspacing", "cellpadding", + "summary", "align", "width")) + ) { $table->setAttr($key, $value); } } } - foreach ($lines as $line){ - if (substr($line,0,1) == "-") { + foreach ($lines as $line) { + if (substr($line, 0, 1) == "-") { if (isset($row)) { if (isset($cell)) { if (isset($content)) { @@ -81,16 +86,17 @@ extends WikiPlugin $table->pushContent($row); } $row = HTML::tr(); - $attrs = parse_attributes(substr($line,1)); + $attrs = parse_attributes(substr($line, 1)); foreach ($attrs as $key => $value) { - if (in_array ($key, array("id", "class", "title", "style", - "bgcolor", "align", "valign"))) { + if (in_array($key, array("id", "class", "title", "style", + "bgcolor", "align", "valign")) + ) { $row->setAttr($key, $value); } } continue; } - if (substr($line,0,1) == "|" and isset($row)) { + if (substr($line, 0, 1) == "|" and isset($row)) { if (isset($cell)) { if (isset ($content)) { if (is_numeric(trim($content))) { @@ -104,12 +110,13 @@ extends WikiPlugin } $cell = HTML::td(); $line = substr($line, 1); - if ($line[0] == "*" ) { - $attrs = parse_attributes(substr($line,1)); + if ($line[0] == "*") { + $attrs = parse_attributes(substr($line, 1)); foreach ($attrs as $key => $value) { - if (in_array ($key, array("id", "class", "title", "style", - "colspan", "rowspan", "width", "height", - "bgcolor", "align", "valign"))) { + if (in_array($key, array("id", "class", "title", "style", + "colspan", "rowspan", "width", "height", + "bgcolor", "align", "valign")) + ) { $cell->setAttr($key, $value); } } diff --git a/lib/plugin/RssFeed.php b/lib/plugin/RssFeed.php index 223c48d31..a40bcef66 100644 --- a/lib/plugin/RssFeed.php +++ b/lib/plugin/RssFeed.php @@ -25,104 +25,111 @@ include 'lib/RssParser.php'; class WikiPlugin_RssFeed -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("RssFeed"); } - function getDescription () { + function getDescription() + { return _("Simple RSS Feed aggregator Plugin"); } // Establish default values for each of this plugin's arguments. - function getDefaultArguments() { - return array('feed' => "", - 'description' => "", - 'url' => "", //"http://phpwiki.org/RecentChanges?format=rss", - 'maxitem' => 0, - 'titleonly' => false, - 'debug' => false, - ); - } + function getDefaultArguments() + { + return array('feed' => "", + 'description' => "", + 'url' => "", //"http://phpwiki.org/RecentChanges?format=rss", + 'maxitem' => 0, + 'titleonly' => false, + 'debug' => false, + ); + } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { extract($this->getArgs($argstr, $request)); if (defined('CHARSET')) - $rss_parser = new RSSParser(CHARSET); + $rss_parser = new RSSParser(CHARSET); else - $rss_parser = new RSSParser(); + $rss_parser = new RSSParser(); if (!empty($url)) - $rss_parser->parse_url( $url, $debug ); + $rss_parser->parse_url($url, $debug); if (!empty($rss_parser->channel['title'])) $feed = $rss_parser->channel['title']; - if (!empty($rss_parser->channel['link'])) $url = $rss_parser->channel['link']; + if (!empty($rss_parser->channel['link'])) $url = $rss_parser->channel['link']; if (!empty($rss_parser->channel['description'])) $description = $rss_parser->channel['description']; if (!empty($feed)) { if (!empty($url)) { - $titre = HTML::span(HTML::a(array('href'=>$rss_parser->channel['link']), - $rss_parser->channel['title'])); + $titre = HTML::span(HTML::a(array('href' => $rss_parser->channel['link']), + $rss_parser->channel['title'])); } else { $titre = HTML::span($rss_parser->channel['title']); } - $th = HTML::div(array('class'=> 'feed'), $titre); + $th = HTML::div(array('class' => 'feed'), $titre); if (!empty($description)) $th->pushContent(HTML::p(array('class' => 'chandesc'), - HTML::raw($description))); + HTML::raw($description))); } else { $th = HTML(); } if (!empty($rss_parser->channel['date'])) - $th->pushContent(HTML::raw("")); - $html = HTML::div(array('class'=> 'rss'), $th); + $th->pushContent(HTML::raw("")); + $html = HTML::div(array('class' => 'rss'), $th); if ($rss_parser->items) { // only maxitem's - if ( $maxitem > 0 ) + if ($maxitem > 0) $rss_parser->items = array_slice($rss_parser->items, 0, $maxitem); foreach ($rss_parser->items as $item) { - $cell = HTML::div(array('class'=> 'rssitem')); + $cell = HTML::div(array('class' => 'rssitem')); if ($item['link'] and empty($item['title'])) $item['title'] = $item['link']; - $cell_title = HTML::div(array('class'=> 'itemname'), - HTML::a(array('href'=>$item['link']), - HTML::raw($item['title']))); + $cell_title = HTML::div(array('class' => 'itemname'), + HTML::a(array('href' => $item['link']), + HTML::raw($item['title']))); $cell->pushContent($cell_title); $cell_author = HTML::raw($item['author']); $cell_pubDate = HTML::raw($item['pubDate']); - $cell_authordate = HTML::div(array('class'=> 'authordate'), - $cell_author, HTML::raw(" - "), $cell_pubDate); + $cell_authordate = HTML::div(array('class' => 'authordate'), + $cell_author, HTML::raw(" - "), $cell_pubDate); $cell->pushContent($cell_authordate); if ((!$titleonly) && (!empty($item['description']))) - $cell->pushContent(HTML::div(array('class'=> 'itemdesc'), - HTML::raw($item['description']))); + $cell->pushContent(HTML::div(array('class' => 'itemdesc'), + HTML::raw($item['description']))); $html->pushContent($cell); } } else { - $html = HTML::div(array('class'=> 'rss'), HTML::em(_("no RSS items"))); + $html = HTML::div(array('class' => 'rss'), HTML::em(_("no RSS items"))); } if (!check_php_version(5)) $rss_parser->__destruct(); return $html; } - function box($args=false, $request=false, $basepage=false) { + function box($args = false, $request = false, $basepage = false) + { if (!$request) $request =& $GLOBALS['request']; extract($args); if (empty($title)) $title = _("RssFeed"); - if (empty($url)) $url = 'http://phpwiki.sourceforge.net/phpwiki/RecentChanges?format=rss'; + if (empty($url)) $url = 'http://phpwiki.sourceforge.net/phpwiki/RecentChanges?format=rss'; $argstr = "url=$url"; - if (isset($maxitem) and is_numeric($maxitem)) $argstr .= " maxitem=$maxitem"; + if (isset($maxitem) and is_numeric($maxitem)) $argstr .= " maxitem=$maxitem"; return $this->makeBox($title, - $this->run($request->_dbi, $argstr, $request, $basepage)); + $this->run($request->_dbi, $argstr, $request, $basepage)); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/SearchHighlight.php b/lib/plugin/SearchHighlight.php index 403ccc15c..28b8b6f9e 100644 --- a/lib/plugin/SearchHighlight.php +++ b/lib/plugin/SearchHighlight.php @@ -33,27 +33,31 @@ require_once 'lib/PageList.php'; * If hits = 1, then the list of found terms is also printed. */ class WikiPlugin_SearchHighlight -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("SearchHighlight"); } - function getDescription() { + function getDescription() + { return _("Hilight referred search terms."); } - function getDefaultArguments() { + function getDefaultArguments() + { // s, engine and engine_url are picked from the request - return array('noheader' => false, //don't print the header - 'hits' => false, //print the list of lines with lines terms additionally - 's' => false, - 'case_exact' => false, //not yet supported - 'regex' => false, //not yet supported - ); + return array('noheader' => false, //don't print the header + 'hits' => false, //print the list of lines with lines terms additionally + 's' => false, + 'case_exact' => false, //not yet supported + 'regex' => false, //not yet supported + ); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); if (empty($args['s']) and isset($request->_searchhighlight)) { $args['s'] = $request->_searchhighlight['query']; @@ -65,10 +69,10 @@ extends WikiPlugin if (!$noheader and isset($request->_searchhighlight)) { $engine = $request->_searchhighlight['engine']; $html->pushContent(HTML::div(array('class' => 'search-context'), - fmt("%s: Found %s through %s", - $basepage, - $request->_searchhighlight['query'], - $engine))); + fmt("%s: Found %s through %s", + $basepage, + $request->_searchhighlight['query'], + $engine))); } if ($hits) { $query = new TextSearchQuery($s, $case_exact, $regex); @@ -80,29 +84,33 @@ extends WikiPlugin return $html; } - function showhits($page, $hilight_re) { + function showhits($page, $hilight_re) + { $current = $page->getCurrentRevision(); $matches = preg_grep("/$hilight_re/i", $current->getContent()); $html = HTML::dl(); foreach ($matches as $line) { $line = $this->highlight_line($line, $hilight_re); $html->pushContent(HTML::dd(array('class' => 'search-context'), - HTML::small($line))); + HTML::small($line))); } return $html; } - function highlight_line ($line, $hilight_re) { + function highlight_line($line, $hilight_re) + { $html = HTML(); while (preg_match("/^(.*?)($hilight_re)/i", $line, $m)) { $line = substr($line, strlen($m[0])); // prematch + match $html->pushContent($m[1], HTML::strong(array('class' => 'search-term'), $m[2])); } - $html->pushContent($line); // postmatch + $html->pushContent($line); // postmatch return $html; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/SemanticRelations.php b/lib/plugin/SemanticRelations.php index eec695c12..7d26f1774 100644 --- a/lib/plugin/SemanticRelations.php +++ b/lib/plugin/SemanticRelations.php @@ -29,25 +29,32 @@ * @see WikiPlugin_SemanticSearch */ class WikiPlugin_SemanticRelations -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("SemanticRelations"); } - function getDescription() { + + function getDescription() + { return _("Display the list of relations and attributes on this page."); } - function getDefaultArguments() { + + function getDefaultArguments() + { return array( - 'page' => "[pagename]", // which pages (glob allowed), default: current - 'relations' => '', // which relations. default all - 'attributes' => '', // which attributes. default all - 'units' => '', // ? - 'noheader' => false, - 'nohelp' => false - ); + 'page' => "[pagename]", // which pages (glob allowed), default: current + 'relations' => '', // which relations. default all + 'attributes' => '', // which attributes. default all + 'units' => '', // ? + 'noheader' => false, + 'nohelp' => false + ); } - function run ($dbi, $argstr, &$request, $basepage) { + + function run($dbi, $argstr, &$request, $basepage) + { global $WikiTheme; $args = $this->getArgs($argstr, $request); extract($args); @@ -65,76 +72,78 @@ extends WikiPlugin foreach (explodePageList($page) as $pagename) { $p = $dbi->getPage($pagename); if ($args['relations'] != '0') { - $links = $p->getRelations(); // iter of pagelinks - // TODO: merge same relations together located_in::here, located_in::there - while ($object = $links->next()) { - if ($related = $object->get('linkrelation')) { // a page name - if ($relfilter and !in_array($related, $relfilter)) { - continue; - } - $rellink = WikiLink($related, false, $related); - $rellink->setAttr('class', $rellink->getAttr('class').' relation'); - $relhtml->pushContent + $links = $p->getRelations(); // iter of pagelinks + // TODO: merge same relations together located_in::here, located_in::there + while ($object = $links->next()) { + if ($related = $object->get('linkrelation')) { // a page name + if ($relfilter and !in_array($related, $relfilter)) { + continue; + } + $rellink = WikiLink($related, false, $related); + $rellink->setAttr('class', $rellink->getAttr('class') . ' relation'); + $relhtml->pushContent ($pagename . " ", - // Link to a special "Relation:" InterWiki link? - $rellink, - HTML::span(array('class'=>'relation-symbol'), "::"), // use spaces? - WikiLink($object->_pagename), - " ", - // Link to SemanticSearch - $WikiTheme->makeActionButton(array('relation' => $related, - 's' => $object->_pagename), - '+', - _("SemanticSearch")), - (count($relfilter) > 3 ? HTML::br() : " ")); + // Link to a special "Relation:" InterWiki link? + $rellink, + HTML::span(array('class' => 'relation-symbol'), "::"), // use spaces? + WikiLink($object->_pagename), + " ", + // Link to SemanticSearch + $WikiTheme->makeActionButton(array('relation' => $related, + 's' => $object->_pagename), + '+', + _("SemanticSearch")), + (count($relfilter) > 3 ? HTML::br() : " ")); + } } - } - if (!empty($relhtml->_content) and !$noheader) - $relhtml = HTML(HTML::hr(), - HTML::h3(fmt("Semantic relations for %s", $pagename)), - $relhtml); + if (!empty($relhtml->_content) and !$noheader) + $relhtml = HTML(HTML::hr(), + HTML::h3(fmt("Semantic relations for %s", $pagename)), + $relhtml); } $atthtml = HTML(); if ($args['attributes'] != '0') { - if ($attributes = $p->get('attributes')) { // a hash of unique pairs - foreach ($attributes as $att => $val) { - if ($attfilter and !in_array($att, $attfilter)) continue; - $rellink = WikiLink($att, false, $att); - $rellink->setAttr('class', $rellink->getAttr('class').' relation'); - $searchlink = $WikiTheme->makeActionButton + if ($attributes = $p->get('attributes')) { // a hash of unique pairs + foreach ($attributes as $att => $val) { + if ($attfilter and !in_array($att, $attfilter)) continue; + $rellink = WikiLink($att, false, $att); + $rellink->setAttr('class', $rellink->getAttr('class') . ' relation'); + $searchlink = $WikiTheme->makeActionButton (array('attribute' => $att, - 's' => $val), - $val, - _("SemanticSearch")); - $searchlink->setAttr('class', $searchlink->getAttr('class').' attribute'); + 's' => $val), + $val, + _("SemanticSearch")); + $searchlink->setAttr('class', $searchlink->getAttr('class') . ' attribute'); + if (!$noheader) + $atthtml->pushContent("$pagename "); + $atthtml->pushContent(HTML::span(array('class' => 'attribute ' . $att), + $rellink, + HTML::span(array('class' => 'relation-symbol'), + ":="), + $searchlink), + (count($attfilter) > 3 ? HTML::br() : " ")); + } if (!$noheader) - $atthtml->pushContent("$pagename "); - $atthtml->pushContent(HTML::span(array('class' => 'attribute '.$att), - $rellink, - HTML::span(array('class'=>'relation-symbol'), - ":="), - $searchlink), - (count($attfilter) > 3 ? HTML::br() : " ")); + $relhtml = HTML($relhtml, + HTML::hr(), + HTML::h3(fmt("Attributes of %s", $pagename)), + $atthtml); + else + $relhtml = HTML($relhtml, $atthtml); } - if (!$noheader) - $relhtml = HTML($relhtml, - HTML::hr(), - HTML::h3(fmt("Attributes of %s", $pagename)), - $atthtml); - else - $relhtml = HTML($relhtml, $atthtml); - } - } + } } if ($nohelp) return $relhtml; return HTML($relhtml, - HTML::hr(), - WikiLink(_("Help/SemanticRelations"), false, - HTML::em(_("Help/SemanticRelations"))), - " - ", - HTML::em(_("Find out how to add relations and attributes to pages."))); + HTML::hr(), + WikiLink(_("Help/SemanticRelations"), false, + HTML::em(_("Help/SemanticRelations"))), + " - ", + HTML::em(_("Find out how to add relations and attributes to pages."))); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/SemanticSearch.php b/lib/plugin/SemanticSearch.php index 7b2924dac..4a7a8f4c8 100644 --- a/lib/plugin/SemanticSearch.php +++ b/lib/plugin/SemanticSearch.php @@ -52,204 +52,211 @@ require_once 'lib/SemanticWeb.php'; * @author: Reini Urban */ class WikiPlugin_SemanticSearch -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("SemanticSearch"); } - function getDescription() { + + function getDescription() + { return _("Search relations and attributes"); } - function getDefaultArguments() { + + function getDefaultArguments() + { return array_merge - ( - PageList::supportedArgs(), // paging and more. - array( - 's' => "*", // linkvalue query string - 'page' => "*", // which pages (glob allowed), default: all - 'relation' => '', // linkname. which relations. default all - 'attribute' => '', // linkname. which attributes. default all - 'attr_op' => ':=', // a funny written way for equality for pure aesthetic pleasure - // "All attributes which have this value set" - 'units' => '', // ? - 'case_exact' => true, - 'regex' => 'auto',// is different here. - // no word splitting, if no regex op is present, defaults to exact match - 'noform' => false, // don't show form with results. - 'noheader' => false, // no caption - 'info' => false // valid: pagename,relation,linkto,attribute,value and all other pagelist columns - )); + ( + PageList::supportedArgs(), // paging and more. + array( + 's' => "*", // linkvalue query string + 'page' => "*", // which pages (glob allowed), default: all + 'relation' => '', // linkname. which relations. default all + 'attribute' => '', // linkname. which attributes. default all + 'attr_op' => ':=', // a funny written way for equality for pure aesthetic pleasure + // "All attributes which have this value set" + 'units' => '', // ? + 'case_exact' => true, + 'regex' => 'auto', // is different here. + // no word splitting, if no regex op is present, defaults to exact match + 'noform' => false, // don't show form with results. + 'noheader' => false, // no caption + 'info' => false // valid: pagename,relation,linkto,attribute,value and all other pagelist columns + )); } - function showForm (&$dbi, &$request, $args) { - global $WikiTheme; + function showForm(&$dbi, &$request, $args) + { + global $WikiTheme; $action = $request->getPostURL(); - $hiddenfield = HiddenInputs($request->getArgs(),'', - array('action','page','s','semsearch', - 'relation','attribute')); + $hiddenfield = HiddenInputs($request->getArgs(), '', + array('action', 'page', 's', 'semsearch', + 'relation', 'attribute')); $pagefilter = HTML::input(array('name' => 'page', - 'value' => $args['page'], - 'title' => _("Search only in these pages. With autocompletion."), - 'class' => 'dropdown', - 'acdropdown' => 'true', - 'autocomplete_complete' => 'true', - 'autocomplete_matchsubstring' => 'false', - 'autocomplete_list' => 'xmlrpc:wiki.titleSearch ^[S] 4' - ), ''); - $allrelations = $dbi->listRelations(false,false,true); + 'value' => $args['page'], + 'title' => _("Search only in these pages. With autocompletion."), + 'class' => 'dropdown', + 'acdropdown' => 'true', + 'autocomplete_complete' => 'true', + 'autocomplete_matchsubstring' => 'false', + 'autocomplete_list' => 'xmlrpc:wiki.titleSearch ^[S] 4' + ), ''); + $allrelations = $dbi->listRelations(false, false, true); $svalues = empty($allrelations) ? "" : join("','", $allrelations); - $reldef = JavaScript("var semsearch_relations = new Array('".$svalues."')"); + $reldef = JavaScript("var semsearch_relations = new Array('" . $svalues . "')"); $relation = HTML::input(array('name' => 'relation', - 'value' => $args['relation'], - 'title' => _("Filter by this relation. With autocompletion."), - 'class' => 'dropdown', - 'style' => 'width:10em', - 'acdropdown' => 'true', - 'autocomplete_assoc' => 'false', - 'autocomplete_complete' => 'true', - 'autocomplete_matchsubstring' => 'true', - 'autocomplete_list' => 'array:semsearch_relations' - ), ''); + 'value' => $args['relation'], + 'title' => _("Filter by this relation. With autocompletion."), + 'class' => 'dropdown', + 'style' => 'width:10em', + 'acdropdown' => 'true', + 'autocomplete_assoc' => 'false', + 'autocomplete_complete' => 'true', + 'autocomplete_matchsubstring' => 'true', + 'autocomplete_list' => 'array:semsearch_relations' + ), ''); $queryrel = HTML::input(array('name' => 's', - 'value' => $args['s'], - 'title' => _("Filter by this link. These are pagenames. With autocompletion."), - 'class' => 'dropdown', - 'acdropdown' => 'true', - 'autocomplete_complete' => 'true', - 'autocomplete_matchsubstring' => 'true', - 'autocomplete_list' => 'xmlrpc:wiki.titleSearch ^[S] 4' - ), ''); - $relsubmit = Button('submit:semsearch[relations]', _("Relations"), false); + 'value' => $args['s'], + 'title' => _("Filter by this link. These are pagenames. With autocompletion."), + 'class' => 'dropdown', + 'acdropdown' => 'true', + 'autocomplete_complete' => 'true', + 'autocomplete_matchsubstring' => 'true', + 'autocomplete_list' => 'xmlrpc:wiki.titleSearch ^[S] 4' + ), ''); + $relsubmit = Button('submit:semsearch[relations]', _("Relations"), false); // just testing some dhtml... not yet done $enhancements = HTML(); $nbsp = HTML::raw(' '); - $this_uri = $_SERVER['REQUEST_URI'].'#'; - $andbutton = new Button(_("AND"),$this_uri,'wikiaction', - array( - 'onclick' => "addquery('rel', 'and')", - 'title' => _("Add an AND query"))); - $orbutton = new Button(_("OR"),$this_uri,'wikiaction', - array( - 'onclick' => "addquery('rel', 'or')", - 'title' => _("Add an OR query"))); + $this_uri = $_SERVER['REQUEST_URI'] . '#'; + $andbutton = new Button(_("AND"), $this_uri, 'wikiaction', + array( + 'onclick' => "addquery('rel', 'and')", + 'title' => _("Add an AND query"))); + $orbutton = new Button(_("OR"), $this_uri, 'wikiaction', + array( + 'onclick' => "addquery('rel', 'or')", + 'title' => _("Add an OR query"))); if (DEBUG) $enhancements = HTML::span($andbutton, $nbsp, $orbutton); $instructions = _("Search in pages for a relation with that value (a pagename)."); $form1 = HTML::form(array('action' => $action, - 'method' => 'post', - 'accept-charset' => $GLOBALS['charset']), - $reldef, - $hiddenfield, HiddenInputs(array('attribute'=>'')), - $instructions, HTML::br(), - HTML::table - (array('border' => 0,'cellspacing' => 2), - HTML::colgroup(array('span' => 6)), - HTML::thead - (HTML::tr( - HTML::th('Pagefilter'), - HTML::th('Relation'), - HTML::th(), - HTML::th('Links'), - HTML::th() - )), - HTML::tbody - (HTML::tr( - HTML::td($pagefilter, _(": ")), - HTML::td($relation), - HTML::td(HTML::strong(HTML::tt(' :: '))), - HTML::td($queryrel), - HTML::td($nbsp, $relsubmit, $nbsp, $enhancements))))); + 'method' => 'post', + 'accept-charset' => $GLOBALS['charset']), + $reldef, + $hiddenfield, HiddenInputs(array('attribute' => '')), + $instructions, HTML::br(), + HTML::table + (array('border' => 0, 'cellspacing' => 2), + HTML::colgroup(array('span' => 6)), + HTML::thead + (HTML::tr( + HTML::th('Pagefilter'), + HTML::th('Relation'), + HTML::th(), + HTML::th('Links'), + HTML::th() + )), + HTML::tbody + (HTML::tr( + HTML::td($pagefilter, _(": ")), + HTML::td($relation), + HTML::td(HTML::strong(HTML::tt(' :: '))), + HTML::td($queryrel), + HTML::td($nbsp, $relsubmit, $nbsp, $enhancements))))); - $allattrs = $dbi->listRelations(false,true,true); + $allattrs = $dbi->listRelations(false, true, true); if (empty($allrelations) and empty($allattrs)) // be nice to the dummy. $this->_norelations_warning = 1; $svalues = empty($allattrs) ? "" : join("','", $allattrs); - $attdef = JavaScript("var semsearch_attributes = new Array('".$svalues."')\n" - ."var semsearch_op = new Array('" - .join("','", $this->_supported_operators) - ."')"); + $attdef = JavaScript("var semsearch_attributes = new Array('" . $svalues . "')\n" + . "var semsearch_op = new Array('" + . join("','", $this->_supported_operators) + . "')"); // TODO: We want some more tricks: Autofill the base unit of the selected // attribute into the s area. $attribute = HTML::input(array('name' => 'attribute', - 'value' => $args['attribute'], - 'title' => _("Filter by this attribute name. With autocompletion."), - 'class' => 'dropdown', - 'style' => 'width:10em', - 'acdropdown' => 'true', - 'autocomplete_complete' => 'true', - 'autocomplete_matchsubstring' => 'true', - 'autocomplete_assoc' => 'false', - 'autocomplete_list' => 'array:semsearch_attributes' - /* 'autocomplete_onselect' => 'check_unit' */ - ), ''); + 'value' => $args['attribute'], + 'title' => _("Filter by this attribute name. With autocompletion."), + 'class' => 'dropdown', + 'style' => 'width:10em', + 'acdropdown' => 'true', + 'autocomplete_complete' => 'true', + 'autocomplete_matchsubstring' => 'true', + 'autocomplete_assoc' => 'false', + 'autocomplete_list' => 'array:semsearch_attributes' + /* 'autocomplete_onselect' => 'check_unit' */ + ), ''); $attr_op = HTML::input(array('name' => 'attr_op', - 'value' => $args['attr_op'], - 'title' => _("Comparison operator. With autocompletion."), - 'class' => 'dropdown', - 'style' => 'width:2em', - 'acdropdown' => 'true', - 'autocomplete_complete' => 'true', - 'autocomplete_matchsubstring' => 'true', - 'autocomplete_assoc' => 'false', - 'autocomplete_list' => 'array:semsearch_op' - ), ''); + 'value' => $args['attr_op'], + 'title' => _("Comparison operator. With autocompletion."), + 'class' => 'dropdown', + 'style' => 'width:2em', + 'acdropdown' => 'true', + 'autocomplete_complete' => 'true', + 'autocomplete_matchsubstring' => 'true', + 'autocomplete_assoc' => 'false', + 'autocomplete_list' => 'array:semsearch_op' + ), ''); $queryatt = HTML::input(array('name' => 's', - 'value' => $args['s'], - 'title' => _("Filter by this numeric attribute value. With autocompletion."), //? - 'class' => 'dropdown', - 'acdropdown' => 'false', - 'autocomplete_complete' => 'true', - 'autocomplete_matchsubstring' => 'false', - 'autocomplete_assoc' => 'false', - 'autocomplete_list' => 'plugin:SemanticSearch page='.$args['page'].' attribute=^[S] attr_op==~' - ), ''); - $andbutton = new Button(_("AND"),$this_uri,'wikiaction', - array( - 'onclick' => "addquery('attr', 'and')", - 'title' => _("Add an AND query"))); - $orbutton = new Button(_("OR"),$this_uri,'wikiaction', - array( - 'onclick' => "addquery('attr', 'or')", - 'title' => _("Add an OR query"))); + 'value' => $args['s'], + 'title' => _("Filter by this numeric attribute value. With autocompletion."), //? + 'class' => 'dropdown', + 'acdropdown' => 'false', + 'autocomplete_complete' => 'true', + 'autocomplete_matchsubstring' => 'false', + 'autocomplete_assoc' => 'false', + 'autocomplete_list' => 'plugin:SemanticSearch page=' . $args['page'] . ' attribute=^[S] attr_op==~' + ), ''); + $andbutton = new Button(_("AND"), $this_uri, 'wikiaction', + array( + 'onclick' => "addquery('attr', 'and')", + 'title' => _("Add an AND query"))); + $orbutton = new Button(_("OR"), $this_uri, 'wikiaction', + array( + 'onclick' => "addquery('attr', 'or')", + 'title' => _("Add an OR query"))); if (DEBUG) $enhancements = HTML::span($andbutton, $nbsp, $orbutton); $attsubmit = Button('submit:semsearch[attributes]', _("Attributes"), false); - $instructions = HTML::span(_("Search in pages for an attribute with that numeric value."),"\n"); + $instructions = HTML::span(_("Search in pages for an attribute with that numeric value."), "\n"); if (DEBUG) $instructions->pushContent - (HTML(" ", new Button(_("Advanced..."),_("SemanticSearchAdvanced")))); + (HTML(" ", new Button(_("Advanced..."), _("SemanticSearchAdvanced")))); $form2 = HTML::form(array('action' => $action, - 'method' => 'post', - 'accept-charset' => $GLOBALS['charset']), - $attdef, - $hiddenfield, HiddenInputs(array('relation'=>'')), - $instructions, HTML::br(), - HTML::table - (array('border' => 0,'cellspacing' => 2), - HTML::colgroup(array('span' => 6)), - HTML::thead - (HTML::tr( - HTML::th('Pagefilter'), - HTML::th('Attribute'), - HTML::th('Op'), - HTML::th('Value'), - HTML::th() - )), - HTML::tbody - (HTML::tr( - HTML::td($pagefilter, _(": ")), - HTML::td($attribute), - HTML::td($attr_op), - HTML::td($queryatt), - HTML::td($nbsp, $attsubmit, $nbsp, $enhancements))))); + 'method' => 'post', + 'accept-charset' => $GLOBALS['charset']), + $attdef, + $hiddenfield, HiddenInputs(array('relation' => '')), + $instructions, HTML::br(), + HTML::table + (array('border' => 0, 'cellspacing' => 2), + HTML::colgroup(array('span' => 6)), + HTML::thead + (HTML::tr( + HTML::th('Pagefilter'), + HTML::th('Attribute'), + HTML::th('Op'), + HTML::th('Value'), + HTML::th() + )), + HTML::tbody + (HTML::tr( + HTML::td($pagefilter, _(": ")), + HTML::td($attribute), + HTML::td($attr_op), + HTML::td($queryatt), + HTML::td($nbsp, $attsubmit, $nbsp, $enhancements))))); return HTML($form1, $form2); } - function regex_query ($string, $case_exact, $regex) { - if ($string != '*' and $regex == 'auto') { + function regex_query($string, $case_exact, $regex) + { + if ($string != '*' and $regex == 'auto') { if (strcspn($string, ".+*?^$\"") == strlen($string)) { - // performance hack: construct an exact query w/o parsing. pcre is fastest. + // performance hack: construct an exact query w/o parsing. pcre is fastest. $q = new TextSearchQuery($string, $case_exact, 'pcre'); // and now override the fields unset ($q->_stoplist); @@ -266,11 +273,12 @@ extends WikiPlugin return new TextSearchQuery($string, $case_exact, $regex); } - function run ($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { global $WikiTheme; - $this->_supported_operators = array(':=','<','<=','>','>=','!=','==','=~'); - $this->_text_operators = array(':=','==','=~','!='); + $this->_supported_operators = array(':=', '<', '<=', '>', '>=', '!=', '==', '=~'); + $this->_text_operators = array(':=', '==', '=~', '!='); $args = $this->getArgs($argstr, $request); if (empty($args['page'])) $args['page'] = "*"; @@ -280,11 +288,11 @@ extends WikiPlugin $form = $this->showForm($dbi, $request, $args); if (isset($this->_norelations_warning)) $form->pushContent - (HTML::div(array('class' => 'warning'), - _("Warning:"),HTML::br(), - _("No relations nor attributes in the whole wikidb defined!") - ,"\n" - ,fmt("See %s",WikiLink(_("Help:SemanticRelations"))))); + (HTML::div(array('class' => 'warning'), + _("Warning:"), HTML::br(), + _("No relations nor attributes in the whole wikidb defined!") + , "\n" + , fmt("See %s", WikiLink(_("Help:SemanticRelations"))))); extract($args); // for convenience and harmony we allow GET requests also. if (!$request->isPost()) { @@ -309,8 +317,8 @@ extends WikiPlugin } $searchtype = "Text"; if (!empty($relation)) { - $querydesc = $relation."::".$s; - $linkquery = $this->regex_query($s, $args['case_exact'], $args['regex']); + $querydesc = $relation . "::" . $s; + $linkquery = $this->regex_query($s, $args['case_exact'], $args['regex']); $relquery = $this->regex_query($relation, $args['case_exact'], $args['regex']); $links = $dbi->linkSearch($pagequery, $linkquery, 'relation', $relquery); $pagelist = new PageList($info, $exclude, $args); @@ -323,19 +331,19 @@ extends WikiPlugin // $pagelist->_columns_seen is the exploded info if (!$info or ($info and isset($pagelist->_columns_seen['relation']))) $pagelist->addColumnObject - (new _PageList_Column_SemanticSearch_relation('relation', _("Relation"), $pagelist)); + (new _PageList_Column_SemanticSearch_relation('relation', _("Relation"), $pagelist)); if (!$args['info'] or ($args['info'] and isset($pagelist->_columns_seen['linkto']))) $pagelist->addColumnObject - (new _PageList_Column_SemanticSearch_link('linkto', _("Link"), $pagelist)); + (new _PageList_Column_SemanticSearch_link('linkto', _("Link"), $pagelist)); } // can we merge two different pagelist? if (!empty($attribute)) { - $relquery = $this->regex_query($attribute, $args['case_exact'], $args['regex']); + $relquery = $this->regex_query($attribute, $args['case_exact'], $args['regex']); if (!in_array($attr_op, $this->_supported_operators)) { return HTML($form, $this->error(fmt("Illegal operator: %s", - HTML::tt($attr_op)))); + HTML::tt($attr_op)))); } - $s_base = preg_replace("/,/","", $s); + $s_base = preg_replace("/,/", "", $s); $units = new Units(); if (!is_numeric($s_base)) { $s_base = $units->basevalue($s_base); @@ -359,29 +367,28 @@ extends WikiPlugin // it might not be the best idea to use '*' as variable to expand. hmm. if ($attribute == '*') $attribute = '_star_'; $searchtype = "Numeric"; - $query = $attribute." ".$attr_op." ".$s_base; + $query = $attribute . " " . $attr_op . " " . $s_base; $linkquery = new SemanticAttributeSearchQuery($query, $attribute, - $units->baseunit($s)); + $units->baseunit($s)); if ($attribute == '_star_') $attribute = '*'; - $querydesc = $attribute." ".$attr_op." ".$s; + $querydesc = $attribute . " " . $attr_op . " " . $s; - // no number or unit: check other text matchers or '*' MATCH_ALL + // no number or unit: check other text matchers or '*' MATCH_ALL } elseif (in_array($attr_op, $this->_text_operators)) { if ($attr_op == '=~') { if ($s == '*') $s = '.*'; // help the poor user. we need pcre syntax. $linkquery = new TextSearchQuery("$s", $args['case_exact'], 'pcre'); - } - else - $linkquery = $this->regex_query($s, $args['case_exact'], $args['regex']); + } else + $linkquery = $this->regex_query($s, $args['case_exact'], $args['regex']); $querydesc = "$attribute $attr_op $s"; - // should we fail or skip when the user clicks on Relations? - } elseif (isset($posted['relations']) and $posted['relations']) { + // should we fail or skip when the user clicks on Relations? + } elseif (isset($posted['relations']) and $posted['relations']) { $linkquery = false; // skip } else { - $querydesc = $attribute." ".$attr_op." ".$s; + $querydesc = $attribute . " " . $attr_op . " " . $s; return HTML($form, $this->error(fmt("Only text operators can be used with strings: %s", - HTML::tt($querydesc)))); + HTML::tt($querydesc)))); } if ($linkquery) { @@ -396,15 +403,17 @@ extends WikiPlugin } // default (=empty info) wants all three. but we want to override this. if (!$args['info'] or - ($args['info'] and isset($pagelist->_columns_seen['attribute']))) + ($args['info'] and isset($pagelist->_columns_seen['attribute'])) + ) $pagelist->addColumnObject - (new _PageList_Column_SemanticSearch_relation('attribute', - _("Attribute"), $pagelist)); + (new _PageList_Column_SemanticSearch_relation('attribute', + _("Attribute"), $pagelist)); if (!$args['info'] or - ($args['info'] and isset($pagelist->_columns_seen['value']))) + ($args['info'] and isset($pagelist->_columns_seen['value'])) + ) $pagelist->addColumnObject - (new _PageList_Column_SemanticSearch_link('value', - _("Value"), $pagelist)); + (new _PageList_Column_SemanticSearch_link('value', + _("Value"), $pagelist)); } } if (!isset($pagelist)) { @@ -412,46 +421,53 @@ extends WikiPlugin $pagelist = new PageList(); } if (!$noheader) { - // We put the form into the caption just to be able to return one pagelist object, - // and to still have the convenience form at the top. we could workaround this by - // putting the form as WikiFormRich into the actionpage. but thid doesnt look as - // nice as this here. + // We put the form into the caption just to be able to return one pagelist object, + // and to still have the convenience form at the top. we could workaround this by + // putting the form as WikiFormRich into the actionpage. but thid doesnt look as + // nice as this here. $pagelist->setCaption - ( // on mozilla the form doesn't fit into the caption very well. - HTML($noform ? '' : HTML($form,HTML::hr()), - fmt("Semantic %s Search Result for \"%s\" in pages \"%s\"", - $searchtype, $querydesc, $page))); + ( // on mozilla the form doesn't fit into the caption very well. + HTML($noform ? '' : HTML($form, HTML::hr()), + fmt("Semantic %s Search Result for \"%s\" in pages \"%s\"", + $searchtype, $querydesc, $page))); } return $pagelist; } -}; +} + +; class _PageList_Column_SemanticSearch_relation -extends _PageList_Column + extends _PageList_Column { - function _PageList_Column_SemanticSearch_relation ($field, $heading, &$pagelist) { + function _PageList_Column_SemanticSearch_relation($field, $heading, &$pagelist) + { $this->_field = $field; $this->_heading = $heading; $this->_need_rev = false; $this->_iscustom = true; $this->_pagelist =& $pagelist; } - function _getValue(&$page, $revision_handle) { + + function _getValue(&$page, $revision_handle) + { if (is_object($page)) $text = $page->getName(); else $text = $page; $link = $this->_pagelist->_links[$this->current_row]; - return WikiLink($link['linkname'],'if_known'); + return WikiLink($link['linkname'], 'if_known'); } } + class _PageList_Column_SemanticSearch_link -extends _PageList_Column_SemanticSearch_relation + extends _PageList_Column_SemanticSearch_relation { - function _getValue(&$page, $revision_handle) { + function _getValue(&$page, $revision_handle) + { if (is_object($page)) $text = $page->getName(); else $text = $page; $link = $this->_pagelist->_links[$this->current_row]; if ($this->_field != 'value') - return WikiLink($link['linkvalue'],'if_known'); + return WikiLink($link['linkvalue'], 'if_known'); else return $link['linkvalue']; } diff --git a/lib/plugin/SemanticSearchAdvanced.php b/lib/plugin/SemanticSearchAdvanced.php index 77f854d57..238f41a00 100644 --- a/lib/plugin/SemanticSearchAdvanced.php +++ b/lib/plugin/SemanticSearchAdvanced.php @@ -56,90 +56,97 @@ require_once 'lib/plugin/SemanticSearch.php'; */ class WikiPlugin_SemanticSearchAdvanced -extends WikiPlugin_SemanticSearch + extends WikiPlugin_SemanticSearch { - function getName() { + function getName() + { return _("SemanticSearchAdvanced"); } - function getDescription() { + + function getDescription() + { return _("Parse and execute a full query expression"); } - function getDefaultArguments() { + + function getDefaultArguments() + { return array_merge - ( - PageList::supportedArgs(), // paging and more. - array( - 's' => "", // query expression - 'page' => "*", // which pages (glob allowed), default: all - 'case_exact' => false, - 'regex' => 'auto', // hmm - 'noform' => false, // don't show form with results. - 'noheader' => false // no caption - )); + ( + PageList::supportedArgs(), // paging and more. + array( + 's' => "", // query expression + 'page' => "*", // which pages (glob allowed), default: all + 'case_exact' => false, + 'regex' => 'auto', // hmm + 'noform' => false, // don't show form with results. + 'noheader' => false // no caption + )); } - function showForm (&$dbi, &$request, $args, $allrelations) { - global $WikiTheme; + function showForm(&$dbi, &$request, $args, $allrelations) + { + global $WikiTheme; $action = $request->getPostURL(); - $hiddenfield = HiddenInputs($request->getArgs(),'', - array('action','page','s')); + $hiddenfield = HiddenInputs($request->getArgs(), '', + array('action', 'page', 's')); $pagefilter = HTML::input(array('name' => 'page', - 'value' => $args['page'], - 'title' => _("Search only in these pages. With autocompletion."), - 'class' => 'dropdown', - 'acdropdown' => 'true', - 'autocomplete_complete' => 'true', - 'autocomplete_matchsubstring' => 'false', - 'autocomplete_list' => 'xmlrpc:wiki.titleSearch ^[S] 4' - ), ''); + 'value' => $args['page'], + 'title' => _("Search only in these pages. With autocompletion."), + 'class' => 'dropdown', + 'acdropdown' => 'true', + 'autocomplete_complete' => 'true', + 'autocomplete_matchsubstring' => 'false', + 'autocomplete_list' => 'xmlrpc:wiki.titleSearch ^[S] 4' + ), ''); $help = Button('submit:semsearch[help]', "?", false); $svalues = empty($allrelations) ? "" : join("','", $allrelations); - $reldef = JavaScript("var semsearch_relations = new Array('".$svalues."')"); + $reldef = JavaScript("var semsearch_relations = new Array('" . $svalues . "')"); $querybox = HTML::textarea(array('name' => 's', - 'title' => _("Enter a valid query expression"), - 'rows' => 4, - 'acdropdown' => 'true', - 'autocomplete_complete' => 'true', - 'autocomplete_assoc' => 'false', - 'autocomplete_matchsubstring' => 'true', - 'autocomplete_list' => 'array:semsearch_relations' - ), $args['s']); - $submit = Button('submit:semsearch[relations]', _("Search"), false, - array('title' => 'Move to help page. No seperate window')); + 'title' => _("Enter a valid query expression"), + 'rows' => 4, + 'acdropdown' => 'true', + 'autocomplete_complete' => 'true', + 'autocomplete_assoc' => 'false', + 'autocomplete_matchsubstring' => 'true', + 'autocomplete_list' => 'array:semsearch_relations' + ), $args['s']); + $submit = Button('submit:semsearch[relations]', _("Search"), false, + array('title' => 'Move to help page. No seperate window')); $instructions = _("Search in all specified pages for the expression."); $form = HTML::form(array('action' => $action, - 'method' => 'post', - 'accept-charset' => $GLOBALS['charset']), - $reldef, - $hiddenfield, HiddenInputs(array('attribute'=>'')), - $instructions, HTML::br(), - HTML::table(array('border'=>'0','width' =>'100%'), - HTML::tr(HTML::td(_("Pagename(s): "), $pagefilter), - HTML::td(array('align' => 'right'), - $help)), - HTML::tr(HTML::td(array('colspan' => 2), - $querybox))), - HTML::br(), - HTML::div(array('align'=>'center'),$submit)); + 'method' => 'post', + 'accept-charset' => $GLOBALS['charset']), + $reldef, + $hiddenfield, HiddenInputs(array('attribute' => '')), + $instructions, HTML::br(), + HTML::table(array('border' => '0', 'width' => '100%'), + HTML::tr(HTML::td(_("Pagename(s): "), $pagefilter), + HTML::td(array('align' => 'right'), + $help)), + HTML::tr(HTML::td(array('colspan' => 2), + $querybox))), + HTML::br(), + HTML::div(array('align' => 'center'), $submit)); return $form; } - function run ($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { global $WikiTheme; - $this->_supported_operators = array(':=','<','<=','>','>=','!=','==','=~'); + $this->_supported_operators = array(':=', '<', '<=', '>', '>=', '!=', '==', '=~'); $args = $this->getArgs($argstr, $request); $posted = $request->getArg('semsearch'); $request->setArg('semsearch', false); if ($request->isPost() and isset($posted['help'])) { $request->redirect(WikiURL(_("Help/SemanticSearchAdvancedPlugin"), - array('redirectfrom' => $basepage), true)); + array('redirectfrom' => $basepage), true)); } $allrelations = $dbi->listRelations(); $form = $this->showForm($dbi, $request, $args, $allrelations); if (isset($this->_norelations_warning)) $form->pushContent(HTML::div(array('class' => 'warning'), - _("Warning:").$this->_norelations_warning)); + _("Warning:") . $this->_norelations_warning)); extract($args); // For convenience, peace and harmony we allow GET requests also. if (!$args['s']) // check for good GET request @@ -160,14 +167,14 @@ extends WikiPlugin_SemanticSearch $pagelist = new PageList($args['info'], $args['exclude'], $args); if (!$noheader) { $pagelist->setCaption - (HTML($noform ? '' : HTML($form,HTML::hr()), - fmt("Semantic %s Search Result for \"%s\" in pages \"%s\"", - '',$s,$page))); + (HTML($noform ? '' : HTML($form, HTML::hr()), + fmt("Semantic %s Search Result for \"%s\" in pages \"%s\"", + '', $s, $page))); } if (!$regex and $missing = array_diff($parsed_relations, $allrelations)) return $pagelist; - $relquery = new TextSearchQuery(join(" ",$parsed_relations)); - if (!$relquery->match(join(" ",$allrelations))) + $relquery = new TextSearchQuery(join(" ", $parsed_relations)); + if (!$relquery->match(join(" ", $allrelations))) return $pagelist; $pagequery = new TextSearchQuery($page, $args['case_exact'], $args['regex']); // if we have only numeric or text ops we can optimize. @@ -182,21 +189,23 @@ extends WikiPlugin_SemanticSearch $pagelist->_links[] = $link; } $pagelist->addColumnObject - (new _PageList_Column_SemanticSearch_relation('relation', _("Relation"), $pagelist)); + (new _PageList_Column_SemanticSearch_relation('relation', _("Relation"), $pagelist)); $pagelist->addColumnObject - (new _PageList_Column_SemanticSearch_link('link', _("Link"), $pagelist)); + (new _PageList_Column_SemanticSearch_link('link', _("Link"), $pagelist)); return $pagelist; } // ... (for _variable subquery) ... - function bindSubquery($query) { + function bindSubquery($query) + { } // is_a::city* and (population < 1.000.000 or population > 10.000.000) // => is_a population // Do we support wildcards in relation names also? is_*::city - function detectRelationsAndAttributes($subquery) { + function detectRelationsAndAttributes($subquery) + { $relations = array(); // relations are easy //$reltoken = preg_grep("/::/", preg_split("/\s+/", $query)); @@ -209,7 +218,9 @@ extends WikiPlugin_SemanticSearch return $relations; // for attributes we might use the tokenizer. All non-numerics excl. units and non-ops } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/SiteMap.php b/lib/plugin/SiteMap.php index a7a5fe8b5..b5de8d244 100644 --- a/lib/plugin/SiteMap.php +++ b/lib/plugin/SiteMap.php @@ -43,34 +43,38 @@ require_once 'lib/PageList.php'; class WikiPlugin_SiteMap -extends WikiPlugin + extends WikiPlugin { var $_pagename; - function getName () { + function getName() + { return _("SiteMap"); } - function getDescription () { + function getDescription() + { return _("Recursively get BackLinks or links"); } - function getDefaultArguments() { - return array('exclude' => '', - 'include_self' => 0, - 'noheader' => 0, - 'page' => '[pagename]', - 'description' => $this->getDescription(), - 'reclimit' => 4, - 'info' => false, - 'direction' => 'back', - 'firstreversed' => false, - 'excludeunknown' => true, - 'includepages' => '', // only for IncludeSiteMap and IncludeTree - 'category' => '', // optional category filter (comma-delimited) - 'dtree' => false, // optional for IncludeTree - ); + function getDefaultArguments() + { + return array('exclude' => '', + 'include_self' => 0, + 'noheader' => 0, + 'page' => '[pagename]', + 'description' => $this->getDescription(), + 'reclimit' => 4, + 'info' => false, + 'direction' => 'back', + 'firstreversed' => false, + 'excludeunknown' => true, + 'includepages' => '', // only for IncludeSiteMap and IncludeTree + 'category' => '', // optional category filter (comma-delimited) + 'dtree' => false, // optional for IncludeTree + ); } + // info arg allows multiple columns // info=mtime,hits,summary,version,author,locked,minor // exclude arg allows multiple pagenames @@ -79,7 +83,8 @@ extends WikiPlugin // Fixme: overcome limitation if two SiteMap plugins are in the same page! // static $VisitedPages still holds it function recursivelyGetBackLinks($startpage, $pagearr, $level = '*', - $reclimit = '***') { + $reclimit = '***') + { static $VisitedPages = array(); $startpagename = $startpage->getName(); @@ -93,19 +98,20 @@ extends WikiPlugin while ($link = $pagelinks->next()) { $linkpagename = $link->getName(); if (($linkpagename != $startpagename) - and (!$this->ExcludedPages or !preg_match("/".$this->ExcludedPages."/", $linkpagename))) - { + and (!$this->ExcludedPages or !preg_match("/" . $this->ExcludedPages . "/", $linkpagename)) + ) { $pagearr[$level . " [$linkpagename]"] = $link; $pagearr = $this->recursivelyGetBackLinks($link, $pagearr, - $level . '*', - $reclimit); + $level . '*', + $reclimit); } } return $pagearr; } function recursivelyGetLinks($startpage, $pagearr, $level = '*', - $reclimit = '***') { + $reclimit = '***') + { static $VisitedPages = array(); $startpagename = $startpage->getName(); @@ -116,19 +122,19 @@ extends WikiPlugin return $pagearr; array_push($VisitedPages, $startpagename); $reversed = (($this->firstreversed) - && ($startpagename == $this->initialpage)); + && ($startpagename == $this->initialpage)); //trigger_error("DEBUG: \$reversed = $reversed"); $pagelinks = $startpage->getLinks($reversed); while ($link = $pagelinks->next()) { $linkpagename = $link->getName(); if (($linkpagename != $startpagename) and - (!$this->ExcludedPages or !preg_match("/$this->ExcludedPages/", $linkpagename))) - { + (!$this->ExcludedPages or !preg_match("/$this->ExcludedPages/", $linkpagename)) + ) { if (!$this->excludeunknown or $this->dbi->isWikiPage($linkpagename)) { $pagearr[$level . " [$linkpagename]"] = $link; $pagearr = $this->recursivelyGetLinks($link, $pagearr, - $level . '*', - $reclimit); + $level . '*', + $reclimit); } } } @@ -136,7 +142,8 @@ extends WikiPlugin } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { include_once 'lib/BlockParser.php'; $args = $this->getArgs($argstr, $request, false); @@ -162,9 +169,9 @@ extends WikiPlugin } //Fixme: override given arg $description = $this->getDescription(); - if (! $noheader) { - $out = $this->getDescription() ." ". sprintf(_("(max. recursion level: %d)"), - $reclimit) . ":\n\n"; + if (!$noheader) { + $out = $this->getDescription() . " " . sprintf(_("(max. recursion level: %d)"), + $reclimit) . ":\n\n"; $html->pushContent(TransformText($out, 1.0, $page)); } $pagelist = new PageList($info, $exclude); @@ -173,8 +180,7 @@ extends WikiPlugin $pagearr = array(); if ($direction == 'back') { $pagearr = $this->recursivelyGetBackLinks($p, $pagearr, "*", $limit); - } - else { + } else { $this->dbi = $dbi; $this->initialpage = $page; $this->firstreversed = $firstreversed; @@ -185,7 +191,7 @@ extends WikiPlugin reset($pagearr); if (!empty($includepages)) { // disallow direct usage, only via child class IncludeSiteMap - if (!isa($this,"WikiPlugin_IncludeSiteMap") and !isa($this,"WikiPlugin_IncludeTree")) + if (!isa($this, "WikiPlugin_IncludeSiteMap") and !isa($this, "WikiPlugin_IncludeTree")) $includepages = ''; if (!is_string($includepages)) $includepages = ' '; // avoid plugin loader problems @@ -205,8 +211,7 @@ extends WikiPlugin $html->pushContent($pagehtml); //$html->pushContent( HTML(TransformText($indenter, 1.0, $page), $pagehtml)); //$out .= $indenter . $pagehtml . "\n"; - } - else { + } else { $out .= $key . "\n"; } } @@ -216,7 +221,9 @@ extends WikiPlugin return $html; } } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/SpellCheck.php b/lib/plugin/SpellCheck.php index 55b2f3734..2664ad37a 100644 --- a/lib/plugin/SpellCheck.php +++ b/lib/plugin/SpellCheck.php @@ -31,61 +31,69 @@ * Currently we do use aspell (via pspell or cmdline) in ispell mode. * Maybe enchant later. * cmdline preparation: - do autosplit wikiwords && sed s,^,\^^, $pagename | aspell --lang=$LANG -a - or - sed s,^,\^^, $pagename | aspell --lang=$LANG -a -C +do autosplit wikiwords && sed s,^,\^^, $pagename | aspell --lang=$LANG -a +or +sed s,^,\^^, $pagename | aspell --lang=$LANG -a -C => - & phpwiki 62 30: pipework, paprika, Popek, Phip, Pike, Viki, pike, ... +& phpwiki 62 30: pipework, paprika, Popek, Phip, Pike, Viki, pike, ... */ // Those settings should really be defined in config.ini, not here. if (!function_exists('pspell_new_config')) { // old pipe interface: if (!defined('ASPELL_EXE')) - define('ASPELL_EXE','aspell'); + define('ASPELL_EXE', 'aspell'); //define('ASPELL_EXE','/usr/local/bin/aspell'); //define('ASPELL_EXE','/home/groups/p/ph/phpwiki/bin/aspell'); if (!defined('ASPELL_DATA_DIR')) if (isWindows()) - define('ASPELL_DATA_DIR','c:\cygwin\usr\share\aspell'); + define('ASPELL_DATA_DIR', 'c:\cygwin\usr\share\aspell'); else - define('ASPELL_DATA_DIR','/usr/share/aspell'); + define('ASPELL_DATA_DIR', '/usr/share/aspell'); //define('ASPELL_DATA_DIR','/home/groups/p/ph/phpwiki/share/highlight'); } else { // new library interface through the pspell extension: // "/var/dictionaries/custom.pws" if (!defined('PSPELL_PWL')) - define('PSPELL_PWL', ''); // phpwiki-special wordlist + define('PSPELL_PWL', ''); // phpwiki-special wordlist // "/var/dictionaries/custom.repl" if (!defined('PSPELL_REPL')) define('PSPELL_REPL', ''); // phpwiki-special replacement list (persistent replacements) } class WikiPlugin_SpellCheck -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("Spell Checker"); } - function getDescription () { + + function getDescription() + { return _("Check the spelling of a page and make suggestions"); } - function managesValidators() { + + function managesValidators() + { return true; } - function getDefaultArguments() { + + function getDefaultArguments() + { return array('pagename' => '[]', // button or preview highlight? - ); + ); } - function pspell_check ($text, $lang=false) { + function pspell_check($text, $lang = false) + { global $charset; if ($lang) $lang = $GLOBALS['LANG']; $words = preg_split('/[\W]+?/', $text); $misspelled = $return = array(); $pspell_config = pspell_config_create($lang, "", "", $charset, - PSPELL_NORMAL|PSPELL_RUN_TOGETHER); + PSPELL_NORMAL | PSPELL_RUN_TOGETHER); //pspell_config_runtogether($pspell_config, true); if (PSPELL_PWL) pspell_config_personal($pspell_config, PSPELL_PWL); @@ -105,11 +113,13 @@ extends WikiPlugin return $return; } - function pspell_correct ($text, $corrections) { + function pspell_correct($text, $corrections) + { ; } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { extract($this->getArgs($argstr, $request)); $page = $dbi->getPage($pagename); $current = $page->getCurrentRevision(); @@ -136,7 +146,7 @@ extends WikiPlugin $cache = new WikiPluginCached; $code = $cache->filterThroughCmd($source, $commandLine); if (empty($code)) - return $this->error(fmt("Couldn't start commandline '%s'",$commandLine)); + return $this->error(fmt("Couldn't start commandline '%s'", $commandLine)); $sugg = array(); foreach (preg_split("/\n/", $code) as $line) { if (preg_match("/^& (\w+) \d+ \d+: (.+)$/", $line, $m)) { @@ -154,8 +164,7 @@ extends WikiPlugin $revision = $page->getRevision($version); if (!$revision) NoSuchRevision($request, $page, $version); - } - else { + } else { $revision = $page->getCurrentRevision(); } $GLOBALS['request']->setArg('suggestions', $sugg); @@ -172,15 +181,17 @@ extends WikiPlugin $r = HTML(); foreach ($suggs as $s) { $r->pushContent(HTML::a(array('class' => 'spell-sugg', - 'href' => "javascript:do_replace('$word','$s')"), - $s),", "); + 'href' => "javascript:do_replace('$word','$s')"), + $s), ", "); } $list->pushContent(HTML::li($w, _(": "), $r)); } $html->pushContent($list); return $html; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/SqlResult.php b/lib/plugin/SqlResult.php index ff5704a18..aa4ba5052 100644 --- a/lib/plugin/SqlResult.php +++ b/lib/plugin/SqlResult.php @@ -59,44 +59,50 @@ require_once 'lib/PageList.php'; class WikiPlugin_SqlResult -extends WikiPlugin + extends WikiPlugin { var $_args; - function getName () { + function getName() + { return _("SqlResult"); } - function getDescription () { + function getDescription() + { return _("Display arbitrary SQL result tables"); } - function getDefaultArguments() { + function getDefaultArguments() + { return array( - 'alias' => false, // DSN database specification - 'ordered' => false, // if to display as
        list: single col only without template - 'template' => false, // use a custom /template.tmpl - 'where' => false, // custom filter for the query - 'sortby' => false, // for paging, default none - 'limit' => "0,50", // for paging, default: only the first 50 - ); + 'alias' => false, // DSN database specification + 'ordered' => false, // if to display as
          list: single col only without template + 'template' => false, // use a custom /template.tmpl + 'where' => false, // custom filter for the query + 'sortby' => false, // for paging, default none + 'limit' => "0,50", // for paging, default: only the first 50 + ); } - function getDsn($alias) { + function getDsn($alias) + { $ini = parse_ini_file(FindFile("config/SqlResult.ini")); return $ini[$alias]; } /** Get the SQL statement from the rest of the lines */ - function handle_plugin_args_cruft($argstr, $args) { - $this->_sql = str_replace("\n"," ",$argstr); + function handle_plugin_args_cruft($argstr, $args) + { + $this->_sql = str_replace("\n", " ", $argstr); return; } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { global $DBParams; - //$request->setArg('nocache','1'); + //$request->setArg('nocache','1'); extract($this->getArgs($argstr, $request)); if (!$alias) return $this->error(_("No DSN alias for SqlResult.ini specified")); @@ -113,7 +119,7 @@ extends WikiPlugin $sql = str_replace("%%limit%%", $limit, $sql); else { if (strstr($sql, "LIMIT")) - $sql = preg_replace("/LIMIT\s+[\d,]+\s+/m", "LIMIT ".$limit." ", $sql); + $sql = preg_replace("/LIMIT\s+[\d,]+\s+/m", "LIMIT " . $limit . " ", $sql); } } if (strstr($sql, "%%sortby%%")) { @@ -121,17 +127,17 @@ extends WikiPlugin $sql = preg_replace("/ORDER BY .*%%sortby%%\s/m", "", $sql); else $sql = str_replace("%%sortby%%", $sortby, $sql); - } elseif (PageList::sortby($sortby,'db')) { // add sorting: support paging sortby links - if (preg_match("/\sORDER\s/",$sql)) - $sql = preg_replace("/ORDER BY\s\S+\s/m", "ORDER BY " . PageList::sortby($sortby,'db'), $sql); + } elseif (PageList::sortby($sortby, 'db')) { // add sorting: support paging sortby links + if (preg_match("/\sORDER\s/", $sql)) + $sql = preg_replace("/ORDER BY\s\S+\s/m", "ORDER BY " . PageList::sortby($sortby, 'db'), $sql); else - $sql .= " ORDER BY " . PageList::sortby($sortby,'db'); + $sql .= " ORDER BY " . PageList::sortby($sortby, 'db'); } $inidsn = $this->getDsn($alias); if (!$inidsn) return $this->error(sprintf(_("No DSN for alias %s in SqlResult.ini found"), - $alias)); + $alias)); // adodb or pear? adodb as default, since we distribute per default it. // for pear there may be overrides. // TODO: native PDO support (for now we use ADODB) @@ -139,7 +145,7 @@ extends WikiPlugin $dbh = DB::connect($inidsn); $all = $dbh->getAll($sql); if (DB::isError($all)) { - return $this->error($all->getMessage(). ' ' . $all->userinfo); + return $this->error($all->getMessage() . ' ' . $all->userinfo); } } else { // unless PearDB use the included ADODB, regardless if dba, file or PDO, ... if ($DBParams['dbtype'] != 'ADODB') { @@ -147,8 +153,8 @@ extends WikiPlugin } $parsed = parseDSN($inidsn); $dbh = &ADONewConnection($parsed['phptype']); - $conn = $dbh->Connect($parsed['hostspec'],$parsed['username'], - $parsed['password'], $parsed['database']); + $conn = $dbh->Connect($parsed['hostspec'], $parsed['username'], + $parsed['password'], $parsed['database']); if (!$conn) return $this->error($dbh->errorMsg()); $GLOBALS['ADODB_FETCH_MODE'] = ADODB_FETCH_ASSOC; @@ -169,50 +175,52 @@ extends WikiPlugin if ($template) { $args = array_merge( - array('SqlResult' => $all, // the resulting array of rows - 'ordered' => $ordered, // whether to display as
            /
            or
              - 'where' => $where, - 'sortby' => $sortby, - 'limit' => $limit), - $args); // paging params override given params + array('SqlResult' => $all, // the resulting array of rows + 'ordered' => $ordered, // whether to display as
                /
                or
                  + 'where' => $where, + 'sortby' => $sortby, + 'limit' => $limit), + $args); // paging params override given params return Template($template, $args); } else { if ($ordered) { - $html = HTML::ol(array('class'=>'sqlresult')); + $html = HTML::ol(array('class' => 'sqlresult')); if ($all) - foreach ($all as $row) { - $html->pushContent(HTML::li(array('class'=> $i++ % 2 ? 'evenrow' : 'oddrow'), $row[0])); - } + foreach ($all as $row) { + $html->pushContent(HTML::li(array('class' => $i++ % 2 ? 'evenrow' : 'oddrow'), $row[0])); + } } else { - $html = HTML::table(array('class'=>'sqlresult')); + $html = HTML::table(array('class' => 'sqlresult')); $i = 0; if ($all) - foreach ($all as $row) { - $tr = HTML::tr(array('class'=> $i++ % 2 ? 'evenrow' : 'oddrow')); - if ($row) - foreach ($row as $col) { - $tr->pushContent(HTML::td($col)); - } - $html->pushContent($tr); - } + foreach ($all as $row) { + $tr = HTML::tr(array('class' => $i++ % 2 ? 'evenrow' : 'oddrow')); + if ($row) + foreach ($row as $col) { + $tr->pushContent(HTML::td($col)); + } + $html->pushContent($tr); + } } } // do paging via pagelink template if (!empty($args['NUMPAGES'])) { $paging = Template("pagelink", $args); $html = $table->pushContent(HTML::thead($paging), - HTML::tbody($html), - HTML::tfoot($paging)); + HTML::tbody($html), + HTML::tfoot($paging)); } if (0 and DEBUG) { // test deferred error/warning/notice collapsing - trigger_error("test notice", E_USER_NOTICE); + trigger_error("test notice", E_USER_NOTICE); trigger_error("test warning", E_USER_WARNING); } return $html; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/SyncWiki.php b/lib/plugin/SyncWiki.php index 81b265efc..e54aa5795 100644 --- a/lib/plugin/SyncWiki.php +++ b/lib/plugin/SyncWiki.php @@ -40,29 +40,33 @@ require_once 'lib/loadsave.php'; include_once 'lib/plugin/WikiAdminUtils.php'; class WikiPlugin_SyncWiki -extends WikiPlugin_WikiAdminUtils + extends WikiPlugin_WikiAdminUtils { - function getName () { + function getName() + { return _("SyncWiki"); } - function getDescription () { + function getDescription() + { return _("Synchronize pages with external PhpWiki"); } - function getDefaultArguments() { - return array('url' => '', - 'noimport' => 0, - 'noexport' => 0, - 'noupload' => 0, - 'label' => $this->getName(), - //'userid' => false, - 'passwd' => false, - 'sid' => false, - ); + function getDefaultArguments() + { + return array('url' => '', + 'noimport' => 0, + 'noexport' => 0, + 'noupload' => 0, + 'label' => $this->getName(), + //'userid' => false, + 'passwd' => false, + 'sid' => false, + ); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); $args['action'] = 'syncwiki'; extract($args); @@ -75,14 +79,16 @@ extends WikiPlugin_WikiAdminUtils $posted = $request->getArg('wikiadminutils'); if ($request->isPost() and $posted['action'] == $action - and $posted['url'] == $url) // multiple buttons + and $posted['url'] == $url + ) // multiple buttons { return $this->_do_syncwiki($request, $posted); } return $this->_makeButton($request, $args, $label); } - function _do_syncwiki(&$request, $args) { + function _do_syncwiki(&$request, $args) + { global $charset; longer_timeout(240); @@ -95,13 +101,13 @@ extends WikiPlugin_WikiAdminUtils if (empty($merge_point)) { $page = $dbh->getPage("ReleaseNotes"); // this is usually the latest official page $last = $page->getCurrentRevision(false); - $merge_point = $last->get("mtime"); // for testing: 1160396075 + $merge_point = $last->get("mtime"); // for testing: 1160396075 $dbh->set('mergepoint', $merge_point); } //TODO: remote auth, set session cookie $pagelist = wiki_xmlrpc_post('wiki.getRecentChanges', - iso8601_encode($merge_point,1), - $args['url'], $args); + iso8601_encode($merge_point, 1), + $args['url'], $args); $html = HTML(); //$html->pushContent(HTML::div(HTML::em("check RPC2 interface..."))); if (gettype($pagelist) === "array") { @@ -111,7 +117,7 @@ extends WikiPlugin_WikiAdminUtils PrintXML(HTML::strong(fmt("Download all externally changed sources."))); echo "
                  \n"; PrintXML(fmt("Retrieving from external url %s wiki.getRecentChanges(%s)...", - $args['url'], iso8601_encode($merge_point,1))); + $args['url'], iso8601_encode($merge_point, 1))); echo "
                  \n"; $ouriter = $dbh->mostRecent(array('since' => $merge_point)); //$ol = HTML::ol(); @@ -119,12 +125,12 @@ extends WikiPlugin_WikiAdminUtils foreach ($pagelist as $ext) { $reaction = _(""); // compare existance and dates with local page - $extdate = iso8601_decode($ext['lastModified']->scalar,1); + $extdate = iso8601_decode($ext['lastModified']->scalar, 1); // TODO: urldecode ??? $name = utf8_decode($ext['name']); $our = $dbh->getPage($name); $done[$name] = 1; - $ourrev = $our->getCurrentRevision(false); + $ourrev = $our->getCurrentRevision(false); $rel = '<=>'; if (!$our->exists()) { // we might have deleted or moved it on purpose? @@ -132,46 +138,46 @@ extends WikiPlugin_WikiAdminUtils if (($ourrev->getVersion() > 1) and ($ourrev->get('mtime') > $merge_point)) { // our was deleted after sync, and changed after last sync. $this->_addConflict('delete', $args, $our, $extdate); - $reaction = (_(" skipped")." ("."locally deleted or moved".")"); + $reaction = (_(" skipped") . " (" . "locally deleted or moved" . ")"); } else { $reaction = $this->_import($args, $our, $extdate); } } else { $ourdate = $ourrev->get('mtime'); if ($extdate > $ourdate and $ourdate < $merge_point) { - $rel = '>'; + $rel = '>'; $reaction = $this->_import($args, $our, $extdate); } elseif ($extdate > $ourdate and $ourdate >= $merge_point) { - $rel = '>'; + $rel = '>'; // our is older then external but newer than last sync $reaction = $this->_addConflict('import', $args, $our, $extdate); } elseif ($extdate < $ourdate and $extdate < $merge_point) { - $rel = '>'; + $rel = '>'; $reaction = $this->_export($args, $our); } elseif ($extdate < $ourdate and $extdate >= $merge_point) { - $rel = '>'; + $rel = '>'; // our is newer and external is also newer $reaction = $this->_addConflict('export', $args, $our, $extdate); } else { - $rel = '=='; + $rel = '=='; $reaction = _("same date"); } } /*$ol->pushContent(HTML::li(HTML::strong($name)," ", $extdate,"<=>",$ourdate," ", HTML::strong($reaction))); */ - PrintXML(HTML::strong($name)," ", - $extdate," $rel ",$ourdate," ", - HTML::strong($reaction), - HTML::br()); + PrintXML(HTML::strong($name), " ", + $extdate, " $rel ", $ourdate, " ", + HTML::strong($reaction), + HTML::br()); $request->chunkOutput(); } //$html->pushContent($ol); } else { $html->pushContent("xmlrpc error: wiki.getRecentChanges returned " - ."(".gettype($pagelist).") ".$pagelist); + . "(" . gettype($pagelist) . ") " . $pagelist); trigger_error("xmlrpc error: wiki.getRecentChanges returned " - ."(".gettype($pagelist).") ".$pagelist, E_USER_WARNING); + . "(" . gettype($pagelist) . ") " . $pagelist, E_USER_WARNING); EndLoadDump($request); return $this->error($html); } @@ -180,7 +186,7 @@ extends WikiPlugin_WikiAdminUtils PrintXML(HTML::strong(fmt("Now upload all locally newer pages."))); echo "
                  \n"; PrintXML(fmt("Checking all local pages newer than %s...", - iso8601_encode($merge_point,1))); + iso8601_encode($merge_point, 1))); echo "
                  \n"; while ($our = $ouriter->next()) { $name = $our->getName(); @@ -188,7 +194,7 @@ extends WikiPlugin_WikiAdminUtils $reaction = _(" skipped"); $ext = wiki_xmlrpc_post('wiki.getPageInfo', $name, $args['url']); if (is_array($ext)) { - $extdate = iso8601_decode($ext['lastModified']->scalar,1); + $extdate = iso8601_decode($ext['lastModified']->scalar, 1); $ourdate = $our->get('mtime'); if ($extdate < $ourdate and $extdate < $merge_point) { $reaction = $this->_export($args, $our); @@ -199,17 +205,17 @@ extends WikiPlugin_WikiAdminUtils } else { $reaction = 'xmlrpc error'; } - PrintXML(HTML::strong($name)," ", - $extdate," < ",$ourdate," ", - HTML::strong($reaction), - HTML::br()); + PrintXML(HTML::strong($name), " ", + $extdate, " < ", $ourdate, " ", + HTML::strong($reaction), + HTML::br()); $request->chunkOutput(); } PrintXML(HTML::strong(fmt("Now upload all locally newer uploads."))); echo "
                  \n"; PrintXML(fmt("Checking all local uploads newer than %s...", - iso8601_encode($merge_point,1))); + iso8601_encode($merge_point, 1))); echo "
                  \n"; $this->_fileList = array(); $prefix = getUploadFilePath(); @@ -217,25 +223,25 @@ extends WikiPlugin_WikiAdminUtils $len = strlen($prefix); foreach ($this->_fileList as $path) { // strip prefix - $file = substr($path,$len); + $file = substr($path, $len); $ourdate = filemtime($path); $oursize = filesize($path); $reaction = _(" skipped"); $ext = wiki_xmlrpc_post('wiki.getUploadedFileInfo', $file, $args['url']); if (is_array($ext)) { - $extdate = iso8601_decode($ext['lastModified']->scalar,1); + $extdate = iso8601_decode($ext['lastModified']->scalar, 1); $extsize = $ext['size']; if (empty($extsize) or $extdate < $ourdate) { - $timeout = $oursize * 0.0002; // assume 50kb/sec upload speed + $timeout = $oursize * 0.0002; // assume 50kb/sec upload speed $reaction = $this->_upload($args, $path, $timeout); } } else { $reaction = 'xmlrpc error wiki.getUploadedFileInfo not supported'; } - PrintXML(HTML::strong($name)," ", - "$extdate ($extsize) < $ourdate ($oursize)", - HTML::strong($reaction), - HTML::br()); + PrintXML(HTML::strong($name), " ", + "$extdate ($extsize) < $ourdate ($oursize)", + HTML::strong($reaction), + HTML::br()); $request->chunkOutput(); } } @@ -246,7 +252,8 @@ extends WikiPlugin_WikiAdminUtils } /* path must have ending slash */ - function _dir($path) { + function _dir($path) + { $dh = @opendir($path); while ($filename = readdir($dh)) { if ($filename[0] == '.') @@ -260,85 +267,89 @@ extends WikiPlugin_WikiAdminUtils closedir($dh); } - function _addConflict($what, $args, $our, $extdate = null) { + function _addConflict($what, $args, $our, $extdate = null) + { $pagename = $our->getName(); $meb = Button(array('action' => $args['action'], - 'merge'=> true, - 'source'=> $f), - _("Merge Edit"), - $args['pagename'], - 'wikiadmin'); + 'merge' => true, + 'source' => $f), + _("Merge Edit"), + $args['pagename'], + 'wikiadmin'); $owb = Button(array('action' => $args['action'], - 'overwrite'=> true, - 'source'=> $f), - sprintf(_("%s force"), strtoupper(substr($what, 0, 1)).substr($what, 1)), - $args['pagename'], - 'wikiunsafe'); + 'overwrite' => true, + 'source' => $f), + sprintf(_("%s force"), strtoupper(substr($what, 0, 1)) . substr($what, 1)), + $args['pagename'], + 'wikiunsafe'); $this->_conflicts[] = $pagename; return HTML(fmt(_("Postponed %s for %s."), $what, $pagename), " ", $meb, " ", $owb); } // TODO: store log or checkpoint for restauration? - function _import($args, $our, $extdate = null) { + function _import($args, $our, $extdate = null) + { global $request; $reaction = 'import '; - if ($args['noimport']) return ($reaction._("skipped")); + if ($args['noimport']) return ($reaction . _("skipped")); //$userid = $request->_user->_userid; $name = $our->getName(); $pagedata = wiki_xmlrpc_post('wiki.getPage', $name, $args['url']); if (is_object($pagedata)) { $pagedata = $pagedata->scalar; - $ourrev = $our->getCurrentRevision(true); + $ourrev = $our->getCurrentRevision(true); $content = $ourrev->getPackedContent(); if ($pagedata == $content) - return $reaction . _("skipped").' '._("same content"); + return $reaction . _("skipped") . ' ' . _("same content"); if (is_null($extdate)) $extdate = time(); $our->save(utf8_decode($pagedata), -1, array('author' => $userid, - 'mtime' => $extdate)); + 'mtime' => $extdate)); $reaction .= _("OK"); } else - $reaction .= (_("FAILED").' ('.gettype($pagedata).')'); + $reaction .= (_("FAILED") . ' (' . gettype($pagedata) . ')'); return $reaction; } // TODO: store log or checkpoint for restauration? - function _export($args, $our) { + function _export($args, $our) + { global $request; $reaction = 'export '; - if ($args['noexport']) return ($reaction._("skipped")); - $userid = $request->_user->_userid; - $name = $our->getName(); - $ourrev = $our->getCurrentRevision(true); + if ($args['noexport']) return ($reaction . _("skipped")); + $userid = $request->_user->_userid; + $name = $our->getName(); + $ourrev = $our->getCurrentRevision(true); $content = $ourrev->getPackedContent(); $extdata = wiki_xmlrpc_post('wiki.getPage', $name, $args['url']); if (is_object($extdata)) { $extdata = $extdata->scalar; if ($extdata == $content) - return $reaction . _("skipped").' '._("same content"); + return $reaction . _("skipped") . ' ' . _("same content"); } - $mypass = $request->getPref('passwd'); // this usually fails + $mypass = $request->getPref('passwd'); // this usually fails $success = wiki_xmlrpc_post('wiki.putPage', - array($name, $content, $userid, $mypass), $args['url']); + array($name, $content, $userid, $mypass), $args['url']); if (is_array($success)) { if ($success['code'] == 200) - $reaction .= (_("OK").' '.$success['code']." ".$success['message']); + $reaction .= (_("OK") . ' ' . $success['code'] . " " . $success['message']); else - $reaction .= (_("FAILED").' '.$success['code']." ".$success['message']); + $reaction .= (_("FAILED") . ' ' . $success['code'] . " " . $success['message']); } else $reaction .= (_("FAILED")); return $reaction; } // TODO: store log or checkpoint for restauration? - function _upload($args, $path, $timeout) { + function _upload($args, $path, $timeout) + { global $request; $reaction = 'upload '; - if ($args['noupload']) return ($reaction._("skipped")); + if ($args['noupload']) return ($reaction . _("skipped")); //$userid = $request->_user->_userid; $url = $args['url']; - $url = str_replace("/RPC2.php","/index.php", $url); + $url = str_replace("/RPC2.php", "/index.php", $url); $server = parse_url($url); $http = new HttpClient($server['host'], $server['port']); $http->timeout = $timeout + 5; @@ -347,12 +358,14 @@ extends WikiPlugin_WikiAdminUtils if ($http->getStatus() == 200) $reaction .= _("OK"); else - $reaction .= (_("FAILED").' '.$http->getStatus()); + $reaction .= (_("FAILED") . ' ' . $http->getStatus()); } else - $reaction .= (_("FAILED").' '.$http->getStatus()." ".$http->errormsg); + $reaction .= (_("FAILED") . ' ' . $http->getStatus() . " " . $http->errormsg); return $reaction; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/SyntaxHighlighter.php b/lib/plugin/SyntaxHighlighter.php index cb412dabe..210b8b509 100644 --- a/lib/plugin/SyntaxHighlighter.php +++ b/lib/plugin/SyntaxHighlighter.php @@ -30,24 +30,24 @@ * style = ["ansi", "gnu", "kr", "java", "linux"] < +#include - int main() { - printf("Lalala\n"); - } +int main() { +printf("Lalala\n"); +} >> - I did not use beautifier, because it used up more than 8M of memory on - my system and PHP killed it. I'm not sure whether this is a problem - with my integration, or with beautifier itself. +I did not use beautifier, because it used up more than 8M of memory on +my system and PHP killed it. I'm not sure whether this is a problem +with my integration, or with beautifier itself. Fixes by Reini Urban: - support options: syntax, style, color. - php version switch - HIGHLIGHT_DATA_DIR, HIGHLIGHT_EXE -*/ +support options: syntax, style, color. +php version switch +HIGHLIGHT_DATA_DIR, HIGHLIGHT_EXE + */ if (!defined('HIGHLIGHT_EXE')) - define('HIGHLIGHT_EXE','highlight'); + define('HIGHLIGHT_EXE', 'highlight'); //define('HIGHLIGHT_EXE','/usr/local/bin/highlight'); //define('HIGHLIGHT_EXE','/home/groups/p/ph/phpwiki/bin/highlight'); @@ -56,41 +56,51 @@ if (!defined('HIGHLIGHT_EXE')) // doesn't have a $HOME if (!defined('HIGHLIGHT_DATA_DIR')) if (isWindows()) - define('HIGHLIGHT_DATA_DIR','f:\cygnus\usr\local\share\highlight'); + define('HIGHLIGHT_DATA_DIR', 'f:\cygnus\usr\local\share\highlight'); else - define('HIGHLIGHT_DATA_DIR','/usr/share/highlight'); - //define('HIGHLIGHT_DATA_DIR','/home/groups/p/ph/phpwiki/share/highlight'); + define('HIGHLIGHT_DATA_DIR', '/usr/share/highlight'); +//define('HIGHLIGHT_DATA_DIR','/home/groups/p/ph/phpwiki/share/highlight'); class WikiPlugin_SyntaxHighlighter -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("SyntaxHighlighter"); } - function getDescription () { + + function getDescription() + { return _("Source code syntax highlighter (via http://www.andre-simon.de)"); } - function managesValidators() { + + function managesValidators() + { return true; } - function getDefaultArguments() { + + function getDefaultArguments() + { return array( - 'syntax' => null, // required argument - 'style' => null, // optional argument ["ansi", "gnu", "kr", "java", "linux"] - 'color' => null, // optional, see highlight/themes - 'number' => 0, - 'wrap' => 0, - ); + 'syntax' => null, // required argument + 'style' => null, // optional argument ["ansi", "gnu", "kr", "java", "linux"] + 'color' => null, // optional, see highlight/themes + 'number' => 0, + 'wrap' => 0, + ); } - function handle_plugin_args_cruft(&$argstr, &$args) { + + function handle_plugin_args_cruft(&$argstr, &$args) + { $this->source = $argstr; } - function newFilterThroughCmd($input, $commandLine) { + function newFilterThroughCmd($input, $commandLine) + { $descriptorspec = array( - 0 => array("pipe", "r"), // stdin is a pipe that the child will read from - 1 => array("pipe", "w"), // stdout is a pipe that the child will write to - 2 => array("pipe", "w"), // stdout is a pipe that the child will write to + 0 => array("pipe", "r"), // stdin is a pipe that the child will read from + 1 => array("pipe", "w"), // stdout is a pipe that the child will write to + 2 => array("pipe", "w"), // stdout is a pipe that the child will write to ); $process = proc_open("$commandLine", $descriptorspec, $pipes); @@ -102,12 +112,12 @@ extends WikiPlugin fwrite($pipes[0], $input); fclose($pipes[0]); $buf = ""; - while(!feof($pipes[1])) { + while (!feof($pipes[1])) { $buf .= fgets($pipes[1], 1024); } fclose($pipes[1]); $stderr = ''; - while(!feof($pipes[2])) { + while (!feof($pipes[2])) { $stderr .= fgets($pipes[2], 1024); } fclose($pipes[2]); @@ -119,10 +129,11 @@ extends WikiPlugin } } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { extract($this->getArgs($argstr, $request)); $source =& $this->source; - if (empty($syntax)) { + if (empty($syntax)) { return $this->error(sprintf(_("A required argument '%s' is missing."), 'syntax')); } if (!empty($source)) { @@ -130,10 +141,10 @@ extends WikiPlugin if (defined('HIGHLIGHT_DATA_DIR')) $args .= " --data-dir " . HIGHLIGHT_DATA_DIR; if ($number != 0) $args .= " -l"; - if ($wrap != 0) $args .= " -V"; + if ($wrap != 0) $args .= " -V"; $html = HTML(); - if (!empty($color) and !preg_match('/^[\w-]+$/',$color)) { - $html->pushContent($this->error(fmt("invalid %s ignored",'color'))); + if (!empty($color) and !preg_match('/^[\w-]+$/', $color)) { + $html->pushContent($this->error(fmt("invalid %s ignored", 'color'))); $color = false; } if (!empty($color)) $args .= " --style $color --inline-css"; @@ -141,7 +152,7 @@ extends WikiPlugin $commandLine = HIGHLIGHT_EXE . "$args -q -X -f -S $syntax"; $code = $this->newFilterThroughCmd($source, $commandLine); if (empty($code)) - return $this->error(fmt("Couldn't start commandline '%s'",$commandLine)); + return $this->error(fmt("Couldn't start commandline '%s'", $commandLine)); $pre = HTML::pre(HTML::raw($code)); $html->pushContent($pre); return HTML($html); @@ -149,7 +160,9 @@ extends WikiPlugin return $this->error(fmt("empty source")); } } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/SystemInfo.php b/lib/plugin/SystemInfo.php index 25c94fe94..3fab59b35 100644 --- a/lib/plugin/SystemInfo.php +++ b/lib/plugin/SystemInfo.php @@ -43,16 +43,20 @@ require_once 'lib/WikiPluginCached.php'; class WikiPlugin_SystemInfo -extends WikiPluginCached + extends WikiPluginCached { - function getPluginType() { + function getPluginType() + { return PLUGIN_CACHED_HTML; } - function getName() { + + function getName() + { return _("SystemInfo"); } - function getDescription() { + function getDescription() + { return _("Provides access to PhpWiki's lower level system information."); } @@ -62,64 +66,72 @@ extends WikiPluginCached * call $request->appendValidators() with appropriate arguments, * and should override this method to return true. */ - function managesValidators() { + function managesValidators() + { return true; } - function getExpire($dbi, $argarray, $request) { + + function getExpire($dbi, $argarray, $request) + { return '+1800'; // 30 minutes } - function getHtml($dbi, $argarray, $request, $basepage) { + + function getHtml($dbi, $argarray, $request, $basepage) + { $loader = new WikiPluginLoader; return $loader->expandPI('<', $request, $this, $basepage); + . WikiPluginCached::glueArgs($argarray) // all + . ' ?>', $request, $this, $basepage); } - function getDefaultArguments() { - return array( - // 'seperator' => ' ', // on multiple args - ); + function getDefaultArguments() + { + return array(// 'seperator' => ' ', // on multiple args + ); } - function database() { + function database() + { global $request; - $s = "DATABASE_TYPE: " . DATABASE_TYPE . ", "; + $s = "DATABASE_TYPE: " . DATABASE_TYPE . ", "; switch (DATABASE_TYPE) { - case 'SQL': // pear - case 'ADODB': - case 'PDO': - $dsn = DATABASE_DSN; - $s .= "DATABASE BACKEND:" . " "; - $s .= (DATABASE_TYPE == 'SQL') ? 'PearDB' : 'ADODB'; - if (preg_match('/^(\w+):/', $dsn, $m)) { - $backend = $m[1]; - $s .= " $backend"; - } - $s .= ", DATABASE_PREFIX: \"".DATABASE_PREFIX."\", "; - break; - case 'dba': - $s .= "DATABASE_DBA_HANDLER: ".DATABASE_DBA_HANDLER.", "; - $s .= "DATABASE_DIRECTORY: \"".DATABASE_DIRECTORY."\", "; - break; - case 'cvs': - $s .= "DATABASE_DIRECTORY: \"".DATABASE_DIRECTORY."\", "; - // $s .= "cvs stuff: , "; - break; - case 'flatfile': - $s .= "DATABASE_DIRECTORY: ".DATABASE_DIRECTORY.", "; - break; + case 'SQL': // pear + case 'ADODB': + case 'PDO': + $dsn = DATABASE_DSN; + $s .= "DATABASE BACKEND:" . " "; + $s .= (DATABASE_TYPE == 'SQL') ? 'PearDB' : 'ADODB'; + if (preg_match('/^(\w+):/', $dsn, $m)) { + $backend = $m[1]; + $s .= " $backend"; + } + $s .= ", DATABASE_PREFIX: \"" . DATABASE_PREFIX . "\", "; + break; + case 'dba': + $s .= "DATABASE_DBA_HANDLER: " . DATABASE_DBA_HANDLER . ", "; + $s .= "DATABASE_DIRECTORY: \"" . DATABASE_DIRECTORY . "\", "; + break; + case 'cvs': + $s .= "DATABASE_DIRECTORY: \"" . DATABASE_DIRECTORY . "\", "; + // $s .= "cvs stuff: , "; + break; + case 'flatfile': + $s .= "DATABASE_DIRECTORY: " . DATABASE_DIRECTORY . ", "; + break; } // hack: suppress error when using sql, so no timeout @$s .= "DATABASE_TIMEOUT: " . DATABASE_TIMEOUT; return $s; } - function cachestats() { + + function cachestats() + { global $request; - if (! defined('USECACHE') or !USECACHE) + if (!defined('USECACHE') or !USECACHE) return _("no cache used"); $dbi =& $this->_dbi; $cache = $dbi->_cache; - $s = _("cached pagedata:") . " " . count($cache->_pagedata_cache); + $s = _("cached pagedata:") . " " . count($cache->_pagedata_cache); $s .= ", " . _("cached versiondata:"); $s .= " " . count($cache->_versiondata_cache); //$s .= ", glv size: " . count($cache->_glv_cache); @@ -127,46 +139,54 @@ extends WikiPluginCached //$s .= ", cache misses: ?"; return $s; } - function ExpireParams() { + + function ExpireParams() + { global $ExpireParams; - $s = sprintf(_("Keep up to %d major edits, but keep them no longer than %d days."), - $ExpireParams['major']['keep'], - $ExpireParams['major']['max_age']); + $s = sprintf(_("Keep up to %d major edits, but keep them no longer than %d days."), + $ExpireParams['major']['keep'], + $ExpireParams['major']['max_age']); $s .= sprintf(_(" Keep up to %d minor edits, but keep them no longer than %d days."), - $ExpireParams['minor']['keep'], - $ExpireParams['minor']['max_age']); + $ExpireParams['minor']['keep'], + $ExpireParams['minor']['max_age']); $s .= sprintf(_(" Keep the latest contributions of the last %d authors up to %d days."), - $ExpireParams['author']['keep'], $ExpireParams['author']['max_age']); + $ExpireParams['author']['keep'], $ExpireParams['author']['max_age']); $s .= sprintf(_(" Additionally, try to keep the latest contributions of all authors in the last %d days (even if there are more than %d of them,) but in no case keep more than %d unique author revisions."), - $ExpireParams['author']['min_age'], - $ExpireParams['author']['keep'], - $ExpireParams['author']['max_keep']); + $ExpireParams['author']['min_age'], + $ExpireParams['author']['keep'], + $ExpireParams['author']['max_keep']); return $s; } - function pagestats() { + + function pagestats() + { global $request; $dbi = $request->getDbh(); - $s = sprintf(_("%d pages"), $dbi->numPages(true)); - $s .= ", " . sprintf(_("%d not-empty pages"), $dbi->numPages(false)); + $s = sprintf(_("%d pages"), $dbi->numPages(true)); + $s .= ", " . sprintf(_("%d not-empty pages"), $dbi->numPages(false)); // more bla.... // $s .= ", " . sprintf(_("earliest page from %s"), $earliestdate); // $s .= ", " . sprintf(_("latest page from %s"), $latestdate); // $s .= ", " . sprintf(_("latest pagerevision from %s"), $latestrevdate); return $s; } + //What kind of link statistics? // total links in, total links out, mean links per page, ... // Any useful numbers similar to a VisualWiki interestmap? - function linkstats() { - $s = _("not yet"); + function linkstats() + { + $s = _("not yet"); return $s; } + // number of homepages: easy // number of anonymous users? // calc this from accesslog info? // number of anonymous edits? // easy. related to the view/edit rate in accessstats. - function userstats() { + function userstats() + { global $request; $dbi =& $this->_dbi; $h = 0; @@ -175,7 +195,7 @@ extends WikiPluginCached if ($page->isUserPage(true)) // check if the admin is there. if not add him to the authusers. $h++; } - $s = sprintf(_("%d homepages"), $h); + $s = sprintf(_("%d homepages"), $h); // $s .= ", " . sprintf(_("%d anonymous users"), $au); // ?? // $s .= ", " . sprintf(_("%d anonymous edits"), $ae); // see recentchanges // $s .= ", " . sprintf(_("%d authenticated users"), $auth); // users with password set @@ -187,29 +207,33 @@ extends WikiPluginCached // total hits per day/month/year // view/edit rate // TODO: see WhoIsOnline hit stats, and sql accesslogs - function accessstats() { - $s = _("not yet"); + function accessstats() + { + $s = _("not yet"); return $s; } // numeric array - function _stats($hits, $treshold = 10.0) { + function _stats($hits, $treshold = 10.0) + { sort($hits); reset($hits); $n = count($hits); - $max = 0; $min = 9999999999999; $sum = 0; + $max = 0; + $min = 9999999999999; + $sum = 0; foreach ($hits as $h) { $sum += $h; $max = max($h, $max); $min = min($h, $min); } - $median_i = (int) $n / 2; - if (! ($n / 2)) + $median_i = (int)$n / 2; + if (!($n / 2)) $median = $hits[$median_i]; else $median = $hits[$median_i]; $treshold = 10; - $mintreshold = $max * $treshold / 100.0; // lower than 10% of the hits + $mintreshold = $max * $treshold / 100.0; // lower than 10% of the hits reset($hits); $nmin = $hits[0] < $mintreshold ? 1 : 0; while (next($hits) < $mintreshold) @@ -219,18 +243,18 @@ extends WikiPluginCached $nmax = 1; while (prev($hits) > $maxtreshold) $nmax++; - return array('n' => $n, - 'sum' => $sum, - 'min' => $min, - 'max' => $max, - 'mean' => $sum / $n, - 'median'=> $median, - 'stddev'=> stddev($hits, $sum), - 'treshold' => $treshold, - 'nmin' => $nmin, - 'mintreshold' => $mintreshold, - 'nmax' => $nmax, - 'maxtreshold' => $maxtreshold); + return array('n' => $n, + 'sum' => $sum, + 'min' => $min, + 'max' => $max, + 'mean' => $sum / $n, + 'median' => $median, + 'stddev' => stddev($hits, $sum), + 'treshold' => $treshold, + 'nmin' => $nmin, + 'mintreshold' => $mintreshold, + 'nmax' => $nmax, + 'maxtreshold' => $maxtreshold); } // only absolute numbers, not for any time interval. see accessstats @@ -238,34 +262,38 @@ extends WikiPluginCached // total, max, mean, median, stddev; // %d pages less than 3 hits (<10%) <10% percent of the leastpopular // %d pages more than 100 hits (>90%) >90% percent of the mostpopular - function hitstats() { + function hitstats() + { global $request; $dbi =& $this->_dbi; $hits = array(); $page_iter = $dbi->getAllPages(true); while ($page = $page_iter->next()) { if (($current = $page->getCurrentRevision()) - && (! $current->hasDefaultContents())) { + && (!$current->hasDefaultContents()) + ) { $hits[] = $page->get('hits'); } } $treshold = 10.0; $stats = $this->_stats($hits, $treshold); - $s = sprintf(_("total hits: %d"), $stats['sum']); + $s = sprintf(_("total hits: %d"), $stats['sum']); $s .= ", " . sprintf(_("max: %d"), $stats['max']); $s .= ", " . sprintf(_("mean: %2.3f"), $stats['mean']); $s .= ", " . sprintf(_("median: %d"), $stats['median']); $s .= ", " . sprintf(_("stddev: %2.3f"), $stats['stddev']); $s .= "; " . sprintf(_("%d pages with less than %d hits (<%d%%)."), - $stats['nmin'], $stats['mintreshold'], $treshold); + $stats['nmin'], $stats['mintreshold'], $treshold); $s .= " " . sprintf(_("%d page(s) with more than %d hits (>%d%%)."), - $stats['nmax'], $stats['maxtreshold'], 100 - $treshold); + $stats['nmax'], $stats['maxtreshold'], 100 - $treshold); return $s; } + /* not yet ready */ - function revisionstats() { + function revisionstats() + { global $request, $LANG; include_once 'lib/WikiPluginCached.php'; @@ -293,73 +321,75 @@ extends WikiPluginCached $stats['latest']['major']++; else $stats['latest']['minor']++; -/* - // FIXME: This needs much too long to be acceptable. - // overall: - // number of revisions: all (100%) / major (60%) / minor (40%) - // revs per page: - // per page: mean 20 / major (60%) / minor (40%) - $rev_iter = $page->getAllRevisions(); - while ($rev = $rev_iter->next()) { - if ($rev->get('is_minor_edit')) - $stats['page']['major']++; - else - $stats['page']['minor']++; - } - $rev_iter->free(); - $stats['page']['all'] = $stats['page']['major'] + $stats['page']['minor']; - $stats['perpage'][] = $stats['page']['all']; - $stats['perpage_major'][] = $stats['page']['major']; - $stats['sum']['all'] += $stats['page']['all']; - $stats['sum']['major'] += $stats['page']['major']; - $stats['sum']['minor'] += $stats['page']['minor']; - $stats['page'] = array(); -*/ + /* + // FIXME: This needs much too long to be acceptable. + // overall: + // number of revisions: all (100%) / major (60%) / minor (40%) + // revs per page: + // per page: mean 20 / major (60%) / minor (40%) + $rev_iter = $page->getAllRevisions(); + while ($rev = $rev_iter->next()) { + if ($rev->get('is_minor_edit')) + $stats['page']['major']++; + else + $stats['page']['minor']++; + } + $rev_iter->free(); + $stats['page']['all'] = $stats['page']['major'] + $stats['page']['minor']; + $stats['perpage'][] = $stats['page']['all']; + $stats['perpage_major'][] = $stats['page']['major']; + $stats['sum']['all'] += $stats['page']['all']; + $stats['sum']['major'] += $stats['page']['major']; + $stats['sum']['minor'] += $stats['page']['minor']; + $stats['page'] = array(); + */ } $page_iter->free(); $stats['numpages'] = $stats['latest']['major'] + $stats['latest']['minor']; $stats['latest']['major_perc'] = $stats['latest']['major'] * 100.0 / $stats['numpages']; $stats['latest']['minor_perc'] = $stats['latest']['minor'] * 100.0 / $stats['numpages']; $empty = sprintf("empty pages: %d (%02.1f%%) / %d (100%%)\n", - $stats['empty'], $stats['empty'] * 100.0 / $stats['numpages'], - $stats['numpages']); + $stats['empty'], $stats['empty'] * 100.0 / $stats['numpages'], + $stats['numpages']); $latest = sprintf("latest revision: major %d (%02.1f%%) / minor %d (%02.1f%%) / all %d (100%%)\n", - $stats['latest']['major'], $stats['latest']['major_perc'], - $stats['latest']['minor'], $stats['latest']['minor_perc'], $stats['numpages']); -/* - $stats['sum']['major_perc'] = $stats['sum']['major'] * 100.0 / $stats['sum']['all']; - $stats['sum']['minor_perc'] = $stats['sum']['minor'] * 100.0 / $stats['sum']['all']; - $sum = sprintf("number of revisions: major %d (%02.1f%%) / minor %d (%02.1f%%) / all %d (100%%)\n", - $stats['sum']['major'], $stats['sum']['major_perc'], - $stats['sum']['minor'], $stats['sum']['minor_perc'], $stats['sum']['all']); - - $stats['perpage'] = $this->_stats($stats['perpage']); - $stats['perpage_major'] = $this->_stats($stats['perpage_major']); - $stats['perpage']['major_perc'] = $stats['perpage_major']['sum'] * 100.0 / $stats['perpage']['sum']; - $stats['perpage']['minor_perc'] = 100 - $stats['perpage']['major_perc']; - $stats['perpage_minor']['sum'] = $stats['perpage']['sum'] - $stats['perpage_major']['sum']; - $stats['perpage_minor']['mean'] = $stats['perpage_minor']['sum'] / ($stats['perpage']['n'] - $stats['perpage_major']['n']); - $perpage = sprintf("revisions per page: all %d, mean %02.1f / major %d (%02.1f%%) / minor %d (%02.1f%%)\n", - $stats['perpage']['sum'], $stats['perpage']['mean'], - $stats['perpage_major']['mean'], $stats['perpage']['major_perc'], - $stats['perpage_minor']['mean'], $stats['perpage']['minor_perc']); - $perpage .= sprintf(" %d page(s) with less than %d revisions (<%d%%)\n", - $stats['perpage']['nmin'], $stats['perpage']['maintreshold'], $treshold); - $perpage .= sprintf(" %d page(s) with more than %d revisions (>%d%%)\n", - $stats['perpage']['nmax'], $stats['perpage']['maxtreshold'], 100 - $treshold); - $content = $empty . $latest . $sum . $perpage; -*/ + $stats['latest']['major'], $stats['latest']['major_perc'], + $stats['latest']['minor'], $stats['latest']['minor_perc'], $stats['numpages']); + /* + $stats['sum']['major_perc'] = $stats['sum']['major'] * 100.0 / $stats['sum']['all']; + $stats['sum']['minor_perc'] = $stats['sum']['minor'] * 100.0 / $stats['sum']['all']; + $sum = sprintf("number of revisions: major %d (%02.1f%%) / minor %d (%02.1f%%) / all %d (100%%)\n", + $stats['sum']['major'], $stats['sum']['major_perc'], + $stats['sum']['minor'], $stats['sum']['minor_perc'], $stats['sum']['all']); + + $stats['perpage'] = $this->_stats($stats['perpage']); + $stats['perpage_major'] = $this->_stats($stats['perpage_major']); + $stats['perpage']['major_perc'] = $stats['perpage_major']['sum'] * 100.0 / $stats['perpage']['sum']; + $stats['perpage']['minor_perc'] = 100 - $stats['perpage']['major_perc']; + $stats['perpage_minor']['sum'] = $stats['perpage']['sum'] - $stats['perpage_major']['sum']; + $stats['perpage_minor']['mean'] = $stats['perpage_minor']['sum'] / ($stats['perpage']['n'] - $stats['perpage_major']['n']); + $perpage = sprintf("revisions per page: all %d, mean %02.1f / major %d (%02.1f%%) / minor %d (%02.1f%%)\n", + $stats['perpage']['sum'], $stats['perpage']['mean'], + $stats['perpage_major']['mean'], $stats['perpage']['major_perc'], + $stats['perpage_minor']['mean'], $stats['perpage']['minor_perc']); + $perpage .= sprintf(" %d page(s) with less than %d revisions (<%d%%)\n", + $stats['perpage']['nmin'], $stats['perpage']['maintreshold'], $treshold); + $perpage .= sprintf(" %d page(s) with more than %d revisions (>%d%%)\n", + $stats['perpage']['nmax'], $stats['perpage']['maxtreshold'], 100 - $treshold); + $content = $empty . $latest . $sum . $perpage; + */ $content = $empty . $latest; // regenerate cache every 30 minutes $cache->save($id, $content, '+1800', $cachedir); return $content; } + // Size of databases/files/cvs are possible plus the known size of the app. // Cache this costly operation. // Even if the whole plugin call is stored internally, we cache this // seperately with a seperate key. - function discspace() { + function discspace() + { global $DBParams, $request; include_once 'lib/WikiPluginCached.php'; @@ -381,7 +411,7 @@ extends WikiPluginCached $dbdir = $DBParams['directory']; if ($DBParams['dba_handler'] == 'db3') $pagesize = filesize($DBParams['directory'] - . "/wiki_pagedb.db3") / 1024; + . "/wiki_pagedb.db3") / 1024; // if issubdirof($dbdir, $dir) $appsize -= $pagesize; } else { // flatfile, cvs $dbdir = $DBParams['directory']; @@ -389,7 +419,7 @@ extends WikiPluginCached // if issubdirof($dbdir, $dir) $appsize -= $pagesize; } $content = array('appsize' => $appsize, - 'pagesize' => $pagesize); + 'pagesize' => $pagesize); // regenerate cache every 30 minutes $cache->save($id, $content, '+1800', $cachedir); } else { @@ -397,110 +427,121 @@ extends WikiPluginCached $pagesize = $content['pagesize']; } - $s = sprintf(_("Application size: %d KiB"), $appsize); + $s = sprintf(_("Application size: %d KiB"), $appsize); if ($pagesize) - $s .= ", " . sprintf(_("Pagedata size: %d KiB", $pagesize)); + $s .= ", " . sprintf(_("Pagedata size: %d KiB", $pagesize)); return $s; } - function inlineimages () { + function inlineimages() + { return implode(' ', explode('|', INLINE_IMAGES)); } - function wikinameregexp () { + + function wikinameregexp() + { return $GLOBALS['WikiNameRegexp']; } - function allowedprotocols () { + + function allowedprotocols() + { return implode(' ', explode('|', ALLOWED_PROTOCOLS)); } - function available_plugins () { + + function available_plugins() + { $fileset = new FileSet(FindFile('lib/plugin'), '*.php'); $list = $fileset->getFiles(); natcasesort($list); reset($list); return sprintf(_("Total %d plugins: "), count($list)) . implode(', ', array_map(create_function('$f', - 'return substr($f,0,-4);'), - $list)); + 'return substr($f,0,-4);'), + $list)); } - function supported_languages () { + + function supported_languages() + { $available_languages = listAvailableLanguages(); natcasesort($available_languages); return sprintf(_("Total of %d languages: "), - count($available_languages)) + count($available_languages)) . implode(', ', $available_languages) . ". " . sprintf(_("Current language: '%s'"), $GLOBALS['LANG']) . ((DEFAULT_LANGUAGE != $GLOBALS['LANG']) - ? ". " . sprintf(_("Default language: '%s'"), DEFAULT_LANGUAGE) - : ''); + ? ". " . sprintf(_("Default language: '%s'"), DEFAULT_LANGUAGE) + : ''); } - function supported_themes () { + function supported_themes() + { global $WikiTheme; $available_themes = listAvailableThemes(); natcasesort($available_themes); return sprintf(_("Total of %d themes: "), count($available_themes)) - . implode(', ',$available_themes) . ". " + . implode(', ', $available_themes) . ". " . sprintf(_("Current theme: '%s'"), $WikiTheme->_name) . ((THEME != $WikiTheme->_name) - ? ". " . sprintf(_("Default theme: '%s'"), THEME) - : ''); + ? ". " . sprintf(_("Default theme: '%s'"), THEME) + : ''); } - function call ($arg, &$availableargs) { + function call($arg, &$availableargs) + { if (!empty($availableargs[$arg])) return $availableargs[$arg](); elseif (method_exists($this, $arg)) // any defined SystemInfo->method() - return call_user_func_array(array(&$this, $arg), array()); - elseif (defined($arg) && // any defined constant - !in_array($arg,array('ADMIN_PASSWD','DATABASE_DSN','DBAUTH_AUTH_DSN'))) - return constant($arg); - else + return call_user_func_array(array(&$this, $arg), array()); elseif (defined($arg) && // any defined constant + !in_array($arg, array('ADMIN_PASSWD', 'DATABASE_DSN', 'DBAUTH_AUTH_DSN')) + ) + return constant($arg); else return $this->error(sprintf(_("unknown argument '%s' to SystemInfo"), $arg)); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { // don't parse argstr for name=value pairs. instead we use just 'name' //$args = $this->getArgs($argstr, $request); $this->_dbi =& $dbi; $args['seperator'] = ' '; $availableargs = // name => callback + 0 args - array ('appname' => create_function('',"return 'PhpWiki';"), - 'version' => create_function('',"return sprintf('%s', PHPWIKI_VERSION);"), - 'LANG' => create_function('','return $GLOBALS["LANG"];'), - 'LC_ALL' => create_function('','return setlocale(LC_ALL, 0);'), - 'current_language' => create_function('','return $GLOBALS["LANG"];'), - 'system_language' => create_function('','return DEFAULT_LANGUAGE;'), - 'current_theme' => create_function('','return $GLOBALS["WikiTheme"]->_name;'), - 'system_theme' => create_function('','return THEME;'), - // more here or as method. - '' => create_function('',"return 'dummy';") - ); + array('appname' => create_function('', "return 'PhpWiki';"), + 'version' => create_function('', "return sprintf('%s', PHPWIKI_VERSION);"), + 'LANG' => create_function('', 'return $GLOBALS["LANG"];'), + 'LC_ALL' => create_function('', 'return setlocale(LC_ALL, 0);'), + 'current_language' => create_function('', 'return $GLOBALS["LANG"];'), + 'system_language' => create_function('', 'return DEFAULT_LANGUAGE;'), + 'current_theme' => create_function('', 'return $GLOBALS["WikiTheme"]->_name;'), + 'system_theme' => create_function('', 'return THEME;'), + // more here or as method. + '' => create_function('', "return 'dummy';") + ); // split the argument string by any number of commas or space // characters, which include " ", \r, \t, \n and \f $allargs = preg_split("/[\s,]+/", $argstr, -1, PREG_SPLIT_NO_EMPTY); if (in_array('all', $allargs) || in_array('table', $allargs)) { - $allargs = array('appname' => _("Application name"), - 'version' => _("PhpWiki engine version"), - 'database' => _("Database"), - 'cachestats' => _("Cache statistics"), - 'pagestats' => _("Page statistics"), - //'revisionstats' => _("Page revision statistics"), - //'linkstats' => _("Link statistics"), - 'userstats' => _("User statistics"), - //'accessstats' => _("Access statistics"), - 'hitstats' => _("Hit statistics"), - 'discspace' => _("Harddisc usage"), - 'expireparams' => _("Expiry parameters"), - 'wikinameregexp' => _("Wikiname regexp"), - 'allowedprotocols' => _("Allowed protocols"), - 'inlineimages' => _("Inline images"), - 'available_plugins' => _("Available plugins"), - 'supported_languages' => _("Supported languages"), - 'supported_themes' => _("Supported themes"), + $allargs = array('appname' => _("Application name"), + 'version' => _("PhpWiki engine version"), + 'database' => _("Database"), + 'cachestats' => _("Cache statistics"), + 'pagestats' => _("Page statistics"), + //'revisionstats' => _("Page revision statistics"), + //'linkstats' => _("Link statistics"), + 'userstats' => _("User statistics"), + //'accessstats' => _("Access statistics"), + 'hitstats' => _("Hit statistics"), + 'discspace' => _("Harddisc usage"), + 'expireparams' => _("Expiry parameters"), + 'wikinameregexp' => _("Wikiname regexp"), + 'allowedprotocols' => _("Allowed protocols"), + 'inlineimages' => _("Inline images"), + 'available_plugins' => _("Available plugins"), + 'supported_languages' => _("Supported languages"), + 'supported_themes' => _("Supported themes"), // '' => _(""), - '' => "" - ); + '' => "" + ); $table = HTML::table(array('class' => 'bordered')); foreach ($allargs as $arg => $desc) { if (!$arg) @@ -508,7 +549,7 @@ extends WikiPluginCached if (!$desc) $desc = _($arg); $table->pushContent(HTML::tr(HTML::th(array('style' => "white-space:nowrap"), $desc), - HTML::td(HTML($this->call($arg, $availableargs))))); + HTML::td(HTML($this->call($arg, $availableargs))))); } return $table; } else { @@ -522,42 +563,47 @@ extends WikiPluginCached } // if more than one arg, remove the trailing seperator if ($output) $output = substr($output, 0, - - strlen($args['seperator'])); + -strlen($args['seperator'])); return HTML($output); } } } -function median($hits) { +function median($hits) +{ sort($hits); reset($hits); $n = count($hits); - $median = (int) $n / 2; - if (! ($n % 2)) // proper rounding on even length - return ($hits[$median] + $hits[$median-1]) * 0.5; + $median = (int)$n / 2; + if (!($n % 2)) // proper rounding on even length + return ($hits[$median] + $hits[$median - 1]) * 0.5; else return $hits[$median]; } -function rsum($a, $b) { +function rsum($a, $b) +{ $a += $b; return $a; } -function mean(&$hits, $total = false) { + +function mean(&$hits, $total = false) +{ $n = count($hits); if (!$total) $total = array_reduce($hits, 'rsum'); - return (float) $total / ($n * 1.0); + return (float)$total / ($n * 1.0); } -function stddev(&$hits, $total = false) { +function stddev(&$hits, $total = false) +{ $n = count($hits); if (!$total) $total = array_reduce($hits, 'rsum'); $GLOBALS['mean'] = $total / $n; $r = array_map(create_function('$i', 'global $mean; return ($i-$mean)*($i-$mean);'), - $hits); + $hits); unset($GLOBALS['mean']); - return (float)sqrt(mean($r, $total) * ($n / (float)($n -1))); + return (float)sqrt(mean($r, $total) * ($n / (float)($n - 1))); } // Local Variables: diff --git a/lib/plugin/TeX2png.php b/lib/plugin/TeX2png.php index 2ff762853..796f79638 100644 --- a/lib/plugin/TeX2png.php +++ b/lib/plugin/TeX2png.php @@ -34,27 +34,31 @@ // LaTeX2HTML ftp://ftp.dante.de/tex-archive/support/latex2html class WikiPlugin_TeX2png -extends WikiPlugin + extends WikiPlugin { var $imagepath = 'images/tex'; var $latexbin = '/usr/bin/latex'; var $dvipsbin = '/usr/bin/dvips'; var $pstoimgbin = '/usr/bin/pstoimg'; - function getName () { + function getName() + { return _("TeX2png"); } - function getDescription () { + function getDescription() + { return _("Convert Tex mathematicals expressions to cached png files." . - " This is for small text"); + " This is for small text"); } - function getDefaultArguments() { + function getDefaultArguments() + { return array('text' => "$$(a + b)^2 = a^2 + 2 ab + b^2$$"); } - function parseArgStr($argstr) { + function parseArgStr($argstr) + { // modified from WikiPlugin.php $arg_p = '\w+'; $op_p = '(?:\|\|)?='; @@ -62,7 +66,7 @@ extends WikiPlugin $opt_ws = '\s*'; $qq_p = '" ( (?:[^"\\\\]|\\\\.)* ) "'; //"<--kludge for brain-dead syntax coloring - $q_p = "' ( (?:[^'\\\\]|\\\\.)* ) '"; + $q_p = "' ( (?:[^'\\\\]|\\\\.)* ) '"; $gt_p = "_\\( $opt_ws $qq_p $opt_ws \\)"; $argspec_p = "($arg_p) $opt_ws ($op_p) $opt_ws (?: $qq_p|$q_p|$gt_p|($word_p))"; @@ -70,7 +74,7 @@ extends WikiPlugin $defaults = array(); while (preg_match("/^$opt_ws $argspec_p $opt_ws/x", $argstr, $m)) { - @ list(,$arg,$op,$qq_val,$q_val,$gt_val,$word_val) = $m; + @ list(, $arg, $op, $qq_val, $q_val, $gt_val, $word_val) = $m; $argstr = substr($argstr, strlen($m[0])); // Remove quotes from string values. @@ -79,16 +83,13 @@ extends WikiPlugin // $val = stripslashes($qq_val); $val = $qq_val; elseif ($q_val) - $val = stripslashes($q_val); - elseif ($gt_val) - $val = _(stripslashes($gt_val)); - else + $val = stripslashes($q_val); elseif ($gt_val) + $val = _(stripslashes($gt_val)); else $val = $word_val; if ($op == '=') { $args[$arg] = $val; - } - else { + } else { // NOTE: This does work for multiple args. Use the // separator character defined in your webserver // configuration, usually & or & (See @@ -107,7 +108,8 @@ extends WikiPlugin return array($args, $defaults); } - function createTexFile($texfile, $text) { + function createTexFile($texfile, $text) + { // this is the small latex file // which contains only the mathematical // expression @@ -126,14 +128,15 @@ extends WikiPlugin return 0; } - function createPngFile($imagepath, $imagename) { + function createPngFile($imagepath, $imagename) + { // to create dvi file from the latex file $commandes = $this->latexbin . " temp.tex;"; exec("cd $imagepath;$commandes"); // to create png file from the dvi file // there is no option but it is possible // to add one (scale for example) - if (file_exists("$imagepath/temp.dvi")){ + if (file_exists("$imagepath/temp.dvi")) { $commandes = $this->dvipsbin . " temp.dvi -o temp.ps;"; $commandes .= $this->pstoimgbin . " -type png -margins 0,0 "; $commandes .= "-crop a -geometry 600x300 "; @@ -151,33 +154,35 @@ extends WikiPlugin return 0; } - function isMathExp(&$text) { + function isMathExp(&$text) + { // this function returns // 0 : text is too long or not a mathematical expression // 1 : text is $xxxxxx$ hence in line // 2 : text is $$xxxx$$ hence centered $last = strlen($text) - 1; - if($last >= 250){ + if ($last >= 250) { $text = "Too long !"; return 0; - } elseif($last <= 1 || strpos($text, '$') != 0){ + } elseif ($last <= 1 || strpos($text, '$') != 0) { return 0; - } elseif(strpos($text, '$', 1) == $last) - return 1; - elseif($last > 3 && - strpos($text, '$', 1) == 1 && - strpos($text, '$', 2) == $last - 1) + } elseif (strpos($text, '$', 1) == $last) + return 1; elseif ($last > 3 && + strpos($text, '$', 1) == 1 && + strpos($text, '$', 2) == $last - 1 + ) return 2; return 0; } - function tex2png($text) { + function tex2png($text) + { // the name of the png cached file $imagename = md5($text) . ".png"; $url = $this->imagepath . "/$imagename"; - if(!file_exists($url)){ - if(is_writable($this->imagepath)){ + if (!file_exists($url)) { + if (is_writable($this->imagepath)) { $texfile = $this->imagepath . "/temp.tex"; $this->createTexFile($texfile, $text); $this->createPngFile($this->imagepath, $imagename); @@ -190,34 +195,35 @@ extends WikiPlugin // there is always something in the html page // even if the tex directory doesn't exist // or mathematical expression is wrong - switch($this->isMathExp($text)) { - case 0: // not a mathematical expression - $html = HTML::tt(array('class'=>'tex', - 'style'=>'color:red;'), $text); - break; - case 1: // an inlined mathematical expression - $html = HTML::img(array('class'=>'tex', - 'src' => $url, - 'alt' => $text)); - break; - case 2: // mathematical expression on separate line - $html = HTML::img(array('class'=>'tex', - 'src' => $url, - 'alt' => $text)); - $html = HTML::div(array('align' => 'center'), $html); - break; - default: - break; + switch ($this->isMathExp($text)) { + case 0: // not a mathematical expression + $html = HTML::tt(array('class' => 'tex', + 'style' => 'color:red;'), $text); + break; + case 1: // an inlined mathematical expression + $html = HTML::img(array('class' => 'tex', + 'src' => $url, + 'alt' => $text)); + break; + case 2: // mathematical expression on separate line + $html = HTML::img(array('class' => 'tex', + 'src' => $url, + 'alt' => $text)); + $html = HTML::div(array('align' => 'center'), $html); + break; + default: + break; } return $html; } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { // from text2png.php if ((function_exists('ImageTypes') and (ImageTypes() & IMG_PNG)) - or function_exists("ImagePNG")) - { + or function_exists("ImagePNG") + ) { // we have gd & png so go ahead. extract($this->getArgs($argstr, $request)); return $this->tex2png($text); @@ -225,12 +231,14 @@ extends WikiPlugin // we don't have png and/or gd. $error_html = _("Sorry, this version of PHP cannot create PNG image files."); $link = "http://www.php.net/manual/pl/ref.image.php"; - $error_html .= sprintf(_("See %s"), $link) ."."; + $error_html .= sprintf(_("See %s"), $link) . "."; trigger_error($error_html, E_USER_NOTICE); return; } } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/Template.php b/lib/plugin/Template.php index 9604f2f48..f70efa941 100644 --- a/lib/plugin/Template.php +++ b/lib/plugin/Template.php @@ -55,35 +55,41 @@ */ class WikiPlugin_Template -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("Template"); } - function getDescription() { + function getDescription() + { return _("Parametrized page inclusion."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array( - 'page' => false, // the page to include - 'vars' => false, // TODO: get rid of this, all remaining args should be vars - 'rev' => false, // the revision (defaults to most recent) - 'section' => false, // just include a named section - 'sectionhead' => false // when including a named section show the heading - ); + 'page' => false, // the page to include + 'vars' => false, // TODO: get rid of this, all remaining args should be vars + 'rev' => false, // the revision (defaults to most recent) + 'section' => false, // just include a named section + 'sectionhead' => false // when including a named section show the heading + ); } - function allow_undeclared_arg($name, $value) { - // either just allow it or you can store it here away also. - $this->vars[$name] = $value; - return $name != 'action'; + + function allow_undeclared_arg($name, $value) + { + // either just allow it or you can store it here away also. + $this->vars[$name] = $value; + return $name != 'action'; } // TODO: check if page can really be pulled from the args, or if it is just the basepage. - function getWikiPageLinks($argstr, $basepage) { + function getWikiPageLinks($argstr, $basepage) + { $args = $this->getArgs($argstr); - $page = isset($args['page'])? $args['page']: ''; + $page = isset($args['page']) ? $args['page'] : ''; if ($page) { // Expand relative page names. $page = new WikiPageName($page, $basepage); @@ -93,7 +99,8 @@ extends WikiPlugin return array(array('linkto' => $page->name, 'relation' => 0)); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $this->vars = array(); $args = $this->getArgs($argstr, $request); $vars = $args['vars'] ? $args['vars'] : $this->vars; @@ -121,7 +128,7 @@ extends WikiPlugin static $included_pages = array(); if (in_array($page, $included_pages)) { return $this->error(sprintf(_("Recursive inclusion of page %s"), - $page)); + $page)); } // Check if page exists @@ -130,20 +137,20 @@ extends WikiPlugin } // Check if user is allowed to get the Page. - if (!mayAccessPage ('view', $page)) { - return $this->error(sprintf(_("Illegal inclusion of page %s: no read access."), - $page)); + if (!mayAccessPage('view', $page)) { + return $this->error(sprintf(_("Illegal inclusion of page %s: no read access."), + $page)); } $p = $dbi->getPage($page); if ($args['rev']) { - if (!is_whole_number($args['rev']) or !($args['rev']>0)) { + if (!is_whole_number($args['rev']) or !($args['rev'] > 0)) { return $this->error(_("Error: rev must be a positive integer.")); } $r = $p->getRevision($args['rev']); if ((!$r) || ($r->hasDefaultContents())) { return $this->error(sprintf(_("%s: no such revision %d."), - $page, $args['rev'])); + $page, $args['rev'])); } } else { $r = $p->getCurrentRevision(); @@ -152,20 +159,21 @@ extends WikiPlugin $content = $r->getContent(); // follow redirects - if ((preg_match('/<'.'\?plugin\s+RedirectTo\s+page=(\S+)\s*\?'.'>/', implode("\n", $content), $m)) - or (preg_match('/<'.'\?plugin\s+RedirectTo\s+page=(.*?)\s*\?'.'>/', implode("\n", $content), $m)) - or (preg_match('/<<\s*RedirectTo\s+page=(\S+)\s*>>/', implode("\n", $content), $m)) - or (preg_match('/<<\s*RedirectTo\s+page="(.*?)"\s*>>/', implode("\n", $content), $m))) - { + if ((preg_match('/<' . '\?plugin\s+RedirectTo\s+page=(\S+)\s*\?' . '>/', implode("\n", $content), $m)) + or (preg_match('/<' . '\?plugin\s+RedirectTo\s+page=(.*?)\s*\?' . '>/', implode("\n", $content), $m)) + or (preg_match('/<<\s*RedirectTo\s+page=(\S+)\s*>>/', implode("\n", $content), $m)) + or (preg_match('/<<\s*RedirectTo\s+page="(.*?)"\s*>>/', implode("\n", $content), $m)) + ) { // Strip quotes (simple or double) from page name if any if ((string_starts_with($m[1], "'")) - or (string_starts_with($m[1], "\""))) { + or (string_starts_with($m[1], "\"")) + ) { $m[1] = substr($m[1], 1, -1); } // trap recursive redirects if (in_array($m[1], $included_pages)) { return $this->error(sprintf(_("Recursive inclusion of page %s ignored"), - $page.' => '.$m[1])); + $page . ' => ' . $m[1])); } $page = $m[1]; $p = $dbi->getPage($page); @@ -181,11 +189,11 @@ extends WikiPlugin // exclude from expansion if (preg_match('/.+<\/noinclude>/s', $initial_content)) { $initial_content = preg_replace("/.+?<\/noinclude>/s", "", - $initial_content); + $initial_content); } // only in expansion $initial_content = preg_replace("/(.+)<\/includeonly>/s", "\\1", - $initial_content); + $initial_content); $this->doVariableExpansion($initial_content, $vars, $basepage, $request); array_push($included_pages, $page); @@ -208,14 +216,15 @@ extends WikiPlugin /** * Expand template variables. Used by the TemplatePlugin and the CreatePagePlugin */ - function doVariableExpansion(&$content, $vars, $basepage, &$request) { + function doVariableExpansion(&$content, $vars, $basepage, &$request) + { if (preg_match('/%%\w+%%/', $content)) // need variable expansion { $dbi =& $request->_dbi; $var = array(); if (is_string($vars) and !empty($vars)) { foreach (explode("&", $vars) as $pair) { - list($key,$val) = explode("=", $pair); + list($key, $val) = explode("=", $pair); $var[$key] = $val; } } elseif (is_array($vars)) { @@ -227,11 +236,11 @@ extends WikiPlugin if (preg_match('/%%USERID%%/', $content)) $var['USERID'] = $request->_user->getId(); if (empty($var['MTIME']) and preg_match('/%%MTIME%%/', $content)) { - $thisrev = $thispage->getCurrentRevision(false); + $thisrev = $thispage->getCurrentRevision(false); $var['MTIME'] = $GLOBALS['WikiTheme']->formatDateTime($thisrev->get('mtime')); } if (empty($var['CTIME']) and preg_match('/%%CTIME%%/', $content)) { - if ($first = $thispage->getRevision(1,false)) + if ($first = $thispage->getRevision(1, false)) $var['CTIME'] = $GLOBALS['WikiTheme']->formatDateTime($first->get('mtime')); } if (empty($var['AUTHOR']) and preg_match('/%%AUTHOR%%/', $content)) @@ -242,7 +251,7 @@ extends WikiPlugin $var['CREATOR'] = $thispage->getCreator(); foreach (array("SERVER_URL", "DATA_PATH", "SCRIPT_NAME", "PHPWIKI_BASE_URL") as $c) { // constants are not overridable - if (preg_match('/%%'.$c.'%%/', $content)) + if (preg_match('/%%' . $c . '%%/', $content)) $var[$c] = constant($c); } if (preg_match('/%%BASE_URL%%/', $content)) @@ -251,12 +260,14 @@ extends WikiPlugin foreach ($var as $key => $val) { // We have to decode the double quotes that have been encoded // in inline or block parser. - $content = str_replace("%%".$key."%%", htmlspecialchars_decode($val), $content); + $content = str_replace("%%" . $key . "%%", htmlspecialchars_decode($val), $content); } } return $content; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/TexToPng.php b/lib/plugin/TexToPng.php index 5c37727ef..9c040874b 100644 --- a/lib/plugin/TexToPng.php +++ b/lib/plugin/TexToPng.php @@ -43,7 +43,7 @@ $pstoimgbin = '/usr/bin/pstoimg'; // output mere debug messages (should be set to false in a stable // version) - define('TexToPng_debug', false); +define('TexToPng_debug', false); /*----------------------------------------------------------------------- | OPTION DEFAULTS @@ -52,7 +52,7 @@ $pstoimgbin = '/usr/bin/pstoimg'; | use antialias for rendering; | anitalias: blurs, _looks better_, needs twice space, renders slowlier | */ - define('TexToPng_antialias', true); +define('TexToPng_antialias', true); /*---- | Use transparent background; dont combine with antialias on a dark @@ -60,13 +60,13 @@ $pstoimgbin = '/usr/bin/pstoimg'; | ps-files (almost non readable,blurred output) even when directly | invoked from shell. So its probably a pstoimg bug. | */ - define('TexToPng_transparent', false); +define('TexToPng_transparent', false); /*---- | default value for rescaling | allowed range: 0 - 5 (integer) | */ - define('TexToPng_magstep', 3); +define('TexToPng_magstep', 3); /*----------------------------------------------------------------------- | @@ -76,9 +76,15 @@ $pstoimgbin = '/usr/bin/pstoimg'; // check boolean constants - if (!defined('TexToPng_debug')) { define('TexToPng_debug', false); } - if (!defined('TexToPng_antialias')) { define('TexToPng_antialias', false); } - if (!defined('TexToPng_transparent')) { define('TexToPng_transparent', false); } +if (!defined('TexToPng_debug')) { + define('TexToPng_debug', false); +} +if (!defined('TexToPng_antialias')) { + define('TexToPng_antialias', false); +} +if (!defined('TexToPng_transparent')) { + define('TexToPng_transparent', false); +} /*----------------------------------------------------------------------- | WikiPlugin_TexToPng @@ -88,64 +94,74 @@ require_once 'lib/WikiPluginCached.php'; class WikiPlugin_TexToPng extends WikiPluginCached { - function getPluginType() { + function getPluginType() + { return PLUGIN_CACHED_IMG_ONDEMAND; } - function getName() { + function getName() + { return "TexToPng"; } - function getDescription() { + function getDescription() + { return _("Converts TeX to an image. May be used to embed formulas in PhpWiki."); } - function getDefaultArguments() { - return array('tex' => "", - 'magstep' => TexToPng_magstep, - 'img' => 'png', - 'subslash' => 'off', - 'antialias' => TexToPng_antialias ? 'on' : 'off', - 'transparent' => TexToPng_transparent ? 'on' : 'off', - 'center' => 'off'); + function getDefaultArguments() + { + return array('tex' => "", + 'magstep' => TexToPng_magstep, + 'img' => 'png', + 'subslash' => 'off', + 'antialias' => TexToPng_antialias ? 'on' : 'off', + 'transparent' => TexToPng_transparent ? 'on' : 'off', + 'center' => 'off'); } - function getImage($dbi, $argarray, $request) { + function getImage($dbi, $argarray, $request) + { extract($argarray); $this->checkParams($tex, $magstep, $subslash, $antialias, $transparent); return $this->TexToImg($tex, $magstep, $antialias, $transparent); } // run - function getExpire($dbi, $argarray, $request) { + function getExpire($dbi, $argarray, $request) + { return '0'; } - function getImageType($dbi, $argarray, $request) { + function getImageType($dbi, $argarray, $request) + { extract($argarray); return $img; } - function getAlt($dbi, $argarray, $request) { + function getAlt($dbi, $argarray, $request) + { extract($argarray); return $tex; } - function embedImg($url,$dbi,$argarray,$request) { - $html = HTML::img( array( - 'src' => $url, - 'alt' => htmlspecialchars($this->getAlt($dbi,$argarray,$request)) - )); - if ($argarray['center']=='on') - return HTML::div( array('style' => 'text-align:center;'), $html); + function embedImg($url, $dbi, $argarray, $request) + { + $html = HTML::img(array( + 'src' => $url, + 'alt' => htmlspecialchars($this->getAlt($dbi, $argarray, $request)) + )); + if ($argarray['center'] == 'on') + return HTML::div(array('style' => 'text-align:center;'), $html); return $html; } /* -------------------- error handling ---------------------------- */ - function dbg( $out ) { + function dbg($out) + { // test if verbose debug info is selected if (TexToPng_debug) { - $this->complain( $out."\n" ); + $this->complain($out . "\n"); } else { if (!$this->_errortext) { // yeah, I've been told to be quiet, but obviously @@ -158,38 +174,44 @@ class WikiPlugin_TexToPng extends WikiPluginCached /* -------------------- parameter handling ------------------------ */ - function helptext() { - $aa= TexToPng_antialias ?'on(default)$|$off':'on$|$off(default)'; - $tp= TexToPng_transparent?'on(default)$|$off':'on$|$off(default)'; + function helptext() + { + $aa = TexToPng_antialias ? 'on(default)$|$off' : 'on$|$off(default)'; + $tp = TexToPng_transparent ? 'on(default)$|$off' : 'on$|$off(default)'; $help = - '/settabs/+/indent&$<$?plugin /bf{Tex} & [{/tt transparent}] & = "png(default)$|$jpeg$|$gif"& /cr'."\n". - '/+&$<$?plugin /bf{TexToPng} & /hfill {/tt tex} & = "/TeX/ commands"& /cr'."\n". - '/+& & /hfill [{/tt img}] & = "png(default)$|$jpeg$|$gif"& /cr'."\n". - '/+& & /hfill [{/tt magstep}] & = "0 to 5 ('.TexToPng_magstep.' default)"& /cr'."\n". - '/+& & /hfill [{/tt center}] & = "on$|$off(default)"& /cr'."\n". - '/+& & /hfill [{/tt subslash}] & = "on$|$off(default)"& /cr'."\n". - '/+& & /hfill [{/tt antialias}] & = "'.$aa.'"& /cr'."\n". - '/+& & /hfill [{/tt transparent}] & = "'.$tp.'"&?$>$ /cr'."\n"; - - return strtr($help, '/', '\\' ); + '/settabs/+/indent&$<$?plugin /bf{Tex} & [{/tt transparent}] & = "png(default)$|$jpeg$|$gif"& /cr' . "\n" . + '/+&$<$?plugin /bf{TexToPng} & /hfill {/tt tex} & = "/TeX/ commands"& /cr' . "\n" . + '/+& & /hfill [{/tt img}] & = "png(default)$|$jpeg$|$gif"& /cr' . "\n" . + '/+& & /hfill [{/tt magstep}] & = "0 to 5 (' . TexToPng_magstep . ' default)"& /cr' . "\n" . + '/+& & /hfill [{/tt center}] & = "on$|$off(default)"& /cr' . "\n" . + '/+& & /hfill [{/tt subslash}] & = "on$|$off(default)"& /cr' . "\n" . + '/+& & /hfill [{/tt antialias}] & = "' . $aa . '"& /cr' . "\n" . + '/+& & /hfill [{/tt transparent}] & = "' . $tp . '"&?$>$ /cr' . "\n"; + + return strtr($help, '/', '\\'); } // helptext - function checkParams( &$tex, &$magstep, $subslash, &$aalias, &$transp ) { + function checkParams(&$tex, &$magstep, $subslash, &$aalias, &$transp) + { - if ($subslash=='on') { + if ($subslash == 'on') { // WORKAROUND for backslashes - $tex = strtr($tex,'/','\\'); + $tex = strtr($tex, '/', '\\'); } // ------- check parameters $def = $this->getDefaultArguments(); - if ($tex=='') { $tex = $this->helptext(); } + if ($tex == '') { + $tex = $this->helptext(); + } - if ($magstep < 0 || $magstep > 5 ) { $magstep = $def["magstep"]; } + if ($magstep < 0 || $magstep > 5) { + $magstep = $def["magstep"]; + } // calculate magnification factor - $magstep = floor(10*pow(1.2,$magstep))/10; + $magstep = floor(10 * pow(1.2, $magstep)) / 10; $aalias = $aalias != 'off'; $transp = $transp != 'off'; @@ -198,19 +220,21 @@ class WikiPlugin_TexToPng extends WikiPluginCached /* ------------------ image creation ------------------------------ */ - function execute($cmd,$complainvisibly=false) { + function execute($cmd, $complainvisibly = false) + { exec($cmd, $errortxt, $returnval); $ok = $returnval == 0; if (!$ok) { if (!$complainvisibly) { - $this->dbg('Error during execution of '.$cmd ); - }; - while (list($key,$value)=each($errortxt)) { + $this->dbg('Error during execution of ' . $cmd); + } + ; + while (list($key, $value) = each($errortxt)) { if ($complainvisibly) { - $this->complain( $value."\n" ); + $this->complain($value . "\n"); } else { - $this->dbg( $value ); + $this->dbg($value); } } } @@ -219,21 +243,22 @@ class WikiPlugin_TexToPng extends WikiPluginCached /* ---------------------------------------------------------------- */ - function createTexFile($texfile,$texstr) { - if ($ok=($fp=fopen($texfile, 'w'))!=0 ) { + function createTexFile($texfile, $texstr) + { + if ($ok = ($fp = fopen($texfile, 'w')) != 0) { // prepare .tex file $texcommands = - '\nopagenumbers' . "\n" . - '\hoffset=0cm' . "\n" . - '\voffset=0cm' . "\n" . - // '\hsize=20cm' . "\n" . - // '\vsize=10ex' . "\n" . - $texstr . "\n" . - '\vfill\eject' . "\n" . - '\end' . "\n\n"; + '\nopagenumbers' . "\n" . + '\hoffset=0cm' . "\n" . + '\voffset=0cm' . "\n" . + // '\hsize=20cm' . "\n" . + // '\vsize=10ex' . "\n" . + $texstr . "\n" . + '\vfill\eject' . "\n" . + '\end' . "\n\n"; $ok = fwrite($fp, $texcommands); - $ok = fclose($fp) && $ok; // close anyway + $ok = fclose($fp) && $ok; // close anyway } if (!$ok) { $this->dbg('could not write .tex file: ' . $texstr); @@ -243,31 +268,32 @@ class WikiPlugin_TexToPng extends WikiPluginCached /* ---------------------------------------------------------------- */ - function TexToImg($texstr, $scale, $aalias, $transp) { + function TexToImg($texstr, $scale, $aalias, $transp) + { //$cacheparams = $GLOBALS['CacheParams']; $tempfiles = $this->tempnam('TexToPng'); $img = 0; // $size = 0; // procuce options for pstoimg $options = - ($aalias ? '-aaliastext -color 8 ' : '-color 1 ') . - ($transp ? '-transparent ' : '') . - '-scale ' . $scale . ' ' . - '-type png -crop btlr -geometry 600x150 -margins 0,0'; + ($aalias ? '-aaliastext -color 8 ' : '-color 1 ') . + ($transp ? '-transparent ' : '') . + '-scale ' . $scale . ' ' . + '-type png -crop btlr -geometry 600x150 -margins 0,0'; // rely on intelligent bool interpretation - $ok= $tempfiles && - $this->createTexFile($tempfiles.'.tex',$texstr) && - $this->execute('cd '.$cacheparams['cache_dir'].'; '. - "$texbin ".$tempfiles.'.tex',true) && - $this->execute("$dvipsbin -o".$tempfiles.'.ps '.$tempfiles.'.dvi') && - $this->execute("$pstoimgbin $options" - .' -out '.$tempfiles.'.png '. - $tempfiles.'.ps' ) && - file_exists( $tempfiles.'.png' ); + $ok = $tempfiles && + $this->createTexFile($tempfiles . '.tex', $texstr) && + $this->execute('cd ' . $cacheparams['cache_dir'] . '; ' . + "$texbin " . $tempfiles . '.tex', true) && + $this->execute("$dvipsbin -o" . $tempfiles . '.ps ' . $tempfiles . '.dvi') && + $this->execute("$pstoimgbin $options" + . ' -out ' . $tempfiles . '.png ' . + $tempfiles . '.ps') && + file_exists($tempfiles . '.png'); if ($ok) { - if (!($img = ImageCreateFromPNG( $tempfiles.'.png' ))) { + if (!($img = ImageCreateFromPNG($tempfiles . '.png'))) { $this->dbg("Could not open just created image file: $tempfiles"); $ok = false; } @@ -275,7 +301,7 @@ class WikiPlugin_TexToPng extends WikiPluginCached // clean up tmpdir; in debug mode only if no error occured - if ( !TexToPng_debug || (TexToPng_debug && $ok)) { + if (!TexToPng_debug || (TexToPng_debug && $ok)) { if ($tempfiles) { unlink($tempfiles); unlink($tempfiles . '.ps'); diff --git a/lib/plugin/TitleSearch.php b/lib/plugin/TitleSearch.php index ea2a25d42..0670b91e0 100644 --- a/lib/plugin/TitleSearch.php +++ b/lib/plugin/TitleSearch.php @@ -38,35 +38,40 @@ require_once 'lib/PageList.php'; * like xx*, *xx, ^xx, xx$, ^word$. */ class WikiPlugin_TitleSearch -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("TitleSearch"); } - function getDescription () { + function getDescription() + { return _("Search the titles of all pages in this wiki."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array_merge - ( - PageList::supportedArgs(), // paging and more. - array('s' => false, - 'auto_redirect' => false, - 'noheader' => false, - 'exclude' => false, - 'info' => false, - 'case_exact' => false, - 'regex' => 'auto', - 'format' => false, - )); + ( + PageList::supportedArgs(), // paging and more. + array('s' => false, + 'auto_redirect' => false, + 'noheader' => false, + 'exclude' => false, + 'info' => false, + 'case_exact' => false, + 'regex' => 'auto', + 'format' => false, + )); } + // info arg allows multiple columns // info=mtime,hits,summary,version,author,locked,minor // exclude arg allows multiple pagenames exclude=Php*,RecentChanges - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); if (empty($args['s'])) { return HTML(); @@ -75,7 +80,7 @@ extends WikiPlugin // ^S != S* ^ matches only beginning of phrase, not of word. // x* matches any word beginning with x $query = new TextSearchQuery($args['s'], $args['case_exact'], $args['regex']); - $pages = $dbi->titleSearch($query,$args['sortby'],$args['limit'],$args['exclude']); + $pages = $dbi->titleSearch($query, $args['sortby'], $args['limit'], $args['exclude']); $pagelist = new PageList($args['info'], $args['exclude'], $args); $pagelist->addPages($pages); @@ -102,7 +107,9 @@ extends WikiPlugin return $pagelist; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/Transclude.php b/lib/plugin/Transclude.php index a78dfab9b..97be4c542 100644 --- a/lib/plugin/Transclude.php +++ b/lib/plugin/Transclude.php @@ -45,25 +45,29 @@ * quite big enough --- the scroll bars remain. Not sure why. */ class WikiPlugin_Transclude -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("Transclude"); } - function getDescription() { - return _("Include an external web page within the body of a wiki page."); + function getDescription() + { + return _("Include an external web page within the body of a wiki page."); } - function getDefaultArguments() { - return array( 'src' => false, // the src url to include - 'title' => _("Transcluded page"), // title of the iframe - 'height' => 450, // height of the iframe - 'quiet' => false // if set, iframe appears as normal content - ); + function getDefaultArguments() + { + return array('src' => false, // the src url to include + 'title' => _("Transcluded page"), // title of the iframe + 'height' => 450, // height of the iframe + 'quiet' => false // if set, iframe appears as normal content + ); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = ($this->getArgs($argstr, $request)); extract($args); @@ -72,37 +76,37 @@ extends WikiPlugin return $this->error(fmt("%s parameter missing", "'src'")); } // Expand possible interwiki link for src - if (strstr($src,':') - and (!strstr($src,'://')) - and ($intermap = getInterwikiMap()) - and preg_match("/^" . $intermap->getRegexp() . ":/", $src)) - { + if (strstr($src, ':') + and (!strstr($src, '://')) + and ($intermap = getInterwikiMap()) + and preg_match("/^" . $intermap->getRegexp() . ":/", $src) + ) { $link = $intermap->link($src); $src = $link->getAttr('href'); } // FIXME: Better recursion detection. // FIXME: Currently this doesnt work at all. - if ($src == $request->getURLtoSelf() ) { + if ($src == $request->getURLtoSelf()) { return $this->error(fmt("Recursive inclusion of url %s", $src)); } - if (! IsSafeURL($src)) { + if (!IsSafeURL($src)) { return $this->error(_("Bad url in src: remove all of <, >, \"")); } $params = array('title' => $title, - 'src' => $src, - 'width' => "100%", - 'height' => $height, - 'marginwidth' => 0, - 'marginheight' => 0, - 'class' => 'transclude', - "onload" => "adjust_iframe_height(this);"); + 'src' => $src, + 'width' => "100%", + 'height' => $height, + 'marginwidth' => 0, + 'marginheight' => 0, + 'class' => 'transclude', + "onload" => "adjust_iframe_height(this);"); $noframe_msg[] = fmt("See: %s", HTML::a(array('href' => $src), $src)); $noframe_msg = HTML::div(array('class' => 'transclusion'), - HTML::p(array(), $noframe_msg)); + HTML::p(array(), $noframe_msg)); $iframe = HTML::iframe($params, $noframe_msg); @@ -114,8 +118,8 @@ extends WikiPlugin return HTML($this->_js(), $iframe); } else { return HTML(HTML::p(array('class' => 'transclusion-title'), - fmt("Transcluded from %s", LinkURL($src))), - $this->_js(), $iframe); + fmt("Transcluded from %s", LinkURL($src))), + $this->_js(), $iframe); } } @@ -128,7 +132,8 @@ extends WikiPlugin * * @access private */ - function _js() { + function _js() + { static $seen = false; if ($seen) @@ -155,7 +160,9 @@ extends WikiPlugin }, false); '); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/TranslateText.php b/lib/plugin/TranslateText.php index 6447c5ca3..a9945eb55 100644 --- a/lib/plugin/TranslateText.php +++ b/lib/plugin/TranslateText.php @@ -38,30 +38,34 @@ require_once 'lib/plugin/_WikiTranslation.php'; class WikiPlugin_TranslateText -extends WikiPlugin__WikiTranslation + extends WikiPlugin__WikiTranslation { - function getName() { + function getName() + { return _("TranslateText"); } - function getDescription() { + function getDescription() + { return _("Define a translation for a specified text"); } - function getDefaultArguments() { + function getDefaultArguments() + { return - array( 'lang' => false, - 'pagename' => '[pagename]', - 'translate' => false, - ); + array('lang' => false, + 'pagename' => '[pagename]', + 'translate' => false, + ); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { extract($this->getArgs($argstr, $request)); if (!$lang) return $this->error( - _("This internal action page cannot viewed.")."\n". - _("You can only use it via the _WikiTranslation plugin.")); + _("This internal action page cannot viewed.") . "\n" . + _("You can only use it via the _WikiTranslation plugin.")); $this->lang = $lang; //action=save @@ -69,14 +73,14 @@ extends WikiPlugin__WikiTranslation $trans = $translate["content"]; if (empty($trans) or $trans == $pagename) { $header = HTML(HTML::h2(_("Translation Error!")), - HTML::p(_("Your translated text is either empty or equal to the untranslated text. Please try again."))); + HTML::p(_("Your translated text is either empty or equal to the untranslated text. Please try again."))); } else { //save translation in a users subpage $user = $request->getUser(); $homepage = $user->_HomePagehandle; $transpagename = $homepage->getName() . SUBPAGE_SEPARATOR . _("ContributedTranslations"); - $page = $dbi->getPage($transpagename); + $page = $dbi->getPage($transpagename); $current = $page->getCurrentRevision(); $version = $current->getVersion(); if ($version) { @@ -85,51 +89,53 @@ extends WikiPlugin__WikiTranslation } else { $text = ''; $meta = array('markup' => 2.0, - 'author' => $user->getId()); + 'author' => $user->getId()); } $text .= $user->getId() . " " . Iso8601DateTime() . "\n" . - "* " . sprintf(_("Translate '%s' to '%s' in *%s*"), - $pagename, $trans, $lang); - $text .= "\n locale/po/$lang.po:\n msgid \"".$pagename."\"\n msgstr \"".$trans."\"\n "; + "* " . sprintf(_("Translate '%s' to '%s' in *%s*"), + $pagename, $trans, $lang); + $text .= "\n locale/po/$lang.po:\n msgid \"" . $pagename . "\"\n msgstr \"" . $trans . "\"\n "; $meta['summary'] = sprintf(_("Translate %s to %s in %s"), - substr($pagename,0,15),substr($trans,0,15),$lang); + substr($pagename, 0, 15), substr($trans, 0, 15), $lang); $page->save($text, $version + 1, $meta); // TODO: admin notification return HTML(HTML::h2(_("Thanks for adding this translation!")), - HTML::p(fmt("Your translated text doesn't yet appear in this %s, but the Administrator will pick it up and add to the installation.", - WIKI_NAME)), - fmt("Your translation is stored in %s",WikiLink($transpagename))); + HTML::p(fmt("Your translated text doesn't yet appear in this %s, but the Administrator will pick it up and add to the installation.", + WIKI_NAME)), + fmt("Your translation is stored in %s", WikiLink($transpagename))); } } - $trans = $this->translate($pagename,$lang,'en'); + $trans = $this->translate($pagename, $lang, 'en'); //Todo: google lookup or at least a google lookup button. if (isset($header)) - $header = HTML($header,fmt("From english to %s: ", HTML::strong($lang))); + $header = HTML($header, fmt("From english to %s: ", HTML::strong($lang))); else $header = fmt("From english to %s: ", HTML::strong($lang)); $button_label = _("Translate"); $buttons = HTML::p(Button('submit:translate[submit]', $button_label, 'wikiadmin'), - Button('submit:translate[cancel]', _("Cancel"), 'button')); + Button('submit:translate[cancel]', _("Cancel"), 'button')); return HTML::form(array('action' => $request->getPostURL(), - 'method' => 'post'), - $header, - HTML::textarea(array('class' => 'wikiedit', - 'name' => 'translate[content]', - 'id' => 'translate[content]', - 'rows' => 4, - 'cols' => $request->getPref('editWidth') - ), - $trans), - HiddenInputs($request->getArgs(), - false, - array('translate')), - HiddenInputs(array('translate[action]' => $pagename, - 'require_authority_for_post' => WIKIAUTH_BOGO, - )), - $buttons); - } -}; + 'method' => 'post'), + $header, + HTML::textarea(array('class' => 'wikiedit', + 'name' => 'translate[content]', + 'id' => 'translate[content]', + 'rows' => 4, + 'cols' => $request->getPref('editWidth') + ), + $trans), + HiddenInputs($request->getArgs(), + false, + array('translate')), + HiddenInputs(array('translate[action]' => $pagename, + 'require_authority_for_post' => WIKIAUTH_BOGO, + )), + $buttons); + } +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/UnfoldSubpages.php b/lib/plugin/UnfoldSubpages.php index c91d184b4..875a149a1 100644 --- a/lib/plugin/UnfoldSubpages.php +++ b/lib/plugin/UnfoldSubpages.php @@ -34,43 +34,47 @@ require_once 'lib/TextSearchQuery.php'; require_once 'lib/plugin/IncludePage.php'; class WikiPlugin_UnfoldSubpages -extends WikiPlugin_IncludePage + extends WikiPlugin_IncludePage { - function getName() { + function getName() + { return _("UnfoldSubpages"); } - function getDescription () { + function getDescription() + { return _("Includes the content of all SubPages of the current page."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array_merge - ( - PageList::supportedArgs(), - array( - 'pagename' => '[pagename]', // default: current page - //'header' => '', // expandable string - 'quiet' => false, // print no header - 'sortby' => '', // [+|-]pagename, [+|-]mtime, [+|-]hits - 'maxpages' => false, // maximum number of pages to include (== limit) - 'smalltitle' => false, // if set, hide transclusion-title, - // just have a small link at the start of - // the page. - 'words' => false, // maximum number of words - // per page to include - 'lines' => false, // maximum number of lines - // per page to include - 'bytes' => false, // maximum number of bytes - // per page to include - 'sections' => false, // maximum number of sections per page to include - 'section' => false, // this named section per page only - 'sectionhead' => false // when including a named - // section show the heading - )); + ( + PageList::supportedArgs(), + array( + 'pagename' => '[pagename]', // default: current page + //'header' => '', // expandable string + 'quiet' => false, // print no header + 'sortby' => '', // [+|-]pagename, [+|-]mtime, [+|-]hits + 'maxpages' => false, // maximum number of pages to include (== limit) + 'smalltitle' => false, // if set, hide transclusion-title, + // just have a small link at the start of + // the page. + 'words' => false, // maximum number of words + // per page to include + 'lines' => false, // maximum number of lines + // per page to include + 'bytes' => false, // maximum number of bytes + // per page to include + 'sections' => false, // maximum number of sections per page to include + 'section' => false, // this named section per page only + 'sectionhead' => false // when including a named + // section show the heading + )); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { static $included_pages = false; if (!$included_pages) $included_pages = array($basepage); @@ -90,92 +94,94 @@ extends WikiPlugin_IncludePage $i = 0; while ($page = $subpages->next()) { $cpagename = $page->getName(); - if ($maxpages and ($i++ > $maxpages)) { + if ($maxpages and ($i++ > $maxpages)) { return $content; } if (in_array($cpagename, $exclude)) - continue; + continue; // A page cannot include itself. Avoid doublettes. if (in_array($cpagename, $included_pages)) { $content->pushContent(HTML::p(sprintf(_("Recursive inclusion of page %s ignored"), - $cpagename))); + $cpagename))); continue; } // Check if user is allowed to get the Page. - if (!mayAccessPage ('view', $cpagename)) { - return $this->error(sprintf(_("Illegal inclusion of page %s: no read access"), + if (!mayAccessPage('view', $cpagename)) { + return $this->error(sprintf(_("Illegal inclusion of page %s: no read access"), $cpagename)); } // trap any remaining nonexistant subpages if ($page->exists()) { $r = $page->getCurrentRevision(); - $c = $r->getContent(); // array of lines + $c = $r->getContent(); // array of lines // follow redirects - if ((preg_match('/<'.'\?plugin\s+RedirectTo\s+page=(\S+)\s*\?'.'>/', implode("\n", $c), $m)) - or (preg_match('/<'.'\?plugin\s+RedirectTo\s+page=(.*?)\s*\?'.'>/', implode("\n", $c), $m)) - or (preg_match('/<<\s*RedirectTo\s+page=(\S+)\s*>>/', implode("\n", $c), $m)) - or (preg_match('/<<\s*RedirectTo\s+page="(.*?)"\s*>>/', implode("\n", $c), $m))) - { + if ((preg_match('/<' . '\?plugin\s+RedirectTo\s+page=(\S+)\s*\?' . '>/', implode("\n", $c), $m)) + or (preg_match('/<' . '\?plugin\s+RedirectTo\s+page=(.*?)\s*\?' . '>/', implode("\n", $c), $m)) + or (preg_match('/<<\s*RedirectTo\s+page=(\S+)\s*>>/', implode("\n", $c), $m)) + or (preg_match('/<<\s*RedirectTo\s+page="(.*?)"\s*>>/', implode("\n", $c), $m)) + ) { // Strip quotes (simple or double) from page name if any if ((string_starts_with($m[1], "'")) - or (string_starts_with($m[1], "\""))) { + or (string_starts_with($m[1], "\"")) + ) { $m[1] = substr($m[1], 1, -1); } // trap recursive redirects if (in_array($m[1], $included_pages)) { - if (!$quiet) + if (!$quiet) $content->pushContent( HTML::p(sprintf(_("Recursive inclusion of page %s ignored"), - $cpagename.' => '.$m[1]))); + $cpagename . ' => ' . $m[1]))); continue; } - $cpagename = $m[1]; + $cpagename = $m[1]; - // Check if user is allowed to get the Page. - if (!mayAccessPage ('view', $cpagename)) { - return $this->error(sprintf(_("Illegal inclusion of page %s: no read access"), - $cpagename)); - } + // Check if user is allowed to get the Page. + if (!mayAccessPage('view', $cpagename)) { + return $this->error(sprintf(_("Illegal inclusion of page %s: no read access"), + $cpagename)); + } - $page = $dbi->getPage($cpagename); + $page = $dbi->getPage($cpagename); $r = $page->getCurrentRevision(); - $c = $r->getContent(); // array of lines + $c = $r->getContent(); // array of lines } // moved to IncludePage - $ct = $this->extractParts ($c, $cpagename, $args); + $ct = $this->extractParts($c, $cpagename, $args); array_push($included_pages, $cpagename); if ($smalltitle) { $pname = array_pop(explode(SUBPAGE_SEPARATOR, $cpagename)); // get last subpage name // Use _("%s: %s") instead of .": ". for French punctuation $ct = TransformText(sprintf(_("%s: %s"), "[$pname|$cpagename]", - $ct), - $r->get('markup'), $cpagename); - } - else { + $ct), + $r->get('markup'), $cpagename); + } else { $ct = TransformText($ct, $r->get('markup'), $cpagename); } array_pop($included_pages); - if (! $smalltitle) { + if (!$smalltitle) { $content->pushContent(HTML::p(array('class' => $quiet ? - '' : 'transclusion-title'), - fmt("Included from %s:", - WikiLink($cpagename)))); + '' : 'transclusion-title'), + fmt("Included from %s:", + WikiLink($cpagename)))); } $content->pushContent(HTML(HTML::div(array('class' => $quiet ? - '' : 'transclusion'), - false, $ct))); + '' : 'transclusion'), + false, $ct))); } } - if (! isset($cpagename)) { + if (!isset($cpagename)) { return $this->error(sprintf(_("%s has no subpages defined."), $pagename)); } return $content; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/UpLoad.php b/lib/plugin/UpLoad.php index d2620d95a..d729e1ae4 100644 --- a/lib/plugin/UpLoad.php +++ b/lib/plugin/UpLoad.php @@ -34,34 +34,38 @@ */ class WikiPlugin_UpLoad -extends WikiPlugin + extends WikiPlugin { var $disallowed_extensions; // TODO: use PagePerms instead var $only_authenticated = true; // allow only authenticated users may upload. - function getName () { + function getName() + { return "UpLoad"; } - function getDescription () { + function getDescription() + { return _("Upload files to the local InterWiki Upload:"); } - function getDefaultArguments() { - return array('logfile' => 'phpwiki-upload.log', - // add a link of the fresh file automatically to the - // end of the page (or current page) - 'autolink' => true, - 'page' => '[pagename]', - 'size' => 50, - 'mode' => 'actionpage', // or edit - ); + function getDefaultArguments() + { + return array('logfile' => 'phpwiki-upload.log', + // add a link of the fresh file automatically to the + // end of the page (or current page) + 'autolink' => true, + 'page' => '[pagename]', + 'size' => 50, + 'mode' => 'actionpage', // or edit + ); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $this->allowed_extensions = explode("\n", -"7z + "7z avi bmp bz2 @@ -100,7 +104,7 @@ xml xsd zip"); $this->disallowed_extensions = explode("\n", -"ad[ep] + "ad[ep] asd ba[st] chm @@ -143,28 +147,28 @@ ws[cfh]"); $file_dir = getUploadFilePath(); $file_dir .= "/"; - $form = HTML::form(array('action' => $request->getPostURL(), - 'enctype' => 'multipart/form-data', - 'method' => 'post')); + $form = HTML::form(array('action' => $request->getPostURL(), + 'enctype' => 'multipart/form-data', + 'method' => 'post')); $contents = HTML::div(array('class' => 'wikiaction')); $contents->pushContent(HTML::input(array('type' => 'hidden', - 'name' => 'MAX_FILE_SIZE', - 'value'=> MAX_UPLOAD_SIZE))); + 'name' => 'MAX_FILE_SIZE', + 'value' => MAX_UPLOAD_SIZE))); $contents->pushContent(HTML::input(array('name' => 'userfile', - 'type' => 'file', - 'size' => $size))); + 'type' => 'file', + 'size' => $size))); if ($mode == 'edit') { $contents->pushContent(HTML::input(array('name' => 'action', - 'type' => 'hidden', - 'value'=> 'edit'))); + 'type' => 'hidden', + 'value' => 'edit'))); $contents->pushContent(HTML::raw(" ")); $contents->pushContent(HTML::input(array('value' => _("Upload"), - 'name' => 'edit[upload]', - 'type' => 'submit'))); + 'name' => 'edit[upload]', + 'type' => 'submit'))); } else { $contents->pushContent(HTML::raw(" ")); $contents->pushContent(HTML::input(array('value' => _("Upload"), - 'type' => 'submit'))); + 'type' => 'submit'))); } $form->pushContent($contents); @@ -175,16 +179,16 @@ ws[cfh]"); if (!$user->isAuthenticated()) { if (defined('FUSIONFORGE') and FUSIONFORGE) { $message->pushContent(HTML::div(array('class' => 'error'), - HTML::p(_("You cannot upload files.")), - HTML::ul( - HTML::li(_("Check you are logged in.")), - HTML::li(_("Check you are in the right project.")), - HTML::li(_("Check you are a member of the current project.")) - ) - )); + HTML::p(_("You cannot upload files.")), + HTML::ul( + HTML::li(_("Check you are logged in.")), + HTML::li(_("Check you are in the right project.")), + HTML::li(_("Check you are a member of the current project.")) + ) + )); } else { $message->pushContent(HTML::div(array('class' => 'error'), - HTML::p(_("ACCESS DENIED: You must log in to upload files.")))); + HTML::p(_("ACCESS DENIED: You must log in to upload files.")))); } $result = HTML(); $result->pushContent($form); @@ -209,45 +213,38 @@ ws[cfh]"); $u_userfile = preg_replace("/ /", "%20", $u_userfile); $userfile_tmpname = $userfile->getTmpName(); $err_header = HTML::div(array('class' => 'error'), - HTML::p(fmt("ERROR uploading '%s'", $userfile_name))); + HTML::p(fmt("ERROR uploading '%s'", $userfile_name))); if (preg_match("/(\." . join("|\.", $this->disallowed_extensions) . ")(\.|\$)/i", - $userfile_name)) - { - $message->pushContent($err_header); + $userfile_name) + ) { + $message->pushContent($err_header); $message->pushContent(HTML::p(fmt("Files with extension %s are not allowed.", - join(", ", $this->disallowed_extensions)))); - } - elseif (! DISABLE_UPLOAD_ONLY_ALLOWED_EXTENSIONS and - ! preg_match("/(\." . join("|\.", $this->allowed_extensions) . ")\$/i", - $userfile_name)) - { - $message->pushContent($err_header); + join(", ", $this->disallowed_extensions)))); + } elseif (!DISABLE_UPLOAD_ONLY_ALLOWED_EXTENSIONS and + !preg_match("/(\." . join("|\.", $this->allowed_extensions) . ")\$/i", + $userfile_name) + ) { + $message->pushContent($err_header); $message->pushContent(HTML::p(fmt("Only files with the extension %s are allowed.", - join(", ", $this->allowed_extensions)))); - } - elseif (preg_match("/[^._a-zA-Z0-9- ]/", strip_accents($userfile_name))) - { - $message->pushContent($err_header); + join(", ", $this->allowed_extensions)))); + } elseif (preg_match("/[^._a-zA-Z0-9- ]/", strip_accents($userfile_name))) { + $message->pushContent($err_header); $message->pushContent(HTML::p(_("Invalid filename. File names may only contain alphanumeric characters and dot, underscore, space or dash."))); - } - elseif (file_exists($file_dir . $userfile_name)) { - $message->pushContent($err_header); + } elseif (file_exists($file_dir . $userfile_name)) { + $message->pushContent($err_header); $message->pushContent(HTML::p(fmt("There is already a file with name %s uploaded.", - $u_userfile))); - } - elseif ($userfile->getSize() > (MAX_UPLOAD_SIZE)) { - $message->pushContent($err_header); + $u_userfile))); + } elseif ($userfile->getSize() > (MAX_UPLOAD_SIZE)) { + $message->pushContent($err_header); $message->pushContent(HTML::p(_("Sorry but this file is too big."))); - } - elseif (move_uploaded_file($userfile_tmpname, $file_dir . $userfile_name) or - (IsWindows() and rename($userfile_tmpname, $file_dir . $userfile_name)) - ) - { - $interwiki = new PageType_interwikimap(); + } elseif (move_uploaded_file($userfile_tmpname, $file_dir . $userfile_name) or + (IsWindows() and rename($userfile_tmpname, $file_dir . $userfile_name)) + ) { + $interwiki = new PageType_interwikimap(); $link = $interwiki->link("Upload:$u_userfile"); $message->pushContent(HTML::div(array('class' => 'feedback'), - HTML::p(_("File successfully uploaded.")), - HTML::p($link))); + HTML::p(_("File successfully uploaded.")), + HTML::p($link))); // the upload was a success and we need to mark this event in the "upload log" if ($logfile) { @@ -257,23 +254,22 @@ ws[cfh]"); if ($autolink) { require_once 'lib/loadsave.php'; $pagehandle = $dbi->getPage($page); - if ($pagehandle->exists()) {// don't replace default contents + if ($pagehandle->exists()) { // don't replace default contents $current = $pagehandle->getCurrentRevision(); $version = $current->getVersion(); $text = $current->getPackedContent(); $newtext = $text . "\n* Upload:$u_userfile"; // don't inline images $meta = $current->_data; - $meta['summary'] = sprintf(_("uploaded %s"),$u_userfile); + $meta['summary'] = sprintf(_("uploaded %s"), $u_userfile); $pagehandle->save($newtext, $version + 1, $meta); } } } else { - $message->pushContent($err_header); - $message->pushContent(HTML::br(),_("Uploading failed."),HTML::br()); + $message->pushContent($err_header); + $message->pushContent(HTML::br(), _("Uploading failed."), HTML::br()); } - } - else { - $message->pushContent(HTML::br(),_("No file selected. Please select one."),HTML::br()); + } else { + $message->pushContent(HTML::br(), _("No file selected. Please select one."), HTML::br()); } //$result = HTML::div( array( 'class' => 'wikiaction' ) ); @@ -283,27 +279,26 @@ ws[cfh]"); return $result; } - function log ($userfile, $upload_log, &$message) { - global $WikiTheme; - $user = $GLOBALS['request']->_user; + function log($userfile, $upload_log, &$message) + { + global $WikiTheme; + $user = $GLOBALS['request']->_user; if (file_exists($upload_log) and (!is_writable($upload_log))) { trigger_error(_("The upload logfile exists but is not writable."), E_USER_WARNING); - } - elseif (!$log_handle = fopen ($upload_log, "a")) { + } elseif (!$log_handle = fopen($upload_log, "a")) { trigger_error(_("Can't open the upload logfile."), E_USER_WARNING); - } - else { // file size in KB; precision of 0.1 - $file_size = round(($userfile->getSize())/1024, 1); + } else { // file size in KB; precision of 0.1 + $file_size = round(($userfile->getSize()) / 1024, 1); if ($file_size <= 0) { $file_size = "< 0.1"; } $userfile_name = $userfile->getName(); fwrite($log_handle, - "\n" - . "$userfile_name" - . "$file_size kB" - . "  " . $WikiTheme->formatDate(time()) . "" - . "  " . $user->getId() . ""); + "\n" + . "$userfile_name" + . "$file_size kB" + . "  " . $WikiTheme->formatDate(time()) . "" + . "  " . $user->getId() . ""); fclose($log_handle); } return; diff --git a/lib/plugin/UriResolver.php b/lib/plugin/UriResolver.php index d04e8f980..7a3144252 100644 --- a/lib/plugin/UriResolver.php +++ b/lib/plugin/UriResolver.php @@ -30,35 +30,42 @@ require_once 'lib/SemanticWeb.php'; class WikiPlugin_UriResolver -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("UriResolver"); } - function getDescription () { + function getDescription() + { return _("Converts an uri-escaped identifier back to an unique XML-ID"); } - function getDefaultArguments() { + function getDefaultArguments() + { return array(); } - function allow_undeclared_arg() { + function allow_undeclared_arg() + { return true; } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $request->getArgs(); unset($args['pagename']); unset($args['action']); unset($args['start_debug']); // FIXME: ?Test=1 => Test - $arg = join("/",array_keys($args)); + $arg = join("/", array_keys($args)); $xmlid = RdfWriter::makeXMLExportId($arg); return $xmlid; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/UserPreferences.php b/lib/plugin/UserPreferences.php index cc06a2a00..c6784a6f8 100644 --- a/lib/plugin/UserPreferences.php +++ b/lib/plugin/UserPreferences.php @@ -31,25 +31,29 @@ * of preferences. */ class WikiPlugin_UserPreferences -extends WikiPlugin + extends WikiPlugin { var $bool_args; - function getName () { + function getName() + { return _("UserPreferences"); } - function getDescription () { + function getDescription() + { return _("Allow any user to adjust his own preferences."); } - function getDefaultArguments() { + function getDefaultArguments() + { global $request; $pagename = $request->getArg('pagename'); $user = $request->getUser(); - if ( isset($user->_prefs) and - isset($user->_prefs->_prefs) and - isset($user->_prefs->_method) ) { + if (isset($user->_prefs) and + isset($user->_prefs->_prefs) and + isset($user->_prefs->_method) + ) { $pref =& $user->_prefs; } else { $pref = $user->getPreferences(); @@ -62,38 +66,38 @@ extends WikiPlugin return $prefs; } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); $user =& $request->_user; $user->_request = $request; - if (isa($request,'MockRequest')) + if (isa($request, 'MockRequest')) return ''; if (defined('FUSIONFORGE') and FUSIONFORGE) { if (!($user->isAuthenticated())) { return HTML::p(array('class' => 'error'), - _("Error: You are not logged in, cannot display UserPreferences.")); + _("Error: You are not logged in, cannot display UserPreferences.")); } } if ((!isActionPage($request->getArg('pagename')) - and (!isset($user->_prefs->_method) - or !in_array($user->_prefs->_method, array('ADODB','SQL','PDO')))) - or (in_array($request->getArg('action'), array('zip','ziphtml','dumphtml'))) - or (isa($user,'_ForbiddenUser'))) - { + and (!isset($user->_prefs->_method) + or !in_array($user->_prefs->_method, array('ADODB', 'SQL', 'PDO')))) + or (in_array($request->getArg('action'), array('zip', 'ziphtml', 'dumphtml'))) + or (isa($user, '_ForbiddenUser')) + ) { $no_args = $this->getDefaultArguments(); $no_args['errmsg'] = HTML::p(array('class' => 'error'), - _("Error: The user HomePage must be a valid WikiWord. Sorry, UserPreferences cannot be saved.")); + _("Error: The user HomePage must be a valid WikiWord. Sorry, UserPreferences cannot be saved.")); $no_args['isForm'] = false; return Template('userprefs', $no_args); } $userid = $user->UserName(); - if ($user->isAuthenticated() and !empty($userid)) - { + if ($user->isAuthenticated() and !empty($userid)) { $pref = &$request->_prefs; $args['isForm'] = true; if ($request->isPost()) { - $errmsg = ''; + $errmsg = ''; $delete = $request->getArg('delete'); if ($delete and $request->getArg('verify')) { // deleting prefs, verified @@ -101,22 +105,22 @@ extends WikiPlugin $default_prefs['userid'] = $user->UserName(); $user->setPreferences($default_prefs); $request->_setUser($user); - $request->setArg("verify",false); - $request->setArg("delete",false); + $request->setArg("verify", false); + $request->setArg("delete", false); $errmsg .= _("Your UserPreferences have been successfully reset to default."); $args['errmsg'] = HTML::div(array('class' => 'feedback'), HTML::p($errmsg)); return Template('userprefs', $args); } elseif ($delete and !$request->getArg('verify')) { return HTML::fieldset( - HTML::form(array('action' => $request->getPostURL(), - 'method' => 'post'), - HiddenInputs(array('verify' => 1)), - HiddenInputs($request->getArgs()), - HTML::p(_("Do you really want to reset all your UserPreferences?")), - HTML::p(Button('submit:delete', _("Yes"), 'delete'), - HTML::Raw(' '), - Button('cancel', _("Cancel"))) - )); + HTML::form(array('action' => $request->getPostURL(), + 'method' => 'post'), + HiddenInputs(array('verify' => 1)), + HiddenInputs($request->getArgs()), + HTML::p(_("Do you really want to reset all your UserPreferences?")), + HTML::p(Button('submit:delete', _("Yes"), 'delete'), + HTML::Raw(' '), + Button('cancel', _("Cancel"))) + )); } elseif ($rp = $request->getArg('pref')) { // replace only changed prefs in $pref with those from request if (!empty($rp['passwd']) and ($rp['passwd2'] != $rp['passwd'])) { @@ -125,7 +129,7 @@ extends WikiPlugin if (empty($rp['passwd'])) unset($rp['passwd']); // fix to set system pulldown's. empty values don't get posted if (empty($rp['theme'])) $rp['theme'] = ''; - if (empty($rp['lang'])) $rp['lang'] = ''; + if (empty($rp['lang'])) $rp['lang'] = ''; $num = $user->setPreferences($rp); if (!empty($rp['passwd'])) { $passchanged = false; @@ -146,17 +150,17 @@ extends WikiPlugin } } if (!$num) { - $errmsg .= " " ._("No changes."); + $errmsg .= " " . _("No changes."); } else { $request->_setUser($user); $pref = $user->_prefs; if ($num == 1) { $errmsg .= _("One UserPreferences field successfully updated."); } else { - $errmsg .= sprintf(_("%d UserPreferences fields successfully updated."), $num); + $errmsg .= sprintf(_("%d UserPreferences fields successfully updated."), $num); + } } } - } $args['errmsg'] = HTML::div(array('class' => 'feedback'), HTML::p($errmsg)); } @@ -170,7 +174,9 @@ extends WikiPlugin return $request->_notAuthorized(WIKIAUTH_BOGO); } } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/UserRatings.php b/lib/plugin/UserRatings.php index a6ec8292b..f78727264 100644 --- a/lib/plugin/UserRatings.php +++ b/lib/plugin/UserRatings.php @@ -38,59 +38,62 @@ else */ class WikiPlugin_UserRatings -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("UserRatings"); } - function getDescription () { + function getDescription() + { return _("List the user's ratings."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array('dimension' => '0', - // array of userids to display ratings for; null/empty for - // active user only - 'userids' => null, - // array of pageids to display ratings for; null for all - // of current active user's ratings - 'pageids' => null, - // a category to display ratings for; null for no category; - // has higher precedence than pageids - 'category' => null, - 'pagename' => '[pagename]', // hackish - 'exclude' => '', - 'limit' => 0, // limit of <=0 is show-all - 'noheader' => 0, - 'userPage' => false, - 'nobuds' => false, - // rating columns are added later - 'info' => 'pagename'); - // getting a bit crowded with the buddies... - // 'info' => 'hits,pagename,author,ratingwidget'); + // array of userids to display ratings for; null/empty for + // active user only + 'userids' => null, + // array of pageids to display ratings for; null for all + // of current active user's ratings + 'pageids' => null, + // a category to display ratings for; null for no category; + // has higher precedence than pageids + 'category' => null, + 'pagename' => '[pagename]', // hackish + 'exclude' => '', + 'limit' => 0, // limit of <=0 is show-all + 'noheader' => 0, + 'userPage' => false, + 'nobuds' => false, + // rating columns are added later + 'info' => 'pagename'); + // getting a bit crowded with the buddies... + // 'info' => 'hits,pagename,author,ratingwidget'); } + // info arg allows multiple columns // info=mtime,hits,summary,version,author,locked,minor // exclude arg allows multiple pagenames exclude=HomePage,RecentChanges - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { extract($this->getArgs($argstr, $request)); // XXX: fix to reflect multi-user ratings? $caption = _("Displaying %d ratings:"); - $active_user = $request->getUser(); + $active_user = $request->getUser(); $active_userid = $active_user->_userid; // check for request to display a category's ratings - if(isset($category) && is_string($category) && strlen($category)) - { + if (isset($category) && is_string($category) && strlen($category)) { $pageids = array(); $category_page = $dbi->getPage($category); $iter = $category_page->getLinks(); - while($item = $iter->next()) - { + while ($item = $iter->next()) { array_push($pageids, $item->getName()); } // XXX: is there a way to retrieve the preferred plural @@ -98,11 +101,9 @@ extends WikiPlugin // XXX: should the category text be a link? can it be one easily? $caption = sprintf(_("Showing all %ss (%%d):"), $category); - } - // if null is passed as the pageids argument and no category was passed, + } // if null is passed as the pageids argument and no category was passed, // show active user's ratings - elseif(!isset($pageids) || !is_array($pageids)) - { + elseif (!isset($pageids) || !is_array($pageids)) { // XXX: need support for sorted ratings // bug: pages excluded from the PageList via the "exclude" argument // count toward the limit! @@ -111,7 +112,7 @@ extends WikiPlugin $active_user_ratings_user = & RatingsUserFactory::getUser($active_user->getId()); $current_user_ratings = $active_user_ratings_user->get_ratings(); - if ($userPage){ + if ($userPage) { //we're on a user's homepage, get *their* ratings $this_page_user = & RatingsUserFactory::getUser($userPage); $caption = _("Here are $userPage" . "'s %d page ratings:"); @@ -122,45 +123,37 @@ extends WikiPlugin } $i = 0; - foreach($ratings as $pagename => $page_ratings) - { + foreach ($ratings as $pagename => $page_ratings) { // limit is currently only honored for "own" ratings - if($limit > 0 && $i >= $limit) - { + if ($limit > 0 && $i >= $limit) { break; } - if(isset($page_ratings[$dimension])) - { + if (isset($page_ratings[$dimension])) { array_push($pageids, $pagename); $i++; } } - // $caption = _("Here are your %d page ratings:"); - //make $ratings the user's ratings again if it had been treated as the current page - // name's ratings - $ratings = $current_user_ratings; + // $caption = _("Here are your %d page ratings:"); + //make $ratings the user's ratings again if it had been treated as the current page + // name's ratings + $ratings = $current_user_ratings; } // if userids is null or empty, fill it with just the active user - if(!isset($userids) || !is_array($userids) || !count($userids)) - { + if (!isset($userids) || !is_array($userids) || !count($userids)) { // TKL: moved getBuddies call inside if statement because it was // causing the userids[] parameter to be ignored - if(is_string($active_userid) && strlen($active_userid) && $active_user->isSignedIn() && !$userPage) { - if (isset($category_page)){ + if (is_string($active_userid) && strlen($active_userid) && $active_user->isSignedIn() && !$userPage) { + if (isset($category_page)) { $userids = getBuddies($active_userid, $dbi, $category_page->getName()); } else { - $userids = getBuddies($active_userid, $dbi); + $userids = getBuddies($active_userid, $dbi); } - } - elseif ($userPage) - { + } elseif ($userPage) { //we're on a user page, show that user's ratings as the only column $userids = array(); array_push($userids, $userPage); - } - else - { + } else { $userids = array(); // XXX: this wipes out the category caption... // $caption = _("You must be logged in to view ratings."); @@ -173,11 +166,9 @@ extends WikiPlugin $allowed_users = array(); // users actually allowed to be shown to the user $allowed_users_toshow = array(); - foreach($userids as $userid) - { + foreach ($userids as $userid) { $user = & RatingsUserFactory::getUser($userid); - if($user->allow_view_ratings($active_user)) - { + if ($user->allow_view_ratings($active_user)) { array_push($allowed_users_toshow, $user); } // all users should be allowed in calculation @@ -188,9 +179,9 @@ extends WikiPlugin } // if no buddies, use allusers in prediction calculation - if (count($userids) == 0 || $userPage){ - $allowed_users = array(); - //$people_iter = $dbi->get_users_rated(); + if (count($userids) == 0 || $userPage) { + $allowed_users = array(); + //$people_iter = $dbi->get_users_rated(); $people_dbi = RatingsDb::getTheRatingsDb(); $people_iter = $people_dbi->sql_get_users_rated(); while ($people_array = $people_iter->next()) { @@ -201,7 +192,7 @@ extends WikiPlugin } } - } + } $columns = $info ? explode(",", $info) : array(); // build our table... @@ -209,38 +200,40 @@ extends WikiPlugin // augment columns //$preds = new _PageList_Column_prediction('prediction', _("Pred"), 'right', $dimension, $allowed_users); - $preds = array('_PageList_column_prediction','custom:prediction', _("Pred"),'right',' ' , $allowed_users); + $preds = array('_PageList_column_prediction', 'custom:prediction', _("Pred"), 'right', ' ', $allowed_users); $pagelist->addColumnObject($preds); //$widget = new _PageList_Column_ratingwidget('ratingwidget', _("Rate"), 'left', $dimension); - $widget = array('_PageList_column_ratingwidget','custom:ratingwidget', _("Rate"), 'center'); + $widget = array('_PageList_column_ratingwidget', 'custom:ratingwidget', _("Rate"), 'center'); $pagelist->addColumnObject($widget); $noRatingUsers = array(); - if (!$nobuds){ - foreach($allowed_users_toshow as $idx => $user) { + if (!$nobuds) { + foreach ($allowed_users_toshow as $idx => $user) { // For proper caching behavior, get a ref, don't user $user $u = & $allowed_users_toshow[$idx]; //$col = & new _PageList_Column_ratingvalue('ratingvalue', $u->getId(), 'right', $dimension, $u); - $col = array('_PageList_Column_ratingvalue','custom:ratingvalue', $u->getId(), 'right',' ' ,$u); + $col = array('_PageList_Column_ratingvalue', 'custom:ratingvalue', $u->getId(), 'right', ' ', $u); $pagelist->addColumnObject($col); unset($u); } } // add rows -- each row represents an item (page) - foreach($pageids as $pagename) { + foreach ($pageids as $pagename) { // addPage can deal with cases where it is passed a string $pagelist->addPage($pagename); } - if (! $noheader) { + if (!$noheader) { $pagelist->setCaption(_($caption)); } return $pagelist; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/Video.php b/lib/plugin/Video.php index e0ace1eb6..fc24f2de6 100644 --- a/lib/plugin/Video.php +++ b/lib/plugin/Video.php @@ -43,32 +43,36 @@ */ class WikiPlugin_Video -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("Video"); } - function getDescription() { + function getDescription() + { return _("Display video in Flash"); } - function getDefaultArguments() { - return array('width' => 460, - 'height' => 320, - 'url' => '', - 'file' => '', - 'autoplay' => 'false' - ); + function getDefaultArguments() + { + return array('width' => 460, + 'height' => 320, + 'url' => '', + 'file' => '', + 'autoplay' => 'false' + ); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { global $WikiTheme; $args = $this->getArgs($argstr, $request); extract($args); - if (! $url && ! $file) { + if (!$url && !$file) { return $this->error(_("Both 'url' or 'file' parameters missing.")); } elseif ($url && $file) { return $this->error(_("Choose only one of 'url' or 'file' parameters.")); @@ -79,68 +83,70 @@ extends WikiPlugin if (string_ends_with($url, ".ogg")) { return HTML::video(array('autoplay' => 'true', 'controls' => 'true', 'src' => $url), - _("Your browser does not understand the HTML 5 video tag.")); + _("Your browser does not understand the HTML 5 video tag.")); } $html = HTML(); if (isBrowserIE()) { $object = HTML::object(array('id' => 'flowplayer', - 'classid' => 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000', - 'width' => $width, - 'height' => $height)); + 'classid' => 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000', + 'width' => $width, + 'height' => $height)); $param = HTML::param(array('name' => 'movie', - 'value' => SERVER_URL . $WikiTheme->_findData('flowplayer-3.2.4.swf'))); + 'value' => SERVER_URL . $WikiTheme->_findData('flowplayer-3.2.4.swf'))); $object->pushContent($param); $param = HTML::param(array('name' => "allowfullscreen", - 'value' => "true")); + 'value' => "true")); $object->pushContent($param); $param = HTML::param(array('name' => "allowscriptaccess", - 'value' => "false")); + 'value' => "false")); $object->pushContent($param); $flashvars = "config={'clip':{'url':'" . $url . "','autoPlay':" . $autoplay . "}}"; $param = HTML::param(array('name' => 'flashvars', - 'value' => $flashvars)); + 'value' => $flashvars)); $object->pushContent($param); $embed = HTML::embed(array('type' => 'application/x-shockwave-flash', - 'width' => $width, - 'height' => $height, - 'src' => SERVER_URL . $WikiTheme->_findData('flowplayer-3.2.4.swf'), - 'flashvars' => $flashvars)); + 'width' => $width, + 'height' => $height, + 'src' => SERVER_URL . $WikiTheme->_findData('flowplayer-3.2.4.swf'), + 'flashvars' => $flashvars)); $object->pushContent($embed); $html->pushContent($object); } else { $object = HTML::object(array('data' => SERVER_URL . $WikiTheme->_findData('flowplayer-3.2.4.swf'), - 'type' => "application/x-shockwave-flash", - 'width' => $width, - 'height' => $height)); + 'type' => "application/x-shockwave-flash", + 'width' => $width, + 'height' => $height)); $param = HTML::param(array('name' => "allowfullscreen", - 'value' => "true")); + 'value' => "true")); $object->pushContent($param); $param = HTML::param(array('name' => "allowscriptaccess", - 'value' => "false")); + 'value' => "false")); $object->pushContent($param); $value = "config={'clip':{'url':'" . $url . "','autoPlay':" . $autoplay . "}}"; $param = HTML::param(array('name' => "flashvars", - 'value' => $value)); + 'value' => $value)); $object->pushContent($param); $html->pushContent($object); } return $html; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/VisualWiki.php b/lib/plugin/VisualWiki.php index dee3eff15..cde56f691 100644 --- a/lib/plugin/VisualWiki.php +++ b/lib/plugin/VisualWiki.php @@ -35,14 +35,15 @@ if (!defined('VISUALWIKI_ALLOWOPTIONS')) require_once 'lib/plugin/GraphViz.php'; class WikiPlugin_VisualWiki -extends WikiPlugin_GraphViz + extends WikiPlugin_GraphViz { /** * Sets plugin type to map production */ - function getPluginType() { + function getPluginType() + { return ($GLOBALS['request']->getArg('debug')) ? PLUGIN_CACHED_IMG_ONDEMAND - : PLUGIN_CACHED_MAP; + : PLUGIN_CACHED_MAP; } /** @@ -50,14 +51,16 @@ extends WikiPlugin_GraphViz * <?plugin VisualWiki?>, now. This * name must correspond to the filename and the class name. */ - function getName() { + function getName() + { return "VisualWiki"; } /** * Sets textual description. */ - function getDescription() { + function getDescription() + { return _("Visualizes the Wiki structure in a graph using the 'dot' commandline tool from graphviz."); } @@ -66,24 +69,25 @@ extends WikiPlugin_GraphViz * function to allow its usage by both getDefaultArguments * and checkArguments */ - function defaultarguments() { - return array('imgtype' => 'png', - 'width' => false, // was 5, scale it automatically - 'height' => false, // was 7, scale it automatically - 'colorby' => 'age', // sort by 'age' or 'revtime' - 'fillnodes' => 'off', - 'label' => 'name', - 'shape' => 'ellipse', - 'large_nb' => 5, - 'recent_nb' => 5, - 'refined_nb' => 15, - 'backlink_nb' => 5, - 'neighbour_list' => '', - 'exclude_list' => '', - 'include_list' => '', - 'fontsize' => 9, - 'debug' => false, - 'help' => false ); + function defaultarguments() + { + return array('imgtype' => 'png', + 'width' => false, // was 5, scale it automatically + 'height' => false, // was 7, scale it automatically + 'colorby' => 'age', // sort by 'age' or 'revtime' + 'fillnodes' => 'off', + 'label' => 'name', + 'shape' => 'ellipse', + 'large_nb' => 5, + 'recent_nb' => 5, + 'refined_nb' => 15, + 'backlink_nb' => 5, + 'neighbour_list' => '', + 'exclude_list' => '', + 'include_list' => '', + 'fontsize' => 9, + 'debug' => false, + 'help' => false); } /** @@ -95,7 +99,8 @@ extends WikiPlugin_GraphViz * to allow no options to be set and use only the default parameters. * This will need an disk space of about 20 Kbyte all the time. */ - function getDefaultArguments() { + function getDefaultArguments() + { if (VISUALWIKI_ALLOWOPTIONS) return $this->defaultarguments(); else @@ -106,7 +111,8 @@ extends WikiPlugin_GraphViz * Substitutes each forbidden parameter value by the default value * defined in defaultarguments. */ - function checkArguments(&$arg) { + function checkArguments(&$arg) + { extract($arg); $def = $this->defaultarguments(); if (($width < 3) || ($width > 15)) @@ -119,7 +125,8 @@ extends WikiPlugin_GraphViz $arg['label'] = $def['label']; if (!in_array($shape, array('ellipse', 'box', 'point', 'circle', - 'plaintext'))) + 'plaintext')) + ) $arg['shape'] = $def['shape']; if (!in_array($colorby, array('age', 'revtime'))) $arg['colorby'] = $def['colorby']; @@ -127,9 +134,9 @@ extends WikiPlugin_GraphViz $arg['fillnodes'] = $def['fillnodes']; if (($large_nb < 0) || ($large_nb > 50)) $arg['large_nb'] = $def['large_nb']; - if (($recent_nb < 0) || ($recent_nb > 50)) + if (($recent_nb < 0) || ($recent_nb > 50)) $arg['recent_nb'] = $def['recent_nb']; - if (($refined_nb < 0 ) || ( $refined_nb > 50)) + if (($refined_nb < 0) || ($refined_nb > 50)) $arg['refined_nb'] = $def['refined_nb']; if (($backlink_nb < 0) || ($backlink_nb > 50)) $arg['backlink_nb'] = $def['backlink_nb']; @@ -145,11 +152,12 @@ extends WikiPlugin_GraphViz * database access and image map production functions. * @return array($map,$html) */ - function getMap($dbi, $argarray, $request) { + function getMap($dbi, $argarray, $request) + { if (!VISUALWIKI_ALLOWOPTIONS) $argarray = $this->defaultarguments(); $this->checkArguments($argarray); - $request->setArg('debug',$argarray['debug']); + $request->setArg('debug', $argarray['debug']); //extract($argarray); if ($argarray['help']) return array($this->helpImage(), ' '); // FIXME @@ -157,7 +165,7 @@ extends WikiPlugin_GraphViz $this->extract_wikipages($dbi, $argarray); /* ($dbi, $large, $recent, $refined, $backlink, $neighbour, $excludelist, $includelist, $color); */ - $result = $this->invokeDot($argarray); + $result = $this->invokeDot($argarray); if (isa($result, 'HtmlElement')) return array(false, $result); else @@ -171,40 +179,41 @@ extends WikiPlugin_GraphViz * Returns an image containing a usage description of the plugin. * @return string image handle */ - function helpImage() { + function helpImage() + { $def = $this->defaultarguments(); $other_imgtypes = $GLOBALS['PLUGIN_CACHED_IMGTYPES']; unset ($other_imgtypes[$def['imgtype']]); $helparr = array( - '<<'.$this->getName() . - ' img' => ' = "' . $def['imgtype'] . "(default)|" . join('|',$GLOBALS['PLUGIN_CACHED_IMGTYPES']).'"', - 'width' => ' = "width in inches"', - 'height' => ' = "height in inches"', - 'fontname' => ' = "font family"', - 'fontsize' => ' = "fontsize in points"', - 'colorby' => ' = "age|revtime|none"', - 'fillnodes' => ' = "on|off"', - 'shape' => ' = "ellipse(default)|box|circle|point"', - 'label' => ' = "name|number"', - 'large_nb' => ' = "number of largest pages to be selected"', - 'recent_nb' => ' = "number of youngest pages"', - 'refined_nb' => ' = "#pages with smallest time between revisions"', - 'backlink_nb' => ' = "number of pages with most backlinks"', - 'neighbour_list' => ' = "find pages linked from and to these pages"', - 'exclude_list' => ' = "colon separated list of pages to be excluded"', - 'include_list' => ' = "colon separated list" >>' - ); + '<<' . $this->getName() . + ' img' => ' = "' . $def['imgtype'] . "(default)|" . join('|', $GLOBALS['PLUGIN_CACHED_IMGTYPES']) . '"', + 'width' => ' = "width in inches"', + 'height' => ' = "height in inches"', + 'fontname' => ' = "font family"', + 'fontsize' => ' = "fontsize in points"', + 'colorby' => ' = "age|revtime|none"', + 'fillnodes' => ' = "on|off"', + 'shape' => ' = "ellipse(default)|box|circle|point"', + 'label' => ' = "name|number"', + 'large_nb' => ' = "number of largest pages to be selected"', + 'recent_nb' => ' = "number of youngest pages"', + 'refined_nb' => ' = "#pages with smallest time between revisions"', + 'backlink_nb' => ' = "number of pages with most backlinks"', + 'neighbour_list' => ' = "find pages linked from and to these pages"', + 'exclude_list' => ' = "colon separated list of pages to be excluded"', + 'include_list' => ' = "colon separated list" >>' + ); $length = 0; - foreach($helparr as $alignright => $alignleft) { + foreach ($helparr as $alignright => $alignleft) { $length = max($length, strlen($alignright)); } - $helptext =''; - foreach($helparr as $alignright => $alignleft) { + $helptext = ''; + foreach ($helparr as $alignright => $alignleft) { $helptext .= substr(' ' - . $alignright, -$length).$alignleft."\n"; + . $alignright, -$length) . $alignleft . "\n"; } return $this->text2img($helptext, 4, array(1, 0, 0), - array(255, 255, 255)); + array(255, 255, 255)); } @@ -218,15 +227,16 @@ extends WikiPlugin_GraphViz * @param minimum boolean true finds smallest, false finds biggest * @return array list of page names found to be the best */ - function findbest($number, $category, $minimum ) { + function findbest($number, $category, $minimum) + { // select the $number best in the category '$category' $pages = &$this->pages; $names = &$this->names; $selected = array(); $i = 0; - foreach($names as $name) { - if ($i++>=$number) + foreach ($names as $name) { + if ($i++ >= $number) break; $selected[$name] = $pages[$name][$category]; } @@ -235,7 +245,7 @@ extends WikiPlugin_GraphViz $i = 0; foreach ($names as $name) { - if ($i++<$number) + if ($i++ < $number) continue; if ($minimum) { if (($crit = $pages[$name][$category]) < $compareto) { @@ -244,7 +254,7 @@ extends WikiPlugin_GraphViz array_pop($selected); $compareto = end($selected); } - } elseif (($crit = $pages[$name][$category]) > $compareto) { + } elseif (($crit = $pages[$name][$category]) > $compareto) { $selected[$name] = $crit; arsort($selected, SORT_NUMERIC); array_pop($selected); @@ -258,45 +268,46 @@ extends WikiPlugin_GraphViz /** - * Extracts a subset of all pages from the wiki and find their - * connections to other pages. Also collects some page features - * like size, age, revision number which are used to find the - * most attractive pages. - * - * @param dbi WikiDB database handle to access all Wiki pages - * @param LARGE integer number of largest pages which should - * be included - * @param RECENT integer number of the youngest pages to be included - * @param REFINED integer number of the pages with shortes revision - * interval - * @param BACKLINK integer number of the pages with most backlinks - * @param EXCLUDELIST string colon ':' separated list of page names which - * should not be displayed (like PhpWiki, for - * example) - * @param INCLUDELIST string colon separated list of pages which are - * always included (for example your own - * page :) - * @param COLOR string 'age', 'revtime' or 'none'; Selects which - * page feature is used to determine the - * filling color of the nodes in the graph. - * @return void - */ - function extract_wikipages($dbi, $argarray) { + * Extracts a subset of all pages from the wiki and find their + * connections to other pages. Also collects some page features + * like size, age, revision number which are used to find the + * most attractive pages. + * + * @param dbi WikiDB database handle to access all Wiki pages + * @param LARGE integer number of largest pages which should + * be included + * @param RECENT integer number of the youngest pages to be included + * @param REFINED integer number of the pages with shortes revision + * interval + * @param BACKLINK integer number of the pages with most backlinks + * @param EXCLUDELIST string colon ':' separated list of page names which + * should not be displayed (like PhpWiki, for + * example) + * @param INCLUDELIST string colon separated list of pages which are + * always included (for example your own + * page :) + * @param COLOR string 'age', 'revtime' or 'none'; Selects which + * page feature is used to determine the + * filling color of the nodes in the graph. + * @return void + */ + function extract_wikipages($dbi, $argarray) + { // $LARGE, $RECENT, $REFINED, $BACKLINK, $NEIGHBOUR, // $EXCLUDELIST, $INCLUDELIST,$COLOR $now = time(); extract($argarray); // FIXME: gettextify? - $exclude_list = $exclude_list ? explode(':', $exclude_list) : array(); - $include_list = $include_list ? explode(':', $include_list) : array(); + $exclude_list = $exclude_list ? explode(':', $exclude_list) : array(); + $include_list = $include_list ? explode(':', $include_list) : array(); $neighbour_list = $neighbour_list ? explode(':', $neighbour_list) : array(); // remove INCLUDED from EXCLUDED, includes override excludes. if ($exclude_list and $include_list) { - $diff = array_diff($exclude_list, $include_list); - if ($diff) - $exclude_list = $diff; + $diff = array_diff($exclude_list, $include_list); + if ($diff) + $exclude_list = $diff; } // collect all pages @@ -308,7 +319,7 @@ extends WikiPlugin_GraphViz // skip excluded pages if (in_array($name, $exclude_list)) { - $page->free(); + $page->free(); continue; } @@ -340,13 +351,13 @@ extends WikiPlugin_GraphViz $rev = $page->getCurrentRevision(); $pages[$name] = array( - 'age' => $now - $rev->get('mtime'), - 'revnr' => $rev->getVersion(), - 'links' => array(), + 'age' => $now - $rev->get('mtime'), + 'revnr' => $rev->getVersion(), + 'links' => array(), 'backlink_nb' => count($bconnection), - 'backlinks' => $bconnection, - 'size' => 1000 // FIXME - ); + 'backlinks' => $bconnection, + 'size' => 1000 // FIXME + ); $pages[$name]['revtime'] = $pages[$name]['age'] / ($pages[$name]['revnr']); unset($page); @@ -359,13 +370,13 @@ extends WikiPlugin_GraphViz // now select each page matching to given parameters $all_selected = array_unique(array_merge( - $this->findbest($recent_nb, 'age', true), - $this->findbest($refined_nb, 'revtime', true), + $this->findbest($recent_nb, 'age', true), + $this->findbest($refined_nb, 'revtime', true), $x = $this->findbest($backlink_nb, 'backlink_nb', false), // $this->findbest($large_nb, 'size', false), $include_list)); - foreach($all_selected as $name) + foreach ($all_selected as $name) if (isset($pages[$name])) $newpages[$name] = $pages[$name]; unset($this->names); @@ -380,14 +391,14 @@ extends WikiPlugin_GraphViz // remove dead links and collect links reset($pages); - while( list($name, $page) = each($pages) ) { + while (list($name, $page) = each($pages)) { if (is_array($page['backlinks'])) { reset($page['backlinks']); - while ( list($index, $link) = each( $page['backlinks'] ) ) { - if ( !isset($pages[$link]) || $link == $name ) { + while (list($index, $link) = each($page['backlinks'])) { + if (!isset($pages[$link]) || $link == $name) { unset($pages[$name]['backlinks'][$index]); } else { - array_push($pages[$link]['links'],$name); + array_push($pages[$link]['links'], $name); //array_push($this->everylink, array($link,$name)); } } @@ -398,7 +409,7 @@ extends WikiPlugin_GraphViz return; list($oldestname) = $this->findbest(1, $colorby, false); $this->oldest = $pages[$oldestname][$colorby]; - foreach($this->names as $name) + foreach ($this->names as $name) $pages[$name]['color'] = $this->getColor($pages[$name][$colorby] / $this->oldest); } @@ -416,7 +427,8 @@ extends WikiPlugin_GraphViz * 'number': label by unique number * @return boolean error status; true=ok; false=error */ - function createDotFile($filename, $argarray) { + function createDotFile($filename, $argarray) + { extract($argarray); if (!$fp = fopen($filename, 'w')) return false; @@ -436,17 +448,17 @@ extends WikiPlugin_GraphViz switch ($shape) { - case 'point': - $dot .= "edge [arrowhead=none];\nnode [shape=$shape,fontname=$fontname,width=0.15,height=0.15,fontsize=$fontsize];\n"; - break; - case 'box': - $dot .= "node [shape=$shape,fontname=$fontname,width=0.4,height=0.4,fontsize=$fontsize];\n"; - break; - case 'circle': - $dot .= "node [shape=$shape,fontname=$fontname,width=0.25,height=0.25,fontsize=$fontsize];\n"; - break; - default : - $dot .= "node [fontname=$fontname,shape=$shape,fontsize=$fontsize];\n" ; + case 'point': + $dot .= "edge [arrowhead=none];\nnode [shape=$shape,fontname=$fontname,width=0.15,height=0.15,fontsize=$fontsize];\n"; + break; + case 'box': + $dot .= "node [shape=$shape,fontname=$fontname,width=0.4,height=0.4,fontsize=$fontsize];\n"; + break; + case 'circle': + $dot .= "node [shape=$shape,fontname=$fontname,width=0.25,height=0.25,fontsize=$fontsize];\n"; + break; + default : + $dot .= "node [fontname=$fontname,shape=$shape,fontsize=$fontsize];\n"; } $dot .= "\n"; $i = 0; @@ -461,48 +473,48 @@ extends WikiPlugin_GraphViz if ($colorby != 'none') { $col = $pages[$name]['color']; $dot .= sprintf(',%scolor="#%02X%02X%02X"', $fillstring, - $col[0], $col[1], $col[2]); + $col[0], $col[1], $col[2]); } $dot .= "];\n"; if (!empty($pages[$name]['links'])) { unset($linkarray); if ($label != 'name') - foreach($pages[$name]['links'] as $linkname) + foreach ($pages[$name]['links'] as $linkname) $linkarray[] = $nametonumber[$linkname] + 1; else $linkarray = $pages[$name]['links']; - $linkstring = join('"; "', $linkarray ); + $linkstring = join('"; "', $linkarray); $c = count($pages[$name]['links']); $dot .= " \"$nodename\" -> " - . ($c>1?'{':'') - . "\"$linkstring\";" - . ($c>1?'}':'') - . "\n"; + . ($c > 1 ? '{' : '') + . "\"$linkstring\";" + . ($c > 1 ? '}' : '') + . "\n"; } } if ($colorby != 'none') { $dot .= "\n subgraph cluster_legend {\n" - . " node[fontname=$fontname,shape=box,width=0.4,height=0.4,fontsize=$fontsize];\n" - . " fillcolor=lightgrey;\n" - . " style=filled;\n" - . " fontname=$fontname;\n" - . " fontsize=$fontsize;\n" - . " label=\"".gettext("Legend")."\";\n"; - $oldest= ceil($this->oldest / (24 * 3600)); + . " node[fontname=$fontname,shape=box,width=0.4,height=0.4,fontsize=$fontsize];\n" + . " fillcolor=lightgrey;\n" + . " style=filled;\n" + . " fontname=$fontname;\n" + . " fontsize=$fontsize;\n" + . " label=\"" . gettext("Legend") . "\";\n"; + $oldest = ceil($this->oldest / (24 * 3600)); $max = 5; $legend = array(); - for($i = 0; $i < $max; $i++) { + for ($i = 0; $i < $max; $i++) { $time = floor($i / $max * $oldest); - $name = '"' . $time .' '. _("days") .'"'; - $col = $this->getColor($i/$max); + $name = '"' . $time . ' ' . _("days") . '"'; + $col = $this->getColor($i / $max); $dot .= sprintf(' %s [%scolor="#%02X%02X%02X"];', - $name, $fillstring, $col[0], $col[1], $col[2]) + $name, $fillstring, $col[0], $col[1], $col[2]) . "\n"; $legend[] = $name; } - $dot .= ' '. join(' -> ', $legend) + $dot .= ' ' . join(' -> ', $legend) . ";\n }\n"; } @@ -511,7 +523,7 @@ extends WikiPlugin_GraphViz $this->source = $dot; // write a temp file $ok = fwrite($fp, $dot); - $ok = fclose($fp) && $ok; // close anyway + $ok = fclose($fp) && $ok; // close anyway return $ok; } @@ -532,7 +544,8 @@ extends WikiPlugin_GraphViz * @param request Request ??? * @return string html output */ - function embedImg($url,&$dbi,$argarray,&$request) { + function embedImg($url, &$dbi, $argarray, &$request) + { if (!VISUALWIKI_ALLOWOPTIONS) $argarray = $this->defaultarguments(); $this->checkArguments($argarray); @@ -545,11 +558,11 @@ extends WikiPlugin_GraphViz // write to uploads and produce static url $file_dir = getUploadFilePath(); $upload_dir = getUploadDataPath(); - $tmpfile = tempnam($file_dir,"VisualWiki").".".$argarray['imgtype']; + $tmpfile = tempnam($file_dir, "VisualWiki") . "." . $argarray['imgtype']; WikiPluginCached::writeImage($argarray['imgtype'], $imagehandle, $tmpfile); ImageDestroy($imagehandle); - return WikiPluginCached::embedMap(1,$upload_dir.basename($tmpfile),$content['html'], - $dbi,$argarray,$request); + return WikiPluginCached::embedMap(1, $upload_dir . basename($tmpfile), $content['html'], + $dbi, $argarray, $request); } /** @@ -557,21 +570,22 @@ extends WikiPlugin_GraphViz * and stores them in an array which may be accessed with * getColor. */ - function createColors() { + function createColors() + { $predefcolors = array( - array('red' => 255, 'green' => 0, 'blue' => 0), - array('red' => 255, 'green' => 255, 'blue' => 0), - array('red' => 0, 'green' => 255, 'blue' => 0), - array('red' => 0, 'green' => 255, 'blue' => 255), - array('red' => 0, 'green' => 0, 'blue' => 255), - array('red' => 100, 'green' => 100, 'blue' => 100) - ); + array('red' => 255, 'green' => 0, 'blue' => 0), + array('red' => 255, 'green' => 255, 'blue' => 0), + array('red' => 0, 'green' => 255, 'blue' => 0), + array('red' => 0, 'green' => 255, 'blue' => 255), + array('red' => 0, 'green' => 0, 'blue' => 255), + array('red' => 100, 'green' => 100, 'blue' => 100) + ); $steps = 2; $numberofcolors = count($predefcolors) * $steps; $promille = -1; - foreach($predefcolors as $color) { + foreach ($predefcolors as $color) { if ($promille < 0) { $oldcolor = $color; $promille = 0; @@ -579,9 +593,9 @@ extends WikiPlugin_GraphViz } for ($i = 0; $i < $steps; $i++) $this->ColorTab[++$promille / $numberofcolors * 1000] = array( - floor(interpolate( $oldcolor['red'], $color['red'], $i/$steps )), - floor(interpolate( $oldcolor['green'], $color['green'], $i/$steps )), - floor(interpolate( $oldcolor['blue'], $color['blue'], $i/$steps )) + floor(interpolate($oldcolor['red'], $color['red'], $i / $steps)), + floor(interpolate($oldcolor['green'], $color['green'], $i / $steps)), + floor(interpolate($oldcolor['blue'], $color['blue'], $i / $steps)) ); $oldcolor = $color; } @@ -595,9 +609,10 @@ extends WikiPlugin_GraphViz * @param promille float value between 0.0 and 1.0 * @return array(red,green,blue) */ - function getColor($promille) { - foreach( $this->ColorTab as $pro => $col ) { - if ($promille*1000 < $pro) + function getColor($promille) + { + foreach ($this->ColorTab as $pro => $col) { + if ($promille * 1000 < $pro) return $col; } $lastcol = end($this->ColorTab); @@ -610,7 +625,8 @@ extends WikiPlugin_GraphViz * at a value pos. * @return float interpolated value */ -function interpolate($a, $b, $pos) { +function interpolate($a, $b, $pos) +{ return $a + ($b - $a) * $pos; } diff --git a/lib/plugin/WantedPages.php b/lib/plugin/WantedPages.php index 2f455fa4c..6521af330 100644 --- a/lib/plugin/WantedPages.php +++ b/lib/plugin/WantedPages.php @@ -33,30 +33,36 @@ include_once 'lib/PageList.php'; class WikiPlugin_WantedPages -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("WantedPages"); } - function getDescription () { + + function getDescription() + { return _("Lists referenced page names which do not exist yet."); } - function getDefaultArguments() { + + function getDefaultArguments() + { return array_merge - ( - PageList::supportedArgs(), - array('page' => '[pagename]', // just for a single page. - 'withlinks' => 0, - 'noheader' => false, - 'exclude_from' => _("PgsrcTranslation").','._("InterWikiMap"), - 'limit' => '100', - 'paging' => 'auto')); + ( + PageList::supportedArgs(), + array('page' => '[pagename]', // just for a single page. + 'withlinks' => 0, + 'noheader' => false, + 'exclude_from' => _("PgsrcTranslation") . ',' . _("InterWikiMap"), + 'limit' => '100', + 'paging' => 'auto')); } // info arg allows multiple columns // info=mtime,hits,summary,version,author,locked,minor,markup or all // exclude arg allows multiple pagenames exclude=HomePage,RecentChanges - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); if (!empty($args['exclude_from'])) $args['exclude_from'] = is_string($args['exclude_from']) @@ -90,15 +96,15 @@ extends WikiPlugin list($offset, $maxcount) = $pagelist->limit($limit); $wanted_iter = $dbi->wantedPages($exclude_from, $exclude, $sortby, $limit); while ($row = $wanted_iter->next()) { - $wantedfrom = $row['pagename']; - $wanted = $row['wantedfrom']; - // ignore duplicates: - if (empty($pagelist->_wpagelist[$wanted])) - $pagelist->addPage($wanted); - if (!isset($pagelist->_wpagelist[$wanted])) - $pagelist->_wpagelist[$wanted][] = $wantedfrom; - elseif (!in_array($wantedfrom, $pagelist->_wpagelist[$wanted])) - $pagelist->_wpagelist[$wanted][] = $wantedfrom; + $wantedfrom = $row['pagename']; + $wanted = $row['wantedfrom']; + // ignore duplicates: + if (empty($pagelist->_wpagelist[$wanted])) + $pagelist->addPage($wanted); + if (!isset($pagelist->_wpagelist[$wanted])) + $pagelist->_wpagelist[$wanted][] = $wantedfrom; + elseif (!in_array($wantedfrom, $pagelist->_wpagelist[$wanted])) + $pagelist->_wpagelist[$wanted][] = $wantedfrom; } $wanted_iter->free(); unset($wanted_iter); @@ -110,7 +116,7 @@ extends WikiPlugin $links = $page_handle->getPageLinks(true); // include_empty while ($link_handle = $links->next()) { $linkname = $link_handle->getName(); - if (! $dbi->isWikiPage($linkname)) { + if (!$dbi->isWikiPage($linkname)) { $pagelist->addPage($linkname); //if (!array_key_exists($linkname, $this->_wpagelist)) $pagelist->_wpagelist[$linkname][] = 1; @@ -130,20 +136,27 @@ extends WikiPlugin } // reference obviously doesn't work, so force an update to add _wpagelist to parentobj if (isset($pagelist->_columns[1]) - and in_array($pagelist->_columns[1]->_field, array('wanted','links'))) + and in_array($pagelist->_columns[1]->_field, array('wanted', 'links')) + ) $pagelist->_columns[1]->parentobj =& $pagelist; return $pagelist; } -}; +} + +; // which links to the missing page -class _PageList_Column_WantedPages_wanted extends _PageList_Column { - function _PageList_Column_WantedPages_wanted (&$params) { +class _PageList_Column_WantedPages_wanted extends _PageList_Column +{ + function _PageList_Column_WantedPages_wanted(&$params) + { $this->parentobj =& $params[3]; - $this->_PageList_Column($params[0],$params[1],$params[2]); + $this->_PageList_Column($params[0], $params[1], $params[2]); } - function _getValue(&$page, $revision_handle) { - $html = false; + + function _getValue(&$page, $revision_handle) + { + $html = false; $pagename = $page->getName(); foreach ($this->parentobj->_wpagelist[$pagename] as $page) { if ($html) @@ -158,17 +171,21 @@ class _PageList_Column_WantedPages_wanted extends _PageList_Column { /* * List of Links and link to ListLinks */ -class _PageList_Column_WantedPages_links extends _PageList_Column { - function _PageList_Column_WantedPages_links (&$params) { +class _PageList_Column_WantedPages_links extends _PageList_Column +{ + function _PageList_Column_WantedPages_links(&$params) + { $this->parentobj =& $params[3]; - $this->_PageList_Column($params[0],$params[1],$params[2]); + $this->_PageList_Column($params[0], $params[1], $params[2]); } - function _getValue(&$page, $revision_handle) { - $html = false; + + function _getValue(&$page, $revision_handle) + { + $html = false; $pagename = $page->getName(); $count = count($this->parentobj->_wpagelist[$pagename]); return LinkURL(WikiURL($page, array('action' => 'BackLinks'), false), - fmt("(%d Links)", $count)); + fmt("(%d Links)", $count)); } } diff --git a/lib/plugin/WantedPagesOld.php b/lib/plugin/WantedPagesOld.php index b44da6222..ee6843cff 100644 --- a/lib/plugin/WantedPagesOld.php +++ b/lib/plugin/WantedPagesOld.php @@ -24,30 +24,34 @@ **/ class WikiPlugin_WantedPagesOld -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("WantedPages"); } - function getDescription () { + function getDescription() + { return _("Lists referenced page names which do not exist yet."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array('noheader' => false, - 'exclude' => _("PgsrcTranslation"), - 'page' => '[pagename]', - 'sortby' => false, - 'limit' => 50, - 'paging' => 'auto'); + 'exclude' => _("PgsrcTranslation"), + 'page' => '[pagename]', + 'sortby' => false, + 'limit' => 50, + 'paging' => 'auto'); } // info arg allows multiple columns // info=mtime,hits,summary,version,author,locked,minor,markup or all // exclude arg allows multiple pagenames exclude=HomePage,RecentChanges - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { extract($this->getArgs($argstr, $request)); if ($exclude) { @@ -67,18 +71,18 @@ extends WikiPlugin // done. if (!$page) { $include_empty = false; - $allpages_iter = $dbi->getAllPages($include_empty,$sortby,$limit); + $allpages_iter = $dbi->getAllPages($include_empty, $sortby, $limit); while ($page_handle = $allpages_iter->next()) { $name = $page_handle->getName(); if ($name == _("InterWikiMap")) continue; - if (! in_array($name, $exclude)) + if (!in_array($name, $exclude)) $this->_iterateLinks($page_handle, $dbi); } } elseif ($page && $pageisWikiPage = $dbi->isWikiPage($page)) { //only get WantedPages links for one page $page_handle = $dbi->getPage($page); $this->_iterateLinks($page_handle, $dbi); - if (! $request->getArg('count')) { + if (!$request->getArg('count')) { $args['count'] = count($this->pagelist); } else { $args['count'] = $request->getArg('count'); @@ -105,7 +109,7 @@ extends WikiPlugin $pagelink = WikiLink($page, 'unknown'); $c = count($this->pagelist); $caption = fmt("Wanted Pages for %s (%d total):", - $pagelink, $c); + $pagelink, $c); } return $this->_generateList($caption); @@ -115,31 +119,31 @@ extends WikiPlugin // FullTextSearch for the citations of the WantedPage // link. foreach ($this->pagelist as $key => $val) { - $key = (string) $key; // TODO: Not sure why, but this - // string cast type-coersion - // does seem necessary here. + $key = (string)$key; // TODO: Not sure why, but this + // string cast type-coersion + // does seem necessary here. // Enclose any FullTextSearch keys containing a space // with quotes in oder to request a defnitive search. $searchkey = (strstr($key, ' ') === false) ? $key : "\"$key\""; $row = HTML::tr(HTML::td(array('align' => 'right'), - Button(array('s' => $searchkey), - $val, _("FullTextSearch")), - // Alternatively, get BackLinks - // instead. - // - //Button(array('action' - // => _("BackLinks")), - // $val, $searchkey), - HTML::td(HTML($spacer, - WikiLink($key, - 'unknown'))) - )); + Button(array('s' => $searchkey), + $val, _("FullTextSearch")), + // Alternatively, get BackLinks + // instead. + // + //Button(array('action' + // => _("BackLinks")), + // $val, $searchkey), + HTML::td(HTML($spacer, + WikiLink($key, + 'unknown'))) + )); $this->_rows->pushContent($row); } $c = count($this->pagelist); if (!$noheader) $caption = sprintf(_("Wanted Pages in this wiki (%d total):"), - $c); + $c); $this->_columns = array(_("Count"), _("Page Name")); if ($c > 0) return $this->_generateTable($caption); @@ -148,30 +152,31 @@ extends WikiPlugin } } - function _generateTable($caption) { + function _generateTable($caption) + { if (count($this->pagelist) > 0) { $table = HTML::table(array('cellpadding' => 0, - 'cellspacing' => 1, - 'border' => 0, - 'class' => 'pagelist')); + 'cellspacing' => 1, + 'border' => 0, + 'class' => 'pagelist')); if ($caption) - $table->pushContent(HTML::caption(array('align'=>'top'), - $caption)); + $table->pushContent(HTML::caption(array('align' => 'top'), + $caption)); $row = HTML::tr(); $spacer = new RawXml("    "); foreach ($this->_columns as $col_heading) { $row->pushContent(HTML::td(HTML($spacer, - HTML::u($col_heading)))); + HTML::u($col_heading)))); $table_summary[] = $col_heading; } // Table summary for non-visual browsers. $table->setAttr('summary', sprintf(_("Columns: %s."), - implode(", ", $table_summary))); + implode(", ", $table_summary))); $table->pushContent(HTML::thead($row), - HTML::tbody(false, $this->_rows)); + HTML::tbody(false, $this->_rows)); } else { $table = HTML(); if ($caption) @@ -182,7 +187,8 @@ extends WikiPlugin return $table; } - function _generateList($caption) { + function _generateList($caption) + { $list = HTML(); $c = count($this->pagelist); if ($caption) @@ -196,18 +202,20 @@ extends WikiPlugin return $list; } - function _iterateLinks($page_handle, $dbi) { + function _iterateLinks($page_handle, $dbi) + { $links_iter = $page_handle->getLinks($reversed = false); - while ($link_handle = $links_iter->next()) - { - if (! $dbi->isWikiPage($linkname = $link_handle->getName())) - if (! in_array($linkname, array_keys($this->pagelist))) + while ($link_handle = $links_iter->next()) { + if (!$dbi->isWikiPage($linkname = $link_handle->getName())) + if (!in_array($linkname, array_keys($this->pagelist))) $this->pagelist[$linkname] = 1; else $this->pagelist[$linkname] += 1; } } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/WatchPage.php b/lib/plugin/WatchPage.php index 7de6d59ee..a758b5265 100644 --- a/lib/plugin/WatchPage.php +++ b/lib/plugin/WatchPage.php @@ -30,34 +30,40 @@ * within the user's home page or in a database. */ class WikiPlugin_WatchPage -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("WatchPage"); } - function getDescription () { + function getDescription() + { return _("Manage notifications emails per page."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array('page' => '[pagename]', - 'mode' => 'add', - ); + 'mode' => 'add', + ); } - function contains($pagelist, $page) { + function contains($pagelist, $page) + { if (!isset($this->_explodePageList)) $this->_explodePageList = explodePageList($pagelist); return in_array($page, $this->_explodePageList); } // This could be expanded as in Mediawiki to a list of each page with a remove button. - function showWatchList($pagelist) { + function showWatchList($pagelist) + { return HTML::strong(HTML::tt(empty($pagelist) ? _("") : $pagelist)); } - function addpagelist($page, $pagelist) { + function addpagelist($page, $pagelist) + { if (!empty($pagelist)) { if ($this->contains($pagelist, $page)) return "$pagelist"; @@ -67,36 +73,38 @@ extends WikiPlugin return "$page"; } - function showNotify(&$request, $messages, $page, $pagelist, $verified) { - $isNecessary = ! $this->contains($pagelist, $page); + function showNotify(&$request, $messages, $page, $pagelist, $verified) + { + $isNecessary = !$this->contains($pagelist, $page); $form = HTML::form(array('action' => $request->getPostURL(), - 'method' => 'post'), - HiddenInputs(array('verify' => 1)), - HiddenInputs($request->getArgs(),false,array('verify')), - $messages, - HTML::p(_("Your current watchlist: "), $this->showWatchList($pagelist))); + 'method' => 'post'), + HiddenInputs(array('verify' => 1)), + HiddenInputs($request->getArgs(), false, array('verify')), + $messages, + HTML::p(_("Your current watchlist: "), $this->showWatchList($pagelist))); if ($isNecessary) { $form->pushContent(HTML::p(_("New watchlist: "), - $this->showWatchList($this->addpagelist($page, $pagelist))), - HTML::p(sprintf(_("Do you %s want to add this page \"%s\" to your WatchList?"), - ($verified ? _("really") : ""), $page)), - HTML::p(Button('submit:add', _("Yes")), - HTML::Raw(' '), - Button('submit:cancel', _("Cancel")))); + $this->showWatchList($this->addpagelist($page, $pagelist))), + HTML::p(sprintf(_("Do you %s want to add this page \"%s\" to your WatchList?"), + ($verified ? _("really") : ""), $page)), + HTML::p(Button('submit:add', _("Yes")), + HTML::Raw(' '), + Button('submit:cancel', _("Cancel")))); } else { $form->pushContent(HTML::p(fmt("The page %s is already watched!", $page)), - HTML::p(Button('submit:edit', _("Edit")), - HTML::Raw(' '), - Button('submit:cancel', _("Cancel")))); + HTML::p(Button('submit:edit', _("Edit")), + HTML::Raw(' '), + Button('submit:cancel', _("Cancel")))); } $fieldset = HTML::fieldset(HTML::legend(_("Watch Page")), $form); return $fieldset; } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); - if (isa($request,'MockRequest')) + if (isa($request, 'MockRequest')) return ''; $user =& $request->_user; $userid = $user->UserName(); @@ -106,7 +114,7 @@ extends WikiPlugin if (defined('FUSIONFORGE') and FUSIONFORGE) { // No login banner for FusionForge return HTML::div(array('class' => 'error'), - HTML::p(_("You must sign in to watch pages."))); + HTML::p(_("You must sign in to watch pages."))); } return $request->_notAuthorized(WIKIAUTH_BOGO); } else { @@ -116,22 +124,22 @@ extends WikiPlugin $email = $pref->get("email"); if (empty($email)) { return HTML::p( - array('class' => 'error'), - _("ERROR: No email defined! You need to do this in your "), - WikiLink(_("UserPreferences"))); + array('class' => 'error'), + _("ERROR: No email defined! You need to do this in your "), + WikiLink(_("UserPreferences"))); } $emailVerified = $pref->get("emailVerified"); if (empty($emailVerified)) { $messages = HTML::div(array('class' => 'mw-warning'), - HTML::p("WARNING! Your email address was not verifed yet!"), - HTML::p("EmailNotifications currently disabled. ")); + HTML::p("WARNING! Your email address was not verifed yet!"), + HTML::p("EmailNotifications currently disabled. ")); } } $pagelist = $pref->get("notifyPages"); - if (! $request->isPost() ) { + if (!$request->isPost()) { return $this->showNotify($request, $messages, $page, $pagelist, false); } else { // POST - $errmsg = ''; + $errmsg = ''; if ($request->getArg('cancel')) { $request->redirect(WikiURL($request->getArg('pagename'), array('warningmsg' => _('WatchPage cancelled')), @@ -141,21 +149,20 @@ extends WikiPlugin } if ($request->getArg('edit')) { $request->redirect(WikiURL(_("UserPreferences"), - false, 'absolute_url')); // noreturn + false, 'absolute_url')); // noreturn return; } $add = $request->getArg('add'); if ($add and !$request->getArg('verify')) { return $this->showNotify($request, $messages, $page, $pagelist, true); - } - elseif ($add and $request->getArg('verify')) { // this is not executed so far. + } elseif ($add and $request->getArg('verify')) { // this is not executed so far. // add page to watchlist, verified $rp = clone($user->getPreferences()); $rp->set('notifyPages', $this->addpagelist($page, $pagelist)); $user->setPreferences($rp); $request->_setUser($user); - $request->setArg("verify",false); - $request->setArg("add",false); + $request->setArg("verify", false); + $request->setArg("add", false); $errmsg .= _("E-Mail Notification for the current page successfully stored in your preferences."); $args['errmsg'] = HTML::div(array('class' => 'feedback'), HTML::p($errmsg)); return Template('userprefs', $args); @@ -163,7 +170,9 @@ extends WikiPlugin } } } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/WhoIsOnline.php b/lib/plugin/WhoIsOnline.php index 8c316e287..64eae3dd1 100644 --- a/lib/plugin/WhoIsOnline.php +++ b/lib/plugin/WhoIsOnline.php @@ -32,33 +32,37 @@ */ class WikiPlugin_WhoIsOnline -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("WhoIsOnline"); } - function getDescription () { + function getDescription() + { return _("Show summary information of the current user sessions."); } - function getDefaultArguments() { + function getDefaultArguments() + { // two modes: summary and detail, page links to the page with the other mode return array( - 'mode' => 'summary', // or "detail" - 'pagename' => '[pagename]', // refer to the page with the other mode - 'allow_detail' => false, // if false, page is ignored - 'dispose_admin' => false, - ); + 'mode' => 'summary', // or "detail" + 'pagename' => '[pagename]', // refer to the page with the other mode + 'allow_detail' => false, // if false, page is ignored + 'dispose_admin' => false, + ); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { global $WikiTheme; - $request->setArg('nocache',1); + $request->setArg('nocache', 1); $args = $this->getArgs($argstr, $request); // use the "online.tmpl" template // todo: check which arguments are really needed in the template. - $stats = $this->getStats($dbi,$request,$args['mode']); + $stats = $this->getStats($dbi, $request, $args['mode']); if ($src = $WikiTheme->getImageURL("whosonline")) $img = HTML::img(array('src' => $src, 'alt' => $this->getName())); else $img = ''; @@ -69,34 +73,42 @@ extends WikiPlugin // box is used to display a fixed-width, narrow version with common header // just the number of online users. - function box($args=false, $request=false, $basepage=false) { + function box($args = false, $request = false, $basepage = false) + { if (!$request) $request =& $GLOBALS['request']; - $stats = $this->getStats($request->_dbi,$request,'summary'); + $stats = $this->getStats($request->_dbi, $request, 'summary'); return $this->makeBox(_("Who is Online"), - HTML(HTML::Raw('· '), - WikiLink(_("WhoIsOnline"),'auto', - fmt("%d online users", $stats['NUM_USERS'])))); + HTML(HTML::Raw('· '), + WikiLink(_("WhoIsOnline"), 'auto', + fmt("%d online users", $stats['NUM_USERS'])))); } - function getSessions($dbi, &$request) { + function getSessions($dbi, &$request) + { // check the current user sessions and what they are doing ; } // check the current sessions - function getStats($dbi, &$request, $mode='summary') { - $num_pages = 0; $num_users = 0; + function getStats($dbi, &$request, $mode = 'summary') + { + $num_pages = 0; + $num_users = 0; $page_iter = $dbi->getAllPages(); while ($page = $page_iter->next()) { if ($page->isUserPage()) $num_users++; $num_pages++; } //get session data from database - $num_online = 0; $num_guests = 0; $num_registered = 0; - $registered = array(); $guests = array(); - $admins = array(); $uniquenames = array(); + $num_online = 0; + $num_guests = 0; + $num_registered = 0; + $registered = array(); + $guests = array(); + $admins = array(); + $uniquenames = array(); $sess_time = ini_get('session.gc_maxlifetime'); // in seconds - if (!$sess_time) $sess_time = 24*60; + if (!$sess_time) $sess_time = 24 * 60; if (isset($request->_dbsession)) { // only ADODB and SQL backends $dbsession =& $request->_dbsession; if (method_exists($dbsession->_backend, "gc")) @@ -109,7 +121,7 @@ extends WikiPlugin $date = $row['date']; //Todo: Security issue: Expose REMOTE_ADDR? // Probably only to WikiAdmin - $ip = $row['ip']; + $ip = $row['ip']; if (empty($date)) continue; $num_online++; $user = @unserialize($data); @@ -119,44 +131,44 @@ extends WikiPlugin $level = @$user->_level; if ($mode == 'summary' and in_array($userid, $uniquenames)) continue; $uniquenames[] = $userid; - $page = _(""); // where is he? + $page = _(""); // where is he? $action = 'browse'; $objvars = array_keys(get_object_vars($user)); - if (in_array('action',$objvars)) + if (in_array('action', $objvars)) $action = @$user->action; - if (in_array('page',$objvars)) + if (in_array('page', $objvars)) $page = @$user->page; if ($level and $userid) { // registered or guest or what? //FIXME: htmlentitities name may not be called here. but where then? $num_registered++; - $registered[] = array('name' => $userid, - 'date' => $date, - 'action'=> $action, - 'page' => $page, - 'level' => $level, - 'ip' => $ip, - 'x' => 'x'); + $registered[] = array('name' => $userid, + 'date' => $date, + 'action' => $action, + 'page' => $page, + 'level' => $level, + 'ip' => $ip, + 'x' => 'x'); if ($user->_level == WIKIAUTH_ADMIN) - $admins[] = $registered[count($registered)-1]; + $admins[] = $registered[count($registered) - 1]; } else { $num_guests++; - $guests[] = array('name' => $guestname, - 'date' => $date, - 'action'=> $action, - 'page' => $page, - 'level' => $level, - 'ip' => $ip, - 'x' => 'x'); + $guests[] = array('name' => $guestname, + 'date' => $date, + 'action' => $action, + 'page' => $page, + 'level' => $level, + 'ip' => $ip, + 'x' => 'x'); } } else { $num_guests++; - $guests[] = array('name' => $guestname, - 'date' => $date, - 'action'=> '', - 'page' => '', - 'level' => 0, - 'ip' => $ip, - 'x' => 'x'); + $guests[] = array('name' => $guestname, + 'date' => $date, + 'action' => '', + 'page' => '', + 'level' => 0, + 'ip' => $ip, + 'x' => 'x'); } } } @@ -164,34 +176,37 @@ extends WikiPlugin //TODO: get and sets max stats in global_data //$page = $dbi->getPage($request->getArg('pagename')); - $stats = array(); $stats['max_online_num'] = 0; + $stats = array(); + $stats['max_online_num'] = 0; if ($stats = $dbi->get('stats')) { if ($num_users > $stats['max_online_num']) { $stats['max_online_num'] = $num_users; $stats['max_online_time'] = time(); - $dbi->set('stats',$stats); + $dbi->set('stats', $stats); } } else { $stats['max_online_num'] = $num_users; $stats['max_online_time'] = time(); - $dbi->set('stats',$stats); + $dbi->set('stats', $stats); } - return array('SESSDATA_BOOL' => !empty($dbsession), - 'NUM_PAGES' => $num_pages, - 'NUM_USERS' => $num_users, - 'NUM_ONLINE' => $num_online, - 'NUM_REGISTERED' => $num_registered, - 'NUM_GUESTS' => $num_guests, - 'NEWEST_USER' => '', // todo - 'MAX_ONLINE_NUM' => $stats['max_online_num'], - 'MAX_ONLINE_TIME' => $stats['max_online_time'], - 'REGISTERED' => $registered, - 'ADMINS' => $admins, - 'GUESTS' => $guests, - 'SESSION_TIME' => sprintf(_("%d minutes"),$sess_time / 60), - ); + return array('SESSDATA_BOOL' => !empty($dbsession), + 'NUM_PAGES' => $num_pages, + 'NUM_USERS' => $num_users, + 'NUM_ONLINE' => $num_online, + 'NUM_REGISTERED' => $num_registered, + 'NUM_GUESTS' => $num_guests, + 'NEWEST_USER' => '', // todo + 'MAX_ONLINE_NUM' => $stats['max_online_num'], + 'MAX_ONLINE_TIME' => $stats['max_online_time'], + 'REGISTERED' => $registered, + 'ADMINS' => $admins, + 'GUESTS' => $guests, + 'SESSION_TIME' => sprintf(_("%d minutes"), $sess_time / 60), + ); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/WikiAdminChmod.php b/lib/plugin/WikiAdminChmod.php index ce8665052..db87b8e3a 100644 --- a/lib/plugin/WikiAdminChmod.php +++ b/lib/plugin/WikiAdminChmod.php @@ -33,43 +33,48 @@ require_once 'lib/PageList.php'; require_once 'lib/plugin/WikiAdminSelect.php'; class WikiPlugin_WikiAdminChmod -extends WikiPlugin_WikiAdminSelect + extends WikiPlugin_WikiAdminSelect { - function getName() { + function getName() + { return _("WikiAdminChmod"); } - function getDescription() { + function getDescription() + { return _("Set individual page permissions."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array_merge - ( - PageList::supportedArgs(), - array( - 's' => false, - 'perm' => false, - /* Columns to include in listing */ - 'info' => 'pagename,perm,mtime,author', - )); + ( + PageList::supportedArgs(), + array( + 's' => false, + 'perm' => false, + /* Columns to include in listing */ + 'info' => 'pagename,perm,mtime,author', + )); } // todo: change permstring to some kind of default ACL hash. // See PagePermission class - function chmodHelper($permstring) { + function chmodHelper($permstring) + { $perm = array(); return $perm; } - function chmodPages(&$dbi, &$request, $pages, $permstring) { + function chmodPages(&$dbi, &$request, $pages, $permstring) + { $ul = HTML::ul(); $count = 0; $acl = chmodHelper($permstring); if ($perm = new PagePermission($acl)) { foreach ($pages as $name) { - if ( $perm->store($dbi->getPage($name)) ) { - $ul->pushContent(HTML::li(fmt("chmod page '%s' to '%s'.",$name, $permstring))); + if ($perm->store($dbi->getPage($name))) { + $ul->pushContent(HTML::li(fmt("chmod page '%s' to '%s'.", $name, $permstring))); $count++; } else { $ul->pushContent(HTML::li(fmt("Couldn't chmod page '%s' to '%s'.", $name, $permstring))); @@ -81,14 +86,15 @@ extends WikiPlugin_WikiAdminSelect if ($count) { $dbi->touch(); return HTML($ul, - HTML::p(fmt("%d pages have been changed.", $count))); + HTML::p(fmt("%d pages have been changed.", $count))); } else { return HTML($ul, - HTML::p(_("No pages changed."))); + HTML::p(_("No pages changed."))); } } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { if (!DEBUG) { return $this->disabled("WikiAdminChmod not yet enabled. Set DEBUG to try it."); } @@ -105,7 +111,8 @@ extends WikiPlugin_WikiAdminSelect if ($p && !$request->isPost()) $pages = $p; if ($p && $request->isPost() && - !empty($post_args['chmod']) && empty($post_args['cancel'])) { + !empty($post_args['chmod']) && empty($post_args['cancel']) + ) { // without individual PagePermissions: if (!ENABLE_PAGEPERM and !$request->_user->isAdmin()) { $request->_notAuthorized(WIKIAUTH_ADMIN); @@ -115,7 +122,7 @@ extends WikiPlugin_WikiAdminSelect if ($post_args['action'] == 'verify') { // Real action return $this->chmodPages($dbi, $request, array_keys($p), - $post_args['perm']); + $post_args['perm']); } if ($post_args['action'] == 'select') { if (!empty($post_args['perm'])) @@ -141,50 +148,50 @@ extends WikiPlugin_WikiAdminSelect $button_label = _("Yes"); $header = $this->chmodForm($header, $post_args); $header->pushContent( - HTML::p(HTML::strong( - _("Are you sure you want to permanently change the selected files?")))); - } - else { + HTML::p(HTML::strong( + _("Are you sure you want to permanently change the selected files?")))); + } else { $button_label = _("Chmod"); $header = $this->chmodForm($header, $post_args); $header->pushContent(HTML::p(_("Select the pages to change:"))); } $buttons = HTML::p(Button('submit:admin_chmod[chmod]', $button_label, 'wikiadmin'), - Button('submit:admin_chmod[cancel]', _("Cancel"), 'button')); + Button('submit:admin_chmod[cancel]', _("Cancel"), 'button')); return HTML::form(array('action' => $request->getPostURL(), - 'method' => 'post'), - $header, - $buttons, - $pagelist->getContent(), - HiddenInputs($request->getArgs(), - false, - array('admin_chmod')), - HiddenInputs(array('admin_chmod[action]' => $next_action)), - ENABLE_PAGEPERM - ? '' - : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN))); + 'method' => 'post'), + $header, + $buttons, + $pagelist->getContent(), + HiddenInputs($request->getArgs(), + false, + array('admin_chmod')), + HiddenInputs(array('admin_chmod[action]' => $next_action)), + ENABLE_PAGEPERM + ? '' + : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN))); } - function chmodForm(&$header, $post_args) { + function chmodForm(&$header, $post_args) + { $header->pushContent( HTML::p(HTML::em( - _("This plugin is currently under development and does not work!")))); + _("This plugin is currently under development and does not work!")))); $header->pushContent(_("Chmod to permission:")); $header->pushContent(HTML::input(array('name' => 'admin_chmod[perm]', - 'value' => $post_args['perm']))); - $header->pushContent(' '._("(ugo : rwx)")); + 'value' => $post_args['perm']))); + $header->pushContent(' ' . _("(ugo : rwx)")); $header->pushContent(HTML::p()); $checkbox = HTML::input(array('type' => 'checkbox', - 'name' => 'admin_chmod[updatechildren]', - 'value' => 1)); - if (!empty($post_args['updatechildren'])) $checkbox->setAttr('checked','checked'); + 'name' => 'admin_chmod[updatechildren]', + 'value' => 1)); + if (!empty($post_args['updatechildren'])) $checkbox->setAttr('checked', 'checked'); $header->pushContent($checkbox, HTML::raw(" "), - _("Propagate new permissions to all subpages?"), - HTML::raw("  "), - HTML::em(_("(disable individual page permissions, enable inheritance)?"))); - $header->pushContent(HTML::hr(),HTML::p()); + _("Propagate new permissions to all subpages?"), + HTML::raw("  "), + HTML::em(_("(disable individual page permissions, enable inheritance)?"))); + $header->pushContent(HTML::hr(), HTML::p()); return $header; } } diff --git a/lib/plugin/WikiAdminChown.php b/lib/plugin/WikiAdminChown.php index 26e78b01f..cf54ea0e4 100644 --- a/lib/plugin/WikiAdminChown.php +++ b/lib/plugin/WikiAdminChown.php @@ -30,56 +30,61 @@ require_once 'lib/PageList.php'; require_once 'lib/plugin/WikiAdminSelect.php'; class WikiPlugin_WikiAdminChown -extends WikiPlugin_WikiAdminSelect + extends WikiPlugin_WikiAdminSelect { - function getName() { + function getName() + { return _("WikiAdminChown"); } - function getDescription() { + function getDescription() + { return _("Change owner of selected pages."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array_merge - ( - WikiPlugin_WikiAdminSelect::getDefaultArguments(), - array( - 'user' => false, - /* Columns to include in listing */ - 'info' => 'pagename,owner,mtime', - )); + ( + WikiPlugin_WikiAdminSelect::getDefaultArguments(), + array( + 'user' => false, + /* Columns to include in listing */ + 'info' => 'pagename,owner,mtime', + )); } - function chownPages(&$dbi, &$request, $pages, $newowner) { + function chownPages(&$dbi, &$request, $pages, $newowner) + { $result = HTML::div(); $ul = HTML::ul(); $count = 0; foreach ($pages as $name) { $page = $dbi->getPage($name); $current = $page->getCurrentRevision(); - if ( ($owner = $page->getOwner()) and - $newowner != $owner ) { + if (($owner = $page->getOwner()) and + $newowner != $owner + ) { if (!mayAccessPage('change', $name)) { $ul->pushContent(HTML::li(fmt("Access denied to change page '%s'.", - WikiLink($name)))); + WikiLink($name)))); } else { $version = $current->getVersion(); $meta = $current->_data; $text = $current->getPackedContent(); - $meta['summary'] = "Change page owner from '".$owner."' to '".$newowner."'"; + $meta['summary'] = "Change page owner from '" . $owner . "' to '" . $newowner . "'"; $meta['is_minor_edit'] = 1; - $meta['author'] = $request->_user->UserName(); + $meta['author'] = $request->_user->UserName(); unset($meta['mtime']); // force new date $page->set('owner', $newowner); $page->save($text, $version + 1, $meta); if ($page->get('owner') === $newowner) { $ul->pushContent(HTML::li(fmt("Change owner of page '%s' to '%s'.", - WikiLink($name), WikiLink($newowner)))); + WikiLink($name), WikiLink($newowner)))); $count++; } else { $ul->pushContent(HTML::li(fmt("Could not change owner of page '%s' to '%s'.", - WikiLink($name), $newowner))); + WikiLink($name), $newowner))); } } } @@ -101,7 +106,8 @@ extends WikiPlugin_WikiAdminSelect } } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { if ($request->getArg('action') != 'browse') { if (!$request->getArg('action') == _("PhpWikiAdministration/Chown")) { return $this->disabled(_("Plugin not run: not in browse mode")); @@ -128,7 +134,8 @@ extends WikiPlugin_WikiAdminSelect if ($p && !$request->isPost()) $pages = $p; if ($p && $request->isPost() && - !empty($post_args['chown']) && empty($post_args['cancel'])) { + !empty($post_args['chown']) && empty($post_args['cancel']) + ) { // without individual PagePermissions: if (!ENABLE_PAGEPERM and !$request->_user->isAdmin()) { $request->_notAuthorized(WIKIAUTH_ADMIN); @@ -138,7 +145,7 @@ extends WikiPlugin_WikiAdminSelect if ($post_args['action'] == 'verify') { // Real action return $this->chownPages($dbi, $request, array_keys($p), - trim($post_args['user'])); + trim($post_args['user'])); } if ($post_args['action'] == 'select') { if (!empty($post_args['user'])) @@ -151,7 +158,7 @@ extends WikiPlugin_WikiAdminSelect if ($next_action == 'select' and empty($pages)) { // List all pages to select from. $pages = $this->collectPages($pages, $dbi, $args['sortby'], $args['limit'], - $args['exclude']); + $args['exclude']); } /* // let the user decide which info if ($next_action == 'verify') { @@ -170,38 +177,38 @@ extends WikiPlugin_WikiAdminSelect $button_label = _("Yes"); $header->pushContent(HTML::legend(_("Confirm ownership change"))); $header->pushContent( - HTML::p(HTML::strong( - _("Are you sure you want to change the owner of the selected pages?")))); + HTML::p(HTML::strong( + _("Are you sure you want to change the owner of the selected pages?")))); $header = $this->chownForm($header, $post_args); - } - else { + } else { $button_label = _("Change owner of selected pages"); $header->pushContent(HTML::legend(_("Select the pages to change the owner"))); $header = $this->chownForm($header, $post_args); } $buttons = HTML::p(Button('submit:admin_chown[chown]', $button_label, 'wikiadmin'), - Button('submit:admin_chown[cancel]', _("Cancel"), 'button')); + Button('submit:admin_chown[cancel]', _("Cancel"), 'button')); $header->pushContent($buttons); return HTML::form(array('action' => $request->getPostURL(), - 'method' => 'post'), - $header, - $pagelist->getContent(), - HiddenInputs($request->getArgs(), - false, - array('admin_chown')), - HiddenInputs(array('admin_chown[action]' => $next_action)), - ENABLE_PAGEPERM - ? '' - : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN))); + 'method' => 'post'), + $header, + $pagelist->getContent(), + HiddenInputs($request->getArgs(), + false, + array('admin_chown')), + HiddenInputs(array('admin_chown[action]' => $next_action)), + ENABLE_PAGEPERM + ? '' + : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN))); } - function chownForm(&$header, $post_args) { + function chownForm(&$header, $post_args) + { $header->pushContent(_("Change owner to: ")); $header->pushContent(HTML::input(array('name' => 'admin_chown[user]', - 'value' => $post_args['user'], - 'size' => 40))); + 'value' => $post_args['user'], + 'size' => 40))); return $header; } } diff --git a/lib/plugin/WikiAdminMarkup.php b/lib/plugin/WikiAdminMarkup.php index 6dd20be2f..290e5e32b 100644 --- a/lib/plugin/WikiAdminMarkup.php +++ b/lib/plugin/WikiAdminMarkup.php @@ -30,28 +30,32 @@ require_once 'lib/PageList.php'; require_once 'lib/plugin/WikiAdminSelect.php'; class WikiPlugin_WikiAdminMarkup -extends WikiPlugin_WikiAdminSelect + extends WikiPlugin_WikiAdminSelect { - function getName() { + function getName() + { return _("WikiAdminMarkup"); } - function getDescription() { + function getDescription() + { return _("Change the markup type of selected pages."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array_merge - ( - WikiPlugin_WikiAdminSelect::getDefaultArguments(), - array( - 'markup' => 2, - /* Columns to include in listing */ - 'info' => 'pagename,markup,mtime', - )); + ( + WikiPlugin_WikiAdminSelect::getDefaultArguments(), + array( + 'markup' => 2, + /* Columns to include in listing */ + 'info' => 'pagename,markup,mtime', + )); } - function chmarkupPages(&$dbi, &$request, $pages, $newmarkup) { + function chmarkupPages(&$dbi, &$request, $pages, $newmarkup) + { $result = HTML::div(); $ul = HTML::ul(); $count = 0; @@ -59,11 +63,11 @@ extends WikiPlugin_WikiAdminSelect $page = $dbi->getPage($name); $current = $page->getCurrentRevision(); $markup = $current->get('markup'); - if ( !$markup or $newmarkup != $markup ) { + if (!$markup or $newmarkup != $markup) { if (!mayAccessPage('change', $name)) { $result->setAttr('class', 'error'); $result->pushContent(HTML::p(fmt("Access denied to change page '%s'.", - WikiLink($name)))); + WikiLink($name)))); } else { $version = $current->getVersion(); $meta = $current->_data; @@ -72,17 +76,17 @@ extends WikiPlugin_WikiAdminSelect $text = $current->getPackedContent(); $meta['summary'] = sprintf(_("Change markup type from %s to %s"), $markup, $newmarkup); $meta['is_minor_edit'] = 1; - $meta['author'] = $request->_user->UserName(); + $meta['author'] = $request->_user->UserName(); unset($meta['mtime']); // force new date $page->save($text, $version + 1, $meta); $current = $page->getCurrentRevision(); if ($current->get('markup') === $newmarkup) { $ul->pushContent(HTML::li(fmt("change page '%s' to markup type '%s'.", - WikiLink($name), $newmarkup))); + WikiLink($name), $newmarkup))); $count++; } else { $ul->pushContent(HTML::li(fmt("Couldn't change page '%s' to markup type '%s'.", - WikiLink($name), $newmarkup))); + WikiLink($name), $newmarkup))); } } } @@ -104,7 +108,8 @@ extends WikiPlugin_WikiAdminSelect } } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { if ($request->getArg('action') != 'browse') { if (!$request->getArg('action') == _("PhpWikiAdministration/Markup")) { return $this->disabled(_("Plugin not run: not in browse mode")); @@ -125,7 +130,8 @@ extends WikiPlugin_WikiAdminSelect if ($p && !$request->isPost()) $pages = $p; if ($p && $request->isPost() && - !empty($post_args['button']) && empty($post_args['cancel'])) { + !empty($post_args['button']) && empty($post_args['cancel']) + ) { // without individual PagePermissions: if (!ENABLE_PAGEPERM and !$request->_user->isAdmin()) { $request->_notAuthorized(WIKIAUTH_ADMIN); @@ -135,7 +141,7 @@ extends WikiPlugin_WikiAdminSelect if ($post_args['action'] == 'verify') { // Real action return $this->chmarkupPages($dbi, $request, array_keys($p), - $post_args['markup']); + $post_args['markup']); } if ($post_args['action'] == 'select') { if (!empty($post_args['markup'])) @@ -147,7 +153,7 @@ extends WikiPlugin_WikiAdminSelect } if ($next_action == 'select' and empty($pages)) { $pages = $this->collectPages($pages, $dbi, $args['sortby'], $args['limit'], - $args['exclude']); + $args['exclude']); } if ($next_action == 'select') { @@ -162,37 +168,37 @@ extends WikiPlugin_WikiAdminSelect $button_label = _("Yes"); $header->pushContent(HTML::legend(_("Confirm markup change"))); $header->pushContent( - HTML::p(HTML::strong( - _("Are you sure you want to change the markup type of the selected files?")))); + HTML::p(HTML::strong( + _("Are you sure you want to change the markup type of the selected files?")))); $header = $this->chmarkupForm($header, $post_args); - } - else { + } else { $button_label = _("Change markup type"); $header->pushContent(HTML::legend(_("Select the pages to change the markup type"))); $header = $this->chmarkupForm($header, $post_args); } $buttons = HTML::p(Button('submit:admin_markup[button]', $button_label, 'wikiadmin'), - Button('submit:admin_markup[cancel]', _("Cancel"), 'button')); + Button('submit:admin_markup[cancel]', _("Cancel"), 'button')); $header->pushContent($buttons); return HTML::form(array('action' => $request->getPostURL(), - 'method' => 'post'), - $header, - $pagelist->getContent(), - HiddenInputs($request->getArgs(), - false, - array('admin_markup')), - HiddenInputs(array('admin_markup[action]' => $next_action)), - ENABLE_PAGEPERM - ? '' - : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN))); + 'method' => 'post'), + $header, + $pagelist->getContent(), + HiddenInputs($request->getArgs(), + false, + array('admin_markup')), + HiddenInputs(array('admin_markup[action]' => $next_action)), + ENABLE_PAGEPERM + ? '' + : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN))); } - function chmarkupForm(&$header, $post_args) { + function chmarkupForm(&$header, $post_args) + { $header->pushContent(_("Change markup to: ")); $header->pushContent(HTML::input(array('name' => 'admin_markup[markup]', - 'value' => $post_args['markup']))); + 'value' => $post_args['markup']))); return $header; } } diff --git a/lib/plugin/WikiAdminPurge.php b/lib/plugin/WikiAdminPurge.php index ff8f21f33..3e3459d14 100644 --- a/lib/plugin/WikiAdminPurge.php +++ b/lib/plugin/WikiAdminPurge.php @@ -28,26 +28,29 @@ require_once 'lib/PageList.php'; require_once 'lib/plugin/WikiAdminSelect.php'; class WikiPlugin_WikiAdminPurge -extends WikiPlugin_WikiAdminSelect + extends WikiPlugin_WikiAdminSelect { - function getName() { + function getName() + { return _("WikiAdminPurge"); } - function getDescription() { + function getDescription() + { return _("Permanently purge all selected pages."); } /* getDefaultArguments() is inherited from WikiAdminSelect class */ - function collectPages(&$list, &$dbi, $sortby, $limit=0) { + function collectPages(&$list, &$dbi, $sortby, $limit = 0) + { - $allPages = $dbi->getAllPages('include_empty',$sortby,$limit); + $allPages = $dbi->getAllPages('include_empty', $sortby, $limit); while ($pagehandle = $allPages->next()) { $pagename = $pagehandle->getName(); $current = $pagehandle->getCurrentRevision(); if ($current->getVersion() < 1) { - continue; // No versions in database + continue; // No versions in database } if (empty($list[$pagename])) { $list[$pagename] = false; @@ -56,18 +59,20 @@ extends WikiPlugin_WikiAdminSelect return $list; } - function purgePages(&$request, $pages) { + function purgePages(&$request, $pages) + { $result = HTML::div(); $ul = HTML::ul(); - $dbi = $request->getDbh(); $count = 0; + $dbi = $request->getDbh(); + $count = 0; foreach ($pages as $name) { - $name = str_replace(array('%5B','%5D'),array('[',']'),$name); - if (mayAccessPage('purge',$name)) { + $name = str_replace(array('%5B', '%5D'), array('[', ']'), $name); + if (mayAccessPage('purge', $name)) { $dbi->purgePage($name); $ul->pushContent(HTML::li(fmt("Purged page '%s' successfully.", $name))); $count++; } else { - $ul->pushContent(HTML::li(fmt("Didn't purge page '%s'. Access denied.", $name))); + $ul->pushContent(HTML::li(fmt("Didn't purge page '%s'. Access denied.", $name))); } } if ($count) { @@ -87,7 +92,8 @@ extends WikiPlugin_WikiAdminSelect } } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { if ($request->getArg('action') != 'browse') { if ($request->getArg('action') != _("PhpWikiAdministration/Purge")) { return $this->disabled(_("Plugin not run: not in browse mode")); @@ -105,7 +111,8 @@ extends WikiPlugin_WikiAdminSelect $next_action = 'select'; $pages = array(); if ($p && $request->isPost() && - !empty($post_args['purge']) && empty($post_args['cancel'])) { + !empty($post_args['purge']) && empty($post_args['cancel']) + ) { // check individual PagePermissions if (!ENABLE_PAGEPERM and !$request->_user->isAdmin()) { @@ -120,17 +127,17 @@ extends WikiPlugin_WikiAdminSelect if ($post_args['action'] == 'select') { $next_action = 'verify'; foreach ($p as $name => $c) { - $name = str_replace(array('%5B','%5D'),array('[',']'),$name); + $name = str_replace(array('%5B', '%5D'), array('[', ']'), $name); $pages[$name] = $c; } } } elseif ($p && is_array($p) && !$request->isPost()) { // from WikiAdminSelect $next_action = 'verify'; foreach ($p as $name => $c) { - $name = str_replace(array('%5B','%5D'),array('[',']'),$name); + $name = str_replace(array('%5B', '%5D'), array('[', ']'), $name); $pages[$name] = $c; } - $request->setArg('p',false); + $request->setArg('p', false); } if ($next_action == 'select') { // List all pages to select from. @@ -145,26 +152,25 @@ extends WikiPlugin_WikiAdminSelect $header->pushContent(HTML::legend(_("Confirm purge"))); $header->pushContent(HTML::p(HTML::strong( _("Are you sure you want to permanently purge the following files?")))); - } - else { + } else { $button_label = _("Permanently purge selected pages"); $header->pushContent(HTML::legend(_("Select the files to purge"))); } $buttons = HTML::p(Button('submit:admin_purge[purge]', $button_label, 'wikiadmin'), - Button('submit:admin_purge[cancel]', _("Cancel"), 'button')); + Button('submit:admin_purge[cancel]', _("Cancel"), 'button')); $header->pushContent($buttons); // TODO: quick select by regex javascript? return HTML::form(array('action' => $request->getPostURL(), - 'method' => 'post'), - $header, - $pagelist->getContent(), - HiddenInputs($request->getArgs(), - false, - array('admin_purge')), - HiddenInputs(array('admin_purge[action]' => $next_action, - 'require_authority_for_post' => WIKIAUTH_ADMIN))); + 'method' => 'post'), + $header, + $pagelist->getContent(), + HiddenInputs($request->getArgs(), + false, + array('admin_purge')), + HiddenInputs(array('admin_purge[action]' => $next_action, + 'require_authority_for_post' => WIKIAUTH_ADMIN))); } } diff --git a/lib/plugin/WikiAdminRemove.php b/lib/plugin/WikiAdminRemove.php index bb8443055..d82bdc73b 100644 --- a/lib/plugin/WikiAdminRemove.php +++ b/lib/plugin/WikiAdminRemove.php @@ -34,60 +34,63 @@ require_once 'lib/PageList.php'; require_once 'lib/plugin/WikiAdminSelect.php'; class WikiPlugin_WikiAdminRemove -extends WikiPlugin_WikiAdminSelect + extends WikiPlugin_WikiAdminSelect { - function getName() { + function getName() + { return _("WikiAdminRemove"); } - function getDescription() { + function getDescription() + { return _("Permanently remove all selected pages."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array_merge - ( - WikiPlugin_WikiAdminSelect::getDefaultArguments(), - array( - /* - * Show only pages which have been 'deleted' this - * long (in days). (negative or non-numeric - * means show all pages, even non-deleted ones.) - * - * FIXME: could use a better name. - */ - 'min_age' => 0, - - /* - * Automatically check the checkboxes for files - * which have been 'deleted' this long (in days). - * - * FIXME: could use a better name. - */ - 'max_age' => 31, - /* Columns to include in listing */ - 'info' => 'most', - )); + ( + WikiPlugin_WikiAdminSelect::getDefaultArguments(), + array( + /* + * Show only pages which have been 'deleted' this + * long (in days). (negative or non-numeric + * means show all pages, even non-deleted ones.) + * + * FIXME: could use a better name. + */ + 'min_age' => 0, + + /* + * Automatically check the checkboxes for files + * which have been 'deleted' this long (in days). + * + * FIXME: could use a better name. + */ + 'max_age' => 31, + /* Columns to include in listing */ + 'info' => 'most', + )); } - function collectPages(&$list, &$dbi, $sortby, $limit=0) { + function collectPages(&$list, &$dbi, $sortby, $limit = 0) + { extract($this->_args); $now = time(); - $allPages = $dbi->getAllPages('include_empty',$sortby,$limit); + $allPages = $dbi->getAllPages('include_empty', $sortby, $limit); while ($pagehandle = $allPages->next()) { $pagename = $pagehandle->getName(); $current = $pagehandle->getCurrentRevision(); if ($current->getVersion() < 1) - continue; // No versions in database + continue; // No versions in database $empty = $current->hasDefaultContents(); if ($empty) { $age = ($now - $current->get('mtime')) / (24 * 3600.0); $checked = $age >= $max_age; - } - else { + } else { $age = 0; $checked = false; } @@ -100,18 +103,20 @@ extends WikiPlugin_WikiAdminSelect return $list; } - function removePages(&$request, $pages) { + function removePages(&$request, $pages) + { $result = HTML::div(); $ul = HTML::ul(); - $dbi = $request->getDbh(); $count = 0; + $dbi = $request->getDbh(); + $count = 0; foreach ($pages as $name) { - $name = str_replace(array('%5B','%5D'),array('[',']'),$name); - if (mayAccessPage('remove',$name)) { + $name = str_replace(array('%5B', '%5D'), array('[', ']'), $name); + if (mayAccessPage('remove', $name)) { $dbi->deletePage($name); $ul->pushContent(HTML::li(fmt("Removed page '%s' successfully.", $name))); $count++; } else { - $ul->pushContent(HTML::li(fmt("Didn't remove page '%s'. Access denied.", $name))); + $ul->pushContent(HTML::li(fmt("Didn't remove page '%s'. Access denied.", $name))); } } if ($count) { @@ -131,7 +136,8 @@ extends WikiPlugin_WikiAdminSelect } } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { if ($request->getArg('action') != 'browse') { if ($request->getArg('action') != _("PhpWikiAdministration/Remove")) { return $this->disabled(_("Plugin not run: not in browse mode")); @@ -155,7 +161,8 @@ extends WikiPlugin_WikiAdminSelect $next_action = 'select'; $pages = array(); if ($p && $request->isPost() && - !empty($post_args['remove']) && empty($post_args['cancel'])) { + !empty($post_args['remove']) && empty($post_args['cancel']) + ) { // check individual PagePermissions if (!ENABLE_PAGEPERM and !$request->_user->isAdmin()) { @@ -170,26 +177,26 @@ extends WikiPlugin_WikiAdminSelect if ($post_args['action'] == 'select') { $next_action = 'verify'; foreach ($p as $name => $c) { - $name = str_replace(array('%5B','%5D'),array('[',']'),$name); + $name = str_replace(array('%5B', '%5D'), array('[', ']'), $name); $pages[$name] = $c; } } } elseif ($p && is_array($p) && !$request->isPost()) { // from WikiAdminSelect $next_action = 'verify'; foreach ($p as $name => $c) { - $name = str_replace(array('%5B','%5D'),array('[',']'),$name); + $name = str_replace(array('%5B', '%5D'), array('[', ']'), $name); $pages[$name] = $c; } - $request->setArg('p',false); + $request->setArg('p', false); } if ($next_action == 'select') { // List all pages to select from. $pages = $this->collectPages($pages, $dbi, $args['sortby'], $args['limit'], $args['exclude']); } $pagelist = new PageList_Selectable($args['info'], $args['exclude'], - array('types' => - array('remove' - => new _PageList_Column_remove('remove', _("Remove"))))); + array('types' => + array('remove' + => new _PageList_Column_remove('remove', _("Remove"))))); $pagelist->addPageList($pages); $header = HTML::fieldset(); @@ -198,8 +205,7 @@ extends WikiPlugin_WikiAdminSelect $header->pushContent(HTML::legend(_("Confirm removal"))); $header->pushContent(HTML::p(HTML::strong( _("Are you sure you want to remove the selected files?")))); - } - else { + } else { $button_label = _("Remove selected pages"); $header->pushContent(HTML::legend(_("Select the files to remove"))); if ($args['min_age'] > 0) { @@ -217,28 +223,32 @@ extends WikiPlugin_WikiAdminSelect } $buttons = HTML::p(Button('submit:admin_remove[remove]', $button_label, 'wikiadmin'), - Button('submit:admin_remove[cancel]', _("Cancel"), 'button')); + Button('submit:admin_remove[cancel]', _("Cancel"), 'button')); $header->pushContent($buttons); // TODO: quick select by regex javascript? return HTML::form(array('action' => $request->getPostURL(), - 'method' => 'post'), - $header, - $pagelist->getContent(), - HiddenInputs($request->getArgs(), - false, - array('admin_remove')), - HiddenInputs(array('admin_remove[action]' => $next_action, - 'require_authority_for_post' => WIKIAUTH_ADMIN))); + 'method' => 'post'), + $header, + $pagelist->getContent(), + HiddenInputs($request->getArgs(), + false, + array('admin_remove')), + HiddenInputs(array('admin_remove[action]' => $next_action, + 'require_authority_for_post' => WIKIAUTH_ADMIN))); } } -class _PageList_Column_remove extends _PageList_Column { - function _getValue ($page_handle, &$revision_handle) { +class _PageList_Column_remove extends _PageList_Column +{ + function _getValue($page_handle, &$revision_handle) + { return Button(array('action' => 'remove'), _("Remove"), - $page_handle->getName()); + $page_handle->getName()); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/WikiAdminRename.php b/lib/plugin/WikiAdminRename.php index 08287d1a5..3156b0c94 100644 --- a/lib/plugin/WikiAdminRename.php +++ b/lib/plugin/WikiAdminRename.php @@ -30,31 +30,35 @@ require_once 'lib/PageList.php'; require_once 'lib/plugin/WikiAdminSelect.php'; class WikiPlugin_WikiAdminRename -extends WikiPlugin_WikiAdminSelect + extends WikiPlugin_WikiAdminSelect { - function getName() { + function getName() + { return _("WikiAdminRename"); } - function getDescription() { + function getDescription() + { return _("Rename selected pages"); } - function getDefaultArguments() { + function getDefaultArguments() + { return array_merge - ( - WikiPlugin_WikiAdminSelect::getDefaultArguments(), - array( - /* Columns to include in listing */ - 'info' => 'pagename,mtime', - 'updatelinks' => 0, - 'createredirect' => 0 - )); + ( + WikiPlugin_WikiAdminSelect::getDefaultArguments(), + array( + /* Columns to include in listing */ + 'info' => 'pagename,mtime', + 'updatelinks' => 0, + 'createredirect' => 0 + )); } - function renameHelper($name, $from, $to, $options = false) { + function renameHelper($name, $from, $to, $options = false) + { if (isset($options['regex'])) { - return preg_replace('/'.$from.'/'.(isset($options['icase'])?'i':''), $to, $name); + return preg_replace('/' . $from . '/' . (isset($options['icase']) ? 'i' : ''), $to, $name); } elseif (isset($options['icase'])) { return str_ireplace($from, $to, $name); } else { @@ -62,29 +66,27 @@ extends WikiPlugin_WikiAdminSelect } } - function renamePages(&$dbi, &$request, $pages, $from, $to, $updatelinks=false, - $createredirect=false) + function renamePages(&$dbi, &$request, $pages, $from, $to, $updatelinks = false, + $createredirect = false) { $result = HTML::div(); $ul = HTML::ul(); $count = 0; $post_args = $request->getArg('admin_rename'); $options = - array('regex' => isset($post_args['regex']) ? $post_args['regex'] : null, + array('regex' => isset($post_args['regex']) ? $post_args['regex'] : null, 'icase' => isset($post_args['icase']) ? $post_args['icase'] : null); foreach ($pages as $name) { - if ( ($newname = $this->renameHelper($name, $from, $to, $options)) - and $newname != $name ) - { + if (($newname = $this->renameHelper($name, $from, $to, $options)) + and $newname != $name + ) { if (strlen($newname) > MAX_PAGENAME_LENGTH) $ul->pushContent(HTML::li(_("Cannot rename. New page name too long."))); elseif ($dbi->isWikiPage($newname)) $ul->pushContent(HTML::li(fmt("Page '%s' already exists. Ignored.", - WikiLink($newname)))); - elseif (! mayAccessPage('edit', $name)) + WikiLink($newname)))); elseif (!mayAccessPage('edit', $name)) $ul->pushContent(HTML::li(fmt("Access denied to rename page '%s'.", - WikiLink($name)))); - elseif ( $dbi->renamePage($name, $newname, $updatelinks)) { + WikiLink($name)))); elseif ($dbi->renamePage($name, $newname, $updatelinks)) { /* not yet implemented for all backends */ $page = $dbi->getPage($newname); $current = $page->getCurrentRevision(); @@ -101,21 +103,21 @@ extends WikiPlugin_WikiAdminSelect $text = "<>"; $meta['summary'] = sprintf(_("Renaming created redirect page from '%s' to '%s'"), - $name, $newname); + $name, $newname); $meta['is_minor_edit'] = 0; $meta['author'] = $request->_user->UserName(); $page->save($text, 1, $meta); } $ul->pushContent(HTML::li(fmt("Renamed page from '%s' to '%s'.", - $name, WikiLink($newname)))); + $name, WikiLink($newname)))); $count++; } else { $ul->pushContent(HTML::li(fmt("Couldn't rename page '%s' to '%s'.", - $name, $newname))); + $name, $newname))); } } else { $ul->pushContent(HTML::li(fmt("Couldn't rename page '%s' to '%s'.", - $name, $newname))); + $name, $newname))); } } if ($count) { @@ -123,10 +125,10 @@ extends WikiPlugin_WikiAdminSelect $result->setAttr('class', 'feedback'); if ($count == 1) { $result->pushContent(HTML::p( - _("One page has been renamed:"))); + _("One page has been renamed:"))); } else { $result->pushContent(HTML::p( - fmt("%d pages have been renamed:", $count))); + fmt("%d pages have been renamed:", $count))); } $result->pushContent($ul); return $result; @@ -138,10 +140,12 @@ extends WikiPlugin_WikiAdminSelect } } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $action = $request->getArg('action'); if ($action != 'browse' and $action != 'rename' - and $action != _("PhpWikiAdministration")."/"._("Rename")) { + and $action != _("PhpWikiAdministration") . "/" . _("Rename") + ) { return $this->disabled(_("Plugin not run: not in browse mode")); } @@ -149,9 +153,9 @@ extends WikiPlugin_WikiAdminSelect // We rename a single page. // No need to display "Regex?" and "Case insensitive?" boxes // No need to confirm - $singlepage = true; + $singlepage = true; } else { - $singlepage = false; + $singlepage = false; } $args = $this->getArgs($argstr, $request); @@ -166,7 +170,8 @@ extends WikiPlugin_WikiAdminSelect if ($p && !$request->isPost()) $pages = $p; if ($p && $request->isPost() && - !empty($post_args['rename']) && empty($post_args['cancel'])) { + !empty($post_args['rename']) && empty($post_args['cancel']) + ) { // without individual PagePermissions: if (!ENABLE_PAGEPERM and !$request->_user->isAdmin()) { $request->_notAuthorized(WIKIAUTH_ADMIN); @@ -176,9 +181,9 @@ extends WikiPlugin_WikiAdminSelect if ($post_args['action'] == 'verify') { // Real action return $this->renamePages($dbi, $request, array_keys($p), - $post_args['from'], $post_args['to'], - !empty($post_args['updatelinks']), - !empty($post_args['createredirect'])); + $post_args['from'], $post_args['to'], + !empty($post_args['updatelinks']), + !empty($post_args['createredirect'])); } } if ($post_args['action'] == 'select') { @@ -191,26 +196,26 @@ extends WikiPlugin_WikiAdminSelect if ($next_action == 'select' and empty($pages)) { // List all pages to select from. $pages = $this->collectPages($pages, $dbi, $args['sortby'], - $args['limit'], $args['exclude']); + $args['limit'], $args['exclude']); } /*if ($next_action == 'verify') { $args['info'] = "checkbox,pagename,renamed_pagename"; }*/ $pagelist = new PageList_Selectable - ( - $args['info'], $args['exclude'], - array('types' => - array('renamed_pagename' - => new _PageList_Column_renamed_pagename('rename', _("Rename to")), - ))); + ( + $args['info'], $args['exclude'], + array('types' => + array('renamed_pagename' + => new _PageList_Column_renamed_pagename('rename', _("Rename to")), + ))); $pagelist->addPageList($pages); $header = HTML::div(); if ($next_action == 'verify') { $button_label = _("Yes"); $header->pushContent( - HTML::p(HTML::strong( - _("Are you sure you want to rename the selected pages?")))); + HTML::p(HTML::strong( + _("Are you sure you want to rename the selected pages?")))); $header = $this->renameForm($header, $post_args, $singlepage); } else { if ($singlepage === true) { @@ -229,8 +234,8 @@ extends WikiPlugin_WikiAdminSelect } $buttons = HTML::p - (Button('submit:admin_rename[rename]', $button_label, 'wikiadmin'), - Button('submit:admin_rename[cancel]', _("Cancel"), 'button')); + (Button('submit:admin_rename[rename]', $button_label, 'wikiadmin'), + Button('submit:admin_rename[cancel]', _("Cancel"), 'button')); if ($singlepage === false) { $list = $pagelist->getContent(); @@ -238,59 +243,61 @@ extends WikiPlugin_WikiAdminSelect $list = ""; } return HTML::form(array('action' => $request->getPostURL(), - 'method' => 'post'), - HTML::fieldset( - HTML::legend(_("Rename Page")), - $header, - $buttons, - $list, - HiddenInputs($request->getArgs(), - false, - array('admin_rename')), - HiddenInputs(array('admin_rename[action]' => $next_action)), - ENABLE_PAGEPERM - ? '' - : HiddenInputs(array('require_authority_for_post' - => WIKIAUTH_ADMIN)))); + 'method' => 'post'), + HTML::fieldset( + HTML::legend(_("Rename Page")), + $header, + $buttons, + $list, + HiddenInputs($request->getArgs(), + false, + array('admin_rename')), + HiddenInputs(array('admin_rename[action]' => $next_action)), + ENABLE_PAGEPERM + ? '' + : HiddenInputs(array('require_authority_for_post' + => WIKIAUTH_ADMIN)))); } - function checkBox (&$post_args, $name, $msg) { - $id = 'admin_rename-'.$name; - $checkbox = HTML::input(array('type' => 'checkbox', - 'name' => 'admin_rename['.$name.']', - 'id' => $id, - 'value' => 1)); + function checkBox(&$post_args, $name, $msg) + { + $id = 'admin_rename-' . $name; + $checkbox = HTML::input(array('type' => 'checkbox', + 'name' => 'admin_rename[' . $name . ']', + 'id' => $id, + 'value' => 1)); if (!empty($post_args[$name])) $checkbox->setAttr('checked', 'checked'); return HTML::div($checkbox, ' ', HTML::label(array('for' => $id), $msg)); } - function renameForm(&$header, $post_args, $singlepage) { + function renameForm(&$header, $post_args, $singlepage) + { $table = HTML::table(); - $this->_tablePush($table, _("Rename"). " ". _("from")._(": "), - HTML::input(array('name' => 'admin_rename[from]', - 'size' => MAX_PAGENAME_LENGTH, - 'maxlength' => MAX_PAGENAME_LENGTH, - 'readonly' => 'readonly', - 'value' => $post_args['from']))); - $this->_tablePush($table, _("to")._(": "), - HTML::input(array('name' => 'admin_rename[to]', - 'size' => MAX_PAGENAME_LENGTH, - 'maxlength' => MAX_PAGENAME_LENGTH, - 'value' => $post_args['to']))); + $this->_tablePush($table, _("Rename") . " " . _("from") . _(": "), + HTML::input(array('name' => 'admin_rename[from]', + 'size' => MAX_PAGENAME_LENGTH, + 'maxlength' => MAX_PAGENAME_LENGTH, + 'readonly' => 'readonly', + 'value' => $post_args['from']))); + $this->_tablePush($table, _("to") . _(": "), + HTML::input(array('name' => 'admin_rename[to]', + 'size' => MAX_PAGENAME_LENGTH, + 'maxlength' => MAX_PAGENAME_LENGTH, + 'value' => $post_args['to']))); if ($singlepage === false) { $this->_tablePush($table, '', - $this->checkBox($post_args, 'regex', _("Regex?"))); + $this->checkBox($post_args, 'regex', _("Regex?"))); $this->_tablePush($table, '', - $this->checkBox($post_args, 'icase', _("Case insensitive?"))); + $this->checkBox($post_args, 'icase', _("Case insensitive?"))); } if (defined('EXPERIMENTAL') and EXPERIMENTAL) // not yet stable $this->_tablePush($table, '', - $this->checkBox($post_args, 'updatelinks', - _("Change pagename in all linked pages also?"))); + $this->checkBox($post_args, 'updatelinks', + _("Change pagename in all linked pages also?"))); $this->_tablePush($table, '', - $this->checkBox($post_args, 'createredirect', - _("Create redirect from old to new name?"))); + $this->checkBox($post_args, 'createredirect', + _("Create redirect from old to new name?"))); $header->pushContent($table); return $header; } @@ -301,26 +308,30 @@ extends WikiPlugin_WikiAdminSelect // TODO: update rename[] fields when case-sensitive and regex is changed // moved from lib/PageList.php -class _PageList_Column_renamed_pagename extends _PageList_Column { - function _getValue ($page_handle, &$revision_handle) { +class _PageList_Column_renamed_pagename extends _PageList_Column +{ + function _getValue($page_handle, &$revision_handle) + { global $request; $post_args = $request->getArg('admin_rename'); $options = - array('regex' => isset($post_args['regex']) ? $post_args['regex'] : null, + array('regex' => isset($post_args['regex']) ? $post_args['regex'] : null, 'icase' => isset($post_args['icase']) ? $post_args['icase'] : null); $value = $post_args ? WikiPlugin_WikiAdminRename::renameHelper - ($page_handle->getName(), - $post_args['from'], $post_args['to'], - $options) + ($page_handle->getName(), + $post_args['from'], $post_args['to'], + $options) : $page_handle->getName(); - $div = HTML::div(" => ",HTML::input(array('type' => 'text', - 'name' => 'rename[]', - 'value' => $value))); + $div = HTML::div(" => ", HTML::input(array('type' => 'text', + 'name' => 'rename[]', + 'value' => $value))); $new_page = $request->getPage($value); return $div; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/WikiAdminSearchReplace.php b/lib/plugin/WikiAdminSearchReplace.php index c6dc97fac..3d1fa542d 100644 --- a/lib/plugin/WikiAdminSearchReplace.php +++ b/lib/plugin/WikiAdminSearchReplace.php @@ -30,34 +30,38 @@ require_once 'lib/PageList.php'; require_once 'lib/plugin/WikiAdminSelect.php'; class WikiPlugin_WikiAdminSearchReplace -extends WikiPlugin_WikiAdminSelect + extends WikiPlugin_WikiAdminSelect { - function getName() { + function getName() + { return _("WikiAdminSearchReplace"); } - function getDescription() { + function getDescription() + { return _("Search and replace text in selected wiki pages."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array_merge - ( - WikiPlugin_WikiAdminSelect::getDefaultArguments(), - array( - /* Columns to include in listing */ - 'info' => 'some', - )); + ( + WikiPlugin_WikiAdminSelect::getDefaultArguments(), + array( + /* Columns to include in listing */ + 'info' => 'some', + )); } - function replaceHelper(&$dbi, &$request, $pagename, $from, $to, $case_exact=true, $regex=false) { + function replaceHelper(&$dbi, &$request, $pagename, $from, $to, $case_exact = true, $regex = false) + { $page = $dbi->getPage($pagename); - if ($page->exists()) {// don't replace default contents + if ($page->exists()) { // don't replace default contents $current = $page->getCurrentRevision(); $version = $current->getVersion(); $text = $current->getPackedContent(); if ($regex) { - $newtext = preg_replace("/".$from."/".($case_exact?'':'i'), $to, $text); + $newtext = preg_replace("/" . $from . "/" . ($case_exact ? '' : 'i'), $to, $text); } else { if ($case_exact) { $newtext = str_replace($from, $to, $text); @@ -74,7 +78,7 @@ extends WikiPlugin_WikiAdminSelect $meta = $current->_data; $meta['summary'] = sprintf(_("Replace '%s' by '%s'"), $from, $to); $meta['is_minor_edit'] = 0; - $meta['author'] = $request->_user->UserName(); + $meta['author'] = $request->_user->UserName(); unset($meta['mtime']); // force new date return $page->save($newtext, $version + 1, $meta); } @@ -82,7 +86,8 @@ extends WikiPlugin_WikiAdminSelect return false; } - function searchReplacePages(&$dbi, &$request, $pages, $from, $to) { + function searchReplacePages(&$dbi, &$request, $pages, $from, $to) + { if (empty($from)) return HTML::p(HTML::strong(fmt("Error: Empty search string."))); $result = HTML::div(); $ul = HTML::ul(); @@ -92,10 +97,10 @@ extends WikiPlugin_WikiAdminSelect $regex = !empty($post_args['regex']); foreach ($pages as $pagename) { if (!mayAccessPage('edit', $pagename)) { - $ul->pushContent(HTML::li(fmt("Access denied to change page '%s'.",$pagename))); + $ul->pushContent(HTML::li(fmt("Access denied to change page '%s'.", $pagename))); } elseif ($this->replaceHelper($dbi, $request, $pagename, $from, $to, $case_exact, $regex)) { $ul->pushContent(HTML::li(fmt("Replaced '%s' with '%s' in page '%s'.", - $from, $to, WikiLink($pagename)))); + $from, $to, WikiLink($pagename)))); $count++; } } @@ -115,7 +120,8 @@ extends WikiPlugin_WikiAdminSelect return $result; } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { // no action=replace support yet if ($request->getArg('action') != 'browse') { return $this->disabled(_("Plugin not run: not in browse mode")); @@ -135,7 +141,8 @@ extends WikiPlugin_WikiAdminSelect if ($p && !$request->isPost()) $pages = $p; if ($p && $request->isPost() && - empty($post_args['cancel'])) { + empty($post_args['cancel']) + ) { // without individual PagePermissions: if (!ENABLE_PAGEPERM and !$request->_user->isAdmin()) { $request->_notAuthorized(WIKIAUTH_ADMIN); @@ -145,7 +152,7 @@ extends WikiPlugin_WikiAdminSelect if ($post_args['action'] == 'verify' and !empty($post_args['from'])) { // Real action return $this->searchReplacePages($dbi, $request, array_keys($p), - $post_args['from'], $post_args['to']); + $post_args['from'], $post_args['to']); } if ($post_args['action'] == 'select') { if (!empty($post_args['from'])) @@ -159,7 +166,7 @@ extends WikiPlugin_WikiAdminSelect // List all pages to select from. //TODO: check for permissions and list only the allowed $pages = $this->collectPages($pages, $dbi, $args['sortby'], - $args['limit'], $args['exclude']); + $args['limit'], $args['exclude']); } if ($next_action == 'verify') { @@ -168,26 +175,26 @@ extends WikiPlugin_WikiAdminSelect $args['info'] = "checkbox,pagename,hi_content,mtime,author"; } $pagelist = new PageList_Selectable - ($args['info'], $args['exclude'], - array_merge - ( - $args, - array('types' => array - ( - 'hi_content' // with highlighted search for SearchReplace - => new _PageList_Column_content('rev:hi_content', _("Content")))))); + ($args['info'], $args['exclude'], + array_merge + ( + $args, + array('types' => array + ( + 'hi_content' // with highlighted search for SearchReplace + => new _PageList_Column_content('rev:hi_content', _("Content")))))); $pagelist->addPageList($pages); $header = HTML::fieldset(); if (empty($post_args['from'])) $header->pushContent( - HTML::p(HTML::em(_("Warning: The search string cannot be empty!")))); + HTML::p(HTML::em(_("Warning: The search string cannot be empty!")))); if ($next_action == 'verify') { $button_label = _("Yes"); $header->pushContent( - HTML::p(HTML::strong( - _("Are you sure you want to replace text in the selected files?")))); + HTML::p(HTML::strong( + _("Are you sure you want to replace text in the selected files?")))); $this->replaceForm($header, $post_args); } else { $button_label = _("Search & Replace"); @@ -196,46 +203,48 @@ extends WikiPlugin_WikiAdminSelect } $buttons = HTML::p(Button('submit:admin_replace[replace]', $button_label, 'wikiadmin'), - Button('submit:admin_replace[cancel]', _("Cancel"), 'button')); + Button('submit:admin_replace[cancel]', _("Cancel"), 'button')); $header->pushContent($buttons); return HTML::form(array('action' => $request->getPostURL(), - 'method' => 'post'), - $header, - $pagelist->getContent(), - HiddenInputs($request->getArgs(), - false, - array('admin_replace')), - HiddenInputs(array('admin_replace[action]' => $next_action)), - ENABLE_PAGEPERM - ? '' - : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN))); + 'method' => 'post'), + $header, + $pagelist->getContent(), + HiddenInputs($request->getArgs(), + false, + array('admin_replace')), + HiddenInputs(array('admin_replace[action]' => $next_action)), + ENABLE_PAGEPERM + ? '' + : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN))); } - function checkBox (&$post_args, $name, $msg) { - $id = 'admin_replace-'.$name; - $checkbox = HTML::input(array('type' => 'checkbox', - 'name' => 'admin_replace['.$name.']', - 'id' => $id, - 'value' => 1)); + function checkBox(&$post_args, $name, $msg) + { + $id = 'admin_replace-' . $name; + $checkbox = HTML::input(array('type' => 'checkbox', + 'name' => 'admin_replace[' . $name . ']', + 'id' => $id, + 'value' => 1)); if (!empty($post_args[$name])) $checkbox->setAttr('checked', 'checked'); return HTML::div($checkbox, ' ', HTML::label(array('for' => $id), $msg)); } - function replaceForm(&$header, $post_args) { - $header->pushContent(HTML::div(array('class'=>'hint'), - _("Replace all occurences of the given string in the content of all pages.")), - HTML::br()); + function replaceForm(&$header, $post_args) + { + $header->pushContent(HTML::div(array('class' => 'hint'), + _("Replace all occurences of the given string in the content of all pages.")), + HTML::br()); $table = HTML::table(); - $this->_tablePush($table, _("Replace")._(": "), - HTML::input(array('name' => 'admin_replace[from]', - 'size' => 90, - 'value' => $post_args['from']))); - $this->_tablePush($table, _("by")._(": "), - HTML::input(array('name' => 'admin_replace[to]', - 'size' => 90, - 'value' => $post_args['to']))); + $this->_tablePush($table, _("Replace") . _(": "), + HTML::input(array('name' => 'admin_replace[from]', + 'size' => 90, + 'value' => $post_args['from']))); + $this->_tablePush($table, _("by") . _(": "), + HTML::input(array('name' => 'admin_replace[to]', + 'size' => 90, + 'value' => $post_args['to']))); $this->_tablePush($table, '', $this->checkBox($post_args, 'case_exact', _("Case exact?"))); $this->_tablePush($table, '', $this->checkBox($post_args, 'regex', _("Regex?"))); $header->pushContent($table); @@ -243,9 +252,10 @@ extends WikiPlugin_WikiAdminSelect } } -function stri_replace($find,$replace,$string) { +function stri_replace($find, $replace, $string) +{ if (!is_array($find)) $find = array($find); - if (!is_array($replace)) { + if (!is_array($replace)) { if (!is_array($find)) $replace = array($replace); else { @@ -259,13 +269,13 @@ function stri_replace($find,$replace,$string) { } } foreach ($find as $fKey => $fItem) { - $between = explode(strtolower($fItem),strtolower($string)); + $between = explode(strtolower($fItem), strtolower($string)); $pos = 0; - foreach($between as $bKey => $bItem) { - $between[$bKey] = substr($string,$pos,strlen($bItem)); + foreach ($between as $bKey => $bItem) { + $between[$bKey] = substr($string, $pos, strlen($bItem)); $pos += strlen($bItem) + strlen($fItem); } - $string = implode($replace[$fKey],$between); + $string = implode($replace[$fKey], $between); } return $string; } diff --git a/lib/plugin/WikiAdminSelect.php b/lib/plugin/WikiAdminSelect.php index fd26afda2..0179649de 100644 --- a/lib/plugin/WikiAdminSelect.php +++ b/lib/plugin/WikiAdminSelect.php @@ -35,36 +35,40 @@ require_once 'lib/PageList.php'; class WikiPlugin_WikiAdminSelect -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("WikiAdminSelect"); } - function getDescription() { + function getDescription() + { return _("Allows selection of multiple pages which get passed to other WikiAdmin plugins."); } - function getDefaultArguments() { - return array('s' => '', // preselect pages - /* select pages by meta-data: */ - 'author' => false, - 'owner' => false, - 'creator' => false, - 'only' => '', - 'exclude' => '', - 'info' => 'most', - 'sortby' => 'pagename', - 'limit' => 0, - 'paging' => 'none' - ); + function getDefaultArguments() + { + return array('s' => '', // preselect pages + /* select pages by meta-data: */ + 'author' => false, + 'owner' => false, + 'creator' => false, + 'only' => '', + 'exclude' => '', + 'info' => 'most', + 'sortby' => 'pagename', + 'limit' => 0, + 'paging' => 'none' + ); } /** * Default collector for all WikiAdmin* plugins. * preSelectS() is similar, but fills $this->_list */ - function collectPages(&$list, &$dbi, $sortby, $limit=0, $exclude='') { + function collectPages(&$list, &$dbi, $sortby, $limit = 0, $exclude = '') + { $allPages = $dbi->getAllPages(0, $sortby, $limit, $exclude); while ($pagehandle = $allPages->next()) { $pagename = $pagehandle->getName(); @@ -81,18 +85,17 @@ extends WikiPlugin * 'only: forgot what the difference to 's' was. * Sets $this->_list, which is picked up by collectPages() and is a default for p[] */ - function preSelectS (&$args, &$request) { + function preSelectS(&$args, &$request) + { // override plugin argument by GET: probably not needed if s||="" is used // anyway, we force it for unique interface. if (!empty($request->getArg['s'])) $args['s'] = $request->getArg['s']; - if ( !empty($args['owner']) ) - $sl = PageList::allPagesByOwner($args['owner'],false,$args['sortby'],$args['limit'],$args['exclude']); - elseif ( !empty($args['author']) ) - $sl = PageList::allPagesByAuthor($args['author'],false,$args['sortby'],$args['limit'],$args['exclude']); - elseif ( !empty($args['creator']) ) - $sl = PageList::allPagesByCreator($args['creator'],false,$args['sortby'],$args['limit'],$args['exclude']); - elseif ( !empty($args['s']) or !empty($args['only']) ) { + if (!empty($args['owner'])) + $sl = PageList::allPagesByOwner($args['owner'], false, $args['sortby'], $args['limit'], $args['exclude']); + elseif (!empty($args['author'])) + $sl = PageList::allPagesByAuthor($args['author'], false, $args['sortby'], $args['limit'], $args['exclude']); elseif (!empty($args['creator'])) + $sl = PageList::allPagesByCreator($args['creator'], false, $args['sortby'], $args['limit'], $args['exclude']); elseif (!empty($args['s']) or !empty($args['only'])) { // all pages by name $sl = explodePageList(empty($args['only']) ? $args['s'] : $args['only']); } @@ -111,7 +114,8 @@ extends WikiPlugin return $this->_list; } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { //if ($request->getArg('action') != 'browse') // return $this->disabled("(action != 'browse')"); $args = $this->getArgs($argstr, $request); @@ -133,25 +137,25 @@ extends WikiPlugin $p = $request->getArg('p'); //$p = @$GLOBALS['HTTP_POST_VARS']['p']; $form->pushContent(HTML::p(array('class' => 'wikitext'), _("Select: "), - HTML::input(array('type' => 'text', - 'name' => 's', - 'value' => $args['s'])), - HTML::input(array('type' => 'submit', - 'name' => 'WikiAdminSelect', - 'value' => _("Go"))))); - if (! $request->getArg('verify')) { + HTML::input(array('type' => 'text', + 'name' => 's', + 'value' => $args['s'])), + HTML::input(array('type' => 'submit', + 'name' => 'WikiAdminSelect', + 'value' => _("Go"))))); + if (!$request->getArg('verify')) { $form->pushContent(HTML::input(array('type' => 'hidden', - 'name' => 'action', - 'value' => 'verify'))); + 'name' => 'action', + 'value' => 'verify'))); $form->pushContent(Button('submit:verify', _("Select pages"), - 'wikiadmin'), - Button('submit:cancel', _("Cancel"), 'button')); + 'wikiadmin'), + Button('submit:cancel', _("Cancel"), 'button')); } else { global $WikiTheme; $form->pushContent(HTML::input(array('type' => 'hidden', - 'name' => 'action', - 'value' => 'WikiAdminSelect')) - ); + 'name' => 'action', + 'value' => 'WikiAdminSelect')) + ); // Add the Buttons for all registered WikiAdmin plugins $plugin_dir = 'lib/plugin'; if (defined('PHPWIKI_DIR')) @@ -160,9 +164,9 @@ extends WikiPlugin $actions = $fs->getFiles(); sort($actions); foreach ($actions as $f) { - $f = preg_replace('/.php$/','', $f); - $s = preg_replace('/^WikiAdmin/','', $f); - if (!in_array($s,array("Select","Utils"))) { // disable Select and Utils + $f = preg_replace('/.php$/', '', $f); + $s = preg_replace('/^WikiAdmin/', '', $f); + if (!in_array($s, array("Select", "Utils"))) { // disable Select and Utils $form->pushContent(Button("submit:wikiadmin[$f]", _($s), "wikiadmin")); $form->pushContent($WikiTheme->getButtonSeparator()); } @@ -171,22 +175,21 @@ extends WikiPlugin } if ($request->isPost() - && ! $request->getArg('wikiadmin') - && !empty($p)) { + && !$request->getArg('wikiadmin') + && !empty($p) + ) { $this->_list = array(); // List all selected pages again. foreach ($p as $page => $name) { $this->_list[$name] = 1; } - } - elseif ($request->isPost() - and $request->_user->isAdmin() + } elseif ($request->isPost() + and $request->_user->isAdmin() and !empty($p) - //and $request->getArg('verify') - and ($request->getArg('action') == 'WikiAdminSelect') - and $request->getArg('wikiadmin') - ) - { + //and $request->getArg('verify') + and ($request->getArg('action') == 'WikiAdminSelect') + and $request->getArg('wikiadmin') + ) { // handle external plugin $loader = new WikiPluginLoader(); $a = array_keys($request->getArg('wikiadmin')); @@ -203,19 +206,19 @@ extends WikiPlugin // then this plugin will not return. (Rename, SearchReplace, ...) $action_result = $plugin->run($dbi, $plugin_args, $request, $basepage); $ul->pushContent(HTML::li(fmt("Selected page '%s' passed to '%s'.", - $name, $select))); + $name, $select))); $ul->pushContent(HTML::ul(HTML::li($action_result))); } } else { // redirect to the plugin page. // in which page is this plugin? - $plugin_action = preg_replace("/^WikiAdmin/","",$plugin_action); + $plugin_action = preg_replace("/^WikiAdmin/", "", $plugin_action); $args = array(); foreach ($p as $page => $x) { - $args["p[$page]"] = 1; + $args["p[$page]"] = 1; } - header("Location: ". - WikiURL(_("PhpWikiAdministration")."/"._($plugin_action),$args,1)); + header("Location: " . + WikiURL(_("PhpWikiAdministration") . "/" . _($plugin_action), $args, 1)); exit(); } } elseif (empty($args['s'])) { @@ -226,21 +229,22 @@ extends WikiPlugin $pagelist->addPageList($this->_list); $form->pushContent($pagelist->getContent()); foreach ($args as $k => $v) { - if (!in_array($k,array('s','WikiAdminSelect','action','verify'))) + if (!in_array($k, array('s', 'WikiAdminSelect', 'action', 'verify'))) $form->pushContent(HiddenInputs(array($k => $v))); // plugin params } - if (! $request->getArg('select')) { + if (!$request->getArg('select')) { return $form; } else { ; //return $action_result; } } - function _tablePush(&$table, $first, $second) { + function _tablePush(&$table, $first, $second) + { $table->pushContent( - HTML::tr( - HTML::td($first), - HTML::td($second))); + HTML::tr( + HTML::td($first), + HTML::td($second))); } } diff --git a/lib/plugin/WikiAdminSetAcl.php b/lib/plugin/WikiAdminSetAcl.php index 3621d6225..5d4599e41 100644 --- a/lib/plugin/WikiAdminSetAcl.php +++ b/lib/plugin/WikiAdminSetAcl.php @@ -35,28 +35,32 @@ require_once 'lib/PageList.php'; require_once 'lib/plugin/WikiAdminSelect.php'; class WikiPlugin_WikiAdminSetAcl -extends WikiPlugin_WikiAdminSelect + extends WikiPlugin_WikiAdminSelect { - function getName() { + function getName() + { return _("WikiAdminSetAcl"); } - function getDescription() { + function getDescription() + { return _("Set individual page permissions."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array_merge - ( - WikiPlugin_WikiAdminSelect::getDefaultArguments(), - array( - 'p' => "[]", // list of pages - /* Columns to include in listing */ - 'info' => 'pagename,perm,mtime,owner,author', - )); + ( + WikiPlugin_WikiAdminSelect::getDefaultArguments(), + array( + 'p' => "[]", // list of pages + /* Columns to include in listing */ + 'info' => 'pagename,perm,mtime,owner,author', + )); } - function setaclPages(&$request, $pages, $acl) { + function setaclPages(&$request, $pages, $acl) + { $result = HTML::div(); $count = 0; $dbi =& $request->_dbi; @@ -69,11 +73,12 @@ extends WikiPlugin_WikiAdminSelect } unset($acl['_add_group']); } - unset($acl['_new_group']); unset($acl['_new_perm']); + unset($acl['_new_group']); + unset($acl['_new_perm']); if (isset($acl['_del_group'])) { //del groups with perm foreach ($acl['_del_group'] as $access => $del) { - while (list($group,$dummy) = each($del)) + while (list($group, $dummy) = each($del)) unset($acl[$access][$group]); } unset($acl['_del_group']); @@ -81,23 +86,23 @@ extends WikiPlugin_WikiAdminSelect if ($perm = new PagePermission($acl)) { $perm->sanify(); foreach ($pages as $pagename) { - // check if unchanged? we need a deep array_equal - $page = $dbi->getPage($pagename); - $oldperm = getPagePermissions($page); + // check if unchanged? we need a deep array_equal + $page = $dbi->getPage($pagename); + $oldperm = getPagePermissions($page); if ($oldperm) $oldperm->sanify(); - if ($oldperm and $perm->equal($oldperm->perm)) { + if ($oldperm and $perm->equal($oldperm->perm)) { $result->setAttr('class', 'error'); - $result->pushContent(HTML::p(fmt("ACL not changed for page '%s'.",$pagename))); + $result->pushContent(HTML::p(fmt("ACL not changed for page '%s'.", $pagename))); } elseif (mayAccessPage('change', $pagename)) { - setPagePermissions ($page, $perm); + setPagePermissions($page, $perm); $result->setAttr('class', 'feedback'); $result->pushContent(HTML::p(fmt("ACL changed for page '%s'", - $pagename))); + $pagename))); $result->pushContent(HTML::p(fmt("from '%s'", - $oldperm ? $oldperm->asAclLines() : "None"))); + $oldperm ? $oldperm->asAclLines() : "None"))); $result->pushContent(HTML::p(fmt("to '%s'.", - $perm->asAclLines()))); + $perm->asAclLines()))); // Create new revision so that ACL change appears in history. $current = $page->getCurrentRevision(); @@ -105,18 +110,18 @@ extends WikiPlugin_WikiAdminSelect $meta = $current->_data; $text = $current->getPackedContent(); $meta['summary'] = sprintf(_("ACL changed for page '%s' from '%s' to '%s'."), - $pagename, - $oldperm ? $oldperm->asAclLines() : "None", - $perm->asAclLines()); + $pagename, + $oldperm ? $oldperm->asAclLines() : "None", + $perm->asAclLines()); $meta['is_minor_edit'] = 1; - $meta['author'] = $request->_user->UserName(); + $meta['author'] = $request->_user->UserName(); unset($meta['mtime']); // force new date $page->save($text, $version + 1, $meta); $count++; } else { $result->setAttr('class', 'error'); - $result->pushContent(HTML::p(fmt("Access denied to change page '%s'.",$pagename))); + $result->pushContent(HTML::p(fmt("Access denied to change page '%s'.", $pagename))); } } } else { @@ -135,7 +140,8 @@ extends WikiPlugin_WikiAdminSelect return $result; } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { if ($request->getArg('action') != 'browse') { if ($request->getArg('action') != _("PhpWikiAdministration/SetAcl")) { return $this->disabled(_("Plugin not run: not in browse mode")); @@ -159,7 +165,8 @@ extends WikiPlugin_WikiAdminSelect $pages = $this->_list; $header = HTML::fieldset(); if ($p && $request->isPost() && - !empty($post_args['acl']) && empty($post_args['cancel'])) { + !empty($post_args['acl']) && empty($post_args['cancel']) + ) { // without individual PagePermissions: if (!ENABLE_PAGEPERM and !$request->_user->isAdmin()) { $request->_notAuthorized(WIKIAUTH_ADMIN); @@ -185,55 +192,55 @@ extends WikiPlugin_WikiAdminSelect $args['info'] = "checkbox,pagename,perm,mtime,owner,author"; } $pagelist = new PageList_Selectable($args['info'], - $args['exclude'], - array('types' => array( - 'perm' - => new _PageList_Column_perm('perm', _("Permission")), - 'acl' - => new _PageList_Column_acl('acl', _("ACL"))))); + $args['exclude'], + array('types' => array( + 'perm' + => new _PageList_Column_perm('perm', _("Permission")), + 'acl' + => new _PageList_Column_acl('acl', _("ACL"))))); $pagelist->addPageList($pages); if ($next_action == 'verify') { $button_label = _("Yes"); $header = $this->setaclForm($header, $post_args, $pages); $header->pushContent( - HTML::p(HTML::strong( - _("Are you sure you want to permanently change access rights to the selected files?")))); - } - else { + HTML::p(HTML::strong( + _("Are you sure you want to permanently change access rights to the selected files?")))); + } else { $button_label = _("Change Access Rights"); $header = $this->setaclForm($header, $post_args, $pages); $header->pushContent(HTML::legend(_("Select the pages where to change access rights"))); } $buttons = HTML::p(Button('submit:admin_setacl[acl]', $button_label, 'wikiadmin'), - Button('submit:admin_setacl[cancel]', _("Cancel"), 'button')); + Button('submit:admin_setacl[cancel]', _("Cancel"), 'button')); $header->pushContent($buttons); return HTML::form(array('action' => $request->getPostURL(), - 'method' => 'post'), - $header, - $pagelist->getContent(), - HiddenInputs($request->getArgs(), - false, - array('admin_setacl')), - HiddenInputs(array('admin_setacl[action]' => $next_action)), - ENABLE_PAGEPERM - ? '' - : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN))); + 'method' => 'post'), + $header, + $pagelist->getContent(), + HiddenInputs($request->getArgs(), + false, + array('admin_setacl')), + HiddenInputs(array('admin_setacl[action]' => $next_action)), + ENABLE_PAGEPERM + ? '' + : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN))); } - function setaclForm(&$header, $post_args, $pagehash) { + function setaclForm(&$header, $post_args, $pagehash) + { $acl = $post_args['acl']; //FIXME: find intersection of all pages perms, not just from the last pagename $pages = array(); foreach ($pagehash as $name => $checked) { - if ($checked) $pages[] = $name; + if ($checked) $pages[] = $name; } $perm_tree = pagePermissions($name); $table = pagePermissionsAclFormat($perm_tree, !empty($pages)); - $header->pushContent(HTML::strong(_("Selected Pages: ")), HTML::tt(join(', ',$pages)), HTML::br()); + $header->pushContent(HTML::strong(_("Selected Pages: ")), HTML::tt(join(', ', $pages)), HTML::br()); $first_page = $GLOBALS['request']->_dbi->getPage($name); $owner = $first_page->getOwner(); list($type, $perm) = pagePermissionsAcl($perm_tree[0], $perm_tree); @@ -241,17 +248,16 @@ extends WikiPlugin_WikiAdminSelect if ($type == 'inherited') $type = sprintf(_("page permission inherited from %s"), $perm_tree[1][0]); elseif ($type == 'page') - $type = _("individual page permission"); - elseif ($type == 'default') + $type = _("individual page permission"); elseif ($type == 'default') $type = _("default page permission"); - $header->pushContent(HTML::strong(_("Type")._(": ")), HTML::tt($type),HTML::br()); - $header->pushContent(HTML::strong(_("ACL")._(": ")), HTML::tt($perm->asAclLines()),HTML::br()); + $header->pushContent(HTML::strong(_("Type") . _(": ")), HTML::tt($type), HTML::br()); + $header->pushContent(HTML::strong(_("ACL") . _(": ")), HTML::tt($perm->asAclLines()), HTML::br()); - $header->pushContent(HTML::p(HTML::strong(_("Description")._(": ")), - _("Selected Grant checkboxes allow access, unselected checkboxes deny access."), - _("To ignore delete the line."), - _("To add check 'Add' near the dropdown list.") - )); + $header->pushContent(HTML::p(HTML::strong(_("Description") . _(": ")), + _("Selected Grant checkboxes allow access, unselected checkboxes deny access."), + _("To ignore delete the line."), + _("To add check 'Add' near the dropdown list.") + )); $header->pushContent($table); // // display array of checkboxes for existing perms @@ -265,16 +271,16 @@ extends WikiPlugin_WikiAdminSelect // 'value' => $post_args['acl']))); $header->pushContent(HTML::br()); if (!empty($pages) and defined('EXPERIMENTAL') and EXPERIMENTAL) { - $checkbox = HTML::input(array('type' => 'checkbox', - 'name' => 'admin_setacl[updatechildren]', - 'value' => 1)); - if (!empty($post_args['updatechildren'])) $checkbox->setAttr('checked','checked'); - $header->pushContent($checkbox, - _("Propagate new permissions to all subpages?"), - HTML::raw("  "), - HTML::em(_("(disable individual page permissions, enable inheritance)?")), - HTML::br(),HTML::em(_("(Currently not working)")) - ); + $checkbox = HTML::input(array('type' => 'checkbox', + 'name' => 'admin_setacl[updatechildren]', + 'value' => 1)); + if (!empty($post_args['updatechildren'])) $checkbox->setAttr('checked', 'checked'); + $header->pushContent($checkbox, + _("Propagate new permissions to all subpages?"), + HTML::raw("  "), + HTML::em(_("(disable individual page permissions, enable inheritance)?")), + HTML::br(), HTML::em(_("(Currently not working)")) + ); } $header->pushContent(HTML::hr()); return $header; diff --git a/lib/plugin/WikiAdminSetAclSimple.php b/lib/plugin/WikiAdminSetAclSimple.php index d2af9592d..e8fe809cb 100644 --- a/lib/plugin/WikiAdminSetAclSimple.php +++ b/lib/plugin/WikiAdminSetAclSimple.php @@ -32,17 +32,20 @@ require_once 'lib/plugin/WikiAdminSetAcl.php'; class WikiPlugin_WikiAdminSetAclSimple -extends WikiPlugin_WikiAdminSetAcl + extends WikiPlugin_WikiAdminSetAcl { - function getName() { + function getName() + { return _("WikiAdminSetAclSimple"); } - function getDescription() { + function getDescription() + { return _("Set simple individual page permissions."); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { if ($request->getArg('action') != 'browse') { if ($request->getArg('action') != _("PhpWikiAdministration/SetAclSimple")) { return $this->disabled(_("Plugin not run: not in browse mode")); @@ -65,7 +68,8 @@ extends WikiPlugin_WikiAdminSetAcl $pages = $this->_list; $header = HTML::fieldset(); if ($p && $request->isPost() && - (!empty($post_args['aclliberal']) || !empty($post_args['aclrestricted']))) { + (!empty($post_args['aclliberal']) || !empty($post_args['aclrestricted'])) + ) { // without individual PagePermissions: if (!ENABLE_PAGEPERM and !$request->_user->isAdmin()) { $request->_notAuthorized(WIKIAUTH_ADMIN); @@ -82,10 +86,10 @@ extends WikiPlugin_WikiAdminSetAcl $pages = $this->collectPages($pages, $dbi, $args['sortby'], $args['limit'], $args['exclude']); } $pagelist = new PageList_Selectable($args['info'], - $args['exclude'], - array('types' => array( - 'acl' - => new _PageList_Column_acl('acl', _("ACL"))))); + $args['exclude'], + array('types' => array( + 'acl' + => new _PageList_Column_acl('acl', _("ACL"))))); $pagelist->addPageList($pages); $button_label_liberal = _("Set Liberal Access Rights"); @@ -94,19 +98,19 @@ extends WikiPlugin_WikiAdminSetAcl $header->pushContent(HTML::legend(_("Select the pages where to change access rights"))); $buttons = HTML::p(Button('submit:admin_setacl[aclliberal]', $button_label_liberal, 'wikiadmin'), - Button('submit:admin_setacl[aclrestricted]', $button_label_restrictive, 'wikiadmin')); + Button('submit:admin_setacl[aclrestricted]', $button_label_restrictive, 'wikiadmin')); $header->pushContent($buttons); return HTML::form(array('action' => $request->getPostURL(), - 'method' => 'post'), - $header, - $pagelist->getContent(), - HiddenInputs($request->getArgs(), - false, - array('admin_setacl')), - ENABLE_PAGEPERM - ? '' - : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN))); + 'method' => 'post'), + $header, + $pagelist->getContent(), + HiddenInputs($request->getArgs(), + false, + array('admin_setacl')), + ENABLE_PAGEPERM + ? '' + : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN))); } /* @@ -116,20 +120,21 @@ extends WikiPlugin_WikiAdminSetAcl * _OWNER: remove purge dump change; */ - function liberalPerms() { - - $perm = array('view' => array(ACL_EVERY => true), - 'edit' => array(ACL_EVERY => true), - 'create' => array(ACL_EVERY => true), - 'list' => array(ACL_EVERY => true), - 'remove' => array(ACL_ADMIN => true, - ACL_OWNER => true), - 'purge' => array(ACL_ADMIN => true, - ACL_OWNER => true), - 'dump' => array(ACL_ADMIN => true, - ACL_OWNER => true), - 'change' => array(ACL_ADMIN => true, - ACL_OWNER => true)); + function liberalPerms() + { + + $perm = array('view' => array(ACL_EVERY => true), + 'edit' => array(ACL_EVERY => true), + 'create' => array(ACL_EVERY => true), + 'list' => array(ACL_EVERY => true), + 'remove' => array(ACL_ADMIN => true, + ACL_OWNER => true), + 'purge' => array(ACL_ADMIN => true, + ACL_OWNER => true), + 'dump' => array(ACL_ADMIN => true, + ACL_OWNER => true), + 'change' => array(ACL_ADMIN => true, + ACL_OWNER => true)); return $perm; } @@ -141,38 +146,42 @@ extends WikiPlugin_WikiAdminSetAcl * _EVERY: -view -edit -list -create; */ - function restrictedPerms() { - - $perm = array('view' => array(ACL_AUTHENTICATED => true, - ACL_EVERY => false), - 'edit' => array(ACL_AUTHENTICATED => true, - ACL_EVERY => false), - 'create' => array(ACL_AUTHENTICATED => true, - ACL_EVERY => false), - 'list' => array(ACL_AUTHENTICATED => true, - ACL_EVERY => false), - 'remove' => array(ACL_ADMIN => true, - ACL_OWNER => true), - 'purge' => array(ACL_ADMIN => true, - ACL_OWNER => true), - 'dump' => array(ACL_ADMIN => true, - ACL_OWNER => true), - 'change' => array(ACL_ADMIN => true, - ACL_OWNER => true)); + function restrictedPerms() + { + + $perm = array('view' => array(ACL_AUTHENTICATED => true, + ACL_EVERY => false), + 'edit' => array(ACL_AUTHENTICATED => true, + ACL_EVERY => false), + 'create' => array(ACL_AUTHENTICATED => true, + ACL_EVERY => false), + 'list' => array(ACL_AUTHENTICATED => true, + ACL_EVERY => false), + 'remove' => array(ACL_ADMIN => true, + ACL_OWNER => true), + 'purge' => array(ACL_ADMIN => true, + ACL_OWNER => true), + 'dump' => array(ACL_ADMIN => true, + ACL_OWNER => true), + 'change' => array(ACL_ADMIN => true, + ACL_OWNER => true)); return $perm; } - function setaclForm(&$header, $pagehash) { + function setaclForm(&$header, $pagehash) + { $pages = array(); foreach ($pagehash as $name => $checked) { - if ($checked) $pages[] = $name; + if ($checked) $pages[] = $name; } - $header->pushContent(HTML::strong(_("Selected Pages: ")), HTML::tt(join(', ',$pages)), HTML::br()); + $header->pushContent(HTML::strong(_("Selected Pages: ")), HTML::tt(join(', ', $pages)), HTML::br()); return $header; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/WikiAdminSetExternal.php b/lib/plugin/WikiAdminSetExternal.php index 1c965c039..ffe761d5c 100644 --- a/lib/plugin/WikiAdminSetExternal.php +++ b/lib/plugin/WikiAdminSetExternal.php @@ -29,28 +29,32 @@ require_once 'lib/PageList.php'; require_once 'lib/plugin/WikiAdminSelect.php'; class WikiPlugin_WikiAdminSetExternal -extends WikiPlugin_WikiAdminSelect + extends WikiPlugin_WikiAdminSelect { - function getName() { + function getName() + { return _("WikiAdminSetExternal"); } - function getDescription() { + function getDescription() + { return _("Mark selected pages as external."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array_merge - ( - WikiPlugin_WikiAdminSelect::getDefaultArguments(), - array( - 'external' => 1, - /* Columns to include in listing */ - 'info' => 'pagename,external,mtime', - )); + ( + WikiPlugin_WikiAdminSelect::getDefaultArguments(), + array( + 'external' => 1, + /* Columns to include in listing */ + 'info' => 'pagename,external,mtime', + )); } - function setExternalPages(&$dbi, &$request, $pages) { + function setExternalPages(&$dbi, &$request, $pages) + { $result = HTML::div(); $ul = HTML::ul(); $count = 0; @@ -64,7 +68,7 @@ extends WikiPlugin_WikiAdminSelect if (!mayAccessPage('change', $name)) { $result->setAttr('class', 'error'); $result->pushContent(HTML::p(fmt("Access denied to change page '%s'.", - WikiLink($name)))); + WikiLink($name)))); } else { $version = $current->getVersion(); $page->set('external', (bool)1); @@ -90,7 +94,8 @@ extends WikiPlugin_WikiAdminSelect } } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { if ($request->getArg('action') != 'browse') { if (!$request->getArg('action') == _("PhpWikiAdministration/SetExternal")) { return $this->disabled(_("Plugin not run: not in browse mode")); @@ -110,7 +115,8 @@ extends WikiPlugin_WikiAdminSelect if ($p && !$request->isPost()) $pages = $p; if ($p && $request->isPost() && - !empty($post_args['button']) && empty($post_args['cancel'])) { + !empty($post_args['button']) && empty($post_args['cancel']) + ) { // without individual PagePermissions: if (!ENABLE_PAGEPERM and !$request->_user->isAdmin()) { $request->_notAuthorized(WIKIAUTH_ADMIN); @@ -128,19 +134,19 @@ extends WikiPlugin_WikiAdminSelect $header->pushContent(HTML::legend(_("Select the pages to set as external"))); $buttons = HTML::p(Button('submit:admin_external[button]', $button_label, 'wikiadmin'), - Button('submit:admin_external[cancel]', _("Cancel"), 'button')); + Button('submit:admin_external[cancel]', _("Cancel"), 'button')); $header->pushContent($buttons); return HTML::form(array('action' => $request->getPostURL(), - 'method' => 'post'), - $header, - $pagelist->getContent(), - HiddenInputs($request->getArgs(), - false, - array('admin_external')), - ENABLE_PAGEPERM - ? '' - : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN))); + 'method' => 'post'), + $header, + $pagelist->getContent(), + HiddenInputs($request->getArgs(), + false, + array('admin_external')), + ENABLE_PAGEPERM + ? '' + : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN))); } } diff --git a/lib/plugin/WikiAdminUtils.php b/lib/plugin/WikiAdminUtils.php index e3e7db5c8..4e2afd169 100644 --- a/lib/plugin/WikiAdminUtils.php +++ b/lib/plugin/WikiAdminUtils.php @@ -22,34 +22,38 @@ */ /** - valid actions: - purge-cache - purge-bad-pagenames - purge-empty-pages - access-restrictions - email-verification - convert-cached-html - db-check - db-rebuild +valid actions: +purge-cache +purge-bad-pagenames +purge-empty-pages +access-restrictions +email-verification +convert-cached-html +db-check +db-rebuild */ class WikiPlugin_WikiAdminUtils -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("WikiAdminUtils"); } - function getDescription () { + function getDescription() + { return _("Miscellaneous utility functions for the Administrator."); } - function getDefaultArguments() { - return array('action' => '', - 'label' => '', - ); + function getDefaultArguments() + { + return array('action' => '', + 'label' => '', + ); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); $args['action'] = strtolower($args['action']); extract($args); @@ -80,18 +84,20 @@ extends WikiPlugin return $this->_makeButton($request, $args, $label); } - function _makeButton(&$request, $args, $label) { + function _makeButton(&$request, $args, $label) + { $args['return_url'] = $request->getURLtoSelf(); return HTML::form(array('action' => $request->getPostURL(), - 'method' => 'post'), - HTML::p(Button('submit:', $label, 'wikiadmin')), - HiddenInputs($args, 'wikiadminutils'), - HiddenInputs(array('require_authority_for_post' => - WIKIAUTH_ADMIN)), - HiddenInputs($request->getArgs(),false,array('action'))); + 'method' => 'post'), + HTML::p(Button('submit:', $label, 'wikiadmin')), + HiddenInputs($args, 'wikiadminutils'), + HiddenInputs(array('require_authority_for_post' => + WIKIAUTH_ADMIN)), + HiddenInputs($request->getArgs(), false, array('action'))); } - function do_action(&$request, $args) { + function do_action(&$request, $args) + { $method = strtolower('_do_' . str_replace('-', '_', $args['action'])); if (!method_exists($this, $method)) return $this->error("Bad action $method"); @@ -100,25 +106,27 @@ extends WikiPlugin // display as seperate page or as alert? $alert = new Alert(fmt("WikiAdminUtils %s returned:", $args['action']), - $message, - array(_("Back") => $args['return_url'])); - $alert->show(); // noreturn + $message, + array(_("Back") => $args['return_url'])); + $alert->show(); // noreturn } - function _getLabel($action) { - $labels = array('purge-cache' => _("Purge Markup Cache"), - 'purge-bad-pagenames' => _("Purge all Pages With Invalid Names"), - 'purge-empty-pages' => _("Purge all empty, unreferenced Pages"), - 'access-restrictions' => _("Access Restrictions"), - 'email-verification' => _("E-mail address confirmation"), - 'convert-cached-html' => _("Convert cached_html"), - 'db-check' => _("DB Check"), - 'db-rebuild' => _("Db Rebuild") - ); + function _getLabel($action) + { + $labels = array('purge-cache' => _("Purge Markup Cache"), + 'purge-bad-pagenames' => _("Purge all Pages With Invalid Names"), + 'purge-empty-pages' => _("Purge all empty, unreferenced Pages"), + 'access-restrictions' => _("Access Restrictions"), + 'email-verification' => _("E-mail address confirmation"), + 'convert-cached-html' => _("Convert cached_html"), + 'db-check' => _("DB Check"), + 'db-rebuild' => _("Db Rebuild") + ); return @$labels[$action]; } - function _do_purge_cache(&$request, $args) { + function _do_purge_cache(&$request, $args) + { $dbi = $request->getDbh(); $pages = $dbi->getAllPages('include_empty'); // Do we really want the empty ones too? while (($page = $pages->next())) { @@ -127,16 +135,17 @@ extends WikiPlugin return _("Markup cache purged!"); } - function _do_purge_bad_pagenames(&$request, $args) { + function _do_purge_bad_pagenames(&$request, $args) + { // FIXME: this should be moved into WikiDB::normalize() or something... $dbi = $request->getDbh(); $count = 0; - $list = HTML::ol(array('align'=>'left')); + $list = HTML::ol(array('align' => 'left')); $pages = $dbi->getAllPages('include_empty'); // Do we really want the empty ones too? while (($page = $pages->next())) { $pagename = $page->getName(); $wpn = new WikiPageName($pagename); - if (! $wpn->isValid() ) { + if (!$wpn->isValid()) { $dbi->purgePage($pagename); $list->pushContent(HTML::li($pagename)); $count++; @@ -147,29 +156,31 @@ extends WikiPlugin return _("No pages with bad names had to be deleted."); else { return HTML(fmt("Deleted %d pages with invalid names:", $count), - HTML::div(array('align'=>'left'), $list)); + HTML::div(array('align' => 'left'), $list)); } } /** * Purge all non-referenced empty pages. Mainly those created by bad link extraction. */ - function _do_purge_empty_pages(&$request, $args) { + function _do_purge_empty_pages(&$request, $args) + { $dbi = $request->getDbh(); - $count = 0; $notpurgable = 0; - $list = HTML::ol(array('align'=>'left')); + $count = 0; + $notpurgable = 0; + $list = HTML::ol(array('align' => 'left')); $pages = $dbi->getAllPages('include_empty'); while (($page = $pages->next())) { if (!$page->exists() and ($links = $page->getBackLinks('include_empty')) - and !$links->next()) - { + and !$links->next() + ) { $pagename = $page->getName(); if ($pagename == 'global_data' or $pagename == '.') continue; if ($dbi->purgePage($pagename)) - $list->pushContent(HTML::li($pagename.' '._("[purged]"))); + $list->pushContent(HTML::li($pagename . ' ' . _("[purged]"))); else { - $list->pushContent(HTML::li($pagename.' '._("[not purgable]"))); + $list->pushContent(HTML::li($pagename . ' ' . _("[not purgable]"))); $notpurgable++; } $count++; @@ -180,14 +191,15 @@ extends WikiPlugin return _("No empty, unreferenced pages were found."); else return HTML(fmt("Deleted %d unreferenced pages:", $count), - HTML::div(array('align'=>'left'), $list), - ($notpurgable ? - fmt("The %d not-purgable pages/links are links in some page(s). You might want to edit them.", - $notpurgable) - : '')); + HTML::div(array('align' => 'left'), $list), + ($notpurgable ? + fmt("The %d not-purgable pages/links are links in some page(s). You might want to edit them.", + $notpurgable) + : '')); } - function _do_convert_cached_html(&$request, $args) { + function _do_convert_cached_html(&$request, $args) + { require_once 'lib/upgrade.php'; $dbh = $request->_dbi; @@ -199,18 +211,20 @@ extends WikiPlugin return _("No old _cached_html pagedata found."); else { return HTML(fmt("Converted successfully %d pages", $count), - HTML::div(array('align'=>'left'), $list)); + HTML::div(array('align' => 'left'), $list)); } } - function _do_db_check(&$request, $args) { + function _do_db_check(&$request, $args) + { longer_timeout(180); $dbh = $request->getDbh(); //FIXME: display result. return $dbh->_backend->check($args); } - function _do_db_rebuild(&$request, $args) { + function _do_db_rebuild(&$request, $args) + { longer_timeout(240); $dbh = $request->getDbh(); //FIXME: display result. @@ -219,18 +233,20 @@ extends WikiPlugin //TODO: We need a seperate plugin for this. // Too many options. - function _do_access_restrictions(&$request, &$args) { - return _("Sorry. Access Restrictions not yet implemented"); + function _do_access_restrictions(&$request, &$args) + { + return _("Sorry. Access Restrictions not yet implemented"); } // pagelist with enable/disable button - function _do_email_verification(&$request, &$args) { + function _do_email_verification(&$request, &$args) + { $dbi = $request->getDbh(); - $pagelist = new PageList('pagename',0,$args); + $pagelist = new PageList('pagename', 0, $args); //$args['return_url'] = 'action=email-verification-verified'; - $email = new _PageList_Column_email('email',_("E-mail"),'left'); + $email = new _PageList_Column_email('email', _("E-mail"), 'left'); $emailVerified = new _PageList_Column_emailVerified('emailVerified', - _("Verification Status"),'center'); + _("Verification Status"), 'center'); $pagelist->_columns[0]->_heading = _("Username"); $pagelist->_columns[] = $email; $pagelist->_columns[] = $emailVerified; @@ -252,8 +268,8 @@ extends WikiPlugin $user = new WikiUser($request, $username); $prefs = $user->getPreferences(); if ($prefs->get('email')) { - if (!$prefs->get('userid')) - $prefs->set('userid',$username); + if (!$prefs->get('userid')) + $prefs->set('userid', $username); if (!empty($pagelist->_rows)) $group = (int)(count($pagelist->_rows) / $pagelist->_group_rows); else @@ -262,11 +278,11 @@ extends WikiPlugin $row = HTML::tr(array('class' => $class)); $page_handle = $dbi->getPage($username); $row->pushContent($pagelist->_columns[0]->format($pagelist, - $page_handle, $page_handle)); + $page_handle, $page_handle)); $row->pushContent($email->format($pagelist, $prefs, $page_handle)); if (!empty($args['verify'])) { $prefs->_prefs['email']->set('emailVerified', - empty($args['verified'][$username]) ? 0 : true); + empty($args['verified'][$username]) ? 0 : true); $user->setPreferences($prefs); } $row->pushContent($emailVerified->format($pagelist, $prefs, $args['verify'])); @@ -280,45 +296,51 @@ extends WikiPlugin $args['verify'] = 1; $args['return_url'] = $request->getURLtoSelf(); return HTML::form(array('action' => $request->getPostURL(), - 'method' => 'post'), - HiddenInputs($args, 'wikiadminutils'), - HiddenInputs(array('require_authority_for_post' => - WIKIAUTH_ADMIN)), - HiddenInputs($request->getArgs()), - $pagelist->_generateTable(false), - HTML::p(Button('submit:', _("Change Verification Status"), - 'wikiadmin'), - HTML::Raw(' '), - Button('cancel', _("Cancel"))) - ); + 'method' => 'post'), + HiddenInputs($args, 'wikiadminutils'), + HiddenInputs(array('require_authority_for_post' => + WIKIAUTH_ADMIN)), + HiddenInputs($request->getArgs()), + $pagelist->_generateTable(false), + HTML::p(Button('submit:', _("Change Verification Status"), + 'wikiadmin'), + HTML::Raw(' '), + Button('cancel', _("Cancel"))) + ); } } -}; +} + +; require_once 'lib/PageList.php'; class _PageList_Column_email -extends _PageList_Column { - function _getValue (&$prefs, $dummy) { + extends _PageList_Column +{ + function _getValue(&$prefs, $dummy) + { return $prefs->get('email'); } } class _PageList_Column_emailVerified -extends _PageList_Column { - function _getValue (&$prefs, $status) { - $name = $prefs->get('userid'); - $input = HTML::input(array('type' => 'checkbox', - 'name' => 'wikiadminutils[verified]['.$name.']', - 'value' => 1)); - if ($prefs->get('emailVerified')) - $input->setAttr('checked','1'); + extends _PageList_Column +{ + function _getValue(&$prefs, $status) + { + $name = $prefs->get('userid'); + $input = HTML::input(array('type' => 'checkbox', + 'name' => 'wikiadminutils[verified][' . $name . ']', + 'value' => 1)); + if ($prefs->get('emailVerified')) + $input->setAttr('checked', '1'); if ($status) - $input->setAttr('disabled','1'); - return HTML($input, HTML::input - (array('type' => 'hidden', - 'name' => 'wikiadminutils[user]['.$name.']', - 'value' => $name))); + $input->setAttr('disabled', '1'); + return HTML($input, HTML::input + (array('type' => 'hidden', + 'name' => 'wikiadminutils[user][' . $name . ']', + 'value' => $name))); } } diff --git a/lib/plugin/WikiBlog.php b/lib/plugin/WikiBlog.php index 533bd1eb5..a07549b01 100644 --- a/lib/plugin/WikiBlog.php +++ b/lib/plugin/WikiBlog.php @@ -81,14 +81,16 @@ require_once 'lib/TextSearchQuery.php'; */ class WikiPlugin_WikiBlog -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("WikiBlog"); } - function getDescription () { - return sprintf(_("Show and add blogs for %s"),'[pagename]'); + function getDescription() + { + return sprintf(_("Show and add blogs for %s"), '[pagename]'); } // Arguments: @@ -111,15 +113,17 @@ extends WikiPlugin // display as e.g. June 2002 archive, July 2002 archive, etc.. // - captions for 'show' and 'add' sections - function getDefaultArguments() { - return array('pagename' => '[pagename]', - 'order' => 'normal', - 'mode' => 'show,add', - 'noheader' => false - ); + function getDefaultArguments() + { + return array('pagename' => '[pagename]', + 'order' => 'normal', + 'mode' => 'show,add', + 'noheader' => false + ); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); // allow empty pagenames for ADMIN_USER style blogs: "Blog/day" //if (!$args['pagename']) @@ -143,14 +147,14 @@ extends WikiPlugin $seen[$show] = 1; switch ($show) { - case 'show': - $html->pushContent($this->showAll($request, $args)); - break; - case 'add': - $html->pushContent($this->showForm($request, $args)); - break; - default: - return $this->error(sprintf("Bad mode ('%s')", $show)); + case 'show': + $html->pushContent($this->showAll($request, $args)); + break; + case 'add': + $html->pushContent($this->showForm($request, $args)); + break; + default: + return $this->error(sprintf("Bad mode ('%s')", $show)); } } return $html; @@ -159,22 +163,20 @@ extends WikiPlugin /** * posted: required: pagename, content. optional: summary */ - function add (&$request, $posted, $type='wikiblog') { + function add(&$request, $posted, $type = 'wikiblog') + { // This is similar to editpage. Shouldn't we use just this for preview? $parent = $posted['pagename']; if (empty($parent)) { - $prefix = ""; // allow empty parent for default "Blog/day" + $prefix = ""; // allow empty parent for default "Blog/day" $parent = HOME_PAGE; - } elseif (($parent == 'Blog' or $parent == 'WikiBlog') and $type == 'wikiblog') - { // avoid Blog/Blog/2003-01-11/14:03:02+00:00 + } elseif (($parent == 'Blog' or $parent == 'WikiBlog') and $type == 'wikiblog') { // avoid Blog/Blog/2003-01-11/14:03:02+00:00 $prefix = ""; $parent = ''; // 'Blog'; - } elseif ($parent == 'Comment' and $type == "comment") - { + } elseif ($parent == 'Comment' and $type == "comment") { $prefix = ""; $parent = ''; // 'Comment'; - } elseif ($parent == 'Forum' and $type == "wikiforum") - { + } elseif ($parent == 'Forum' and $type == "wikiforum") { $prefix = ""; $parent = ''; // 'Forum'; } else { @@ -199,25 +201,25 @@ extends WikiPlugin * updates are atomic with the version creation. */ - $blog_meta = array('ctime' => $now, - 'creator' => $user->getId(), - 'creator_id' => $user->getAuthenticatedId(), - ); + $blog_meta = array('ctime' => $now, + 'creator' => $user->getId(), + 'creator_id' => $user->getAuthenticatedId(), + ); // Version meta-data $summary = trim($posted['summary']); // edit: private only $perm = new PagePermission(); $perm->perm['edit'] = $perm->perm['remove']; - $version_meta = array('author' => $blog_meta['creator'], - 'author_id' => $blog_meta['creator_id'], - 'markup' => 2.0, // assume new markup - 'summary' => $summary ? $summary : _("New comment."), - 'mtime' => $now, - 'pagetype' => $type, - $type => $blog_meta, - 'perm' => $perm->perm, - ); + $version_meta = array('author' => $blog_meta['creator'], + 'author_id' => $blog_meta['creator_id'], + 'markup' => 2.0, // assume new markup + 'summary' => $summary ? $summary : _("New comment."), + 'mtime' => $now, + 'pagetype' => $type, + $type => $blog_meta, + 'perm' => $perm->perm, + ); if ($type == 'comment') unset($version_meta['summary']); @@ -228,7 +230,7 @@ extends WikiPlugin if ($type != 'wikiforum') $pagename = $this->_blogPrefix($type); else { - $pagename = substr($summary,0,12); + $pagename = substr($summary, 0, 12); if (empty($pagename)) { $saved = true; trigger_error("Empty title", E_USER_WARNING); @@ -247,29 +249,29 @@ extends WikiPlugin // Maybe add the BlogArchives plugin instead for the new interim subpage. $redirected = $prefix . $pagename; if (!$dbi->isWikiPage($redirected)) { - if (!$parent) $parent = HOME_PAGE; + if (!$parent) $parent = HOME_PAGE; require_once 'lib/loadsave.php'; $pageinfo = array('pagename' => $redirected, - 'content' => '', - 'pagedata' => array(), - 'versiondata' => array('author' => $blog_meta['creator'], 'is_minor_edit' => 1), - ); + 'content' => '', + 'pagedata' => array(), + 'versiondata' => array('author' => $blog_meta['creator'], 'is_minor_edit' => 1), + ); SavePage($request, $pageinfo, '', ''); } $redirected = $prefix . $pagename . SUBPAGE_SEPARATOR . preg_replace("/T.*/", "", "$time"); if (!$dbi->isWikiPage($redirected)) { - if (!$parent) $parent = HOME_PAGE; + if (!$parent) $parent = HOME_PAGE; require_once 'lib/loadsave.php'; $pageinfo = array('pagename' => $redirected, - 'content' => '', - 'pagedata' => array(), - 'versiondata' => array('author' => $blog_meta['creator'], 'is_minor_edit' => 1), - ); + 'content' => '', + 'pagedata' => array(), + 'versiondata' => array('author' => $blog_meta['creator'], 'is_minor_edit' => 1), + ); SavePage($request, $pageinfo, '', ''); } $p = $dbi->getPage($prefix . $pagename . SUBPAGE_SEPARATOR - . str_replace("T", SUBPAGE_SEPARATOR, "$time")); + . str_replace("T", SUBPAGE_SEPARATOR, "$time")); $pr = $p->getCurrentRevision(); // Version should be zero. If not, page already exists @@ -298,7 +300,8 @@ extends WikiPlugin // Any way to jump back to preview mode??? } - function showAll (&$request, $args, $type="wikiblog") { + function showAll(&$request, $args, $type = "wikiblog") + { // FIXME: currently blogSearch uses WikiDB->titleSearch to // get results, so results are in alphabetical order. // When PageTypes fully implemented, could have smarter @@ -311,20 +314,19 @@ extends WikiPlugin if ($blogs) { // First reorder usort($blogs, array("WikiPlugin_WikiBlog", - "cmp")); + "cmp")); if ($args['order'] == 'reverse') $blogs = array_reverse($blogs); $name = $this->_blogPrefix($type); if (!$args['noheader']) $html->pushContent(HTML::h4(array('class' => "$type-heading"), - fmt("%s on %s:", $name, WikiLink($basepage)))); + fmt("%s on %s:", $name, WikiLink($basepage)))); foreach ($blogs as $rev) { if (!$rev->get($type)) { // Ack! this is an old-style blog with data ctime in page meta-data. $content = $this->_transformOldFormatBlog($rev, $type); - } - else { + } else { $content = $rev->getTransformedContent($type); } $html->pushContent($content); @@ -336,18 +338,19 @@ extends WikiPlugin // Subpage for the basepage. All Blogs/Forum/Comment entries are // Subpages under this pagename, to find them faster. - function _blogPrefix($type='wikiblog') { + function _blogPrefix($type = 'wikiblog') + { if ($type == 'wikiblog') $basepage = "Blog"; elseif ($type == 'comment') - $basepage = "Comment"; - elseif ($type == 'wikiforum') - $basepage = substr($summary,0,12); - //$basepage = _("Message"); // FIXME: we use now the first 12 chars of the summary + $basepage = "Comment"; elseif ($type == 'wikiforum') + $basepage = substr($summary, 0, 12); + //$basepage = _("Message"); // FIXME: we use now the first 12 chars of the summary return $basepage; } - function _transformOldFormatBlog($rev, $type='wikiblog') { + function _transformOldFormatBlog($rev, $type = 'wikiblog') + { $page = $rev->getPage(); $metadata = array(); foreach (array('ctime', 'creator', 'creator_id') as $key) @@ -359,11 +362,12 @@ extends WikiPlugin return new TransformedText($page, $rev->getPackedContent(), $meta, $type); } - function findBlogs (&$dbi, $basepage='', $type='wikiblog') { + function findBlogs(&$dbi, $basepage = '', $type = 'wikiblog') + { $prefix = (empty($basepage) - ? "" - : $basepage . SUBPAGE_SEPARATOR) . $this->_blogPrefix($type); - $pages = $dbi->titleSearch(new TextSearchQuery('"'.$prefix.'"', true, 'none')); + ? "" + : $basepage . SUBPAGE_SEPARATOR) . $this->_blogPrefix($type); + $pages = $dbi->titleSearch(new TextSearchQuery('"' . $prefix . '"', true, 'none')); $blogs = array(); while ($page = $pages->next()) { @@ -377,16 +381,18 @@ extends WikiPlugin return $blogs; } - function cmp($a, $b) { - return(strcmp($a->get('mtime'), - $b->get('mtime'))); + function cmp($a, $b) + { + return (strcmp($a->get('mtime'), + $b->get('mtime'))); } - function showForm (&$request, $args, $template='blogform') { + function showForm(&$request, $args, $template = 'blogform') + { // Show blog-entry form. $args = array('PAGENAME' => $args['pagename'], - 'HIDDEN_INPUTS' => - HiddenInputs($request->getArgs())); + 'HIDDEN_INPUTS' => + HiddenInputs($request->getArgs())); if (ENABLE_EDIT_TOOLBAR and !ENABLE_WYSIWYG and ($template != 'addcomment')) { include_once 'lib/EditToolbar.php'; $toolbar = new EditToolbar(); @@ -396,32 +402,37 @@ extends WikiPlugin } // "2004-12" => "December 2004" - function _monthTitle($month){ - if (!$month) $month = strftime("%Y-%m"); + function _monthTitle($month) + { + if (!$month) $month = strftime("%Y-%m"); //list($year,$mon) = explode("-",$month); - return strftime("%B %Y", strtotime($month."-01")); + return strftime("%B %Y", strtotime($month . "-01")); } // "UserName/Blog/2004-12-13/12:28:50+01:00" => array('month' => "2004-12", ...) - function _blog($rev_or_page) { - $pagename = $rev_or_page->getName(); + function _blog($rev_or_page) + { + $pagename = $rev_or_page->getName(); if (preg_match("/^(.*Blog)\/(\d\d\d\d-\d\d)-(\d\d)\/(.*)/", $pagename, $m)) - list(,$prefix,$month,$day,$time) = $m; + list(, $prefix, $month, $day, $time) = $m; return array('pagename' => $pagename, - // page (list pages per month) or revision (list months)? - //'title' => isa($rev_or_page,'WikiDB_PageRevision') ? $rev_or_page->get('summary') : '', - //'monthtitle' => $this->_monthTitle($month), - 'month' => $month, - 'day' => $day, - 'time' => $time, - 'prefix' => $prefix); + // page (list pages per month) or revision (list months)? + //'title' => isa($rev_or_page,'WikiDB_PageRevision') ? $rev_or_page->get('summary') : '', + //'monthtitle' => $this->_monthTitle($month), + 'month' => $month, + 'day' => $day, + 'time' => $time, + 'prefix' => $prefix); } - function _nonDefaultArgs($args) { - return array_diff_assoc($args, $this->getDefaultArguments()); + function _nonDefaultArgs($args) + { + return array_diff_assoc($args, $this->getDefaultArguments()); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/WikiForm.php b/lib/plugin/WikiForm.php index bf1f0af21..4512298a5 100644 --- a/lib/plugin/WikiForm.php +++ b/lib/plugin/WikiForm.php @@ -26,76 +26,80 @@ * encoded with the phpwiki: syntax. */ class WikiPlugin_WikiForm -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("WikiForm"); } - function getDescription () { + function getDescription() + { return _("Provide generic WikiForm input buttons"); } - function getDefaultArguments() { + function getDefaultArguments() + { return array('action' => 'upload', // 'upload', 'loadfile', - // 'dumphtml' or 'dumpserial' - 'default' => false, - 'buttontext' => false, - 'overwrite' => false, - 'size' => 50); + // 'dumphtml' or 'dumpserial' + 'default' => false, + 'buttontext' => false, + 'overwrite' => false, + 'size' => 50); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { extract($this->getArgs($argstr, $request)); $form = HTML::form(array('action' => $request->getPostURL(), - 'method' => 'post', - 'class' => 'wikiadmin', - 'accept-charset' => $GLOBALS['charset']), - HiddenInputs(array('action' => $action, - 'overwrite' => $overwrite, - 'pagename' => $basepage))); + 'method' => 'post', + 'class' => 'wikiadmin', + 'accept-charset' => $GLOBALS['charset']), + HiddenInputs(array('action' => $action, + 'overwrite' => $overwrite, + 'pagename' => $basepage))); $input = array('type' => 'text', - 'value' => $default, - 'size' => $size); + 'value' => $default, + 'size' => $size); switch ($action) { - case 'loadfile': - $input['name'] = 'source'; - if (!$default) - $input['value'] = DEFAULT_DUMP_DIR; - if (!$buttontext) - $buttontext = _("Load File"); - $class = false; - break; - case 'dumpserial': - $input['name'] = 'directory'; - if (!$default) - $input['value'] = DEFAULT_DUMP_DIR; - if (!$buttontext) - $buttontext = _("Dump Pages"); - $class = 'wikiadmin'; - break; - case 'dumphtml': - $input['name'] = 'directory'; - if (!$default) - $input['value'] = HTML_DUMP_DIR; - if (!$buttontext) - $buttontext = _("Dump Pages as XHTML"); - $class = 'wikiadmin'; - break; - case 'upload': - $form->setAttr('enctype', 'multipart/form-data'); - $form->pushContent(HTML::input(array('name' => 'MAX_FILE_SIZE', - 'value' => MAX_UPLOAD_SIZE, - 'type' => 'hidden'))); - $input['name'] = 'file'; - $input['type'] = 'file'; - if (!$buttontext) - $buttontext = _("Upload"); - $class = false; // local OS function, so use native OS button - break; - default: - return HTML::div(array('class' => "error"), fmt("WikiForm: %s: unknown action", $action)); + case 'loadfile': + $input['name'] = 'source'; + if (!$default) + $input['value'] = DEFAULT_DUMP_DIR; + if (!$buttontext) + $buttontext = _("Load File"); + $class = false; + break; + case 'dumpserial': + $input['name'] = 'directory'; + if (!$default) + $input['value'] = DEFAULT_DUMP_DIR; + if (!$buttontext) + $buttontext = _("Dump Pages"); + $class = 'wikiadmin'; + break; + case 'dumphtml': + $input['name'] = 'directory'; + if (!$default) + $input['value'] = HTML_DUMP_DIR; + if (!$buttontext) + $buttontext = _("Dump Pages as XHTML"); + $class = 'wikiadmin'; + break; + case 'upload': + $form->setAttr('enctype', 'multipart/form-data'); + $form->pushContent(HTML::input(array('name' => 'MAX_FILE_SIZE', + 'value' => MAX_UPLOAD_SIZE, + 'type' => 'hidden'))); + $input['name'] = 'file'; + $input['type'] = 'file'; + if (!$buttontext) + $buttontext = _("Upload"); + $class = false; // local OS function, so use native OS button + break; + default: + return HTML::div(array('class' => "error"), fmt("WikiForm: %s: unknown action", $action)); } $input = HTML::input($input); @@ -103,14 +107,16 @@ extends WikiPlugin $button = Button('submit:', $buttontext, $class); if ($request->getArg('start_debug')) $form->pushContent(HTML::input(array('name' => 'start_debug', - 'value' => $request->getArg('start_debug'), - 'type' => 'hidden'))); + 'value' => $request->getArg('start_debug'), + 'type' => 'hidden'))); $form->pushContent(HTML::span(array('class' => $class), - $input, $button)); + $input, $button)); return $form; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/WikiFormRich.php b/lib/plugin/WikiFormRich.php index 5fd2d4679..bef741a1a 100644 --- a/lib/plugin/WikiFormRich.php +++ b/lib/plugin/WikiFormRich.php @@ -34,7 +34,6 @@ * - submit[] * - action, submit buttontext, optional cancel button (bool) * - method=get or post, Default: post. - * Valid arguments for pulldown and editbox: autocomplete=1, Default: 0 * If autocomplete=1, additional arguments method and args may be used. * If no method is given, value will be used to fill in the valid values. @@ -44,257 +43,264 @@ * A combobox is a pulldown with autocomplete=1. * * @Author: Reini Urban - * Values which are constants are evaluated. * The cancel button must be supported by the action. * (just some wikiadmin actions so far) * improve layout by: nobr=1 * some allow values as list from from - Samples: - <> - <> - <> - <> - <> - < - < - ?> - < - ?> - < - ?> - < - < -*/ +Samples: +<> +<> +<> +<> +<> +< +< +?> +< +?> +< +?> +< +< + */ class WikiPlugin_WikiFormRich -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return "WikiFormRich"; } - function getDescription () { + + function getDescription() + { return _("Provide generic WikiForm input buttons"); } - function getDefaultArguments() { - return array('action' => false, // required argument - 'method' => 'post', // or get - 'class' => 'wikiaction', - 'buttontext' => false, // for the submit button. default: action - 'cancel' => false, // boolean if the action supports cancel also - 'nobr' => false, // "no break": linebreaks or not - ); + + function getDefaultArguments() + { + return array('action' => false, // required argument + 'method' => 'post', // or get + 'class' => 'wikiaction', + 'buttontext' => false, // for the submit button. default: action + 'cancel' => false, // boolean if the action supports cancel also + 'nobr' => false, // "no break": linebreaks or not + ); } /* TODO: support better block alignment:
                  , tables, indent */ - function handle_plugin_args_cruft($argstr, $args) { - $allowed = array("editbox", "hidden", "checkbox", "radiobutton"/*deprecated*/, - "radio", "pulldown", "submit", "reset", "combobox"); - // no editbox[] = array(...) allowed (space) - $arg_array = preg_split("/\n/", $argstr); - // for security we should check this better + function handle_plugin_args_cruft($argstr, $args) + { + $allowed = array("editbox", "hidden", "checkbox", "radiobutton" /*deprecated*/, + "radio", "pulldown", "submit", "reset", "combobox"); + // no editbox[] = array(...) allowed (space) + $arg_array = preg_split("/\n/", $argstr); + // for security we should check this better $arg = ''; - for ($i = 0; $i < count($arg_array); $i++) { - //TODO: we require an name=value pair here, but submit may go without also. - if (preg_match("/^\s*(".join("|",$allowed).")\[\](.*)$/", $arg_array[$i], $m)) { - $name = $m[1]; // one of the allowed input types - $this->inputbox[][$name] = array(); $j = count($this->inputbox) - 1; + for ($i = 0; $i < count($arg_array); $i++) { + //TODO: we require an name=value pair here, but submit may go without also. + if (preg_match("/^\s*(" . join("|", $allowed) . ")\[\](.*)$/", $arg_array[$i], $m)) { + $name = $m[1]; // one of the allowed input types + $this->inputbox[][$name] = array(); + $j = count($this->inputbox) - 1; $curargs = trim($m[2]); // must match name=NAME and also value= while (preg_match("/^(\w+?)=((?:\".*?\")|(?:\w+)|(?:\"?\"?))\s*/", - $curargs, $m)) { - $attr = $m[1]; $value = $m[2]; + $curargs, $m)) { + $attr = $m[1]; + $value = $m[2]; $curargs = substr($curargs, strlen($m[0])); if (preg_match("/^\"(.*)\"$/", $value, $m)) $value = $m[1]; - if (in_array($name, array("pulldown","checkbox","radio","radiobutton","combobox")) - and preg_match('/^$/', $value, $m)) - // like pulldown[] name=test value= + if (in_array($name, array("pulldown", "checkbox", "radio", "radiobutton", "combobox")) + and preg_match('/^$/', $value, $m) + ) // like pulldown[] name=test value= { - $loader = new WikiPluginLoader(); - $markup = null; - $basepage = null; - $plugin_str = preg_replace(array("/^$/"),array(""), $value); - // will return a pagelist object! pulldown,checkbox,radiobutton - $value = $loader->expandPI($plugin_str, $GLOBALS['request'], $markup, $basepage); - if (isa($value, 'PageList')) - $value = $value->pageNames(); // apply limit - elseif (!is_array($value)) - trigger_error(sprintf("Invalid argument %s ignored", htmlentities($arg_array[$i])), - E_USER_WARNING); - } - elseif (defined($value)) + $loader = new WikiPluginLoader(); + $markup = null; + $basepage = null; + $plugin_str = preg_replace(array("/^$/"), array(""), $value); + // will return a pagelist object! pulldown,checkbox,radiobutton + $value = $loader->expandPI($plugin_str, $GLOBALS['request'], $markup, $basepage); + if (isa($value, 'PageList')) + $value = $value->pageNames(); // apply limit + elseif (!is_array($value)) + trigger_error(sprintf("Invalid argument %s ignored", htmlentities($arg_array[$i])), + E_USER_WARNING); + } elseif (defined($value)) $value = constant($value); $this->inputbox[$j][$name][$attr] = $value; } - //trigger_error("not yet finished"); + //trigger_error("not yet finished"); //eval('$this->inputbox[]["'.$m[1].'"]='.$m[2].';'); } else { - trigger_error(sprintf("Invalid argument %s ignored", htmlentities($arg_array[$i])), - E_USER_WARNING); - } + trigger_error(sprintf("Invalid argument %s ignored", htmlentities($arg_array[$i])), + E_USER_WARNING); } + } return; } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { extract($this->getArgs($argstr, $request)); if (empty($action)) { return $this->error(fmt("A required argument '%s' is missing.", "action")); } $form = HTML::form(array('action' => $request->getPostURL(), - 'method' => strtolower($method), - 'class' => 'wikiformrich', - 'accept-charset' => $GLOBALS['charset']), - HiddenInputs(array('action' => $action))); + 'method' => strtolower($method), + 'class' => 'wikiformrich', + 'accept-charset' => $GLOBALS['charset']), + HiddenInputs(array('action' => $action))); $nbsp = HTML::Raw(' '); $already_submit = 0; foreach ($this->inputbox as $inputbox) { foreach ($inputbox as $inputtype => $input) { - if ($inputtype == 'radiobutton') $inputtype = 'radio'; // convert from older versions - $input['type'] = $inputtype; - $text = ''; - if ($inputtype != 'submit') { - if (empty($input['name'])) - return $this->error(fmt("A required argument '%s' is missing.", - $inputtype."[][name]")); - if (!isset($input['text'])) $input['text'] = gettext($input['name']); - $text = $input['text']; - unset($input['text']); - } - switch($inputtype) { - case 'checkbox': // text right - case 'radio': - if (empty($input['value'])) $input['value'] = 1; - if (is_array($input['value'])) { - $div = HTML::div(array('class' => $class)); - $values = $input['value']; - $name = $input['name']; - $input['name'] = $inputtype == 'checkbox' ? $name."[]" : $name; - foreach ($values as $val) { - $input['value'] = $val; - if ($request->getArg($name)) { - if ($request->getArg($name) == $val) + if ($inputtype == 'radiobutton') $inputtype = 'radio'; // convert from older versions + $input['type'] = $inputtype; + $text = ''; + if ($inputtype != 'submit') { + if (empty($input['name'])) + return $this->error(fmt("A required argument '%s' is missing.", + $inputtype . "[][name]")); + if (!isset($input['text'])) $input['text'] = gettext($input['name']); + $text = $input['text']; + unset($input['text']); + } + switch ($inputtype) { + case 'checkbox': // text right + case 'radio': + if (empty($input['value'])) $input['value'] = 1; + if (is_array($input['value'])) { + $div = HTML::div(array('class' => $class)); + $values = $input['value']; + $name = $input['name']; + $input['name'] = $inputtype == 'checkbox' ? $name . "[]" : $name; + foreach ($values as $val) { + $input['value'] = $val; + if ($request->getArg($name)) { + if ($request->getArg($name) == $val) + $input['checked'] = 'checked'; + else + unset($input['checked']); + } + $div->pushContent(HTML::input($input), $nbsp, $val, $nbsp, "\n"); + if (!$nobr) + $div->pushContent(HTML::br()); + } + $form->pushContent($div); + } else { + if (empty($input['checked'])) { + if ($request->getArg($input['name'])) + $input['checked'] = 'checked'; + } else { $input['checked'] = 'checked'; + } + if ($nobr) + $form->pushContent(HTML::input($input), $nbsp, $text, $nbsp); else - unset($input['checked']); + $form->pushContent(HTML::div(array('class' => $class), HTML::input($input), $nbsp, $text)); } - $div->pushContent(HTML::input($input), $nbsp, $val, $nbsp, "\n"); - if (!$nobr) - $div->pushContent(HTML::br()); - } - $form->pushContent($div); - } else { - if (empty($input['checked'])) { - if ($request->getArg($input['name'])) - $input['checked'] = 'checked'; - } else { - $input['checked'] = 'checked'; - } - if ($nobr) - $form->pushContent(HTML::input($input), $nbsp, $text, $nbsp); - else - $form->pushContent(HTML::div(array('class' => $class), HTML::input($input), $nbsp, $text)); + break; + case 'editbox': // text left + $input['type'] = 'text'; + if (empty($input['value']) and ($s = $request->getArg($input['name']))) + $input['value'] = $s; + if (!empty($input['autocomplete'])) + $this->_doautocomplete($form, $inputtype, $input, $input['value']); + if ($nobr) + $form->pushContent($text, $nbsp, HTML::input($input)); + else + $form->pushContent(HTML::div(array('class' => $class), $text, $nbsp, HTML::input($input))); + break; + case 'combobox': // text left + $input['autocomplete'] = 1; + case 'pulldown': + $values = isset($input['value']) ? $input['value'] : ''; + unset($input['value']); + unset($input['type']); + if (is_string($values)) $values = explode(",", $values); + if (!empty($input['autocomplete'])) + $this->_doautocomplete($form, $inputtype, $input, $values); + $select = HTML::select($input); + if (empty($values) and ($s = $request->getArg($input['name']))) { + $select->pushContent(HTML::option(array('value' => $s), $s)); + } elseif (is_array($values)) { + $name = $input['name']; + unset($input['name']); + foreach ($values as $val) { + $input = array('value' => $val); + if ($request->getArg($name)) { + if ($request->getArg($name) == $val) + $input['selected'] = 'selected'; + else + unset($input['selected']); + } + //TODO: filter uneeded attributes + $select->pushContent(HTML::option($input, $val)); + } + } else { // force empty option + $select->pushContent(HTML::option(array(), '')); + } + $form->pushContent($text, $nbsp, $select); + break; + case 'reset': + case 'hidden': + $form->pushContent(HTML::input($input)); + break; + // change the order of inputs, by explicitly placing a submit button here. + case 'submit': // text right (?) + //$input['type'] = 'submit'; + if (empty($input['value'])) $input['value'] = $buttontext ? $buttontext : $action; + unset($input['text']); + if (empty($input['class'])) $input['class'] = $class; + if ($nobr) + $form->pushContent(HTML::input($input), $nbsp, $text, $nbsp); + else + $form->pushContent(HTML::div(array('class' => $class), HTML::input($input), $text)); + // unset the default submit button + $already_submit = 1; + break; } - break; - case 'editbox': // text left - $input['type'] = 'text'; - if (empty($input['value']) and ($s = $request->getArg($input['name']))) - $input['value'] = $s; - if (!empty($input['autocomplete'])) - $this->_doautocomplete($form, $inputtype, $input, $input['value']); - if ($nobr) - $form->pushContent($text, $nbsp, HTML::input($input)); - else - $form->pushContent(HTML::div(array('class' => $class), $text, $nbsp, HTML::input($input))); - break; - case 'combobox': // text left - $input['autocomplete'] = 1; - case 'pulldown': - $values = isset($input['value']) ? $input['value'] : ''; - unset($input['value']); - unset($input['type']); - if (is_string($values)) $values = explode(",", $values); - if (!empty($input['autocomplete'])) - $this->_doautocomplete($form, $inputtype, $input, $values); - $select = HTML::select($input); - if (empty($values) and ($s = $request->getArg($input['name']))) { - $select->pushContent(HTML::option(array('value'=> $s), $s)); - } elseif (is_array($values)) { - $name = $input['name']; - unset($input['name']); - foreach ($values as $val) { - $input = array('value' => $val); - if ($request->getArg($name)) { - if ($request->getArg($name) == $val) - $input['selected'] = 'selected'; - else - unset($input['selected']); - } - //TODO: filter uneeded attributes - $select->pushContent(HTML::option($input, $val)); - } - } else { // force empty option - $select->pushContent(HTML::option(array(), '')); - } - $form->pushContent($text, $nbsp, $select); - break; - case 'reset': - case 'hidden': - $form->pushContent(HTML::input($input)); - break; - // change the order of inputs, by explicitly placing a submit button here. - case 'submit': // text right (?) - //$input['type'] = 'submit'; - if (empty($input['value'])) $input['value'] = $buttontext ? $buttontext : $action; - unset($input['text']); - if (empty($input['class'])) $input['class'] = $class; - if ($nobr) - $form->pushContent(HTML::input($input), $nbsp, $text, $nbsp); - else - $form->pushContent(HTML::div(array('class' => $class), HTML::input($input), $text)); - // unset the default submit button - $already_submit = 1; - break; - } } } if ($request->getArg('start_debug')) $form->pushContent(HTML::input - (array('name' => 'start_debug', - 'value' => $request->getArg('start_debug'), - 'type' => 'hidden'))); + (array('name' => 'start_debug', + 'value' => $request->getArg('start_debug'), + 'type' => 'hidden'))); if (!USE_PATH_INFO) $form->pushContent(HiddenInputs(array('pagename' => $basepage))); if (!$already_submit) { @@ -302,18 +308,19 @@ extends WikiPlugin $submit = Button('submit:', $buttontext, $class); if ($cancel) { $form->pushContent(HTML::span - (array('class' => $class), - $submit, - Button('submit:cancel', _("Cancel"), $class))); + (array('class' => $class), + $submit, + Button('submit:cancel', _("Cancel"), $class))); } else { $form->pushContent(HTML::span(array('class' => $class), - $submit)); + $submit)); } } return $form; } - function _doautocomplete(&$form, $inputtype, &$input, &$values) { + function _doautocomplete(&$form, $inputtype, &$input, &$values) + { global $request; $input['class'] = "dropdown"; $input['acdropdown'] = "true"; @@ -324,7 +331,7 @@ extends WikiPlugin if (empty($values)) { if (isset($input['method']) && $input['method']) { if (empty($input['args'])) { - if (preg_match("/^(.*?) (.*)$/",$input['method'],$m)) { + if (preg_match("/^(.*?) (.*)$/", $input['method'], $m)) { $input['method'] = $m[1]; $input['args'] = $m[2]; } else @@ -334,28 +341,28 @@ extends WikiPlugin // deferred remote xmlrpc call if (string_starts_with($input['method'], "dynxmlrpc:")) { // how is server + method + args encoding parsed by acdropdown? - $input['autocomplete_list'] = substr($input['method'],3); + $input['autocomplete_list'] = substr($input['method'], 3); if ($input['args']) - $input['autocomplete_list'] .= (" ".$input['args']); - // static xmlrpc call, local only + $input['autocomplete_list'] .= (" " . $input['args']); + // static xmlrpc call, local only } elseif (string_starts_with($input['method'], "xmlrpc:")) { include_once 'lib/XmlRpcClient.php'; - $values = wiki_xmlrpc_post(substr($input['method'],7), $input['args']); + $values = wiki_xmlrpc_post(substr($input['method'], 7), $input['args']); } elseif (string_starts_with($input['method'], "url:")) { include_once 'lib/HttpClient.php'; - $html = HttpClient::quickGet(substr($input['method'],4)); + $html = HttpClient::quickGet(substr($input['method'], 4)); //TODO: how to parse the HTML result into a list? } elseif (string_starts_with($input['method'], "dynurl:")) { - $input['autocomplete_list'] = substr($input['method'],3); + $input['autocomplete_list'] = substr($input['method'], 3); } elseif (string_starts_with($input['method'], "plugin:")) { $dbi = $request->getDbh(); - $pluginName = substr($input['method'],7); + $pluginName = substr($input['method'], 7); $basepage = ''; require_once 'lib/WikiPlugin.php'; $w = new WikiPluginLoader; $p = $w->getPlugin($pluginName, false); // second arg? if (!is_object($p)) - trigger_error("invalid input['method'] ".$input['method'], E_USER_WARNING); + trigger_error("invalid input['method'] " . $input['method'], E_USER_WARNING); $pagelist = $p->run($dbi, @$input['args'], $request, $basepage); $values = array(); if (is_object($pagelist) and isa($pagelist, 'PageList')) { @@ -370,14 +377,13 @@ extends WikiPlugin // some predefined values (e.g. in a template or themeinfo.php) $input['autocomplete_list'] = $input['method']; } else { - trigger_error("invalid input['method'] ".$input['method'], E_USER_WARNING); + trigger_error("invalid input['method'] " . $input['method'], E_USER_WARNING); } - if (empty($input['autocomplete_list'])) - { + if (empty($input['autocomplete_list'])) { $tmpArray++; - $input['autocomplete_list']="array:".$tmpArray; + $input['autocomplete_list'] = "array:" . $tmpArray; $svalues = empty($values) ? "" : join("','", $values); - $form->pushContent(JavaScript("var $tmpArray = new Array('".$svalues."')")); + $form->pushContent(JavaScript("var $tmpArray = new Array('" . $svalues . "')")); } if (count($values) == 1) $input['value'] = $values[0]; @@ -386,13 +392,14 @@ extends WikiPlugin unset($input['method']); unset($input['args']); //unset($input['autocomplete']); - } - elseif ($s = $request->getArg($input['name'])) + } elseif ($s = $request->getArg($input['name'])) $input['value'] = $s; } return true; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/WikiForum.php b/lib/plugin/WikiForum.php index 334382c15..a159c2ebc 100644 --- a/lib/plugin/WikiForum.php +++ b/lib/plugin/WikiForum.php @@ -46,26 +46,30 @@ include_once 'lib/plugin/WikiBlog.php'; class WikiPlugin_WikiForum -extends WikiPlugin_WikiBlog + extends WikiPlugin_WikiBlog { - function getName () { + function getName() + { return _("WikiForum"); } - function getDescription () { + function getDescription() + { return _("Handles threaded topics with comments/news and provide a input form"); } - function getDefaultArguments() { - return array('pagename' => '[pagename]', - 'order' => 'normal', // oldest first - 'mode' => 'show,add', // 'summary', - 'info' => '', - 'noheader' => false - ); + function getDefaultArguments() + { + return array('pagename' => '[pagename]', + 'order' => 'normal', // oldest first + 'mode' => 'show,add', // 'summary', + 'info' => '', + 'noheader' => false + ); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); if (!$args['pagename']) { return $this->error(sprintf(_("A required argument '%s' is missing."), 'pagename')); @@ -88,17 +92,17 @@ extends WikiPlugin_WikiBlog $seen[$show] = 1; switch ($show) { - case 'summary': // main page: list of all titles - $html->pushContent($this->showTopics($request, $args)); - break; - case 'show': // list of all contents - $html->pushContent($this->showAll($request, $args, 'wikiforum')); - break; - case 'add': // add to or create a new thread - $html->pushContent($this->showForm($request, $args, 'forumadd')); - break; - default: - return $this->error(sprintf("Bad mode ('%s')", $show)); + case 'summary': // main page: list of all titles + $html->pushContent($this->showTopics($request, $args)); + break; + case 'show': // list of all contents + $html->pushContent($this->showAll($request, $args, 'wikiforum')); + break; + case 'add': // add to or create a new thread + $html->pushContent($this->showForm($request, $args, 'forumadd')); + break; + default: + return $this->error(sprintf("Bad mode ('%s')", $show)); } } // FIXME: on empty showTopics() and mode!=add and mode!=summary provide a showForm() here. @@ -107,29 +111,32 @@ extends WikiPlugin_WikiBlog // Table of titles(subpages) without content // TODO: use $args['info'] - function showTopics($request, $args) { + function showTopics($request, $args) + { global $WikiTheme; $dbi = $request->getDbh(); $topics = $this->findBlogs($dbi, $args['pagename'], 'wikiforum'); - $html = HTML::table(array('border'=>0)); + $html = HTML::table(array('border' => 0)); $row = HTML::tr(HTML::th('title'), - HTML::th('last post'), - HTML::th('author')); + HTML::th('last post'), + HTML::th('author')); $html->pushContent($row); foreach ($topics as $rev) { //TODO: get numposts, number of replies $meta = $rev->get('wikiforum'); // format as list, not as wikiforum content - $page = new WikiPageName($rev,$args['pagename']); - $row = HTML::tr(HTML::td(WikiLink($page,'if_known',$rev->get('summary'))), - HTML::td($WikiTheme->formatDateTime($meta['ctime'])), - HTML::td(WikiLink($meta['creator'],'if_known'))); + $page = new WikiPageName($rev, $args['pagename']); + $row = HTML::tr(HTML::td(WikiLink($page, 'if_known', $rev->get('summary'))), + HTML::td($WikiTheme->formatDateTime($meta['ctime'])), + HTML::td(WikiLink($meta['creator'], 'if_known'))); $html->pushContent($row); } return $html; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/WikiPoll.php b/lib/plugin/WikiPoll.php index f8700e097..f8469cc94 100644 --- a/lib/plugin/WikiPoll.php +++ b/lib/plugin/WikiPoll.php @@ -25,19 +25,19 @@ * * Usage: <> * * Administration: @@ -52,92 +52,98 @@ */ class WikiPlugin_WikiPoll -extends WikiPlugin + extends WikiPlugin { var $_args; - function getName () { + function getName() + { return _("WikiPoll"); } - function getDescription () { + function getDescription() + { return _("Enable configurable polls"); } - function getDefaultArguments() { - return array('page' => '[pagename]', - 'admin' => false, - 'require_all' => 1, // 1 if all questions must be answered - 'require_least' => 0, // how many at least - ); + function getDefaultArguments() + { + return array('page' => '[pagename]', + 'admin' => false, + 'require_all' => 1, // 1 if all questions must be answered + 'require_least' => 0, // how many at least + ); } - function getArgs($argstr, $request=false, $defaults = false) { + function getArgs($argstr, $request = false, $defaults = false) + { if ($defaults === false) $defaults = $this->getDefaultArguments(); //Fixme: on POST argstr is empty $args = array(); list ($argstr_args, $argstr_defaults) = $this->parseArgStr($argstr); if (isset($argstr_args["question_1"])) { - $args['question'] = $this->str2array("question",$argstr_args); - $args['answer'] = array(); - for ($i = 0; $i <= count($args['question']); $i++) { - if ($array = $this->str2array(sprintf("%s_%d","answer",$i),$argstr_args)) - $args['answer'][$i] = $array; - } + $args['question'] = $this->str2array("question", $argstr_args); + $args['answer'] = array(); + for ($i = 0; $i <= count($args['question']); $i++) { + if ($array = $this->str2array(sprintf("%s_%d", "answer", $i), $argstr_args)) + $args['answer'][$i] = $array; + } } if (!empty($defaults)) - foreach ($defaults as $arg => $default_val) { - if (isset($argstr_args[$arg])) - $args[$arg] = $argstr_args[$arg]; - elseif ( $request and ($argval = $request->getArg($arg)) !== false ) - $args[$arg] = $argval; - elseif (isset($argstr_defaults[$arg])) - $args[$arg] = (string) $argstr_defaults[$arg]; - else - $args[$arg] = $default_val; + foreach ($defaults as $arg => $default_val) { + if (isset($argstr_args[$arg])) + $args[$arg] = $argstr_args[$arg]; + elseif ($request and ($argval = $request->getArg($arg)) !== false) + $args[$arg] = $argval; elseif (isset($argstr_defaults[$arg])) + $args[$arg] = (string)$argstr_defaults[$arg]; else + $args[$arg] = $default_val; - if ($request) - $args[$arg] = $this->expandArg($args[$arg], $request); + if ($request) + $args[$arg] = $this->expandArg($args[$arg], $request); - unset($argstr_args[$arg]); - unset($argstr_defaults[$arg]); - } + unset($argstr_args[$arg]); + unset($argstr_defaults[$arg]); + } foreach (array_merge($argstr_args, $argstr_defaults) as $arg => $val) { - if (!preg_match("/^(answer_|question_)/",$arg)) + if (!preg_match("/^(answer_|question_)/", $arg)) trigger_error(sprintf(_("argument '%s' not declared by plugin"), - $arg), E_USER_NOTICE); + $arg), E_USER_NOTICE); } return $args; } - function handle_plugin_args_cruft($argstr, $args) { - $argstr = str_replace("\n"," ",$argstr); - $argstr = str_replace(array("[","]"),array("_",""),$argstr); - $this->_args = $this->getArgs($argstr, $GLOBALS['request']); + function handle_plugin_args_cruft($argstr, $args) + { + $argstr = str_replace("\n", " ", $argstr); + $argstr = str_replace(array("[", "]"), array("_", ""), $argstr); + $this->_args = $this->getArgs($argstr, $GLOBALS['request']); return; } - function str2array($var, $obarray=false) { - if (!$obarray) $obarray = $GLOBALS; - $i = 0; $array = array(); - $name = sprintf("%s_%d",$var,$i); + function str2array($var, $obarray = false) + { + if (!$obarray) $obarray = $GLOBALS; + $i = 0; + $array = array(); + $name = sprintf("%s_%d", $var, $i); + if (isset($obarray[$name])) $array[$i] = $obarray[$name]; + do { + $i++; + $name = sprintf("%s_%d", $var, $i); if (isset($obarray[$name])) $array[$i] = $obarray[$name]; - do { - $i++; - $name = sprintf("%s_%d",$var,$i); - if (isset($obarray[$name])) $array[$i] = $obarray[$name]; - } while (isset($obarray[$name])); - return $array; + } while (isset($obarray[$name])); + return $array; } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { if (!isset($_SERVER)) $_SERVER =& $GLOBALS['HTTP_SERVER_VARS']; - $request->setArg('nocache','purge'); + $request->setArg('nocache', 'purge'); $args = $this->getArgs($argstr, $request); if (!$args['page']) { return $this->error(sprintf(_("A required argument '%s' is missing."), 'page')); @@ -152,31 +158,32 @@ extends WikiPlugin $poll = $page->get("poll"); $ip = $_SERVER['REMOTE_ADDR']; $disable_submit = false; - if (isset($poll['ip'][$ip]) and ((time() - $poll['ip'][$ip]) < 20*60)) { + if (isset($poll['ip'][$ip]) and ((time() - $poll['ip'][$ip]) < 20 * 60)) { //view at least the result or disable the Go button $html = HTML(HTML::strong( - _("Sorry! You must wait at least 20 minutes until you can vote again!"))); - $html->pushContent($this->doPoll($page, $request, $request->getArg('answer'),true)); + _("Sorry! You must wait at least 20 minutes until you can vote again!"))); + $html->pushContent($this->doPoll($page, $request, $request->getArg('answer'), true)); return $html; } $poll['ip'][$ip] = time(); // purge older ip's foreach ($poll['ip'] as $ip => $time) { - if ((time() - $time) > 21*60) + if ((time() - $time) > 21 * 60) unset($poll['ip'][$ip]); } $html = HTML::form(array('action' => $request->getPostURL(), - 'method' => 'post')); + 'method' => 'post')); if ($request->isPost()) { // checkme: check if all answers are answered if ($request->getArg('answer') and ( - ($args['require_all'] and - count($request->getArg('answer')) == count($question)) - or - ($args['require_least'] and - count($request->getArg('answer')) >= $args['require_least']))) { + ($args['require_all'] and + count($request->getArg('answer')) == count($question)) + or + ($args['require_least'] and + count($request->getArg('answer')) >= $args['require_least'])) + ) { $page->set("poll", $poll); // update statistics and present them the user return $this->doPoll($page, $request, $request->getArg('answer')); @@ -190,59 +197,61 @@ extends WikiPlugin if (!isset($question[$i])) break; $q = $question[$i]; if (!isset($answer[$i])) - trigger_error(fmt("Missing %s for %s","answer"."[$i]","question"."[$i]"), - E_USER_ERROR); + trigger_error(fmt("Missing %s for %s", "answer" . "[$i]", "question" . "[$i]"), + E_USER_ERROR); $a = $answer[$i]; - if (! is_array($a)) { + if (!is_array($a)) { // a simple checkbox $html->pushContent(HTML::p(HTML::strong($q))); $html->pushContent(HTML::div( - HTML::input(array('type' => 'checkbox', - 'name' => "answer[$i]", - 'value' => 1)), - HTML::raw(" "), $a)); + HTML::input(array('type' => 'checkbox', + 'name' => "answer[$i]", + 'value' => 1)), + HTML::raw(" "), $a)); } else { $row = HTML(); - for ($j=0; $j <= count($a); $j++) { + for ($j = 0; $j <= count($a); $j++) { if (isset($a[$j])) $row->pushContent(HTML::div( - HTML::input(array('type' => 'radio', - 'name' => "answer[$i]", - 'value' => $j)), - HTML::raw(" "), $a[$j])); + HTML::input(array('type' => 'radio', + 'name' => "answer[$i]", + 'value' => $j)), + HTML::raw(" "), $a[$j])); } - $html->pushContent(HTML::p(HTML::strong($q)),$row); + $html->pushContent(HTML::p(HTML::strong($q)), $row); } } if (!$disable_submit) $html->pushContent(HTML::p( HTML::input(array('type' => 'submit', - 'name' => "WikiPoll", - 'value' => _("OK"))), + 'name' => "WikiPoll", + 'value' => _("OK"))), HTML::input(array('type' => 'reset', - 'name' => "reset", - 'value' => _("Reset"))))); + 'name' => "reset", + 'value' => _("Reset"))))); else - $html->pushContent(HTML::p(),HTML::strong( - _("Sorry! You must wait at least 20 minutes until you can vote again!"))); + $html->pushContent(HTML::p(), HTML::strong( + _("Sorry! You must wait at least 20 minutes until you can vote again!"))); return $html; } - function bar($percent) { + function bar($percent) + { global $WikiTheme; return HTML(HTML::img(array('src' => $WikiTheme->getImageUrl('leftbar'), - 'alt' => '<')), - HTML::img(array('src' => $WikiTheme->getImageUrl('mainbar'), - 'alt' => '-', - 'width' => sprintf("%02d",$percent), - 'height' => 14)), - HTML::img(array('src' => $WikiTheme->getImageUrl('rightbar'), - 'alt' => '>'))); + 'alt' => '<')), + HTML::img(array('src' => $WikiTheme->getImageUrl('mainbar'), + 'alt' => '-', + 'width' => sprintf("%02d", $percent), + 'height' => 14)), + HTML::img(array('src' => $WikiTheme->getImageUrl('rightbar'), + 'alt' => '>'))); } - function doPoll($page, $request, $answers, $readonly = false) { - $question = $this->_args['question']; - $answer = $this->_args['answer']; + function doPoll($page, $request, $answers, $readonly = false) + { + $question = $this->_args['question']; + $answer = $this->_args['answer']; $html = HTML::table(array('cellspacing' => 2)); $init = isset($question[0]) ? 0 : 1; for ($i = $init; $i <= count($question); $i++) { @@ -251,80 +260,84 @@ extends WikiPlugin @$poll['data']['all'][$i]++; $q = $question[$i]; if (!isset($answer[$i])) - trigger_error(fmt("Missing %s for %s","answer"."[$i]","question"."[$i]"), - E_USER_ERROR); + trigger_error(fmt("Missing %s for %s", "answer" . "[$i]", "question" . "[$i]"), + E_USER_ERROR); if (!$readonly) - $page->set('poll',$poll); + $page->set('poll', $poll); $a = $answer[$i]; $result = (isset($answers[$i])) ? $answers[$i] : -1; - if (! is_array($a) ) { + if (!is_array($a)) { $checkbox = HTML::input(array('type' => 'checkbox', - 'name' => "answer[$i]", - 'value' => $a)); + 'name' => "answer[$i]", + 'value' => $a)); if ($result >= 0) $checkbox->setAttr('checked', "checked"); if (!$readonly) - list($percent,$count,$all) = $this->storeResult($page, $i, $result ? 1 : 0); + list($percent, $count, $all) = $this->storeResult($page, $i, $result ? 1 : 0); else - list($percent,$count,$all) = $this->getResult($page, $i, 1); + list($percent, $count, $all) = $this->getResult($page, $i, 1); $print = sprintf(_(" %d%% (%d/%d)"), $percent, $count, $all); - $html->pushContent(HTML::tr(HTML::th(array('colspan' => 4,'align'=>'left'),$q))); + $html->pushContent(HTML::tr(HTML::th(array('colspan' => 4, 'align' => 'left'), $q))); $html->pushContent(HTML::tr(HTML::td($checkbox), - HTML::td($a), - HTML::td($this->bar($percent)), - HTML::td($print))); + HTML::td($a), + HTML::td($this->bar($percent)), + HTML::td($print))); } else { - $html->pushContent(HTML::tr(HTML::th(array('colspan' => 4,'align'=>'left'),$q))); + $html->pushContent(HTML::tr(HTML::th(array('colspan' => 4, 'align' => 'left'), $q))); $row = HTML(); if (!$readonly) $this->storeResult($page, $i, $answers[$i]); - for ($j=0; $j <= count($a); $j++) { + for ($j = 0; $j <= count($a); $j++) { if (isset($a[$j])) { - list($percent,$count,$all) = $this->getResult($page,$i,$j); + list($percent, $count, $all) = $this->getResult($page, $i, $j); $print = sprintf(_(" %d%% (%d/%d)"), $percent, $count, $all); $radio = HTML::input(array('type' => 'radio', - 'name' => "answer[$i]", - 'value' => $j)); + 'name' => "answer[$i]", + 'value' => $j)); if ($result == $j) $radio->setAttr('checked', "checked"); $row->pushContent(HTML::tr(HTML::td($radio), - HTML::td($a[$j]), - HTML::td($this->bar($percent)), - HTML::td($print))); + HTML::td($a[$j]), + HTML::td($this->bar($percent)), + HTML::td($print))); } } $html->pushContent($row); } } if (!$readonly) - return HTML(HTML::h3(_("The result of this poll so far:")),$html,HTML::p(_("Thanks for participating!"))); + return HTML(HTML::h3(_("The result of this poll so far:")), $html, HTML::p(_("Thanks for participating!"))); else - return HTML(HTML::h3(_("The result of this poll so far:")),$html); + return HTML(HTML::h3(_("The result of this poll so far:")), $html); } - function getResult($page,$i,$j) { - $poll = $page->get("poll"); - @$count = $poll['data']['count'][$i][$j]; - @$all = $poll['data']['all'][$i]; - $percent = sprintf("%d", $count * 100.0 / $all); - return array($percent,$count,$all); + function getResult($page, $i, $j) + { + $poll = $page->get("poll"); + @$count = $poll['data']['count'][$i][$j]; + @$all = $poll['data']['all'][$i]; + $percent = sprintf("%d", $count * 100.0 / $all); + return array($percent, $count, $all); } - function storeResult($page, $i, $j) { - $poll = $page->get("poll"); - if (!$poll) { - $poll = array('data' => array('count' => array(), - 'all' => array())); - } - @$poll['data']['count'][$i][$j]++; - //@$poll['data']['all'][$i]; - $page->set("poll",$poll); - $percent = sprintf("%d", $poll['data']['count'][$i][$j] * 100.0 / $poll['data']['all'][$i]); - return array($percent,$poll['data']['count'][$i][$j],$poll['data']['all'][$i]); + function storeResult($page, $i, $j) + { + $poll = $page->get("poll"); + if (!$poll) { + $poll = array('data' => array('count' => array(), + 'all' => array())); + } + @$poll['data']['count'][$i][$j]++; + //@$poll['data']['all'][$i]; + $page->set("poll", $poll); + $percent = sprintf("%d", $poll['data']['count'][$i][$j] * 100.0 / $poll['data']['all'][$i]); + return array($percent, $poll['data']['count'][$i][$j], $poll['data']['all'][$i]); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/WikicreoleTable.php b/lib/plugin/WikicreoleTable.php index 4e80909cc..7361632ff 100644 --- a/lib/plugin/WikicreoleTable.php +++ b/lib/plugin/WikicreoleTable.php @@ -49,25 +49,30 @@ */ class WikiPlugin_WikicreoleTable -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("WikicreoleTable"); } - function getDescription() { - return _("Layout tables using the Wikicreole syntax."); + function getDescription() + { + return _("Layout tables using the Wikicreole syntax."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array(); } - function handle_plugin_args_cruft($argstr, $args) { + function handle_plugin_args_cruft($argstr, $args) + { return; } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { include_once 'lib/InlineParser.php'; $table = array(); @@ -80,7 +85,7 @@ extends WikiPlugin } $line = trim($line); // If line ends with a '|', remove it - if ($line[strlen($line)-1] == '|') { + if ($line[strlen($line) - 1] == '|') { $line = substr($line, 0, -1); } if ($line[0] == '|') { @@ -96,12 +101,12 @@ extends WikiPlugin // Number of columns is the number of cells in the longer row $nbcols = 0; - for ($i=0; $i<$nbrows; $i++) { + for ($i = 0; $i < $nbrows; $i++) { $nbcols = max($nbcols, sizeof($table[$i])); } - for ($i=0; $i<$nbrows; $i++) { - for ($j=0; $j<$nbcols; $j++) { + for ($i = 0; $i < $nbrows; $i++) { + for ($j = 0; $j < $nbcols; $j++) { if (!isset($table[$i][$j])) { $table[$i][$j] = ''; } elseif (preg_match('/@@/', $table[$i][$j])) { @@ -130,18 +135,19 @@ extends WikiPlugin return $htmltable; } - function _parse_row ($line) { + function _parse_row($line) + { $brkt_link = "\\[ .*? [^]\s] .*? \\]"; - $cell_content = "(?: [^[] | ".ESCAPE_CHAR."\\[ | $brkt_link )*?"; + $cell_content = "(?: [^[] | " . ESCAPE_CHAR . "\\[ | $brkt_link )*?"; preg_match_all("/(\\|+) \s* ($cell_content) \s* (?=\\||\$)/x", - $line, $matches, PREG_SET_ORDER); + $line, $matches, PREG_SET_ORDER); $row = array(); foreach ($matches as $m) { $cell = $m[2]; - $row[]= $cell; + $row[] = $cell; } return $row; } @@ -152,7 +158,8 @@ extends WikiPlugin * $i and $j: indexes of cell to compute * $imax and $jmax: table dimensions */ - function _compute_tablecell ($table, $i, $j, $imax, $jmax) { + function _compute_tablecell($table, $i, $j, $imax, $jmax) + { // What is implemented: // @@=SUM(R)@@ : sum of cells in current row @@ -168,12 +175,12 @@ extends WikiPlugin // @@=COUNT(C)@@ : number of cells in current column // (numeric or not, excluding headers and current cell) - $result=0; - $counter=0; - $found=false; + $result = 0; + $counter = 0; + $found = false; if (strpos($table[$i][$j], "@@=SUM(C)@@") !== false) { - for ($index=0; $index<$imax; $index++) { + for ($index = 0; $index < $imax; $index++) { if (is_numeric($table[$index][$j])) { $result += $table[$index][$j]; } @@ -181,7 +188,7 @@ extends WikiPlugin return str_replace("@@=SUM(C)@@", $result, $table[$i][$j]); } elseif (strpos($table[$i][$j], "@@=SUM(R)@@") !== false) { - for ($index=0; $index<$jmax; $index++) { + for ($index = 0; $index < $jmax; $index++) { if (is_numeric($table[$i][$index])) { $result += $table[$i][$index]; } @@ -189,107 +196,107 @@ extends WikiPlugin return str_replace("@@=SUM(R)@@", $result, $table[$i][$j]); } elseif (strpos($table[$i][$j], "@@=AVERAGE(C)@@") !== false) { - for ($index=0; $index<$imax; $index++) { + for ($index = 0; $index < $imax; $index++) { if (is_numeric($table[$index][$j])) { $result += $table[$index][$j]; $counter++; } } - $result=$result/$counter; + $result = $result / $counter; return str_replace("@@=AVERAGE(C)@@", $result, $table[$i][$j]); } elseif (strpos($table[$i][$j], "@@=AVERAGE(R)@@") !== false) { - for ($index=0; $index<$jmax; $index++) { + for ($index = 0; $index < $jmax; $index++) { if (is_numeric($table[$i][$index])) { $result += $table[$i][$index]; $counter++; } } - $result=$result/$counter; + $result = $result / $counter; return str_replace("@@=AVERAGE(R)@@", $result, $table[$i][$j]); } elseif (strpos($table[$i][$j], "@@=MAX(C)@@") !== false) { - for ($index=0; $index<$imax; $index++) { + for ($index = 0; $index < $imax; $index++) { if (is_numeric($table[$index][$j])) { if (!$found) { - $found=true; - $result=$table[$index][$j]; + $found = true; + $result = $table[$index][$j]; } else { $result = max($result, $table[$index][$j]); } } } if (!$found) { - $result=""; + $result = ""; } return str_replace("@@=MAX(C)@@", $result, $table[$i][$j]); } elseif (strpos($table[$i][$j], "@@=MAX(R)@@") !== false) { - for ($index=0; $index<$jmax; $index++) { + for ($index = 0; $index < $jmax; $index++) { if (is_numeric($table[$i][$index])) { if (!$found) { - $found=true; - $result=$table[$i][$index]; + $found = true; + $result = $table[$i][$index]; } else { $result = max($result, $table[$i][$index]); } } } if (!$found) { - $result=""; + $result = ""; } return str_replace("@@=MAX(R)@@", $result, $table[$i][$j]); } elseif (strpos($table[$i][$j], "@@=MIN(C)@@") !== false) { - for ($index=0; $index<$imax; $index++) { + for ($index = 0; $index < $imax; $index++) { if (is_numeric($table[$index][$j])) { if (!$found) { - $found=true; - $result=$table[$index][$j]; + $found = true; + $result = $table[$index][$j]; } else { $result = min($result, $table[$index][$j]); } } } if (!$found) { - $result=""; + $result = ""; } return str_replace("@@=MIN(C)@@", $result, $table[$i][$j]); } elseif (strpos($table[$i][$j], "@@=MIN(R)@@") !== false) { - for ($index=0; $index<$jmax; $index++) { + for ($index = 0; $index < $jmax; $index++) { if (is_numeric($table[$i][$index])) { if (!$found) { - $found=true; - $result=$table[$i][$index]; + $found = true; + $result = $table[$i][$index]; } else { $result = min($result, $table[$i][$index]); } } } if (!$found) { - $result=""; + $result = ""; } return str_replace("@@=MIN(R)@@", $result, $table[$i][$j]); } elseif (strpos($table[$i][$j], "@@=COUNT(C)@@") !== false) { - for ($index=0; $index<$imax; $index++) { + for ($index = 0; $index < $imax; $index++) { // exclude header if (!string_starts_with(trim($table[$index][$j]), "=")) { $counter++; } } - $result = $counter-1; // exclude self + $result = $counter - 1; // exclude self return str_replace("@@=COUNT(C)@@", $result, $table[$i][$j]); } elseif (strpos($table[$i][$j], "@@=COUNT(R)@@") !== false) { - for ($index=0; $index<$jmax; $index++) { + for ($index = 0; $index < $jmax; $index++) { // exclude header if (!string_starts_with(trim($table[$i][$index]), "=")) { $counter++; } } - $result = $counter-1; // exclude self + $result = $counter - 1; // exclude self return str_replace("@@=COUNT(R)@@", $result, $table[$i][$j]); } diff --git a/lib/plugin/YouTube.php b/lib/plugin/YouTube.php index 852b18462..78e256f30 100644 --- a/lib/plugin/YouTube.php +++ b/lib/plugin/YouTube.php @@ -35,78 +35,82 @@ */ class WikiPlugin_YouTube -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("YouTube"); } - function getDescription () { + function getDescription() + { return _("Embed YouTube videos"); } - function getDefaultArguments() { + function getDefaultArguments() + { return array('v' => "", - 'browse' => '', // see above - 'time' => '', // only if browse - 'category' => '', // only if browse - 'language' => '', // only if browse - 'index' => 0, // only if browse - 'style' => 'inline', // or link. link links to youtube. - 'size' => 'medium', // or large, medium or small - 'autoplay' => 0, - 'width' => "425", - 'height' => "350"); + 'browse' => '', // see above + 'time' => '', // only if browse + 'category' => '', // only if browse + 'language' => '', // only if browse + 'index' => 0, // only if browse + 'style' => 'inline', // or link. link links to youtube. + 'size' => 'medium', // or large, medium or small + 'autoplay' => 0, + 'width' => "425", + 'height' => "350"); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); extract($args); if (empty($args['v'])) { if (empty($args['browse'])) return $this->error(fmt("Required argument %s missing", "v")); - $this->_browse = array("Most Recent" => "mr", - "Most Viewed" => "mp", - "Top Rated" => "tr", - "Most Discussed"=> "md", - "Top Favorites" => "mf", - "Most Linked" => "mrd", - "Recently Featured"=> "rf", - "Most Responded" => "ms", - "Watch on Mobile" => "mv"); - $this->browse = array_keys($this->_browse); + $this->_browse = array("Most Recent" => "mr", + "Most Viewed" => "mp", + "Top Rated" => "tr", + "Most Discussed" => "md", + "Top Favorites" => "mf", + "Most Linked" => "mrd", + "Recently Featured" => "rf", + "Most Responded" => "ms", + "Watch on Mobile" => "mv"); + $this->browse = array_keys($this->_browse); array_unshift($this->browse, "Daily Pick"); - $this->_time = array("Today" => "t", - "This Week" => "w", - "This Month" => "m", - "All Time" => "a"); - $this->_category = array("All" => "0", - "Autos & Vehicles" => "2", - "Comedy" => "23", - "Entertainment" => "24", - "Film & Animation" => "1", - "Gadgets & Games" => "20", - "Howto & DIY" => "26", - "Music" => "10", - "News & Politics" => "25", - "People & Blogs" => "22", - "Pets & Animals" => "15", - "Sports" => "17", - "Travel & Places" => "19"); - $this->_language = array("All" => "", - "English" => "EN", - "Spanish" => "ES", - "Japanese"=> "JA", - "German" => "DE", - "Chinese" => "CN", - "French" => "FR"); - if (!in_array($browse,$this->browse)) + $this->_time = array("Today" => "t", + "This Week" => "w", + "This Month" => "m", + "All Time" => "a"); + $this->_category = array("All" => "0", + "Autos & Vehicles" => "2", + "Comedy" => "23", + "Entertainment" => "24", + "Film & Animation" => "1", + "Gadgets & Games" => "20", + "Howto & DIY" => "26", + "Music" => "10", + "News & Politics" => "25", + "People & Blogs" => "22", + "Pets & Animals" => "15", + "Sports" => "17", + "Travel & Places" => "19"); + $this->_language = array("All" => "", + "English" => "EN", + "Spanish" => "ES", + "Japanese" => "JA", + "German" => "DE", + "Chinese" => "CN", + "French" => "FR"); + if (!in_array($browse, $this->browse)) return $this->error(fmt("Invalid argument %s", "browse")); - if ($time and !in_array($time,array_keys($this->_time))) + if ($time and !in_array($time, array_keys($this->_time))) return $this->error(fmt("Invalid argument %s", "time")); - if ($category and !in_array($category,$this->category)) + if ($category and !in_array($category, $this->category)) return $this->error(fmt("Invalid argument %s", "category")); - if ($language and !in_array($language,$this->language)) + if ($language and !in_array($language, $this->language)) return $this->error(fmt("Invalid argument %s", "language")); if ($browse == "Daily Pick") $v = $this->Daily_pick(); @@ -115,14 +119,13 @@ extends WikiPlugin $t = $time ? $this->_time[$time] : 't'; $c = $category ? $this->_category[$category] : '0'; $l = $language ? $this->_language[$language] : ''; - $url = "http://www.youtube.com/browse?s=$s&t=$t&c=$c&l=$l"; - $m = array('',''); + $url = "http://www.youtube.com/browse?s=$s&t=$t&c=$c&l=$l"; + $m = array('', ''); if ($xml = url_get_contents($url)) { if ($index) { if (preg_match_all('/
                  .*?\n.*?.*?\n.*? 12) return $this->error(fmt("Invalid argument %s", "v")); - if (strcspn($v,"-_0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")) + if (strcspn($v, "-_0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")) return $this->error(fmt("Invalid argument %s", "v")); $url = "http://www.youtube.com/v/" . $v; if ($autoplay) $url .= "?autoplay=1"; if ($size != 'medium') { - if ($size == 'large') { $width = 640; $height = 526; } - elseif ($size == 'small') { $width = 240; $height = 200; } + if ($size == 'large') { + $width = 640; + $height = 526; + } elseif ($size == 'small') { + $width = 240; + $height = 200; + } } unset($args['size']); unset($args['style']); $args['src'] = $v; unset($args['v']); if ($style == 'link') { - if ($size == 'medium') { $width = 130; $height = 97; } - elseif ($size == 'large') { $width = 320; $height = 240; } - elseif ($size == 'small') { $width = 90; $height = 60; } + if ($size == 'medium') { + $width = 130; + $height = 97; + } elseif ($size == 'large') { + $width = 320; + $height = 240; + } elseif ($size == 'small') { + $width = 90; + $height = 60; + } // img: http://img.youtube.com/vi/KKTDRqQtPO8/2.jpg or 0.jpg $link = HTML::a(array('href' => $url), - HTML::img(array('src' => "http://img.youtube.com/vi/". - $v."/".(($size == 'large')?"0":"2").".jpg", - 'width' => $width, - 'height' => $height, - 'alt' => "YouTube video $v"))); + HTML::img(array('src' => "http://img.youtube.com/vi/" . + $v . "/" . (($size == 'large') ? "0" : "2") . ".jpg", + 'width' => $width, + 'height' => $height, + 'alt' => "YouTube video $v"))); return $link; } $object = HTML::object(array('class' => 'inlineobject', - 'width' => $width, - 'height' => $height, - )); + 'width' => $width, + 'height' => $height, + )); $attrs = array('data' => $url, - 'type' => 'application/x-shockwave-flash', - 'width' => $width, - 'height' => $height); + 'type' => 'application/x-shockwave-flash', + 'width' => $width, + 'height' => $height); if (isBrowserSafari()) { return HTML::object($attrs); } @@ -175,14 +190,17 @@ extends WikiPlugin return $object; } - function Daily_pick() { + function Daily_pick() + { if ($xml = url_get_contents("http://www.youtube.com/categories")) { if (preg_match('/
                  Pick of The Day<\/b><\/div>.*?/s', $xml, $m)) return $m[1]; } return ''; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/_AuthInfo.php b/lib/plugin/_AuthInfo.php index e60724321..40ec7871d 100644 --- a/lib/plugin/_AuthInfo.php +++ b/lib/plugin/_AuthInfo.php @@ -29,21 +29,25 @@ require_once 'lib/Template.php'; * Warning! This may display db and user passwords in cleartext. */ class WikiPlugin__AuthInfo -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("AuthInfo"); } - function getDescription () { + function getDescription() + { return _("Display general and user specific auth information."); } - function getDefaultArguments() { + function getDefaultArguments() + { return array('userid' => ''); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); extract($args); if (empty($userid) or $userid == $request->_user->UserName()) { @@ -52,35 +56,35 @@ extends WikiPlugin } else { $user = WikiUser($userid); } - if (!$user->isAdmin() and ! (DEBUG && _DEBUG_LOGIN)) { + if (!$user->isAdmin() and !(DEBUG && _DEBUG_LOGIN)) { $request->_notAuthorized(WIKIAUTH_ADMIN); $this->disabled("! user->isAdmin"); } $html = HTML(HTML::h3(fmt("General Auth Settings"))); $table = HTML::table(array('border' => 1, - 'cellpadding' => 2, - 'cellspacing' => 0)); + 'cellpadding' => 2, + 'cellspacing' => 0)); $table->pushContent($this->_showhash("AUTH DEFINES", - $this->_buildConstHash( - array("ENABLE_USER_NEW","ALLOW_ANON_USER", - "ALLOW_ANON_EDIT","ALLOW_BOGO_LOGIN", - "REQUIRE_SIGNIN_BEFORE_EDIT","ALLOW_USER_PASSWORDS", - "PASSWORD_LENGTH_MINIMUM","USE_DB_SESSION")))); - if ((defined('ALLOW_LDAP_LOGIN') && ALLOW_LDAP_LOGIN) or in_array("LDAP",$GLOBALS['USER_AUTH_ORDER'])) + $this->_buildConstHash( + array("ENABLE_USER_NEW", "ALLOW_ANON_USER", + "ALLOW_ANON_EDIT", "ALLOW_BOGO_LOGIN", + "REQUIRE_SIGNIN_BEFORE_EDIT", "ALLOW_USER_PASSWORDS", + "PASSWORD_LENGTH_MINIMUM", "USE_DB_SESSION")))); + if ((defined('ALLOW_LDAP_LOGIN') && ALLOW_LDAP_LOGIN) or in_array("LDAP", $GLOBALS['USER_AUTH_ORDER'])) $table->pushContent($this->_showhash("LDAP DEFINES", - $this->_buildConstHash(array("LDAP_AUTH_HOST","LDAP_BASE_DN")))); - if ((defined('ALLOW_IMAP_LOGIN') && ALLOW_IMAP_LOGIN) or in_array("IMAP",$GLOBALS['USER_AUTH_ORDER'])) + $this->_buildConstHash(array("LDAP_AUTH_HOST", "LDAP_BASE_DN")))); + if ((defined('ALLOW_IMAP_LOGIN') && ALLOW_IMAP_LOGIN) or in_array("IMAP", $GLOBALS['USER_AUTH_ORDER'])) $table->pushContent($this->_showhash("IMAP DEFINES", array("IMAP_AUTH_HOST" => IMAP_AUTH_HOST))); - if (defined('AUTH_USER_FILE') or in_array("File",$GLOBALS['USER_AUTH_ORDER'])) + if (defined('AUTH_USER_FILE') or in_array("File", $GLOBALS['USER_AUTH_ORDER'])) $table->pushContent($this->_showhash("AUTH_USER_FILE", - $this->_buildConstHash(array("AUTH_USER_FILE", - "AUTH_USER_FILE_STORABLE")))); + $this->_buildConstHash(array("AUTH_USER_FILE", + "AUTH_USER_FILE_STORABLE")))); if (defined('GROUP_METHOD')) $table->pushContent($this->_showhash("GROUP_METHOD", - $this->_buildConstHash(array("GROUP_METHOD","AUTH_GROUP_FILE","GROUP_LDAP_QUERY")))); + $this->_buildConstHash(array("GROUP_METHOD", "AUTH_GROUP_FILE", "GROUP_LDAP_QUERY")))); $table->pushContent($this->_showhash("\$USER_AUTH_ORDER[]", $GLOBALS['USER_AUTH_ORDER'])); - $table->pushContent($this->_showhash("USER_AUTH_POLICY", array("USER_AUTH_POLICY"=>USER_AUTH_POLICY))); + $table->pushContent($this->_showhash("USER_AUTH_POLICY", array("USER_AUTH_POLICY" => USER_AUTH_POLICY))); $DBParams = $GLOBALS['DBParams']; $DBParams['dsn'] = class_exists('WikiDB_SQL') ? WikiDB_SQL::view_dsn($DBParams['dsn']) : ''; $table->pushContent($this->_showhash("\$DBParams[]", $DBParams)); @@ -97,96 +101,96 @@ extends WikiPlugin $html->pushContent(HTML::p(fmt("No userid"))); } else { $table = HTML::table(array('border' => 1, - 'cellpadding' => 2, - 'cellspacing' => 0)); + 'cellpadding' => 2, + 'cellspacing' => 0)); //$table->pushContent(HTML::tr(HTML::td(array('colspan' => 2)))); - $userdata = obj2hash($user, array('_dbi','_request', 'password', 'passwd')); + $userdata = obj2hash($user, array('_dbi', '_request', 'password', 'passwd')); if (isa($user, "_FilePassUser")) { - foreach ($userdata['_file']->users as $u => $p) { - $userdata['_file']->users[$u] = ""; - } + foreach ($userdata['_file']->users as $u => $p) { + $userdata['_file']->users[$u] = ""; + } } - $table->pushContent($this->_showhash("User: Object of ".get_class($user), $userdata)); + $table->pushContent($this->_showhash("User: Object of " . get_class($user), $userdata)); if (ENABLE_USER_NEW) { - $group = &$request->getGroup(); - $groups = $group->getAllGroupsIn(); - $groupdata = obj2hash($group, array('_dbi','_request', 'password', 'passwd')); - unset($groupdata['request']); - $table->pushContent($this->_showhash("Group: Object of ".get_class($group), $groupdata)); - $groups = $group->getAllGroupsIn(); - $groupdata = array('getAllGroupsIn' => $groups); - foreach ($groups as $g) { - $groupdata["getMembersOf($g)"] = $group->getMembersOf($g); - $groupdata["isMember($g)"] = $group->isMember($g); - } - $table->pushContent($this->_showhash("Group Methods: ", $groupdata)); + $group = &$request->getGroup(); + $groups = $group->getAllGroupsIn(); + $groupdata = obj2hash($group, array('_dbi', '_request', 'password', 'passwd')); + unset($groupdata['request']); + $table->pushContent($this->_showhash("Group: Object of " . get_class($group), $groupdata)); + $groups = $group->getAllGroupsIn(); + $groupdata = array('getAllGroupsIn' => $groups); + foreach ($groups as $g) { + $groupdata["getMembersOf($g)"] = $group->getMembersOf($g); + $groupdata["isMember($g)"] = $group->isMember($g); + } + $table->pushContent($this->_showhash("Group Methods: ", $groupdata)); } $html->pushContent($table); } return $html; } - function _showhash ($heading, $hash, $depth = 0) { - static $seen = array(); - static $maxdepth = 0; + function _showhash($heading, $hash, $depth = 0) + { + static $seen = array(); + static $maxdepth = 0; $rows = array(); $maxdepth++; if ($maxdepth > 35) return $heading; if ($heading) $rows[] = HTML::tr(array('bgcolor' => '#ffcccc', - 'style' => 'color:#000000'), - HTML::td(array('colspan' => 2, - 'style' => 'color:#000000'), - $heading)); + 'style' => 'color:#000000'), + HTML::td(array('colspan' => 2, + 'style' => 'color:#000000'), + $heading)); if (is_object($hash)) $hash = obj2hash($hash); if (!empty($hash)) { ksort($hash); foreach ($hash as $key => $val) { if (is_object($val)) { - $heading = "Object of ".get_class($val); + $heading = "Object of " . get_class($val); if ($depth > 3) $val = $heading; - elseif ($heading == "Object of wikidb_sql") $val = $heading; - elseif (substr($heading,0,13) == "Object of db_") $val = $heading; - elseif (!isset($seen[$heading])) { + elseif ($heading == "Object of wikidb_sql") $val = $heading; elseif (substr($heading, 0, 13) == "Object of db_") $val = $heading; elseif (!isset($seen[$heading])) { //if (empty($seen[$heading])) $seen[$heading] = 1; $val = HTML::table(array('border' => 1, - 'cellpadding' => 2, - 'cellspacing' => 0), - $this->_showhash($heading, obj2hash($val), $depth+1)); + 'cellpadding' => 2, + 'cellspacing' => 0), + $this->_showhash($heading, obj2hash($val), $depth + 1)); } else { $val = $heading; } } elseif (is_array($val)) { - $heading = $key."[]"; + $heading = $key . "[]"; if ($depth > 3) $val = $heading; elseif (!isset($seen[$heading])) { //if (empty($seen[$heading])) $seen[$heading] = 1; $val = HTML::table(array('border' => 1, - 'cellpadding' => 2, - 'cellspacing' => 0), - $this->_showhash($heading, $val, $depth+1)); + 'cellpadding' => 2, + 'cellspacing' => 0), + $this->_showhash($heading, $val, $depth + 1)); } else { $val = $heading; } } $rows[] = HTML::tr(HTML::td(array('align' => 'right', - 'bgcolor' => '#cccccc', - 'style' => 'color:#000000'), - HTML(HTML::raw(' '), $key, - HTML::raw(' '))), - HTML::td(array('bgcolor' => '#ffffff', - 'style' => 'color:#000000'), - $val ? $val : HTML::raw(' ')) - ); + 'bgcolor' => '#cccccc', + 'style' => 'color:#000000'), + HTML(HTML::raw(' '), $key, + HTML::raw(' '))), + HTML::td(array('bgcolor' => '#ffffff', + 'style' => 'color:#000000'), + $val ? $val : HTML::raw(' ')) + ); //if (empty($seen[$key])) $seen[$key] = 1; } } return $rows; } - function _buildConstHash($constants) { + function _buildConstHash($constants) + { $hash = array(); foreach ($constants as $c) { $hash[$c] = defined($c) ? constant($c) : ''; @@ -195,7 +199,9 @@ extends WikiPlugin } return $hash; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/_BackendInfo.php b/lib/plugin/_BackendInfo.php index 8516a3427..98c2e141e 100644 --- a/lib/plugin/_BackendInfo.php +++ b/lib/plugin/_BackendInfo.php @@ -24,22 +24,26 @@ require_once 'lib/Template.php'; /** */ class WikiPlugin__BackendInfo -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("DebugInfo"); } - function getDescription () { + function getDescription() + { return sprintf(_("Get debugging information for %s."), '[pagename]'); } - function getDefaultArguments() { + function getDefaultArguments() + { return array('page' => '[pagename]', - 'notallversions' => 0); + 'notallversions' => 0); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); extract($args); if (empty($page)) @@ -48,20 +52,19 @@ extends WikiPlugin $backend = &$dbi->_backend; $this->chunk_split = true; $this->readonly_pagemeta = array(); - $this->hidden_pagemeta = array ('_cached_html'); + $this->hidden_pagemeta = array('_cached_html'); $html = HTML(HTML::h3(fmt("Querying backend directly for '%s'", - $page))); + $page))); $table = HTML::table(array('border' => 1, - 'cellpadding' => 2, - 'cellspacing' => 0)); + 'cellpadding' => 2, + 'cellspacing' => 0)); $pagedata = $backend->get_pagedata($page); if (!$pagedata) { // FIXME: invalid HTML $html->pushContent(HTML::p(fmt("No pagedata for %s", $page))); - } - else { + } else { $this->_fixupData($pagedata); $table->pushContent($this->_showhash("get_pagedata('$page')", $pagedata)); } @@ -71,18 +74,17 @@ extends WikiPlugin $this->_fixupData($vdata); $table->pushContent(HTML::tr(HTML::td(array('colspan' => 2)))); $table->pushContent($this->_showhash("get_versiondata('$page',$version)", - $vdata)); + $vdata)); } else { for ($version = $backend->get_latest_version($page); $version; - $version = $backend->get_previous_version($page, $version)) - { - $vdata = $backend->get_versiondata($page, $version, true); - $this->_fixupData($vdata); - $table->pushContent(HTML::tr(HTML::td(array('colspan' => 2)))); - $table->pushContent($this->_showhash("get_versiondata('$page',$version)", - $vdata)); - } + $version = $backend->get_previous_version($page, $version)) { + $vdata = $backend->get_versiondata($page, $version, true); + $this->_fixupData($vdata); + $table->pushContent(HTML::tr(HTML::td(array('colspan' => 2)))); + $table->pushContent($this->_showhash("get_versiondata('$page',$version)", + $vdata)); + } } $linkdata = $backend->get_links($page, false); @@ -106,7 +108,8 @@ extends WikiPlugin * Really should have a _fixupPagedata and _fixupVersiondata, but this works. * also used in plugin/EditMetaData */ - function _fixupData(&$data, $prefix='') { + function _fixupData(&$data, $prefix = '') + { if (!is_array($data)) return; global $request; @@ -114,7 +117,7 @@ extends WikiPlugin foreach ($data as $key => $val) { $fullkey = $prefix . '[' . $key . ']'; if (is_integer($key)) { - ; + ; } elseif ($key == 'passwd' and !$user->isAdmin()) { $data[$key] = $val ? _("") : _(""); } elseif ($key and $key == '_cached_html') { @@ -123,28 +126,25 @@ extends WikiPlugin print_r($val); $data[$key] = HTML::pre(ob_get_contents()); ob_end_clean(); - } - elseif (is_bool($val)) { - $data[$key] = $this->_showvalue($key, $val ? "true" : "false", $prefix); - } - elseif (is_string($val) && ((substr($val, 0, 2) == 'a:' - or (substr($val, 0, 2) == 'O:')))) - { + } elseif (is_bool($val)) { + $data[$key] = $this->_showvalue($key, $val ? "true" : "false", $prefix); + } elseif (is_string($val) && ((substr($val, 0, 2) == 'a:' + or (substr($val, 0, 2) == 'O:'))) + ) { // how to indent this table? $val = unserialize($val); $this->_fixupData($val, $fullkey); $data[$key] = HTML::table(array('border' => 1, - 'cellpadding' => 2, - 'cellspacing' => 0), - $this->_showhash(false, $val, $fullkey)); - } - elseif (is_array($val)) { + 'cellpadding' => 2, + 'cellspacing' => 0), + $this->_showhash(false, $val, $fullkey)); + } elseif (is_array($val)) { // how to indent this table? $this->_fixupData($val, $fullkey); $data[$key] = HTML::table(array('border' => 1, - 'cellpadding' => 2, - 'cellspacing' => 0), - $this->_showhash(false, $val, $fullkey)); + 'cellpadding' => 2, + 'cellspacing' => 0), + $this->_showhash(false, $val, $fullkey)); } elseif (is_object($val)) { // how to indent this table? ob_start(); @@ -152,15 +152,14 @@ extends WikiPlugin $val = HTML::pre(ob_get_contents()); ob_end_clean(); $data[$key] = HTML::table(array('border' => 1, - 'cellpadding' => 2, - 'cellspacing' => 0), - $this->_showhash(false, $val, $fullkey)); - } - elseif ($key and $key == '%content') { + 'cellpadding' => 2, + 'cellspacing' => 0), + $this->_showhash(false, $val, $fullkey)); + } elseif ($key and $key == '%content') { if ($val === true) $val = ''; elseif (strlen($val) > 40) - $val = substr($val,0,40) . " ..."; + $val = substr($val, 0, 40) . " ..."; $data[$key] = $val; } } @@ -168,37 +167,41 @@ extends WikiPlugin } /* also used in plugin/EditMetaData */ - function _showhash ($heading, $hash, $prefix='') { + function _showhash($heading, $hash, $prefix = '') + { $rows = array(); if ($heading) $rows[] = HTML::tr(array('bgcolor' => '#ffcccc', - 'style' => 'color:#000000'), - HTML::td(array('colspan' => 2, - 'style' => 'color:#000000'), - $heading)); + 'style' => 'color:#000000'), + HTML::td(array('colspan' => 2, + 'style' => 'color:#000000'), + $heading)); if (!is_array($hash)) return array(); ksort($hash); foreach ($hash as $key => $val) { if ($this->chunk_split and is_string($val)) $val = chunk_split($val); $rows[] = HTML::tr(HTML::td(array('align' => 'right', - 'bgcolor' => '#cccccc', - 'style' => 'color:#000000'), - HTML(HTML::raw(' '), $key, - HTML::raw(' '))), - HTML::td(array('bgcolor' => '#ffffff', - 'style' => 'color:#000000'), - $this->_showvalue($key, $val, $prefix)) - ); + 'bgcolor' => '#cccccc', + 'style' => 'color:#000000'), + HTML(HTML::raw(' '), $key, + HTML::raw(' '))), + HTML::td(array('bgcolor' => '#ffffff', + 'style' => 'color:#000000'), + $this->_showvalue($key, $val, $prefix)) + ); } return $rows; } /* also used in plugin/EditMetaData */ - function _showvalue ($key, $val, $prefix='') { + function _showvalue($key, $val, $prefix = '') + { return $val ? $val : HTML::raw(' '); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/_GroupInfo.php b/lib/plugin/_GroupInfo.php index 45d61b6ce..fbeb5090a 100644 --- a/lib/plugin/_GroupInfo.php +++ b/lib/plugin/_GroupInfo.php @@ -24,21 +24,25 @@ * @author: Charles Corrigan */ class WikiPlugin__GroupInfo -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("DebugGroupInfo"); } - function getDescription () { + function getDescription() + { return sprintf(_("Show Group Information")); } - function getDefaultArguments() { + function getDefaultArguments() + { return array(); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); extract($args); @@ -48,17 +52,19 @@ extends WikiPlugin $allGroups = $group->getAllGroupsIn(); foreach ($allGroups as $g) { - $members = $group->getMembersOf($g); - $output->pushContent(HTML::h3($g . " - members: " . -sizeof($members) . " - isMember: " . ($group->isMember($g) ? "yes" : "no") -)); - foreach($members as $m) { - $output->pushContent($m); - $output->pushContent(HTML::br()); - } + $members = $group->getMembersOf($g); + $output->pushContent(HTML::h3($g . " - members: " . + sizeof($members) . " - isMember: " . ($group->isMember($g) ? "yes" : "no") + )); + foreach ($members as $m) { + $output->pushContent($m); + $output->pushContent(HTML::br()); + } } $output->pushContent(HTML::p("--- the end ---")); return $output; } -}; +} + +; diff --git a/lib/plugin/_PreferencesInfo.php b/lib/plugin/_PreferencesInfo.php index 3c3a797c7..56da7866b 100644 --- a/lib/plugin/_PreferencesInfo.php +++ b/lib/plugin/_PreferencesInfo.php @@ -24,28 +24,34 @@ * Plugin to display the current preferences without auth check. */ class WikiPlugin__PreferencesInfo -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("PreferencesInfo"); } - function getDescription () { + function getDescription() + { return sprintf(_("Get preferences information for current user %s."), - '[userid]'); + '[userid]'); } - function getDefaultArguments() { + function getDefaultArguments() + { return array('page' => '[pagename]', - 'userid' => '[userid]'); + 'userid' => '[userid]'); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); // $user = &$request->getUser(); return Template('userprefs', $args); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/_Retransform.php b/lib/plugin/_Retransform.php index 4f97f2d0a..47a96a60f 100644 --- a/lib/plugin/_Retransform.php +++ b/lib/plugin/_Retransform.php @@ -24,29 +24,33 @@ * Only useful for link and parser debugging purposes. */ class WikiPlugin__Retransform -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return _("Retransform CachedMarkup"); } - function getDescription () { + function getDescription() + { return sprintf(_("Show a markup retransformation of page %s."), '[pagename]'); } - function getDefaultArguments() { + function getDefaultArguments() + { return array('page' => '[pagename]', - ); + ); } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $args = $this->getArgs($argstr, $request); extract($args); if (empty($page)) return ''; $html = HTML(HTML::h3(fmt("Retransform page '%s'", - $page))); + $page))); // bypass WikiDB and cache, go directly through the backend. $backend = &$dbi->_backend; @@ -60,25 +64,28 @@ extends WikiPlugin $html->pushContent($this->_DebugPrintArray($content)); $links = $formatted->getWikiPageLinks(); if (count($links) > 0) { - $html->pushContent(HTML::h3("Links")); - $html->pushContent($this->_DebugPrintArray($links)); + $html->pushContent(HTML::h3("Links")); + $html->pushContent($this->_DebugPrintArray($links)); } return $html; } - function _DebugPrintArray(&$array) { - $html = HTML(); - foreach ($array as $line) { + function _DebugPrintArray(&$array) + { + $html = HTML(); + foreach ($array as $line) { ob_start(); - print_r($line); - $s = HTML::pre(ob_get_contents()); - ob_end_clean(); - $html->pushContent($s); + print_r($line); + $s = HTML::pre(ob_get_contents()); + ob_end_clean(); + $html->pushContent($s); } return $html; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/plugin/_WikiTranslation.php b/lib/plugin/_WikiTranslation.php index 669299fd9..717fb9e7f 100644 --- a/lib/plugin/_WikiTranslation.php +++ b/lib/plugin/_WikiTranslation.php @@ -44,128 +44,133 @@ /* Container for untranslated pagenames. Needed to show up in locale/po/phpwiki.pot */ $pgsrc_container = - _("AllPagesCreatedByMe") .','. - _("AllPagesLastEditedByMe") .','. - _("AllPagesOwnedByMe") .','. - _("BackLinks") .','. - _("CategoryCategory") .','. - _("CategoryHomePages") .','. - _("DebugInfo") .','. - _("EditMetaData") .','. - _("FindPage") .','. - _("FullRecentChanges") .','. - _("Help/AddingPages") .','. - _("Help/AddCommentPlugin") .','. - _("Help/AuthorHistoryPlugin") .','. - _("Help/CalendarListPlugin") .','. - _("Help/CalendarPlugin") .','. - _("Help/CommentPlugin") .','. - _("Help/CreateTocPlugin") .','. - _("Help/EditMetaDataPlugin") .','. - _("Help/ExternalSearchPlugin") .','. - _("Help/FoafViewerPlugin") .','. - _("Help/FrameIncludePlugin") .','. - _("Help/HelloWorldPlugin") .','. - _("Help/IncludePagePlugin") .','. - _("Help/LinkIcons") .','. - _("Help/MagicPhpWikiURLs") .','. - _("Help/MoreAboutMechanics") .','. - _("Help/OldStyleTablePlugin") .','. - _("Help/PhotoAlbumPlugin") .','. - _("Help/PhpHighlightPlugin") .','. - _("Help/PhpWeatherPlugin") .','. - _("Help/PhpWiki") .','. - _("Help/PloticusPlugin") .','. - _("Help/RawHtmlPlugin") .','. - _("Help/RedirectToPlugin") .','. - _("Help/RichTablePlugin") .','. - _("Help/SystemInfoPlugin") .','. - _("Help/TranscludePlugin") .','. - _("Help/UnfoldSubpagesPlugin") .','. - _("Help/UpLoadPlugin") .','. - _("Help/WabiSabi") .','. - _("Help/WikiBlogPlugin") .','. - _("Help/WikiPlugin") .','. - _("Help/WikiWikiWeb"); - _("HomePageAlias") .','. - _("InterWiki") .','. + _("AllPagesCreatedByMe") . ',' . + _("AllPagesLastEditedByMe") . ',' . + _("AllPagesOwnedByMe") . ',' . + _("BackLinks") . ',' . + _("CategoryCategory") . ',' . + _("CategoryHomePages") . ',' . + _("DebugInfo") . ',' . + _("EditMetaData") . ',' . + _("FindPage") . ',' . + _("FullRecentChanges") . ',' . + _("Help/AddingPages") . ',' . + _("Help/AddCommentPlugin") . ',' . + _("Help/AuthorHistoryPlugin") . ',' . + _("Help/CalendarListPlugin") . ',' . + _("Help/CalendarPlugin") . ',' . + _("Help/CommentPlugin") . ',' . + _("Help/CreateTocPlugin") . ',' . + _("Help/EditMetaDataPlugin") . ',' . + _("Help/ExternalSearchPlugin") . ',' . + _("Help/FoafViewerPlugin") . ',' . + _("Help/FrameIncludePlugin") . ',' . + _("Help/HelloWorldPlugin") . ',' . + _("Help/IncludePagePlugin") . ',' . + _("Help/LinkIcons") . ',' . + _("Help/MagicPhpWikiURLs") . ',' . + _("Help/MoreAboutMechanics") . ',' . + _("Help/OldStyleTablePlugin") . ',' . + _("Help/PhotoAlbumPlugin") . ',' . + _("Help/PhpHighlightPlugin") . ',' . + _("Help/PhpWeatherPlugin") . ',' . + _("Help/PhpWiki") . ',' . + _("Help/PloticusPlugin") . ',' . + _("Help/RawHtmlPlugin") . ',' . + _("Help/RedirectToPlugin") . ',' . + _("Help/RichTablePlugin") . ',' . + _("Help/SystemInfoPlugin") . ',' . + _("Help/TranscludePlugin") . ',' . + _("Help/UnfoldSubpagesPlugin") . ',' . + _("Help/UpLoadPlugin") . ',' . + _("Help/WabiSabi") . ',' . + _("Help/WikiBlogPlugin") . ',' . + _("Help/WikiPlugin") . ',' . + _("Help/WikiWikiWeb"); +_("HomePageAlias") . ',' . + _("InterWiki") . ',' . // _("PageDump") .','. - _("PhpWikiAdministration/Chmod") .','. - _("PhpWikiAdministration/Chown") .','. - _("PhpWikiAdministration/Remove") .','. - _("PhpWikiAdministration/Rename") .','. - _("PhpWikiAdministration/Replace") .','. - _("PhpWikiAdministration/SetAcl") .','. - _("PhpWikiDocumentation") .','. - _("PhpWikiPoll") .','. - _("RecentVisitors") .','. - _("ReleaseNotes") .','. + _("PhpWikiAdministration/Chmod") . ',' . + _("PhpWikiAdministration/Chown") . ',' . + _("PhpWikiAdministration/Remove") . ',' . + _("PhpWikiAdministration/Rename") . ',' . + _("PhpWikiAdministration/Replace") . ',' . + _("PhpWikiAdministration/SetAcl") . ',' . + _("PhpWikiDocumentation") . ',' . + _("PhpWikiPoll") . ',' . + _("RecentVisitors") . ',' . + _("ReleaseNotes") . ',' . // _("SpellCheck") .','. - _("SteveWainstead") .','. - _("TranslateText") .','. - _("UpLoad") .','. + _("SteveWainstead") . ',' . + _("TranslateText") . ',' . + _("UpLoad") . ',' . -require_once 'lib/PageList.php'; + require_once 'lib/PageList.php'; class WikiPlugin__WikiTranslation -extends WikiPlugin + extends WikiPlugin { - function getName() { + function getName() + { return _("_WikiTranslation"); } - function getDescription() { + function getDescription() + { return _("Show translations of various words or pages"); } - function getDefaultArguments() { + function getDefaultArguments() + { return array_merge - ( - PageList::supportedArgs(), - array( 'languages' => '', // comma delimited string of de,en,sv,... - 'string' => '', - 'page' => '', // use a translation service - 'what' => 'pages', // or 'buttons', 'plugins' or 'wikiwords' + ( + PageList::supportedArgs(), + array('languages' => '', // comma delimited string of de,en,sv,... + 'string' => '', + 'page' => '', // use a translation service + 'what' => 'pages', // or 'buttons', 'plugins' or 'wikiwords' - 'match' => '*', - 'from_lang' => false, - 'include_empty' => false, - //'exclude' => '', - //'sortby' => '', - //'limit' => 0, - 'nolinks' => false, // don't display any links - // (for development only) - 'noT' => false // don't display the T link - // (for development only) - )); + 'match' => '*', + 'from_lang' => false, + 'include_empty' => false, + //'exclude' => '', + //'sortby' => '', + //'limit' => 0, + 'nolinks' => false, // don't display any links + // (for development only) + 'noT' => false // don't display the T link + // (for development only) + )); } - function init_locale($lang) { + function init_locale($lang) + { if ($lang != $this->lang) update_locale($lang); if ($lang == 'en') { // Hack alert! we need hash for stepping through it, even if it's // in the wrong language - include (FindFile("locale/de/LC_MESSAGES/phpwiki.php", 0,'reinit')); + include (FindFile("locale/de/LC_MESSAGES/phpwiki.php", 0, 'reinit')); foreach ($locale as $en => $de) { - $locale[$en] = $en; + $locale[$en] = $en; } - // gettext module loaded: must load the LC_MESSAGES php hash - } elseif (function_exists ('bindtextdomain')) { - include (FindFile("locale/$lang/LC_MESSAGES/phpwiki.php", 0,'reinit')); + // gettext module loaded: must load the LC_MESSAGES php hash + } elseif (function_exists('bindtextdomain')) { + include (FindFile("locale/$lang/LC_MESSAGES/phpwiki.php", 0, 'reinit')); //include (FindLocalizedFile("LC_MESSAGES/phpwiki.php", 0,'reinit')); - // we already have a $locale, but maybe it's in the wrong language + // we already have a $locale, but maybe it's in the wrong language } elseif ($lang != $this->lang or empty($GLOBALS['locale'])) { - include (FindFile("locale/$lang/LC_MESSAGES/phpwiki.php", 0,'reinit')); + include (FindFile("locale/$lang/LC_MESSAGES/phpwiki.php", 0, 'reinit')); } else { - $locale = & $GLOBALS['locale']; + $locale = & $GLOBALS['locale']; } $this->_locales[$lang] = $locale; } // reverse translation: - function translate_to_en($text, $lang=false) { + function translate_to_en($text, $lang = false) + { if (!$lang) $lang = $this->lang; // current locale if ($lang == 'en') return $text; @@ -191,7 +196,8 @@ extends WikiPlugin * setlocale() switching with the gettext extension is by far too slow. * So use the hash regardless if gettext is loaded or not. */ - function fast_translate($text, $to_lang, $from_lang=false) { + function fast_translate($text, $to_lang, $from_lang = false) + { if (!$from_lang) $from_lang = $this->lang; // current locale if ($from_lang == $to_lang) return $text; // setup hash from en => to_lang @@ -202,12 +208,13 @@ extends WikiPlugin $text = $this->translate_to_en($text, $from_lang); } return !empty($this->_locales[$to_lang][$text]) - ? $this->_locales[$to_lang][$text] - : $text; + ? $this->_locales[$to_lang][$text] + : $text; } //FIXME! There's something wrong. - function translate($text, $to_lang, $from_lang=false) { + function translate($text, $to_lang, $from_lang = false) + { if (!$from_lang) $from_lang = $this->lang; // current locale if ($from_lang == $to_lang) return $text; // Speed up hash lookup. Not needed for gettext module @@ -235,7 +242,8 @@ extends WikiPlugin return $result; } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $this->args = $this->getArgs($argstr, $request); extract($this->args); $this->request = &$request; @@ -253,8 +261,8 @@ extends WikiPlugin if (in_array($from_lang, $available_languages)) $languages = $available_languages; else - $languages = array_merge($available_languages, array($from_lang)); - } elseif (strstr($languages,',')) { + $languages = array_merge($available_languages, array($from_lang)); + } elseif (strstr($languages, ',')) { $languages = explode(',', $languages); } else { $languages = array($languages); @@ -266,34 +274,34 @@ extends WikiPlugin // or display them with all the errors. //FIXME: do iconv the ob if ($GLOBALS['charset'] != 'utf-8' and !defined('NEED_ICONV_TO')) { - define('NEED_ICONV_TO', 'utf-8'); - //either the extension or external + define('NEED_ICONV_TO', 'utf-8'); + //either the extension or external //$GLOBALS['charset'] = 'utf-8'; } } $to_lang = $languages[0]; - if (!empty($string) and count($languages)==1) { + if (!empty($string) and count($languages) == 1) { return $this->translate($string, $to_lang, $from_lang); } if (!empty($page)) { $pagename = $page; if ($dbi->isWikiPage($pagename)) { - $url = ''; - // google can only translate from english and french - if (in_array($from_lang, array('en', 'fr'))) { + $url = ''; + // google can only translate from english and french + if (in_array($from_lang, array('en', 'fr'))) { $url = "http://translate.google.com/translate"; - $url .= "?langpair=" . urlencode($from_lang."|".$to_lang); + $url .= "?langpair=" . urlencode($from_lang . "|" . $to_lang); $url .= "&u=" . urlencode(WikiURL($pagename, false, true)); - } - // redirect or transclude? + } + // redirect or transclude? if ($url) { return $request->redirect($url); } - return HTML(fmt("TODO: Google can only translate from english and french. Find a translation service for %s to language %s", - WikiURL($pagename, false, true), - $to_lang)); + return HTML(fmt("TODO: Google can only translate from english and french. Find a translation service for %s to language %s", + WikiURL($pagename, false, true), + $to_lang)); } else { - return $this->error(fmt("%s is empty",$pagename)); + return $this->error(fmt("%s is empty", $pagename)); } } @@ -302,80 +310,84 @@ extends WikiPlugin foreach ($languages as $lang) { if ($lang == $from_lang) continue; $field = "custom:$lang"; - $pagelist->addColumnObject ( - new _PageList_Column_customlang($field, $from_lang, $this)); + $pagelist->addColumnObject( + new _PageList_Column_customlang($field, $from_lang, $this)); } if (!empty($string)) { - $pagelist->addPage( $string ); + $pagelist->addPage($string); return $pagelist; } switch ($what) { - case 'allpages': - $pagelist->addPages( $dbi->getAllPages($include_empty, $sortby, - $limit, $exclude) ); - break; - case 'pages': - // not all pages, only the pgsrc pages - if (!is_array($exclude)) - $exclude = $pagelist->explodePageList($exclude, false, $sortby, - $limit, $exclude); - $path = FindLocalizedFile(WIKI_PGSRC); - $pgsrc = new fileSet($path); - foreach ($pgsrc->getFiles($exclude, $sortby, $limit) as $pagename) { - $pagename = urldecode($pagename); - if (substr($pagename,-1,1) == '~') continue; - if (in_array($pagename, $exclude)) - continue; // exclude page. - if ($match != '*' and !glob_match($match, $pagename)) - continue; - $page_handle = $dbi->getPage($pagename); - $pagelist->addPage( $page_handle ); - } - break; - case 'wikiwords': - if (!isset($this->_locales[$from_lang])) { - $this->init_locale($from_lang); - } - $locale = & $this->_locales[$from_lang]; - if (is_array($locale)) { - $count = 0; - foreach ($locale as $from => $to) { - if ($match != '*' and !glob_match($match, $from)) + case 'allpages': + $pagelist->addPages($dbi->getAllPages($include_empty, $sortby, + $limit, $exclude)); + break; + case 'pages': + // not all pages, only the pgsrc pages + if (!is_array($exclude)) + $exclude = $pagelist->explodePageList($exclude, false, $sortby, + $limit, $exclude); + $path = FindLocalizedFile(WIKI_PGSRC); + $pgsrc = new fileSet($path); + foreach ($pgsrc->getFiles($exclude, $sortby, $limit) as $pagename) { + $pagename = urldecode($pagename); + if (substr($pagename, -1, 1) == '~') continue; + if (in_array($pagename, $exclude)) + continue; // exclude page. + if ($match != '*' and !glob_match($match, $pagename)) continue; - if (isWikiWord($from)) { - $count++; - $pagelist->addPage( $from ); - if ($limit and $count > $limit) break; + $page_handle = $dbi->getPage($pagename); + $pagelist->addPage($page_handle); + } + break; + case 'wikiwords': + if (!isset($this->_locales[$from_lang])) { + $this->init_locale($from_lang); + } + $locale = & $this->_locales[$from_lang]; + if (is_array($locale)) { + $count = 0; + foreach ($locale as $from => $to) { + if ($match != '*' and !glob_match($match, $from)) + continue; + if (isWikiWord($from)) { + $count++; + $pagelist->addPage($from); + if ($limit and $count > $limit) break; + } } } - } - break; - // all Button texts, which need a localized .png - // where to get them from? templates/*.tmpl: Button() - // and WikiLink(?,'button') - // navbar links, actionpages, and admin requests - case 'buttons': - $buttons = $GLOBALS['AllActionPages']; - $fileset = new FileSet(FindFile("themes/MacOSX/buttons/en"), - "*.png"); - foreach ($fileset->getFiles() as $file) { - $b = urldecode(substr($file, 0, -4)); - if (!in_array($b,$buttons)) - $buttons[] = $b; - } - $count = 0; - foreach ($buttons as $button) { - $pagelist->addPage( $button ); - if ($limit and ++$count > $limit) break; - } - break; + break; + // all Button texts, which need a localized .png + // where to get them from? templates/*.tmpl: Button() + // and WikiLink(?,'button') + // navbar links, actionpages, and admin requests + case 'buttons': + $buttons = $GLOBALS['AllActionPages']; + $fileset = new FileSet(FindFile("themes/MacOSX/buttons/en"), + "*.png"); + foreach ($fileset->getFiles() as $file) { + $b = urldecode(substr($file, 0, -4)); + if (!in_array($b, $buttons)) + $buttons[] = $b; + } + $count = 0; + foreach ($buttons as $button) { + $pagelist->addPage($button); + if ($limit and ++$count > $limit) break; + } + break; } return $pagelist; } -}; +} + +; -class _PageList_Column_customlang extends _PageList_Column { - function _PageList_Column_customlang($field, $from_lang, $plugin) { +class _PageList_Column_customlang extends _PageList_Column +{ + function _PageList_Column_customlang($field, $from_lang, $plugin) + { $this->_field = $field; $this->_from_lang = $from_lang; $this->_plugin =& $plugin; @@ -390,30 +402,31 @@ class _PageList_Column_customlang extends _PageList_Column { $this->_PageList_Column_base($this->_field); } - function _getValue($page, &$revision_handle) { - if (is_object($page)) $text = $page->getName(); + function _getValue($page, &$revision_handle) + { + if (is_object($page)) $text = $page->getName(); else $text = $page; - $trans = $this->_plugin->fast_translate($text, $this->_field, - $this->_from_lang); + $trans = $this->_plugin->fast_translate($text, $this->_field, + $this->_from_lang); // how to markup untranslated words and not existing pages? // untranslated: (TODO) link to translation editor if ($trans == $text or // untranslated (($this->_from_lang != 'en') and - ($this->_field != 'en') and - ($trans == $this->_plugin->fast_translate($text, 'en', - $this->_from_lang)) - )) - { + ($this->_field != 'en') and + ($trans == $this->_plugin->fast_translate($text, 'en', + $this->_from_lang)) + ) + ) { global $WikiTheme; $link = $WikiTheme->linkUnknownWikiWord($trans); if (!($this->_noT or $this->_nolinks) - and $this->dbi->isWikiPage($trans)) - { + and $this->dbi->isWikiPage($trans) + ) { $url = WikiURL($trans, array('action' => 'TranslateText', - 'lang' => $this->_field)); + 'lang' => $this->_field)); $button = $WikiTheme->makeButton('T', $url); $button->addTooltip(sprintf(_("Define the translation for %s in %s"), - $trans, $this->_field)); + $trans, $this->_field)); $link = HTML::span($button); $link->setAttr('class', 'wikiunknown'); $text = HTML::span($WikiTheme->maybeSplitWikiWord($trans)); @@ -421,8 +434,7 @@ class _PageList_Column_customlang extends _PageList_Column { $link->pushContent($text); return $link; } elseif (is_object($page)) - return ''; - else // not existing: empty + return ''; else // not existing: empty return ''; } elseif (is_object($page)) { if (!$this->_nolinks) diff --git a/lib/plugin/text2png.php b/lib/plugin/text2png.php index fdf276199..c6db60c25 100644 --- a/lib/plugin/text2png.php +++ b/lib/plugin/text2png.php @@ -46,30 +46,34 @@ if (!defined('text2png_debug')) class WikiPlugin_text2png -extends WikiPlugin + extends WikiPlugin { - function getName () { + function getName() + { return "text2png"; } - function getDescription() { + function getDescription() + { return _("Convert text into a png image using GD."); } - function getDefaultArguments() { + function getDefaultArguments() + { global $LANG; // TODO: add fixed size and center. - return array('text' => "text2png testtext", - 'lang' => $LANG, - '_force' => 0, - 'fontsize' => 18, // with GD1 it's the pixelsize, with GD2 the pointsize - 'with_shadow' => 1, - 'fontcolor' => '#000000', - 'shadowcolor' => '#AFAFAF', - 'backcolor' => '#ffffff'); - } + return array('text' => "text2png testtext", + 'lang' => $LANG, + '_force' => 0, + 'fontsize' => 18, // with GD1 it's the pixelsize, with GD2 the pointsize + 'with_shadow' => 1, + 'fontcolor' => '#000000', + 'shadowcolor' => '#AFAFAF', + 'backcolor' => '#ffffff'); + } - function run($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { if (ImageTypes() & IMG_PNG) { // we have gd & png so go ahead. $args = $this->getArgs($argstr, $request); @@ -78,29 +82,31 @@ extends WikiPlugin // we don't have png and/or gd. $error_html = _("Sorry, this version of PHP cannot create PNG image files."); $link = "http://www.php.net/manual/pl/ref.image.php"; - $error_html .= sprintf(_("See %s"), $link) ."."; + $error_html .= sprintf(_("See %s"), $link) . "."; trigger_error($error_html, E_USER_NOTICE); return; } } - /** - * Parse hexcolor into ordinal rgb array. - * '#000' => array(0,0,0) - * '#000000' => array(0,0,0) - */ - function hexcolor($h, $default=false) { + /** + * Parse hexcolor into ordinal rgb array. + * '#000' => array(0,0,0) + * '#000000' => array(0,0,0) + */ + function hexcolor($h, $default = false) + { if ($h[0] != '#') return $default; - $rgb = substr($h,1); + $rgb = substr($h, 1); if (strlen($rgb) == 3) - return array(hexdec($rgb{0}),hexdec($rgb{1}),hexdec($rgb{2})); + return array(hexdec($rgb{0}), hexdec($rgb{1}), hexdec($rgb{2})); elseif (strlen($rgb) == 6) - return array(hexdec(substr($rgb,0,2)),hexdec(substr($rgb,2,2)),hexdec(substr($rgb,4,2))); + return array(hexdec(substr($rgb, 0, 2)), hexdec(substr($rgb, 2, 2)), hexdec(substr($rgb, 4, 2))); return $default; } - function text2png($args) { - extract ($args); + function text2png($args) + { + extract($args); /** * Basic image creation and caching * @@ -119,11 +125,11 @@ extends WikiPlugin if ($l == "C") { $l = "en"; //english=C } else { - $l = urlencode ($l); // who on earth forgot his? + $l = urlencode($l); // who on earth forgot his? } $basedir = "text2png-image"; $filepath = getUploadFilePath() . "$basedir/$l"; - if ($_force or !file_exists($filepath.$filename)) { + if ($_force or !file_exists($filepath . $filename)) { if (!file_exists($filepath)) { $oldumask = umask(0); // permissions affected by user the www server is running as @@ -143,9 +149,8 @@ extends WikiPlugin if (defined('TTFONT')) $ttfont = TTFONT; elseif (PHP_OS == "Darwin") // Mac OS X - $ttfont = "/System/Library/Frameworks/JavaVM.framework/Versions/1.3.1/Home/lib/fonts/LucidaSansRegular.ttf"; - elseif (isWindows()) { - $ttfont = $_ENV['windir'].'\Fonts\Arial.ttf'; + $ttfont = "/System/Library/Frameworks/JavaVM.framework/Versions/1.3.1/Home/lib/fonts/LucidaSansRegular.ttf"; elseif (isWindows()) { + $ttfont = $_ENV['windir'] . '\Fonts\Arial.ttf'; } else { $ttfont = 'luximr'; // This is the only what sourceforge offered. //$ttfont = 'Helvetica'; @@ -158,28 +163,28 @@ extends WikiPlugin // get ready to draw $s = ImageTTFBBox($fontsize, 0, $ttfont, $text); - $im = @ImageCreate(abs($s[4])+20, abs($s[7])+10); + $im = @ImageCreate(abs($s[4]) + 20, abs($s[7]) + 10); if (empty($im)) { $error_html = _("PHP was unable to create a new GD image stream. Read 'lib/plugin/text2png.php' for details."); // FIXME: Error manager does not transform URLs passed // through it. $link = "http://www.php.net/manual/en/function.imagecreate.php"; - $error_html .= sprintf(_("See %s"), $link) ."."; - trigger_error( $error_html, E_USER_NOTICE ); + $error_html .= sprintf(_("See %s"), $link) . "."; + trigger_error($error_html, E_USER_NOTICE); return; } - $rgb = $this->hexcolor($backcolor, array(255,255,255)); + $rgb = $this->hexcolor($backcolor, array(255, 255, 255)); $bg_color = ImageColorAllocate($im, $rgb[0], $rgb[1], $rgb[2]); if ($with_shadow) { - $rgb = $this->hexcolor($shadowcolor, array(175,175,175)); + $rgb = $this->hexcolor($shadowcolor, array(175, 175, 175)); $text_color = ImageColorAllocate($im, $rgb[0], $rgb[1], $rgb[2]); // shadow is 1 pixel down and 2 pixels right - ImageTTFText($im, $fontsize, 0, 12, abs($s[7])+6, $text_color, $ttfont, $text); + ImageTTFText($im, $fontsize, 0, 12, abs($s[7]) + 6, $text_color, $ttfont, $text); } // draw text - $rgb = $this->hexcolor($fontcolor, array(0,0,0)); + $rgb = $this->hexcolor($fontcolor, array(0, 0, 0)); $text_color = ImageColorAllocate($im, $rgb[0], $rgb[1], $rgb[2]); - ImageTTFText($im, $fontsize, 0, 10, abs($s[7])+5, $text_color, $ttfont, $text); + ImageTTFText($im, $fontsize, 0, 10, abs($s[7]) + 5, $text_color, $ttfont, $text); /** * An alternate text drawing method in case ImageTTFText @@ -203,28 +208,30 @@ extends WikiPlugin $html = HTML(); if ($success > 0) { if (defined('text2png_debug')) { - switch($success) { - case 1: - trigger_error(sprintf(_("Image saved to cache file: %s"), - $filepath . $filename), - E_USER_NOTICE); - case 2: - trigger_error(sprintf(_("Image loaded from cache file: %s"), - $filepath . $filename), - E_USER_NOTICE); + switch ($success) { + case 1: + trigger_error(sprintf(_("Image saved to cache file: %s"), + $filepath . $filename), + E_USER_NOTICE); + case 2: + trigger_error(sprintf(_("Image loaded from cache file: %s"), + $filepath . $filename), + E_USER_NOTICE); } } - $url = getUploadDataPath()."$basedir/".urlencode($l)."/".urlencode($filename); + $url = getUploadDataPath() . "$basedir/" . urlencode($l) . "/" . urlencode($filename); $html->pushContent(HTML::img(array('src' => $url, - 'alt' => $text, - 'title' => '"'.$text.'"'. _(" produced by "). $this->getName()))); + 'alt' => $text, + 'title' => '"' . $text . '"' . _(" produced by ") . $this->getName()))); } else { trigger_error(sprintf(_("couldn't open file '%s' for writing"), - $filepath . $filename), E_USER_NOTICE); + $filepath . $filename), E_USER_NOTICE); } return $html; } -}; +} + +; // Local Variables: // mode: php -- 2.45.0