4 * Server-side module for Wiki rooms. This handles things like version control.
6 * Copyright (c) 2009 by the citadel.org team
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
32 #include <sys/types.h>
34 #if TIME_WITH_SYS_TIME
35 # include <sys/time.h>
39 # include <sys/time.h>
48 #include <libcitadel.h>
51 #include "citserver.h"
59 #include "euidindex.h"
60 #include "ctdl_module.h"
63 * Data passed back and forth between wiki_rev() and its MIME parser callback
65 struct HistoryEraserCallBackData {
66 char *tempfilename; /* name of temp file being patched */
67 char *stop_when; /* stop when we hit this uuid */
68 int done; /* set to nonzero when we're done patching */
72 * Name of the temporary room we create to store old revisions when someone requests them.
73 * We put it in an invalid namespace so the DAP cleans up after us later.
75 char *wwm = "9999999999.WikiWaybackMachine";
78 * Before allowing a wiki page save to execute, we have to perform version control.
79 * This involves fetching the old version of the page if it exists.
81 int wiki_upload_beforesave(struct CtdlMessage *msg) {
82 struct CitContext *CCC = CC;
83 long old_msgnum = (-1L);
84 struct CtdlMessage *old_msg = NULL;
85 long history_msgnum = (-1L);
86 struct CtdlMessage *history_msg = NULL;
87 char diff_old_filename[PATH_MAX];
88 char diff_new_filename[PATH_MAX];
89 char diff_cmd[PATH_MAX];
92 char history_page[1024];
94 char prefixed_boundary[258];
98 size_t diffbuf_len = 0;
101 if (!CCC->logged_in) return(0); /* Only do this if logged in. */
103 /* Is this a room with a Wiki in it, don't run this hook. */
104 if (CCC->room.QRdefaultview != VIEW_WIKI) {
108 /* If this isn't a MIME message, don't bother. */
109 if (msg->cm_format_type != 4) return(0);
111 /* If there's no EUID we can't do this. */
112 if (msg->cm_fields['E'] == NULL) return(0);
113 snprintf(history_page, sizeof history_page, "%s_HISTORY_", msg->cm_fields['E']);
115 /* Make sure we're saving a real wiki page rather than a wiki history page.
116 * This is important in order to avoid recursing infinitely into this hook.
118 if ( (strlen(msg->cm_fields['E']) >= 9)
119 && (!strcasecmp(&msg->cm_fields['E'][strlen(msg->cm_fields['E'])-9], "_HISTORY_"))
121 CtdlLogPrintf(CTDL_DEBUG, "History page not being historied\n");
125 /* If there's no message text, obviously this is all b0rken and shouldn't happen at all */
126 if (msg->cm_fields['M'] == NULL) return(0);
128 /* Set the message subject identical to the page name */
129 if (msg->cm_fields['U'] != NULL) {
130 free(msg->cm_fields['U']);
132 msg->cm_fields['U'] = strdup(msg->cm_fields['E']);
134 /* See if we can retrieve the previous version. */
135 old_msgnum = locate_message_by_euid(msg->cm_fields['E'], &CCC->room);
136 if (old_msgnum > 0L) {
137 old_msg = CtdlFetchMessage(old_msgnum, 1);
143 if ((old_msg != NULL) && (old_msg->cm_fields['M'] == NULL)) { /* old version is corrupt? */
144 CtdlFreeMessage(old_msg);
148 /* If no changes were made, don't bother saving it again */
149 if ((old_msg != NULL) && (!strcmp(msg->cm_fields['M'], old_msg->cm_fields['M']))) {
150 CtdlFreeMessage(old_msg);
157 CtdlMakeTempFileName(diff_old_filename, sizeof diff_old_filename);
158 CtdlMakeTempFileName(diff_new_filename, sizeof diff_new_filename);
160 if (old_msg != NULL) {
161 fp = fopen(diff_old_filename, "w");
162 rv = fwrite(old_msg->cm_fields['M'], strlen(old_msg->cm_fields['M']), 1, fp);
164 CtdlFreeMessage(old_msg);
167 fp = fopen(diff_new_filename, "w");
168 rv = fwrite(msg->cm_fields['M'], strlen(msg->cm_fields['M']), 1, fp);
173 snprintf(diff_cmd, sizeof diff_cmd,
176 ((old_msg != NULL) ? diff_old_filename : "/dev/null")
178 fp = popen(diff_cmd, "r");
181 diffbuf = realloc(diffbuf, diffbuf_len + 1025);
182 nbytes = fread(&diffbuf[diffbuf_len], 1, 1024, fp);
183 diffbuf_len += nbytes;
184 } while (nbytes == 1024);
185 diffbuf[diffbuf_len] = 0;
188 CtdlLogPrintf(CTDL_DEBUG, "diff length is %d bytes\n", diffbuf_len);
190 unlink(diff_old_filename);
191 unlink(diff_new_filename);
193 /* Determine whether this was a bogus (empty) edit */
194 if ((diffbuf_len = 0) && (diffbuf != NULL)) {
198 if (diffbuf == NULL) {
199 return(1); /* No changes at all? Abandon the post entirely! */
202 /* Now look for the existing edit history */
204 history_msgnum = locate_message_by_euid(history_page, &CCC->room);
206 if (history_msgnum > 0L) {
207 history_msg = CtdlFetchMessage(history_msgnum, 1);
210 /* Create a new history message if necessary */
211 if (history_msg == NULL) {
212 history_msg = malloc(sizeof(struct CtdlMessage));
213 memset(history_msg, 0, sizeof(struct CtdlMessage));
214 history_msg->cm_magic = CTDLMESSAGE_MAGIC;
215 history_msg->cm_anon_type = MES_NORMAL;
216 history_msg->cm_format_type = FMT_RFC822;
217 history_msg->cm_fields['A'] = strdup("Citadel");
218 history_msg->cm_fields['R'] = strdup(CCC->room.QRname);
219 history_msg->cm_fields['E'] = strdup(history_page);
220 history_msg->cm_fields['U'] = strdup(history_page);
221 history_msg->cm_fields['1'] = strdup("1"); /* suppress full text indexing */
222 snprintf(boundary, sizeof boundary, "Citadel--Multipart--%04x--%08lx", getpid(), time(NULL));
223 history_msg->cm_fields['M'] = malloc(1024);
224 snprintf(history_msg->cm_fields['M'], 1024,
225 "Content-type: multipart/mixed; boundary=\"%s\"\n\n"
226 "This is a Citadel wiki history encoded as multipart MIME.\n"
227 "Each part is comprised of a diff script representing one change set.\n"
235 /* Update the history message (regardless of whether it's new or existing) */
237 /* Remove the Message-ID from the old version of the history message. This will cause a brand
238 * new one to be generated, avoiding an uninitentional hit of the loop zapper when we replicate.
240 if (history_msg->cm_fields['I'] != NULL) {
241 free(history_msg->cm_fields['I']);
244 /* Figure out the boundary string. We do this even when we generated the
245 * boundary string in the above code, just to be safe and consistent.
247 strcpy(boundary, "");
249 ptr = history_msg->cm_fields['M'];
251 ptr = memreadline(ptr, buf, sizeof buf);
254 if (!IsEmptyStr(buf) && (!strncasecmp(buf, "Content-type:", 13))) {
256 (bmstrcasestr(buf, "multipart") != NULL)
257 && (bmstrcasestr(buf, "boundary=") != NULL)
259 safestrncpy(boundary, bmstrcasestr(buf, "\""), sizeof boundary);
261 qu = strchr(boundary, '\"');
263 strcpy(boundary, ++qu);
265 qu = strchr(boundary, '\"');
272 } while ( (IsEmptyStr(boundary)) && (*ptr != 0) );
274 /* Now look for the first boundary. That is where we need to insert our fun.
276 if (!IsEmptyStr(boundary)) {
277 snprintf(prefixed_boundary, sizeof prefixed_boundary, "--%s", boundary);
278 history_msg->cm_fields['M'] = realloc(history_msg->cm_fields['M'],
279 strlen(history_msg->cm_fields['M']) + strlen(diffbuf) + 1024
281 ptr = bmstrcasestr(history_msg->cm_fields['M'], prefixed_boundary);
283 char *the_rest_of_it = strdup(ptr);
286 char encoded_memo[768];
288 snprintf(memo, sizeof memo, "%s|%ld|%s|%s",
293 /* no longer logging CCC->cs_inet_email */
295 CtdlEncodeBase64(encoded_memo, memo, strlen(memo), 0);
296 sprintf(ptr, "--%s\n"
297 "Content-type: text/plain\n"
298 "Content-Disposition: inline; filename=\"%s\"\n"
299 "Content-Transfer-Encoding: 8bit\n"
309 free(the_rest_of_it);
312 history_msg->cm_fields['T'] = realloc(history_msg->cm_fields['T'], 32);
313 snprintf(history_msg->cm_fields['T'], 32, "%ld", time(NULL));
315 CtdlSubmitMsg(history_msg, NULL, "", 0);
318 CtdlLogPrintf(CTDL_ALERT, "Empty boundary string in history message. No history!\n");
328 * MIME Parser callback for wiki_history()
330 * The "filename" field will contain a memo field. All we have to do is decode
331 * the base64 and output it. The data is already in a delimited format suitable
332 * for our client protocol.
334 void wiki_history_callback(char *name, char *filename, char *partnum, char *disp,
335 void *content, char *cbtype, char *cbcharset, size_t length,
336 char *encoding, char *cbid, void *cbuserdata)
340 CtdlDecodeBase64(memo, filename, strlen(filename));
341 cprintf("%s\n", memo);
346 * Fetch a list of revisions for a particular wiki page
348 void wiki_history(char *pagename) {
350 char history_page_name[270];
352 struct CtdlMessage *msg;
354 r = CtdlDoIHavePermissionToReadMessagesInThisRoom();
356 if (r == om_not_logged_in) {
357 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
360 cprintf("%d An unknown error has occurred.\n", ERROR);
365 snprintf(history_page_name, sizeof history_page_name, "%s_HISTORY_", pagename);
366 msgnum = locate_message_by_euid(history_page_name, &CC->room);
368 msg = CtdlFetchMessage(msgnum, 1);
374 if ((msg != NULL) && (msg->cm_fields['M'] == NULL)) {
375 CtdlFreeMessage(msg);
380 cprintf("%d Revision history for '%s' was not found.\n", ERROR+MESSAGE_NOT_FOUND, pagename);
385 cprintf("%d Revision history for '%s'\n", LISTING_FOLLOWS, pagename);
386 mime_parser(msg->cm_fields['M'], NULL, *wiki_history_callback, NULL, NULL, NULL, 0);
389 CtdlFreeMessage(msg);
394 * MIME Parser callback for wiki_rev()
396 * The "filename" field will contain a memo field, which includes (among other things)
397 * the uuid of this revision. After we hit the desired revision, we stop processing.
399 * The "content" filed will contain "diff" output suitable for applying via "patch"
400 * to our temporary file.
402 void wiki_rev_callback(char *name, char *filename, char *partnum, char *disp,
403 void *content, char *cbtype, char *cbcharset, size_t length,
404 char *encoding, char *cbid, void *cbuserdata)
406 struct HistoryEraserCallBackData *hecbd = (struct HistoryEraserCallBackData *)cbuserdata;
413 /* Did a previous callback already indicate that we've reached our target uuid?
414 * If so, don't process anything else.
420 CtdlDecodeBase64(memo, filename, strlen(filename));
421 extract_token(this_rev, memo, 0, '|', sizeof this_rev);
422 CtdlLogPrintf(CTDL_DEBUG, "callback found rev: %s\n", this_rev);
424 /* Perform the patch */
425 fp = popen("patch -f -s -p0 >/dev/null 2>/dev/null", "w");
427 /* Replace the filenames in the patch with the tempfilename we're actually tweaking */
428 fprintf(fp, "--- %s\n", hecbd->tempfilename);
429 fprintf(fp, "+++ %s\n", hecbd->tempfilename);
431 ptr = (char *)content;
435 ptr = memreadline(ptr, buf, sizeof buf);
438 /* skip the first two lines; they contain bogus filenames */
441 fprintf(fp, "%s\n", buf);
444 } while ((*ptr != 0) && ((int)ptr < ((int)content + length)));
448 if (!strcasecmp(this_rev, hecbd->stop_when)) {
449 /* Found our target rev. Tell any subsequent callbacks to suppress processing. */
450 CtdlLogPrintf(CTDL_DEBUG, "Target revision has been reached -- stop patching.\n");
457 * Fetch a specific revision of a wiki page. The "operation" string may be set to "fetch" in order
458 * to simply fetch the desired revision and store it in a temporary location for viewing, or "revert"
459 * to revert the currently active page to that revision.
461 void wiki_rev(char *pagename, char *rev, char *operation)
464 char history_page_name[270];
468 struct CtdlMessage *msg;
470 struct HistoryEraserCallBackData hecbd;
474 r = CtdlDoIHavePermissionToReadMessagesInThisRoom();
476 if (r == om_not_logged_in) {
477 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
480 cprintf("%d An unknown error has occurred.\n", ERROR);
485 /* Begin by fetching the current version of the page. We're going to patch
486 * backwards through the diffs until we get the one we want.
488 msgnum = locate_message_by_euid(pagename, &CC->room);
490 msg = CtdlFetchMessage(msgnum, 1);
496 if ((msg != NULL) && (msg->cm_fields['M'] == NULL)) {
497 CtdlFreeMessage(msg);
502 cprintf("%d Page '%s' was not found.\n", ERROR+MESSAGE_NOT_FOUND, pagename);
506 /* Output it to a temporary file */
508 CtdlMakeTempFileName(temp, sizeof temp);
509 fp = fopen(temp, "w");
511 r = fwrite(msg->cm_fields['M'], strlen(msg->cm_fields['M']), 1, fp);
515 CtdlLogPrintf(CTDL_ALERT, "Cannot open %s: %s\n", temp, strerror(errno));
517 CtdlFreeMessage(msg);
519 /* Get the revision history */
521 snprintf(history_page_name, sizeof history_page_name, "%s_HISTORY_", pagename);
522 msgnum = locate_message_by_euid(history_page_name, &CC->room);
524 msg = CtdlFetchMessage(msgnum, 1);
530 if ((msg != NULL) && (msg->cm_fields['M'] == NULL)) {
531 CtdlFreeMessage(msg);
536 cprintf("%d Revision history for '%s' was not found.\n", ERROR+MESSAGE_NOT_FOUND, pagename);
540 /* Start patching backwards (newest to oldest) through the revision history until we
541 * hit the revision uuid requested by the user. (The callback will perform each one.)
544 memset(&hecbd, 0, sizeof(struct HistoryEraserCallBackData));
545 hecbd.tempfilename = temp;
546 hecbd.stop_when = rev;
548 mime_parser(msg->cm_fields['M'], NULL, *wiki_rev_callback, NULL, NULL, (void *)&hecbd, 0);
549 CtdlFreeMessage(msg);
551 /* Were we successful? */
552 if (hecbd.done == 0) {
553 cprintf("%d Revision '%s' of page '%s' was not found.\n",
554 ERROR + MESSAGE_NOT_FOUND, rev, pagename
558 /* We have the desired revision on disk. Now do something with it. */
560 else if ( (!strcasecmp(operation, "fetch")) || (!strcasecmp(operation, "revert")) ) {
561 msg = malloc(sizeof(struct CtdlMessage));
562 memset(msg, 0, sizeof(struct CtdlMessage));
563 msg->cm_magic = CTDLMESSAGE_MAGIC;
564 msg->cm_anon_type = MES_NORMAL;
565 msg->cm_format_type = FMT_RFC822;
566 fp = fopen(temp, "r");
568 fseek(fp, 0L, SEEK_END);
570 fseek(fp, 0L, SEEK_SET);
571 msg->cm_fields['M'] = malloc(len + 1);
572 rv = fread(msg->cm_fields['M'], len, 1, fp);
573 CtdlLogPrintf(CTDL_DEBUG, "\033[32mdid %d blocks of %d bytes\033[0m\n", rv, len);
574 msg->cm_fields['M'][len] = 0;
580 else if (!strcasecmp(operation, "fetch")) {
581 msg->cm_fields['A'] = strdup("Citadel");
582 CtdlCreateRoom(wwm, 5, "", 0, 1, 1, VIEW_BBS); /* Not an error if already exists */
583 msgnum = CtdlSubmitMsg(msg, NULL, wwm, 0); /* Store the revision here */
585 else if (!strcasecmp(operation, "revert")) {
586 snprintf(timestamp, sizeof timestamp, "%ld", time(NULL));
587 msg->cm_fields['T'] = strdup(timestamp);
588 msg->cm_fields['A'] = strdup(CC->user.fullname);
589 msg->cm_fields['F'] = strdup(CC->cs_inet_email);
590 msg->cm_fields['O'] = strdup(CC->room.QRname);
591 msg->cm_fields['N'] = strdup(NODENAME);
592 msg->cm_fields['E'] = strdup(pagename);
593 msgnum = CtdlSubmitMsg(msg, NULL, "", 0); /* Replace the current revision */
596 /* Theoretically it is impossible to get here, but throw an error anyway */
599 CtdlFreeMessage(msg);
601 cprintf("%d %ld\n", CIT_OK, msgnum); /* Give the client a msgnum */
604 cprintf("%d Error %ld has occurred.\n", ERROR+INTERNAL_ERROR, msgnum);
608 /* We did all this work for nothing. Express anguish to the caller. */
610 cprintf("%d An unknown operation was requested.\n", ERROR+CMD_NOT_SUPPORTED);
620 * commands related to wiki management
622 void cmd_wiki(char *argbuf) {
628 extract_token(subcmd, argbuf, 0, '|', sizeof subcmd);
630 if (!strcasecmp(subcmd, "history")) {
631 extract_token(pagename, argbuf, 1, '|', sizeof pagename);
632 wiki_history(pagename);
636 if (!strcasecmp(subcmd, "rev")) {
637 extract_token(pagename, argbuf, 1, '|', sizeof pagename);
638 extract_token(rev, argbuf, 2, '|', sizeof rev);
639 extract_token(operation, argbuf, 3, '|', sizeof operation);
640 wiki_rev(pagename, rev, operation);
644 cprintf("%d Invalid subcommand\n", ERROR + CMD_NOT_SUPPORTED);
650 * Module initialization
652 CTDL_MODULE_INIT(wiki)
656 CtdlRegisterMessageHook(wiki_upload_beforesave, EVT_BEFORESAVE);
657 CtdlRegisterProtoHook(cmd_wiki, "WIKI", "Commands related to Wiki management");
660 /* return our Subversion id for the Log */