Route all access to cm_fields[] through api functions
[citadel.git] / citadel / modules / wiki / serv_wiki.c
1 /*
2  * Server-side module for Wiki rooms.  This handles things like version control. 
3  * 
4  * Copyright (c) 2009-2012 by the citadel.org team
5  *
6  * This program is open source software.  You can redistribute it and/or
7  * modify it under the terms of the GNU General Public License, version 3.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #include "sysdep.h"
16 #include <stdlib.h>
17 #include <unistd.h>
18 #include <stdio.h>
19 #include <fcntl.h>
20 #include <signal.h>
21 #include <pwd.h>
22 #include <errno.h>
23 #include <ctype.h>
24 #include <sys/types.h>
25
26 #if TIME_WITH_SYS_TIME
27 # include <sys/time.h>
28 # include <time.h>
29 #else
30 # if HAVE_SYS_TIME_H
31 #  include <sys/time.h>
32 # else
33 #  include <time.h>
34 # endif
35 #endif
36
37 #include <sys/wait.h>
38 #include <string.h>
39 #include <limits.h>
40 #include <libcitadel.h>
41 #include "citadel.h"
42 #include "server.h"
43 #include "citserver.h"
44 #include "support.h"
45 #include "config.h"
46 #include "control.h"
47 #include "user_ops.h"
48 #include "database.h"
49 #include "msgbase.h"
50 #include "euidindex.h"
51 #include "ctdl_module.h"
52
53 /*
54  * Data passed back and forth between wiki_rev() and its MIME parser callback
55  */
56 struct HistoryEraserCallBackData {
57         char *tempfilename;             /* name of temp file being patched */
58         char *stop_when;                /* stop when we hit this uuid */
59         int done;                       /* set to nonzero when we're done patching */
60 };
61
62 /*
63  * Name of the temporary room we create to store old revisions when someone requests them.
64  * We put it in an invalid namespace so the DAP cleans up after us later.
65  */
66 char *wwm = "9999999999.WikiWaybackMachine";
67
68 /*
69  * Before allowing a wiki page save to execute, we have to perform version control.
70  * This involves fetching the old version of the page if it exists.
71  */
72 int wiki_upload_beforesave(struct CtdlMessage *msg) {
73         struct CitContext *CCC = CC;
74         long old_msgnum = (-1L);
75         struct CtdlMessage *old_msg = NULL;
76         long history_msgnum = (-1L);
77         struct CtdlMessage *history_msg = NULL;
78         char diff_old_filename[PATH_MAX];
79         char diff_new_filename[PATH_MAX];
80         char diff_out_filename[PATH_MAX];
81         char diff_cmd[PATH_MAX];
82         FILE *fp;
83         int rv;
84         char history_page[1024];
85         long history_page_len;
86         char boundary[256];
87         char prefixed_boundary[258];
88         char buf[1024];
89         char *diffbuf = NULL;
90         size_t diffbuf_len = 0;
91         char *ptr = NULL;
92
93         if (!CCC->logged_in) return(0); /* Only do this if logged in. */
94
95         /* Is this a room with a Wiki in it, don't run this hook. */
96         if (CCC->room.QRdefaultview != VIEW_WIKI) {
97                 return(0);
98         }
99
100         /* If this isn't a MIME message, don't bother. */
101         if (msg->cm_format_type != 4) return(0);
102
103         /* If there's no EUID we can't do this.  Reject the post. */
104         if (msg->cm_fields[eExclusiveID] == NULL) return(1);
105
106         history_page_len = snprintf(history_page, sizeof history_page,
107                                     "%s_HISTORY_", msg->cm_fields[eExclusiveID]);
108
109         /* Make sure we're saving a real wiki page rather than a wiki history page.
110          * This is important in order to avoid recursing infinitely into this hook.
111          */
112         if (    (strlen(msg->cm_fields[eExclusiveID]) >= 9)
113                 && (!strcasecmp(&msg->cm_fields[eExclusiveID][strlen(msg->cm_fields[eExclusiveID])-9], "_HISTORY_"))
114         ) {
115                 syslog(LOG_DEBUG, "History page not being historied\n");
116                 return(0);
117         }
118
119         /* If there's no message text, obviously this is all b0rken and shouldn't happen at all */
120         if (msg->cm_fields[eMesageText] == NULL) return(0);
121
122         /* Set the message subject identical to the page name */
123         CM_CopyField(msg, eMsgSubject, eExclusiveID);
124
125         /* See if we can retrieve the previous version. */
126         old_msgnum = CtdlLocateMessageByEuid(msg->cm_fields[eExclusiveID], &CCC->room);
127         if (old_msgnum > 0L) {
128                 old_msg = CtdlFetchMessage(old_msgnum, 1);
129         }
130         else {
131                 old_msg = NULL;
132         }
133
134         if ((old_msg != NULL) && (old_msg->cm_fields[eMesageText] == NULL)) {   /* old version is corrupt? */
135                 CtdlFreeMessage(old_msg);
136                 old_msg = NULL;
137         }
138         
139         /* If no changes were made, don't bother saving it again */
140         if ((old_msg != NULL) && (!strcmp(msg->cm_fields[eMesageText], old_msg->cm_fields[eMesageText]))) {
141                 CtdlFreeMessage(old_msg);
142                 return(1);
143         }
144
145         /*
146          * Generate diffs
147          */
148         CtdlMakeTempFileName(diff_old_filename, sizeof diff_old_filename);
149         CtdlMakeTempFileName(diff_new_filename, sizeof diff_new_filename);
150         CtdlMakeTempFileName(diff_out_filename, sizeof diff_out_filename);
151
152         if (old_msg != NULL) {
153                 fp = fopen(diff_old_filename, "w");
154                 rv = fwrite(old_msg->cm_fields[eMesageText], strlen(old_msg->cm_fields[eMesageText]), 1, fp);
155                 fclose(fp);
156                 CtdlFreeMessage(old_msg);
157         }
158
159         fp = fopen(diff_new_filename, "w");
160         rv = fwrite(msg->cm_fields[eMesageText], strlen(msg->cm_fields[eMesageText]), 1, fp);
161         fclose(fp);
162
163         snprintf(diff_cmd, sizeof diff_cmd,
164                 DIFF " -u %s %s >%s",
165                 diff_new_filename,
166                 ((old_msg != NULL) ? diff_old_filename : "/dev/null"),
167                 diff_out_filename
168         );
169         syslog(LOG_DEBUG, "diff cmd: %s", diff_cmd);
170         rv = system(diff_cmd);
171         syslog(LOG_DEBUG, "diff cmd returned %d", rv);
172
173         diffbuf_len = 0;
174         diffbuf = NULL;
175         fp = fopen(diff_out_filename, "r");
176         if (fp == NULL) {
177                 fp = fopen("/dev/null", "r");
178         }
179         if (fp != NULL) {
180                 fseek(fp, 0L, SEEK_END);
181                 diffbuf_len = ftell(fp);
182                 fseek(fp, 0L, SEEK_SET);
183                 diffbuf = malloc(diffbuf_len + 1);
184                 fread(diffbuf, diffbuf_len, 1, fp);
185                 diffbuf[diffbuf_len] = '\0';
186                 fclose(fp);
187         }
188
189         syslog(LOG_DEBUG, "diff length is "SIZE_T_FMT" bytes", diffbuf_len);
190
191         unlink(diff_old_filename);
192         unlink(diff_new_filename);
193         unlink(diff_out_filename);
194
195         /* Determine whether this was a bogus (empty) edit */
196         if ((diffbuf_len = 0) && (diffbuf != NULL)) {
197                 free(diffbuf);
198                 diffbuf = NULL;
199         }
200         if (diffbuf == NULL) {
201                 return(1);              /* No changes at all?  Abandon the post entirely! */
202         }
203
204         /* Now look for the existing edit history */
205
206         history_msgnum = CtdlLocateMessageByEuid(history_page, &CCC->room);
207         history_msg = NULL;
208         if (history_msgnum > 0L) {
209                 history_msg = CtdlFetchMessage(history_msgnum, 1);
210         }
211
212         /* Create a new history message if necessary */
213         if (history_msg == NULL) {
214                 char *buf;
215                 long len;
216
217                 history_msg = malloc(sizeof(struct CtdlMessage));
218                 memset(history_msg, 0, sizeof(struct CtdlMessage));
219                 history_msg->cm_magic = CTDLMESSAGE_MAGIC;
220                 history_msg->cm_anon_type = MES_NORMAL;
221                 history_msg->cm_format_type = FMT_RFC822;
222                 CM_SetField(history_msg, eAuthor, HKEY("Citadel"));
223                 CM_SetField(history_msg, eRecipient, CCC->room.QRname, strlen(CCC->room.QRname));
224                 CM_SetField(history_msg, eExclusiveID, history_page, history_page_len);
225                 CM_SetField(history_msg, eMsgSubject, history_page, history_page_len);
226                 CM_SetField(history_msg, eSuppressIdx, HKEY("1")); /* suppress full text indexing */
227                 snprintf(boundary, sizeof boundary, "Citadel--Multipart--%04x--%08lx", getpid(), time(NULL));
228                 buf = (char*) malloc(1024);
229                 len = snprintf(buf, 1024,
230                                "Content-type: multipart/mixed; boundary=\"%s\"\n\n"
231                                "This is a Citadel wiki history encoded as multipart MIME.\n"
232                                "Each part is comprised of a diff script representing one change set.\n"
233                                "\n"
234                                "--%s--\n",
235                                boundary, boundary
236                 );
237                 CM_SetAsField(history_msg, eMesageText, &buf, len);
238         }
239
240         /* Update the history message (regardless of whether it's new or existing) */
241
242         /* Remove the Message-ID from the old version of the history message.  This will cause a brand
243          * new one to be generated, avoiding an uninitentional hit of the loop zapper when we replicate.
244          */
245         CM_FlushField(history_msg, emessageId);
246
247         /* Figure out the boundary string.  We do this even when we generated the
248          * boundary string in the above code, just to be safe and consistent.
249          */
250         *boundary = '\0';
251
252         ptr = history_msg->cm_fields[eMesageText];
253         do {
254                 ptr = memreadline(ptr, buf, sizeof buf);
255                 if (*ptr != 0) {
256                         striplt(buf);
257                         if (!IsEmptyStr(buf) && (!strncasecmp(buf, "Content-type:", 13))) {
258                                 if (
259                                         (bmstrcasestr(buf, "multipart") != NULL)
260                                         && (bmstrcasestr(buf, "boundary=") != NULL)
261                                 ) {
262                                         safestrncpy(boundary, bmstrcasestr(buf, "\""), sizeof boundary);
263                                         char *qu;
264                                         qu = strchr(boundary, '\"');
265                                         if (qu) {
266                                                 strcpy(boundary, ++qu);
267                                         }
268                                         qu = strchr(boundary, '\"');
269                                         if (qu) {
270                                                 *qu = 0;
271                                         }
272                                 }
273                         }
274                 }
275         } while ( (IsEmptyStr(boundary)) && (*ptr != 0) );
276
277         /*
278          * Now look for the first boundary.  That is where we need to insert our fun.
279          */
280         if (!IsEmptyStr(boundary)) {
281                 char *MsgText;
282                 long MsgTextLen;
283                 time_t Now = time(NULL);
284
285                 snprintf(prefixed_boundary, sizeof(prefixed_boundary), "--%s", boundary);
286                 
287                 CM_GetAsField(history_msg, eMesageText, &MsgText, &MsgTextLen);
288
289                 ptr = bmstrcasestr(MsgText, prefixed_boundary);
290                 if (ptr != NULL) {
291                         StrBuf *NewMsgText;
292                         char uuid[64];
293                         char memo[512];
294                         long memolen;
295                         char encoded_memo[1024];
296                         
297                         NewMsgText = NewStrBufPlain(NULL, MsgTextLen + diffbuf_len + 1024);
298
299                         generate_uuid(uuid);
300                         memolen = snprintf(memo, sizeof(memo), "%s|%ld|%s|%s", 
301                                            uuid,
302                                            Now,
303                                            CCC->user.fullname,
304                                            config.c_nodename);
305
306                         memolen = CtdlEncodeBase64(encoded_memo, memo, memolen, 0);
307
308                         StrBufAppendBufPlain(NewMsgText, HKEY("--"), 0);
309                         StrBufAppendBufPlain(NewMsgText, boundary, -1, 0);
310                         StrBufAppendBufPlain(
311                                 NewMsgText, 
312                                 HKEY("\n"
313                                      "Content-type: text/plain\n"
314                                      "Content-Disposition: inline; filename=\""), 0);
315
316                         StrBufAppendBufPlain(NewMsgText, encoded_memo, memolen, 0);
317
318                         StrBufAppendBufPlain(
319                                 NewMsgText, 
320                                 HKEY("\"\n"
321                                      "Content-Transfer-Encoding: 8bit\n"
322                                      "\n"), 0);
323
324                         StrBufAppendBufPlain(NewMsgText, diffbuf, diffbuf_len, 0);
325                         StrBufAppendBufPlain(NewMsgText, HKEY("\n"), 0);
326
327                         StrBufAppendBufPlain(NewMsgText, ptr, MsgTextLen - (ptr - MsgText), 0);
328                         free(MsgText);
329                         CM_SetAsFieldSB(history_msg, eMesageText, &NewMsgText); 
330                 }
331                 else
332                 {
333                         CM_SetAsField(history_msg, eMesageText, &MsgText, MsgTextLen); 
334                 }
335
336                 CM_SetFieldLONG(history_msg, eTimestamp, Now);
337         
338                 CtdlSubmitMsg(history_msg, NULL, "", 0);
339         }
340         else {
341                 syslog(LOG_ALERT, "Empty boundary string in history message.  No history!\n");
342         }
343
344         free(diffbuf);
345         CtdlFreeMessage(history_msg);
346         return(0);
347 }
348
349
350 /*
351  * MIME Parser callback for wiki_history()
352  *
353  * The "filename" field will contain a memo field.  All we have to do is decode
354  * the base64 and output it.  The data is already in a delimited format suitable
355  * for our client protocol.
356  */
357 void wiki_history_callback(char *name, char *filename, char *partnum, char *disp,
358                    void *content, char *cbtype, char *cbcharset, size_t length,
359                    char *encoding, char *cbid, void *cbuserdata)
360 {
361         char memo[1024];
362
363         CtdlDecodeBase64(memo, filename, strlen(filename));
364         cprintf("%s\n", memo);
365 }
366
367
368 /*
369  * Fetch a list of revisions for a particular wiki page
370  */
371 void wiki_history(char *pagename) {
372         int r;
373         char history_page_name[270];
374         long msgnum;
375         struct CtdlMessage *msg;
376
377         r = CtdlDoIHavePermissionToReadMessagesInThisRoom();
378         if (r != om_ok) {
379                 if (r == om_not_logged_in) {
380                         cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
381                 }
382                 else {
383                         cprintf("%d An unknown error has occurred.\n", ERROR);
384                 }
385                 return;
386         }
387
388         snprintf(history_page_name, sizeof history_page_name, "%s_HISTORY_", pagename);
389         msgnum = CtdlLocateMessageByEuid(history_page_name, &CC->room);
390         if (msgnum > 0L) {
391                 msg = CtdlFetchMessage(msgnum, 1);
392         }
393         else {
394                 msg = NULL;
395         }
396
397         if ((msg != NULL) && (msg->cm_fields[eMesageText] == NULL)) {
398                 CtdlFreeMessage(msg);
399                 msg = NULL;
400         }
401
402         if (msg == NULL) {
403                 cprintf("%d Revision history for '%s' was not found.\n", ERROR+MESSAGE_NOT_FOUND, pagename);
404                 return;
405         }
406
407         
408         cprintf("%d Revision history for '%s'\n", LISTING_FOLLOWS, pagename);
409         mime_parser(msg->cm_fields[eMesageText], NULL, *wiki_history_callback, NULL, NULL, NULL, 0);
410         cprintf("000\n");
411
412         CtdlFreeMessage(msg);
413         return;
414 }
415
416 /*
417  * MIME Parser callback for wiki_rev()
418  *
419  * The "filename" field will contain a memo field, which includes (among other things)
420  * the uuid of this revision.  After we hit the desired revision, we stop processing.
421  *
422  * The "content" filed will contain "diff" output suitable for applying via "patch"
423  * to our temporary file.
424  */
425 void wiki_rev_callback(char *name, char *filename, char *partnum, char *disp,
426                    void *content, char *cbtype, char *cbcharset, size_t length,
427                    char *encoding, char *cbid, void *cbuserdata)
428 {
429         struct HistoryEraserCallBackData *hecbd = (struct HistoryEraserCallBackData *)cbuserdata;
430         char memo[1024];
431         char this_rev[256];
432         FILE *fp;
433         char *ptr = NULL;
434         char buf[1024];
435
436         /* Did a previous callback already indicate that we've reached our target uuid?
437          * If so, don't process anything else.
438          */
439         if (hecbd->done) {
440                 return;
441         }
442
443         CtdlDecodeBase64(memo, filename, strlen(filename));
444         extract_token(this_rev, memo, 0, '|', sizeof this_rev);
445         striplt(this_rev);
446
447         /* Perform the patch */
448         fp = popen(PATCH " -f -s -p0 -r /dev/null >/dev/null 2>/dev/null", "w");
449         if (fp) {
450                 /* Replace the filenames in the patch with the tempfilename we're actually tweaking */
451                 fprintf(fp, "--- %s\n", hecbd->tempfilename);
452                 fprintf(fp, "+++ %s\n", hecbd->tempfilename);
453
454                 ptr = (char *)content;
455                 int linenum = 0;
456                 do {
457                         ++linenum;
458                         ptr = memreadline(ptr, buf, sizeof buf);
459                         if (*ptr != 0) {
460                                 if (linenum <= 2) {
461                                         /* skip the first two lines; they contain bogus filenames */
462                                 }
463                                 else {
464                                         fprintf(fp, "%s\n", buf);
465                                 }
466                         }
467                 } while ((*ptr != 0) && (ptr < ((char*)content + length)));
468                 if (pclose(fp) != 0) {
469                         syslog(LOG_ERR, "pclose() returned an error - patch failed\n");
470                 }
471         }
472
473         if (!strcasecmp(this_rev, hecbd->stop_when)) {
474                 /* Found our target rev.  Tell any subsequent callbacks to suppress processing. */
475                 syslog(LOG_DEBUG, "Target revision has been reached -- stop patching.\n");
476                 hecbd->done = 1;
477         }
478 }
479
480
481 /*
482  * Fetch a specific revision of a wiki page.  The "operation" string may be set to "fetch" in order
483  * to simply fetch the desired revision and store it in a temporary location for viewing, or "revert"
484  * to revert the currently active page to that revision.
485  */
486 void wiki_rev(char *pagename, char *rev, char *operation)
487 {
488         struct CitContext *CCC = CC;
489         int r;
490         char history_page_name[270];
491         long msgnum;
492         char temp[PATH_MAX];
493         struct CtdlMessage *msg;
494         FILE *fp;
495         struct HistoryEraserCallBackData hecbd;
496         long len = 0L;
497         int rv;
498
499         r = CtdlDoIHavePermissionToReadMessagesInThisRoom();
500         if (r != om_ok) {
501                 if (r == om_not_logged_in) {
502                         cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
503                 }
504                 else {
505                         cprintf("%d An unknown error has occurred.\n", ERROR);
506                 }
507                 return;
508         }
509
510         if (!strcasecmp(operation, "revert")) {
511                 r = CtdlDoIHavePermissionToPostInThisRoom(temp, sizeof temp, NULL, POST_LOGGED_IN, 0);
512                 if (r != 0) {
513                         cprintf("%d %s\n", r, temp);
514                         return;
515                 }
516         }
517
518         /* Begin by fetching the current version of the page.  We're going to patch
519          * backwards through the diffs until we get the one we want.
520          */
521         msgnum = CtdlLocateMessageByEuid(pagename, &CCC->room);
522         if (msgnum > 0L) {
523                 msg = CtdlFetchMessage(msgnum, 1);
524         }
525         else {
526                 msg = NULL;
527         }
528
529         if ((msg != NULL) && (msg->cm_fields[eMesageText] == NULL)) {
530                 CtdlFreeMessage(msg);
531                 msg = NULL;
532         }
533
534         if (msg == NULL) {
535                 cprintf("%d Page '%s' was not found.\n", ERROR+MESSAGE_NOT_FOUND, pagename);
536                 return;
537         }
538
539         /* Output it to a temporary file */
540
541         CtdlMakeTempFileName(temp, sizeof temp);
542         fp = fopen(temp, "w");
543         if (fp != NULL) {
544                 r = fwrite(msg->cm_fields[eMesageText], strlen(msg->cm_fields[eMesageText]), 1, fp);
545                 fclose(fp);
546         }
547         else {
548                 syslog(LOG_ALERT, "Cannot open %s: %s\n", temp, strerror(errno));
549         }
550         CtdlFreeMessage(msg);
551
552         /* Get the revision history */
553
554         snprintf(history_page_name, sizeof history_page_name, "%s_HISTORY_", pagename);
555         msgnum = CtdlLocateMessageByEuid(history_page_name, &CCC->room);
556         if (msgnum > 0L) {
557                 msg = CtdlFetchMessage(msgnum, 1);
558         }
559         else {
560                 msg = NULL;
561         }
562
563         if ((msg != NULL) && (msg->cm_fields[eMesageText] == NULL)) {
564                 CtdlFreeMessage(msg);
565                 msg = NULL;
566         }
567
568         if (msg == NULL) {
569                 cprintf("%d Revision history for '%s' was not found.\n", ERROR+MESSAGE_NOT_FOUND, pagename);
570                 return;
571         }
572
573         /* Start patching backwards (newest to oldest) through the revision history until we
574          * hit the revision uuid requested by the user.  (The callback will perform each one.)
575          */
576
577         memset(&hecbd, 0, sizeof(struct HistoryEraserCallBackData));
578         hecbd.tempfilename = temp;
579         hecbd.stop_when = rev;
580         striplt(hecbd.stop_when);
581
582         mime_parser(msg->cm_fields[eMesageText], NULL, *wiki_rev_callback, NULL, NULL, (void *)&hecbd, 0);
583         CtdlFreeMessage(msg);
584
585         /* Were we successful? */
586         if (hecbd.done == 0) {
587                 cprintf("%d Revision '%s' of page '%s' was not found.\n",
588                         ERROR + MESSAGE_NOT_FOUND, rev, pagename
589                 );
590         }
591
592         /* We have the desired revision on disk.  Now do something with it. */
593
594         else if ( (!strcasecmp(operation, "fetch")) || (!strcasecmp(operation, "revert")) ) {
595                 msg = malloc(sizeof(struct CtdlMessage));
596                 memset(msg, 0, sizeof(struct CtdlMessage));
597                 msg->cm_magic = CTDLMESSAGE_MAGIC;
598                 msg->cm_anon_type = MES_NORMAL;
599                 msg->cm_format_type = FMT_RFC822;
600                 fp = fopen(temp, "r");
601                 if (fp) {
602                         char *msgbuf;
603                         fseek(fp, 0L, SEEK_END);
604                         len = ftell(fp);
605                         fseek(fp, 0L, SEEK_SET);
606                         msgbuf = malloc(len + 1);
607                         rv = fread(msgbuf, len, 1, fp);
608                         syslog(LOG_DEBUG, "did %d blocks of %ld bytes\n", rv, len);
609                         msgbuf[len] = '\0';
610                         CM_SetAsField(msg, eMesageText, &msgbuf, len);
611                         fclose(fp);
612                 }
613                 if (len <= 0) {
614                         msgnum = (-1L);
615                 }
616                 else if (!strcasecmp(operation, "fetch")) {
617                         CM_SetField(msg, eAuthor, HKEY("Citadel"));
618                         CtdlCreateRoom(wwm, 5, "", 0, 1, 1, VIEW_BBS);  /* Not an error if already exists */
619                         msgnum = CtdlSubmitMsg(msg, NULL, wwm, 0);      /* Store the revision here */
620
621                         /*
622                          * WARNING: VILE SLEAZY HACK
623                          * This will avoid the 'message xxx is not in this room' security error,
624                          * but only if the client fetches the message we just generated immediately
625                          * without first trying to perform other fetch operations.
626                          */
627                         if (CCC->cached_msglist != NULL) {
628                                 free(CCC->cached_msglist);
629                                 CCC->cached_msglist = NULL;
630                                 CCC->cached_num_msgs = 0;
631                         }
632                         CCC->cached_msglist = malloc(sizeof(long));
633                         if (CCC->cached_msglist != NULL) {
634                                 CCC->cached_num_msgs = 1;
635                                 CCC->cached_msglist[0] = msgnum;
636                         }
637
638                 }
639                 else if (!strcasecmp(operation, "revert")) {
640                         CM_SetFieldLONG(msg, eTimestamp, time(NULL));
641                         CM_SetField(msg, eAuthor, CCC->user.fullname, strlen(CCC->user.fullname));
642                         CM_SetField(msg, erFc822Addr, CCC->cs_inet_email, strlen(CCC->cs_inet_email));
643                         CM_SetField(msg, eOriginalRoom, CCC->room.QRname, strlen(CCC->room.QRname));
644                         CM_SetField(msg, eNodeName, NODENAME, strlen(NODENAME));
645                         CM_SetField(msg, eExclusiveID, pagename, strlen(pagename));
646                         msgnum = CtdlSubmitMsg(msg, NULL, "", 0);       /* Replace the current revision */
647                 }
648                 else {
649                         /* Theoretically it is impossible to get here, but throw an error anyway */
650                         msgnum = (-1L);
651                 }
652                 CtdlFreeMessage(msg);
653                 if (msgnum >= 0L) {
654                         cprintf("%d %ld\n", CIT_OK, msgnum);            /* Give the client a msgnum */
655                 }
656                 else {
657                         cprintf("%d Error %ld has occurred.\n", ERROR+INTERNAL_ERROR, msgnum);
658                 }
659         }
660
661         /* We did all this work for nothing.  Express anguish to the caller. */
662         else {
663                 cprintf("%d An unknown operation was requested.\n", ERROR+CMD_NOT_SUPPORTED);
664         }
665
666         unlink(temp);
667         return;
668 }
669
670
671
672 /*
673  * commands related to wiki management
674  */
675 void cmd_wiki(char *argbuf) {
676         char subcmd[32];
677         char pagename[256];
678         char rev[128];
679         char operation[16];
680
681         extract_token(subcmd, argbuf, 0, '|', sizeof subcmd);
682
683         if (!strcasecmp(subcmd, "history")) {
684                 extract_token(pagename, argbuf, 1, '|', sizeof pagename);
685                 wiki_history(pagename);
686                 return;
687         }
688
689         if (!strcasecmp(subcmd, "rev")) {
690                 extract_token(pagename, argbuf, 1, '|', sizeof pagename);
691                 extract_token(rev, argbuf, 2, '|', sizeof rev);
692                 extract_token(operation, argbuf, 3, '|', sizeof operation);
693                 wiki_rev(pagename, rev, operation);
694                 return;
695         }
696
697         cprintf("%d Invalid subcommand\n", ERROR + CMD_NOT_SUPPORTED);
698 }
699
700
701
702 /*
703  * Module initialization
704  */
705 CTDL_MODULE_INIT(wiki)
706 {
707         if (!threading)
708         {
709                 CtdlRegisterMessageHook(wiki_upload_beforesave, EVT_BEFORESAVE);
710                 CtdlRegisterProtoHook(cmd_wiki, "WIKI", "Commands related to Wiki management");
711         }
712
713         /* return our module name for the log */
714         return "wiki";
715 }