namespaces-2.2.6.pl 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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. =head1 Namespaces Extension
  15. This module allows you to create namespaces in Oddmuse. The effect is
  16. that C<http://localhost/cgi-bin/wiki/Claudia/HomePage> and
  17. C<http://localhost/cgi-bin/wiki/Alex/HomePage> are two different
  18. pages. The first URL points to the C<HomePage> in the C<Claudia>
  19. namespace, the second URL points to the C<HomePage> in the C<Alex>
  20. namespace. Both namespaces have their own list of pages and their own
  21. list of changes, and so on.
  22. C<http://localhost/cgi-bin/wiki/HomePage> points to the C<HomePage> in
  23. the main namespace. It is usually named C<Main>. The name can be
  24. changed using the C<$NamespacesMain> option.
  25. URL abbreviations will automatically be created for you. Thus, you can
  26. link to the various pages using C<Claudia:HomePage>, C<Alex:HomePage>,
  27. and C<Main:HomePage>. An additional abbreviation is also created
  28. automatically: C<Self>. You can use it to link to actions such as
  29. C<Self:action=index>. The name of this self-referring abbreviation can
  30. be changed using the C<$NamespacesSelf> option.
  31. =cut
  32. $ModulesDescription .= '<p><a href="http://git.savannah.gnu.org/cgit/oddmuse.git/tree/modules/namespaces.pl">namespaces.pl</a>, see <a href="http://www.oddmuse.org/cgi-bin/oddmuse/Namespaces_Extension">Namespaces Extension</a></p>';
  33. use File::Glob ':glob';
  34. use vars qw($NamespacesMain $NamespacesSelf $NamespaceCurrent
  35. $NamespaceRoot $NamespaceSlashing @NamespaceParameters
  36. %Namespaces);
  37. $NamespacesMain = 'Main'; # to get back to the main namespace
  38. $NamespacesSelf = 'Self'; # for your own namespace
  39. $NamespaceCurrent = ''; # the current namespace, if any
  40. $NamespaceRoot = ''; # the original $ScriptName
  41. =head2 Configuration
  42. The option C<@NamespaceParameters> can be used by programmers to
  43. indicate for which parameters the last element of path_info shall
  44. count as a namespace. Consider these examples:
  45. http://example.org/wiki/Foo/Bar
  46. http://example.org/wiki/Foo?action=browse;id=Bar
  47. http://example.org/wiki/Foo?title=Bar;text=Baz
  48. http://example.org/wiki/Foo?search=bar
  49. In all the listed cases, Foo is supposed to be the namespace.
  50. In the following cases, however, we're interested in the page Foo and
  51. not the namespace Foo.
  52. http://example.org/wiki/Foo?username=bar
  53. =cut
  54. @NamespaceParameters = qw(action search title);
  55. $NamespaceSlashing = 0; # affects : decoding NamespaceRcLines
  56. # try to do it before any other module starts meddling with the
  57. # variables (eg. localnames.pl)
  58. unshift(@MyInitVariables, \&NamespacesInitVariables);
  59. sub NamespacesInitVariables {
  60. %Namespaces = ();
  61. # Do this before changing the $DataDir and $ScriptName
  62. if (!$Monolithic and $UsePathInfo) {
  63. $Namespaces{$NamespacesMain} = $ScriptName . '/';
  64. foreach my $name (bsd_glob("$DataDir/*")) {
  65. utf8::decode($name);
  66. if (-d $name
  67. and $name =~ m|/($InterSitePattern)$|
  68. and $name ne $NamespacesMain
  69. and $name ne $NamespacesSelf) {
  70. $Namespaces{$1} = $ScriptName . '/' . $1 . '/';
  71. }
  72. }
  73. }
  74. $NamespaceRoot = $ScriptName; # $ScriptName may be changed below
  75. $NamespaceCurrent = '';
  76. my $ns = GetParam('ns', '');
  77. if (not $ns and $UsePathInfo) {
  78. my $path_info = $q->path_info();
  79. utf8::decode($path_info);
  80. # make sure ordinary page names are not matched!
  81. if ($path_info =~ m|^/($InterSitePattern)(/.*)?|
  82. and ($2 or $q->keywords or NamespaceRequiredByParameter())) {
  83. $ns = $1;
  84. }
  85. }
  86. ReportError(Ts('%s is not a legal name for a namespace', $ns))
  87. if $ns and $ns !~ m/^($InterSitePattern)$/;
  88. if ($ns
  89. and $ns ne $NamespacesMain
  90. and $ns ne $NamespacesSelf) {
  91. $NamespaceCurrent = $ns;
  92. # Change some stuff from the original InitVariables call:
  93. $SiteName .= ' ' . $NamespaceCurrent;
  94. $InterWikiMoniker = $NamespaceCurrent;
  95. $DataDir .= '/' . $NamespaceCurrent;
  96. $PageDir = "$DataDir/page";
  97. $KeepDir = "$DataDir/keep";
  98. $RefererDir = "$DataDir/referer";
  99. $TempDir = "$DataDir/temp";
  100. $LockDir = "$TempDir/lock";
  101. $NoEditFile = "$DataDir/noedit";
  102. $RcFile = "$DataDir/rc.log";
  103. $RcOldFile = "$DataDir/oldrc.log";
  104. $IndexFile = "$DataDir/pageidx";
  105. $VisitorFile = "$DataDir/visitors.log";
  106. $PermanentAnchorsFile = "$DataDir/permanentanchors";
  107. # $ConfigFile -- shared
  108. # $ModuleDir -- shared
  109. # $NearDir -- shared
  110. $ScriptName .= '/' . UrlEncode($NamespaceCurrent);
  111. $FullUrl .= '/' . UrlEncode($NamespaceCurrent);
  112. $StaticDir .= '/' . $NamespaceCurrent; # from static-copy.pl
  113. $StaticUrl .= UrlEncode($NamespaceCurrent) . '/'
  114. if substr($StaticUrl,-1) eq '/'; # from static-copy.pl
  115. $WikiDescription .= "<p>Current namespace: $NamespaceCurrent</p>";
  116. # override LastUpdate
  117. my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks)
  118. = stat($IndexFile);
  119. $LastUpdate = $mtime;
  120. CreateDir($DataDir); # Create directory if it doesn't exist
  121. ReportError(Ts('Cannot create %s', $DataDir) . ": $!", '500 INTERNAL SERVER ERROR')
  122. unless -d $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 $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 $file (@rcfiles) {
  195. open(F, '<:encoding(UTF-8)', $file);
  196. my $line = <F>;
  197. my ($ts) = split(/$FS/o, $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{$file}, $starttime,\%match, \%following));
  201. }
  202. push(@new, GetRcLinesFor($file, $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{$file};
  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 ($text, $revision) = GetTextRevision(GetParam('revision', ''), 1);
  327. my $oldId = GetParam('oldid', '');
  328. if (not $oldId and not $revision and (substr($text, 0, 10) eq '#REDIRECT ')
  329. and (($WikiLinks and $text =~ /^\#REDIRECT\s+(($InterSitePattern:)?$InterLinkPattern)/)
  330. or ($FreeLinks and $text =~ /^\#REDIRECT\s+\[\[(($InterSitePattern:)?$FreeInterLinkPattern)\]\]/))) {
  331. my ($ns, $page) = map { UrlEncode($_) } split(/:/, FreeToNormal($1));
  332. $oldid = ($NamespaceCurrent || $NamespacesMain) . ':' . $id;
  333. local $ScriptName = $NamespaceRoot || $ScriptName;
  334. print GetRedirectPage("action=browse;ns=$ns;oldid=$oldid;id=$page", $id);
  335. } else {
  336. return OldNamespaceBrowsePage(@_);
  337. }
  338. }
  339. =head2 List Namespaces
  340. The namespaces action will link all known namespaces.
  341. =cut
  342. $Action{namespaces} = \&DoNamespacesList;
  343. sub DoNamespacesList {
  344. if (GetParam('raw', 0)) {
  345. print GetHttpHeader('text/plain');
  346. print join("\n", keys %Namespaces), "\n";
  347. } else {
  348. print GetHeader('', T('Namespaces')),
  349. $q->start_div({-class=>'content namespaces'}),
  350. GetFormStart(undef, 'get'), GetHiddenValue('action', 'browse'),
  351. GetHiddenValue('id', $HomePage);
  352. my $new = $q->textfield('ns') . ' ' . $q->submit('donamespace', T('Go!'));
  353. print $q->ul($q->li([map { $q->a({-href => $Namespaces{$_} . $HomePage},
  354. $_); } keys %Namespaces]), $q->li($new));
  355. print $q->end_form() . $q->end_div();
  356. PrintFooter();
  357. }
  358. }
  359. push(@MyAdminCode, \&NamespacesMenu);
  360. sub NamespacesMenu {
  361. my ($id, $menuref, $restref) = @_;
  362. push(@$menuref,
  363. ScriptLink('action=namespaces',
  364. T('Namespaces'),
  365. 'namespaces'));
  366. }
  367. *NamespacesOldGetId = *GetId;
  368. *GetId = *NamespacesNewGetId;
  369. sub NamespacesNewGetId {
  370. my $id = NamespacesOldGetId(@_);
  371. # http://example.org/cgi-bin/wiki.pl?action=browse;ns=Test;id=Test means NamespaceCurrent=Test and id=Test
  372. # http://example.org/cgi-bin/wiki.pl/Test/Test means NamespaceCurrent=Test and id=Test
  373. # In this case GetId() will have set the parameter Test to 1.
  374. # http://example.org/cgi-bin/wiki.pl/Test?rollback-1234=foo
  375. # This doesn't set the Test parameter.
  376. if ($UsePathInfo and $id eq $NamespaceCurrent and not GetParam($id) and not GetParam('ns')) {
  377. $id = undef;
  378. }
  379. return $id;
  380. }