namespaces.pl 16 KB

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