2 * Server-side module for Wiki rooms. This handles things like version control.
4 * Copyright (c) 2009-2011 by the citadel.org team
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 as
8 * published by the Free Software Foundation; either version 3 of the
9 * License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30 #include <sys/types.h>
32 #if TIME_WITH_SYS_TIME
33 # include <sys/time.h>
37 # include <sys/time.h>
46 #include <libcitadel.h>
49 #include "citserver.h"
56 #include "euidindex.h"
57 #include "ctdl_module.h"
60 * Data passed back and forth between wiki_rev() and its MIME parser callback
62 struct HistoryEraserCallBackData {
63 char *tempfilename; /* name of temp file being patched */
64 char *stop_when; /* stop when we hit this uuid */
65 int done; /* set to nonzero when we're done patching */
69 * Name of the temporary room we create to store old revisions when someone requests them.
70 * We put it in an invalid namespace so the DAP cleans up after us later.
72 char *wwm = "9999999999.WikiWaybackMachine";
75 * Before allowing a wiki page save to execute, we have to perform version control.
76 * This involves fetching the old version of the page if it exists.
78 int wiki_upload_beforesave(struct CtdlMessage *msg) {
79 struct CitContext *CCC = CC;
80 long old_msgnum = (-1L);
81 struct CtdlMessage *old_msg = NULL;
82 long history_msgnum = (-1L);
83 struct CtdlMessage *history_msg = NULL;
84 char diff_old_filename[PATH_MAX];
85 char diff_new_filename[PATH_MAX];
86 char diff_out_filename[PATH_MAX];
87 char diff_cmd[PATH_MAX];
90 char history_page[1024];
92 char prefixed_boundary[258];
95 size_t diffbuf_len = 0;
98 if (!CCC->logged_in) return(0); /* Only do this if logged in. */
100 /* Is this a room with a Wiki in it, don't run this hook. */
101 if (CCC->room.QRdefaultview != VIEW_WIKI) {
105 /* If this isn't a MIME message, don't bother. */
106 if (msg->cm_format_type != 4) return(0);
108 /* If there's no EUID we can't do this. Reject the post. */
109 if (msg->cm_fields['E'] == NULL) return(1);
111 snprintf(history_page, sizeof history_page, "%s_HISTORY_", msg->cm_fields['E']);
113 /* Make sure we're saving a real wiki page rather than a wiki history page.
114 * This is important in order to avoid recursing infinitely into this hook.
116 if ( (strlen(msg->cm_fields['E']) >= 9)
117 && (!strcasecmp(&msg->cm_fields['E'][strlen(msg->cm_fields['E'])-9], "_HISTORY_"))
119 syslog(LOG_DEBUG, "History page not being historied\n");
123 /* If there's no message text, obviously this is all b0rken and shouldn't happen at all */
124 if (msg->cm_fields['M'] == NULL) return(0);
126 /* Set the message subject identical to the page name */
127 if (msg->cm_fields['U'] != NULL) {
128 free(msg->cm_fields['U']);
130 msg->cm_fields['U'] = strdup(msg->cm_fields['E']);
132 /* See if we can retrieve the previous version. */
133 old_msgnum = CtdlLocateMessageByEuid(msg->cm_fields['E'], &CCC->room);
134 if (old_msgnum > 0L) {
135 old_msg = CtdlFetchMessage(old_msgnum, 1);
141 if ((old_msg != NULL) && (old_msg->cm_fields['M'] == NULL)) { /* old version is corrupt? */
142 CtdlFreeMessage(old_msg);
146 /* If no changes were made, don't bother saving it again */
147 if ((old_msg != NULL) && (!strcmp(msg->cm_fields['M'], old_msg->cm_fields['M']))) {
148 CtdlFreeMessage(old_msg);
155 CtdlMakeTempFileName(diff_old_filename, sizeof diff_old_filename);
156 CtdlMakeTempFileName(diff_new_filename, sizeof diff_new_filename);
157 CtdlMakeTempFileName(diff_out_filename, sizeof diff_out_filename);
159 if (old_msg != NULL) {
160 fp = fopen(diff_old_filename, "w");
161 rv = fwrite(old_msg->cm_fields['M'], strlen(old_msg->cm_fields['M']), 1, fp);
163 CtdlFreeMessage(old_msg);
166 fp = fopen(diff_new_filename, "w");
167 rv = fwrite(msg->cm_fields['M'], strlen(msg->cm_fields['M']), 1, fp);
170 snprintf(diff_cmd, sizeof diff_cmd,
173 ((old_msg != NULL) ? diff_old_filename : "/dev/null"),
176 syslog(LOG_DEBUG, "diff cmd: %s", diff_cmd);
177 rv = system(diff_cmd);
178 syslog(LOG_DEBUG, "diff cmd returned %d", rv);
182 fp = fopen(diff_out_filename, "r");
184 fp = fopen("/dev/null", "r");
187 fseek(fp, 0L, SEEK_END);
188 diffbuf_len = ftell(fp);
189 fseek(fp, 0L, SEEK_SET);
190 diffbuf = malloc(diffbuf_len + 1);
191 fread(diffbuf, diffbuf_len, 1, fp);
192 diffbuf[diffbuf_len] = 0;
196 syslog(LOG_DEBUG, "diff length is %d bytes", diffbuf_len);
198 unlink(diff_old_filename);
199 unlink(diff_new_filename);
200 unlink(diff_out_filename);
202 /* Determine whether this was a bogus (empty) edit */
203 if ((diffbuf_len = 0) && (diffbuf != NULL)) {
207 if (diffbuf == NULL) {
208 return(1); /* No changes at all? Abandon the post entirely! */
211 /* Now look for the existing edit history */
213 history_msgnum = CtdlLocateMessageByEuid(history_page, &CCC->room);
215 if (history_msgnum > 0L) {
216 history_msg = CtdlFetchMessage(history_msgnum, 1);
219 /* Create a new history message if necessary */
220 if (history_msg == NULL) {
221 history_msg = malloc(sizeof(struct CtdlMessage));
222 memset(history_msg, 0, sizeof(struct CtdlMessage));
223 history_msg->cm_magic = CTDLMESSAGE_MAGIC;
224 history_msg->cm_anon_type = MES_NORMAL;
225 history_msg->cm_format_type = FMT_RFC822;
226 history_msg->cm_fields['A'] = strdup("Citadel");
227 history_msg->cm_fields['R'] = strdup(CCC->room.QRname);
228 history_msg->cm_fields['E'] = strdup(history_page);
229 history_msg->cm_fields['U'] = strdup(history_page);
230 history_msg->cm_fields['1'] = strdup("1"); /* suppress full text indexing */
231 snprintf(boundary, sizeof boundary, "Citadel--Multipart--%04x--%08lx", getpid(), time(NULL));
232 history_msg->cm_fields['M'] = malloc(1024);
233 snprintf(history_msg->cm_fields['M'], 1024,
234 "Content-type: multipart/mixed; boundary=\"%s\"\n\n"
235 "This is a Citadel wiki history encoded as multipart MIME.\n"
236 "Each part is comprised of a diff script representing one change set.\n"
244 /* Update the history message (regardless of whether it's new or existing) */
246 /* Remove the Message-ID from the old version of the history message. This will cause a brand
247 * new one to be generated, avoiding an uninitentional hit of the loop zapper when we replicate.
249 if (history_msg->cm_fields['I'] != NULL) {
250 free(history_msg->cm_fields['I']);
251 history_msg->cm_fields['I'] = NULL;
254 /* Figure out the boundary string. We do this even when we generated the
255 * boundary string in the above code, just to be safe and consistent.
257 strcpy(boundary, "");
259 ptr = history_msg->cm_fields['M'];
261 ptr = memreadline(ptr, buf, sizeof buf);
264 if (!IsEmptyStr(buf) && (!strncasecmp(buf, "Content-type:", 13))) {
266 (bmstrcasestr(buf, "multipart") != NULL)
267 && (bmstrcasestr(buf, "boundary=") != NULL)
269 safestrncpy(boundary, bmstrcasestr(buf, "\""), sizeof boundary);
271 qu = strchr(boundary, '\"');
273 strcpy(boundary, ++qu);
275 qu = strchr(boundary, '\"');
282 } while ( (IsEmptyStr(boundary)) && (*ptr != 0) );
285 /****************** STACK SMASH IS SOMEWHERE BELOW THIS LINE **************/
288 /* Now look for the first boundary. That is where we need to insert our fun.
290 if (!IsEmptyStr(boundary)) {
291 snprintf(prefixed_boundary, sizeof prefixed_boundary, "--%s", boundary);
292 history_msg->cm_fields['M'] = realloc(history_msg->cm_fields['M'],
293 strlen(history_msg->cm_fields['M']) + strlen(diffbuf) + 1024
295 ptr = bmstrcasestr(history_msg->cm_fields['M'], prefixed_boundary);
297 char *the_rest_of_it = strdup(ptr);
300 char encoded_memo[768];
302 snprintf(memo, sizeof memo, "%s|%ld|%s|%s",
307 /* no longer logging CCC->cs_inet_email */
309 CtdlEncodeBase64(encoded_memo, memo, strlen(memo), 0);
310 sprintf(ptr, "--%s\n"
311 "Content-type: text/plain\n"
312 "Content-Disposition: inline; filename=\"%s\"\n"
313 "Content-Transfer-Encoding: 8bit\n"
323 free(the_rest_of_it);
326 history_msg->cm_fields['T'] = realloc(history_msg->cm_fields['T'], 32);
327 if (history_msg->cm_fields['T'] == NULL) {
328 syslog(LOG_EMERG, "*** REALLOC FAILED *** %s", strerror(errno));
330 snprintf(history_msg->cm_fields['T'], 32, "%ld", time(NULL));
332 CtdlSubmitMsg(history_msg, NULL, "", 0);
335 syslog(LOG_ALERT, "Empty boundary string in history message. No history!\n");
339 /****************** STACK SMASH IS SOMEWHERE BELOW THIS LINE **************/
349 * MIME Parser callback for wiki_history()
351 * The "filename" field will contain a memo field. All we have to do is decode
352 * the base64 and output it. The data is already in a delimited format suitable
353 * for our client protocol.
355 void wiki_history_callback(char *name, char *filename, char *partnum, char *disp,
356 void *content, char *cbtype, char *cbcharset, size_t length,
357 char *encoding, char *cbid, void *cbuserdata)
361 CtdlDecodeBase64(memo, filename, strlen(filename));
362 cprintf("%s\n", memo);
367 * Fetch a list of revisions for a particular wiki page
369 void wiki_history(char *pagename) {
371 char history_page_name[270];
373 struct CtdlMessage *msg;
375 r = CtdlDoIHavePermissionToReadMessagesInThisRoom();
377 if (r == om_not_logged_in) {
378 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
381 cprintf("%d An unknown error has occurred.\n", ERROR);
386 snprintf(history_page_name, sizeof history_page_name, "%s_HISTORY_", pagename);
387 msgnum = CtdlLocateMessageByEuid(history_page_name, &CC->room);
389 msg = CtdlFetchMessage(msgnum, 1);
395 if ((msg != NULL) && (msg->cm_fields['M'] == NULL)) {
396 CtdlFreeMessage(msg);
401 cprintf("%d Revision history for '%s' was not found.\n", ERROR+MESSAGE_NOT_FOUND, pagename);
406 cprintf("%d Revision history for '%s'\n", LISTING_FOLLOWS, pagename);
407 mime_parser(msg->cm_fields['M'], NULL, *wiki_history_callback, NULL, NULL, NULL, 0);
410 CtdlFreeMessage(msg);
415 * MIME Parser callback for wiki_rev()
417 * The "filename" field will contain a memo field, which includes (among other things)
418 * the uuid of this revision. After we hit the desired revision, we stop processing.
420 * The "content" filed will contain "diff" output suitable for applying via "patch"
421 * to our temporary file.
423 void wiki_rev_callback(char *name, char *filename, char *partnum, char *disp,
424 void *content, char *cbtype, char *cbcharset, size_t length,
425 char *encoding, char *cbid, void *cbuserdata)
427 struct HistoryEraserCallBackData *hecbd = (struct HistoryEraserCallBackData *)cbuserdata;
434 /* Did a previous callback already indicate that we've reached our target uuid?
435 * If so, don't process anything else.
441 CtdlDecodeBase64(memo, filename, strlen(filename));
442 extract_token(this_rev, memo, 0, '|', sizeof this_rev);
443 syslog(LOG_DEBUG, "callback found rev: %s\n", this_rev);
445 /* Perform the patch */
446 fp = popen("patch -f -s -p0 -r /dev/null >/dev/null 2>/dev/null", "w");
448 /* Replace the filenames in the patch with the tempfilename we're actually tweaking */
449 fprintf(fp, "--- %s\n", hecbd->tempfilename);
450 fprintf(fp, "+++ %s\n", hecbd->tempfilename);
452 ptr = (char *)content;
456 ptr = memreadline(ptr, buf, sizeof buf);
459 /* skip the first two lines; they contain bogus filenames */
462 fprintf(fp, "%s\n", buf);
465 } while ((*ptr != 0) && (ptr < ((char*)content + length)));
466 if (pclose(fp) != 0) {
467 syslog(LOG_ERR, "pclose() returned an error - patch failed\n");
471 if (!strcasecmp(this_rev, hecbd->stop_when)) {
472 /* Found our target rev. Tell any subsequent callbacks to suppress processing. */
473 syslog(LOG_DEBUG, "Target revision has been reached -- stop patching.\n");
480 * Fetch a specific revision of a wiki page. The "operation" string may be set to "fetch" in order
481 * to simply fetch the desired revision and store it in a temporary location for viewing, or "revert"
482 * to revert the currently active page to that revision.
484 void wiki_rev(char *pagename, char *rev, char *operation)
487 char history_page_name[270];
491 struct CtdlMessage *msg;
493 struct HistoryEraserCallBackData hecbd;
497 r = CtdlDoIHavePermissionToReadMessagesInThisRoom();
499 if (r == om_not_logged_in) {
500 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
503 cprintf("%d An unknown error has occurred.\n", ERROR);
508 if (!strcasecmp(operation, "revert")) {
509 r = CtdlDoIHavePermissionToPostInThisRoom(temp, sizeof temp, NULL, POST_LOGGED_IN, 0);
511 cprintf("%d %s\n", r, temp);
516 /* Begin by fetching the current version of the page. We're going to patch
517 * backwards through the diffs until we get the one we want.
519 msgnum = CtdlLocateMessageByEuid(pagename, &CC->room);
521 msg = CtdlFetchMessage(msgnum, 1);
527 if ((msg != NULL) && (msg->cm_fields['M'] == NULL)) {
528 CtdlFreeMessage(msg);
533 cprintf("%d Page '%s' was not found.\n", ERROR+MESSAGE_NOT_FOUND, pagename);
537 /* Output it to a temporary file */
539 CtdlMakeTempFileName(temp, sizeof temp);
540 fp = fopen(temp, "w");
542 r = fwrite(msg->cm_fields['M'], strlen(msg->cm_fields['M']), 1, fp);
546 syslog(LOG_ALERT, "Cannot open %s: %s\n", temp, strerror(errno));
548 CtdlFreeMessage(msg);
550 /* Get the revision history */
552 snprintf(history_page_name, sizeof history_page_name, "%s_HISTORY_", pagename);
553 msgnum = CtdlLocateMessageByEuid(history_page_name, &CC->room);
555 msg = CtdlFetchMessage(msgnum, 1);
561 if ((msg != NULL) && (msg->cm_fields['M'] == NULL)) {
562 CtdlFreeMessage(msg);
567 cprintf("%d Revision history for '%s' was not found.\n", ERROR+MESSAGE_NOT_FOUND, pagename);
571 /* Start patching backwards (newest to oldest) through the revision history until we
572 * hit the revision uuid requested by the user. (The callback will perform each one.)
575 memset(&hecbd, 0, sizeof(struct HistoryEraserCallBackData));
576 hecbd.tempfilename = temp;
577 hecbd.stop_when = rev;
579 mime_parser(msg->cm_fields['M'], NULL, *wiki_rev_callback, NULL, NULL, (void *)&hecbd, 0);
580 CtdlFreeMessage(msg);
582 /* Were we successful? */
583 if (hecbd.done == 0) {
584 cprintf("%d Revision '%s' of page '%s' was not found.\n",
585 ERROR + MESSAGE_NOT_FOUND, rev, pagename
589 /* We have the desired revision on disk. Now do something with it. */
591 else if ( (!strcasecmp(operation, "fetch")) || (!strcasecmp(operation, "revert")) ) {
592 msg = malloc(sizeof(struct CtdlMessage));
593 memset(msg, 0, sizeof(struct CtdlMessage));
594 msg->cm_magic = CTDLMESSAGE_MAGIC;
595 msg->cm_anon_type = MES_NORMAL;
596 msg->cm_format_type = FMT_RFC822;
597 fp = fopen(temp, "r");
599 fseek(fp, 0L, SEEK_END);
601 fseek(fp, 0L, SEEK_SET);
602 msg->cm_fields['M'] = malloc(len + 1);
603 rv = fread(msg->cm_fields['M'], len, 1, fp);
604 syslog(LOG_DEBUG, "did %d blocks of %ld bytes\n", rv, len);
605 msg->cm_fields['M'][len] = 0;
611 else if (!strcasecmp(operation, "fetch")) {
612 msg->cm_fields['A'] = strdup("Citadel");
613 CtdlCreateRoom(wwm, 5, "", 0, 1, 1, VIEW_BBS); /* Not an error if already exists */
614 msgnum = CtdlSubmitMsg(msg, NULL, wwm, 0); /* Store the revision here */
616 else if (!strcasecmp(operation, "revert")) {
617 snprintf(timestamp, sizeof timestamp, "%ld", time(NULL));
618 msg->cm_fields['T'] = strdup(timestamp);
619 msg->cm_fields['A'] = strdup(CC->user.fullname);
620 msg->cm_fields['F'] = strdup(CC->cs_inet_email);
621 msg->cm_fields['O'] = strdup(CC->room.QRname);
622 msg->cm_fields['N'] = strdup(NODENAME);
623 msg->cm_fields['E'] = strdup(pagename);
624 msgnum = CtdlSubmitMsg(msg, NULL, "", 0); /* Replace the current revision */
627 /* Theoretically it is impossible to get here, but throw an error anyway */
630 CtdlFreeMessage(msg);
632 cprintf("%d %ld\n", CIT_OK, msgnum); /* Give the client a msgnum */
635 cprintf("%d Error %ld has occurred.\n", ERROR+INTERNAL_ERROR, msgnum);
639 /* We did all this work for nothing. Express anguish to the caller. */
641 cprintf("%d An unknown operation was requested.\n", ERROR+CMD_NOT_SUPPORTED);
651 * commands related to wiki management
653 void cmd_wiki(char *argbuf) {
659 extract_token(subcmd, argbuf, 0, '|', sizeof subcmd);
661 if (!strcasecmp(subcmd, "history")) {
662 extract_token(pagename, argbuf, 1, '|', sizeof pagename);
663 wiki_history(pagename);
667 if (!strcasecmp(subcmd, "rev")) {
668 extract_token(pagename, argbuf, 1, '|', sizeof pagename);
669 extract_token(rev, argbuf, 2, '|', sizeof rev);
670 extract_token(operation, argbuf, 3, '|', sizeof operation);
671 wiki_rev(pagename, rev, operation);
675 cprintf("%d Invalid subcommand\n", ERROR + CMD_NOT_SUPPORTED);
681 * Module initialization
683 CTDL_MODULE_INIT(wiki)
687 CtdlRegisterMessageHook(wiki_upload_beforesave, EVT_BEFORESAVE);
688 CtdlRegisterProtoHook(cmd_wiki, "WIKI", "Commands related to Wiki management");
691 /* return our Subversion id for the Log */