namespaces.pl 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. # Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2012 Alex Schroeder <alex@gnu.org>
  2. #
  3. # This program is free software; you can redistribute it and/or modify it under
  4. # the terms of the GNU General Public License as published by the Free Software
  5. # Foundation; either version 3 of the License, or (at your option) any later
  6. # version.
  7. #
  8. # This program is distributed in the hope that it will be useful, but WITHOUT
  9. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  10. # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  11. #
  12. # You should have received a copy of the GNU General Public License along with
  13. # this program. If not, see <http://www.gnu.org/licenses/>.
  14. use strict;
  15. use v5.10;
  16. =head1 Namespaces Extension
  17. This module allows you to create namespaces in Oddmuse. The effect is
  18. that C<http://localhost/cgi-bin/wiki/Claudia/HomePage> and
  19. C<http://localhost/cgi-bin/wiki/Alex/HomePage> are two different
  20. pages. The first URL points to the C<HomePage> in the C<Claudia>
  21. namespace, the second URL points to the C<HomePage> in the C<Alex>
  22. namespace. Both namespaces have their own list of pages and their own
  23. list of changes, and so on.
  24. C<http://localhost/cgi-bin/wiki/HomePage> points to the C<HomePage> in
  25. the main namespace. It is usually named C<Main>. The name can be
  26. changed using the C<$NamespacesMain> option.
  27. URL abbreviations will automatically be created for you. Thus, you can
  28. link to the various pages using C<Claudia:HomePage>, C<Alex:HomePage>,
  29. and C<Main:HomePage>. An additional abbreviation is also created
  30. automatically: C<Self>. You can use it to link to actions such as
  31. C<Self:action=index>. The name of this self-referring abbreviation can
  32. be changed using the C<$NamespacesSelf> option.
  33. =cut
  34. AddModuleDescription('namespaces.pl', 'Namespaces Extension');
  35. use File::Glob ':glob';
  36. our ($q, %Action, %Page, @IndexList, $Now, %InterSite, $SiteName, $ScriptName, $UsePathInfo, $DataDir, $HomePage, @MyInitVariables, @MyAdminCode, $FullUrl, $LinkPattern, $InterSitePattern, $FreeLinks, $FreeLinkPattern, $InterLinkPattern, $FreeInterLinkPattern, $UrlProtocols, $WikiLinks, $FS, $RcFile, $RcOldFile, $RcDefault, $PageDir, $KeepDir, $LockDir, $TempDir, $IndexFile, $VisitorFile, $NoEditFile, $WikiDescription, $LastUpdate, $StaticDir, $StaticUrl, $InterWikiMoniker, $RefererDir, $PermanentAnchorsFile);
  37. our ($NamespacesMain, $NamespacesSelf, $NamespaceCurrent,
  38. $NamespaceRoot, $NamespaceSlashing, @NamespaceParameters,
  39. %Namespaces);
  40. $NamespacesMain = 'Main'; # to get back to the main namespace
  41. $NamespacesSelf = 'Self'; # for your own namespace
  42. $NamespaceCurrent = ''; # the current namespace, if any
  43. $NamespaceRoot = ''; # the original $ScriptName
  44. =head2 Configuration
  45. The option C<@NamespaceParameters> can be used by programmers to
  46. indicate for which parameters the last element of path_info shall
  47. count as a namespace. Consider these examples:
  48. http://example.org/wiki/Foo/Bar
  49. http://example.org/wiki/Foo?action=browse;id=Bar
  50. http://example.org/wiki/Foo?title=Bar;text=Baz
  51. http://example.org/wiki/Foo?search=bar
  52. In all the listed cases, Foo is supposed to be the namespace.
  53. In the following cases, however, we're interested in the page Foo and
  54. not the namespace Foo.
  55. http://example.org/wiki/Foo?username=bar
  56. =cut
  57. @NamespaceParameters = qw(action search title match);
  58. $NamespaceSlashing = 0; # affects : decoding NamespaceRcLines
  59. # try to do it before any other module starts meddling with the
  60. # variables (eg. localnames.pl)
  61. unshift(@MyInitVariables, \&NamespacesInitVariables);
  62. sub NamespacesInitVariables {
  63. %Namespaces = ();
  64. # Do this before changing the $DataDir and $ScriptName
  65. if ($UsePathInfo) {
  66. $Namespaces{$NamespacesMain} = $ScriptName . '/';
  67. foreach my $name (Glob("$DataDir/*")) {
  68. if (IsDir($name)
  69. and $name =~ m|/($InterSitePattern)$|
  70. and $name ne $NamespacesMain
  71. and $name ne $NamespacesSelf) {
  72. $Namespaces{$1} = $ScriptName . '/' . $1 . '/';
  73. }
  74. }
  75. }
  76. $NamespaceRoot = $ScriptName; # $ScriptName may be changed below
  77. $NamespaceCurrent = '';
  78. my $ns = decode_utf8(GetParam('ns', ''));
  79. if (not $ns and $UsePathInfo) {
  80. my $path_info = decode_utf8($q->path_info());
  81. # make sure ordinary page names are not matched!
  82. if ($path_info =~ m|^/($InterSitePattern)(/.*)?|
  83. and ($2 or $q->keywords or NamespaceRequiredByParameter())) {
  84. $ns = $1;
  85. }
  86. }
  87. ReportError(Ts('%s is not a legal name for a namespace', $ns))
  88. if $ns and $ns !~ m/^($InterSitePattern)$/;
  89. if ($ns
  90. and $ns ne $NamespacesMain
  91. and $ns ne $NamespacesSelf) {
  92. $NamespaceCurrent = $ns;
  93. # Change some stuff from the original InitVariables call:
  94. $SiteName .= ' ' . $NamespaceCurrent;
  95. $InterWikiMoniker = $NamespaceCurrent;
  96. $DataDir .= '/' . $NamespaceCurrent;
  97. $PageDir = "$DataDir/page";
  98. $KeepDir = "$DataDir/keep";
  99. $RefererDir = "$DataDir/referer";
  100. $TempDir = "$DataDir/temp";
  101. $LockDir = "$TempDir/lock";
  102. $NoEditFile = "$DataDir/noedit";
  103. $RcFile = "$DataDir/rc.log";
  104. $RcOldFile = "$DataDir/oldrc.log";
  105. $IndexFile = "$DataDir/pageidx";
  106. $VisitorFile = "$DataDir/visitors.log";
  107. $PermanentAnchorsFile = "$DataDir/permanentanchors";
  108. # $ConfigFile -- shared
  109. # $ModuleDir -- shared
  110. # $NearDir -- shared
  111. $ScriptName .= '/' . UrlEncode($NamespaceCurrent);
  112. $FullUrl .= '/' . UrlEncode($NamespaceCurrent);
  113. $StaticDir .= '/' . $NamespaceCurrent; # from static-copy.pl
  114. $StaticUrl .= UrlEncode($NamespaceCurrent) . '/'
  115. if substr($StaticUrl,-1) eq '/'; # from static-copy.pl
  116. $WikiDescription .= "<p>Current namespace: $NamespaceCurrent</p>";
  117. $LastUpdate = Modified($IndexFile);
  118. CreateDir($DataDir);
  119. }
  120. $Namespaces{$NamespacesSelf} = $ScriptName . '?';
  121. # reinitialize
  122. @IndexList = ();
  123. ReInit();
  124. # transfer list of sites
  125. foreach my $key (keys %Namespaces) {
  126. $InterSite{$key} = $Namespaces{$key} unless $InterSite{$key};
  127. }
  128. # remove the artificial ones
  129. delete $Namespaces{$NamespacesMain};
  130. delete $Namespaces{$NamespacesSelf};
  131. }
  132. sub NamespaceRequiredByParameter {
  133. foreach my $key (@NamespaceParameters) {
  134. return 1 if $q->param($key);
  135. }
  136. }
  137. =head2 RecentChanges
  138. RecentChanges in the main namespace will list changes to all the
  139. namespaces. In order to limit it to the changes in the main namespace
  140. itself, you need to use the local=1 parameter. Example:
  141. C<http://localhost/cgi-bin/wiki?action=rc;local=1>
  142. First we need to read all the C<rc.log> files from the various
  143. namespace directories. If the first entry in the log file is not old
  144. enough, we need to prepend the C<oldrc.log> file.
  145. The tricky part is how to introduce the namespace prefixes to the
  146. links to be printed without copying the whole machinery. All the new
  147. lines belong to a namespace. Prefix every pagename with the namespace
  148. and a colon, ie. C<Alex:HomePage>. This provides
  149. C<NewNamespaceScriptUrl> with the necessary information to build the
  150. correct URL to link to.
  151. =cut
  152. *OldNamespaceGetRcLines = \&GetRcLines;
  153. *GetRcLines = \&NewNamespaceGetRcLines;
  154. sub NewNamespaceGetRcLines { # starttime, hash of seen pages to use as a second return value
  155. my $starttime = shift || GetParam('from', 0) ||
  156. $Now - GetParam('days', $RcDefault) * 86400; # 24*60*60
  157. my $filterOnly = GetParam('rcfilteronly', '');
  158. # these variables apply accross logfiles
  159. my %match = $filterOnly ? map { $_ => 1 } SearchTitleAndBody($filterOnly) : ();
  160. my %following = ();
  161. my @result = ();
  162. # Get the list of rc.log and oldrc.log files we need; rcoldfiles is
  163. # a mapping from rcfiles to rcoldfiles.
  164. my @rcfiles = ();
  165. my %rcoldfiles = ();
  166. my %namespaces = ();
  167. if ($NamespaceCurrent or GetParam('local', 0)) {
  168. push(@rcfiles, $RcFile);
  169. $rcoldfiles{$RcFile} = $RcOldFile;
  170. } else {
  171. push(@rcfiles, $RcFile);
  172. $rcoldfiles{$RcFile} = $RcOldFile;
  173. # Get the namespaces from the intermap instead of parsing the
  174. # directory. This reduces the chances of getting different
  175. # results.
  176. foreach my $site (keys %InterSite) {
  177. if (substr($InterSite{$site}, 0, length($ScriptName)) eq $ScriptName) {
  178. my $ns = $site;
  179. my $file = "$DataDir/$ns/rc.log";
  180. push(@rcfiles, $file);
  181. $namespaces{$file} = $ns;
  182. $rcoldfiles{$file} = "$DataDir/$ns/oldrc.log";
  183. }
  184. }
  185. }
  186. # Now each rcfile and the matching rcoldfile if required. When
  187. # opening a rcfile, compare the first timestamp with the
  188. # starttime. If any rcfile exists with no timestamp before the
  189. # starttime, we need to open its rcoldfile.
  190. foreach my $rcfile (@rcfiles) {
  191. open(my $F, '<:encoding(UTF-8)', encode_utf8($rcfile));
  192. my $line = <$F>;
  193. my ($ts) = split(/$FS/, $line); # the first timestamp in the regular rc file
  194. my @new;
  195. if (not $ts or $ts > $starttime) { # we need to read the old rc file, too
  196. push(@new, GetRcLinesFor($rcoldfiles{$rcfile}, $starttime,\%match, \%following));
  197. }
  198. push(@new, GetRcLinesFor($rcfile, $starttime, \%match, \%following));
  199. # strip rollbacks in each namespace separately
  200. @new = StripRollbacks(@new);
  201. # prepend the namespace to both pagename and author
  202. my $ns = $namespaces{$rcfile};
  203. if ($ns) {
  204. for (my $i = $#new; $i >= 0; $i--) {
  205. # page id
  206. $new[$i][1] = $ns . ':' . $new[$i][1];
  207. # username
  208. $new[$i][5] = $ns . ':' . $new[$i][5];
  209. }
  210. }
  211. push(@result, @new);
  212. }
  213. # We need to resort these lines... <=> forces numerical comparison
  214. # which is just what we need here, as the timestamp is the first
  215. # part of the line.
  216. @result = sort { $a->[0] <=> $b->[0] } @result;
  217. # check the first timestamp in the default file, maybe read old log file
  218. # GetRcLinesFor is trying to save memory space, but some operations
  219. # can only happen once we have all the data.
  220. return LatestChanges(@result);
  221. }
  222. =head2 RSS feed
  223. When retrieving the RSS feed with the parameter full=1, one would
  224. expect the various items to contain the fully rendered HTML.
  225. Unfortunately, this is not so, the reason being that OpenPage tries to
  226. open a file for id C<Test:Foo> which does not exist. Now, just
  227. fiddling with OpenPage will not work, because when rendering a page
  228. within a particular namespace, we need a separate C<%IndexHash> to
  229. figure out which links will actually point to existing pages and which
  230. will not. In fact, we need something alike the code for
  231. C<NamespacesInitVariables> to run. To do this elegantly would require
  232. us to create some sort of context, and cache it, and restore the
  233. default when we're done. All of this would be complicated and brittle.
  234. Until then, the parameter full=1 just is not supported.
  235. =head2 Encoding pagenames
  236. C<NewNamespaceUrlEncode> uses C<UrlEncode> to encode pagenames, with
  237. one exception. If the local variable C<$NamespaceSlashing> has been
  238. set, the first encoded slash is converted back into an ordinary slash.
  239. This should preserve the slash added between namespace and pagename.
  240. =cut
  241. *OldNamespaceUrlEncode = \&UrlEncode;
  242. *UrlEncode = \&NewNamespaceUrlEncode;
  243. sub NewNamespaceUrlEncode {
  244. my $result = OldNamespaceUrlEncode(@_);
  245. $result =~ s/\%2f/\// if $NamespaceSlashing; # just one should be enough
  246. return $result;
  247. }
  248. =head2 Printing Links
  249. We also need to override C<ScriptUrl>. This is done by
  250. C<NewNamespaceScriptUrl>. This is where the slash in the pagename is
  251. used to build a new URL pointing to the appropriate page in the
  252. appropriate namespace.
  253. In addition to that, this function makes sure that backlinks to edit
  254. pages with redirections result in an appropriate URL.
  255. This is used for ordinary page viewing and RecentChanges.
  256. =cut
  257. *OldNamespaceScriptUrl = \&ScriptUrl;
  258. *ScriptUrl = \&NewNamespaceScriptUrl;
  259. sub NewNamespaceScriptUrl {
  260. my ($action, @rest) = @_;
  261. local $ScriptName = $ScriptName;
  262. if ($action =~ /^($UrlProtocols)\%3a/) { # URL-encoded URL
  263. # do nothing (why do we need this?)
  264. } elsif ($action =~ m!(.*?)([^/?&;=]+)%3a(.*)!) {
  265. # $2 is supposed to match the $InterSitePattern, but it might be
  266. # UrlEncoded in Main:RecentChanges. If $2 contains Umlauts, for
  267. # example, the encoded $2 will no longer match $InterSitePattern.
  268. # We have a likely candidate -- now perform an additional test.
  269. my ($s1, $s2, $s3) = ($1, $2, $3);
  270. my $s = UrlDecode($s2);
  271. if ($s =~ /^$InterSitePattern$/) {
  272. if ("$s2:$s3" eq GetParam('oldid', '')) {
  273. if ($s2 eq $NamespacesMain) {
  274. $ScriptName = $NamespaceRoot;
  275. } else {
  276. $ScriptName = $NamespaceRoot . '/' . $s2;
  277. }
  278. } else {
  279. $ScriptName .= '/' . $s2;
  280. }
  281. $action = $s1 . $s3;
  282. }
  283. }
  284. return OldNamespaceScriptUrl($action, @rest);
  285. }
  286. =head2 Invalid Pagenames
  287. Since the adding of a namespace and colon makes all these new
  288. pagenames invalid, C<NamespaceValidId> is overridden with an empty
  289. function called C<NamespaceValidId> while C<NewNamespaceDoRc> is
  290. running. This is important so that author links are printed.
  291. =cut
  292. *OldNamespaceGetAuthorLink = \&GetAuthorLink;
  293. *GetAuthorLink = \&NewNamespaceGetAuthorLink;
  294. sub NewNamespaceGetAuthorLink {
  295. local *OldNamespaceValidId = \&ValidId;
  296. local *ValidId = \&NewNamespaceValidId;
  297. # local $NamespaceSlashing = 1;
  298. return OldNamespaceGetAuthorLink(@_);
  299. }
  300. sub NewNamespaceValidId {
  301. local $FreeLinkPattern = "($InterSitePattern:)?$FreeLinkPattern";
  302. local $LinkPattern = "($InterSitePattern:)?$LinkPattern";
  303. return OldNamespaceValidId(@_);
  304. }
  305. =head2 Redirection User Interface
  306. When redirection form page A to B, you will never see the link "Edit
  307. this page" at the bottom of page A. Therefore Oddmuse adds a link at
  308. the top of page B (if you arrived there via a redirection), linking to
  309. the edit page for A. C<NewNamespaceBrowsePage> has the necessary code
  310. to make this work for redirections between namespaces. This involves
  311. passing namespace and pagename via the C<oldid> parameter to the next
  312. script invokation, where C<ScriptUrl> will be used to create the
  313. appropriate link. This is where C<NewNamespaceScriptUrl> comes into
  314. play.
  315. =cut
  316. *OldNamespaceBrowsePage = \&BrowsePage;
  317. *BrowsePage = \&NewNamespaceBrowsePage;
  318. sub NewNamespaceBrowsePage {
  319. #REDIRECT into different namespaces
  320. my ($id, $raw, $comment, $status) = @_;
  321. OpenPage($id);
  322. my ($revisionPage, $revision) = GetTextRevision(GetParam('revision', ''), 1);
  323. my $text = $revisionPage->{text};
  324. my $oldId = GetParam('oldid', '');
  325. if (not $oldId and not $revision and (substr($text, 0, 10) eq '#REDIRECT ')
  326. and (($WikiLinks and $text =~ /^\#REDIRECT\s+(($InterSitePattern:)?$InterLinkPattern)/)
  327. or ($FreeLinks and $text =~ /^\#REDIRECT\s+\[\[(($InterSitePattern:)?$FreeInterLinkPattern)\]\]/))) {
  328. my ($ns, $page) = map { UrlEncode($_) } split(/:/, FreeToNormal($1));
  329. $oldId = ($NamespaceCurrent || $NamespacesMain) . ':' . $id;
  330. local $ScriptName = $NamespaceRoot || $ScriptName;
  331. print GetRedirectPage("action=browse;ns=$ns;oldid=$oldId;id=$page", $id);
  332. } else {
  333. return OldNamespaceBrowsePage(@_);
  334. }
  335. }
  336. =head2 List Namespaces
  337. The namespaces action will link all known namespaces.
  338. =cut
  339. $Action{namespaces} = \&DoNamespacesList;
  340. sub DoNamespacesList {
  341. if (GetParam('raw', 0)) {
  342. print GetHttpHeader('text/plain');
  343. print join("\n", keys %Namespaces), "\n";
  344. } else {
  345. print GetHeader('', T('Namespaces')),
  346. $q->start_div({-class=>'content namespaces'}),
  347. GetFormStart(undef, 'get'), GetHiddenValue('action', 'browse'),
  348. GetHiddenValue('id', $HomePage);
  349. my $new = $q->textfield('ns') . ' ' . $q->submit('donamespace', T('Go!'));
  350. print $q->ul($q->li([map { $q->a({-href => $Namespaces{$_} . $HomePage},
  351. $_); } keys %Namespaces]), $q->li($new));
  352. print $q->end_form() . $q->end_div();
  353. PrintFooter();
  354. }
  355. }
  356. push(@MyAdminCode, \&NamespacesMenu);
  357. sub NamespacesMenu {
  358. my ($id, $menuref, $restref) = @_;
  359. push(@$menuref,
  360. ScriptLink('action=namespaces',
  361. T('Namespaces'),
  362. 'namespaces'));
  363. }
  364. *NamespacesOldGetId = \&GetId;
  365. *GetId = \&NamespacesNewGetId;
  366. sub NamespacesNewGetId {
  367. my $id = NamespacesOldGetId(@_);
  368. # http://example.org/cgi-bin/wiki.pl?action=browse;ns=Test;id=Test means NamespaceCurrent=Test and id=Test
  369. # http://example.org/cgi-bin/wiki.pl/Test/Test means NamespaceCurrent=Test and id=Test
  370. # In this case GetId() will have set the parameter Test to 1.
  371. # http://example.org/cgi-bin/wiki.pl/Test?rollback-1234=foo
  372. # This doesn't set the Test parameter.
  373. return if $id and $UsePathInfo and $id eq $NamespaceCurrent and not GetParam($id) and not GetParam('ns');
  374. return $id;
  375. }