1 (* COCANWIKI - a wiki written in Objective CAML.
2 * Written by Richard W.M. Jones <rich@merjis.com>.
3 * Copyright (C) 2004 Merjis Ltd.
4 * $Id: edit.ml,v 1.16 2004/10/09 09:41:38 rich Exp $
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (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; see the file COPYING. If not, write to
18 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 * Boston, MA 02111-1307, USA.
30 open Cocanwiki_template
32 open Cocanwiki_emailnotify
34 open Cocanwiki_strings
37 type pt_t = Page of string | Title of string
39 (* We keep an "internal model" of the page - see build_internal_model ()
43 id : int; (* Original page ID (0 = none). *)
44 pt : pt_t; (* Page of title (only used if id=0) *)
45 description : string; (* Description. *)
46 redirect : string; (* Redirect to ("" = none). *)
47 contents : (string * string * string) list;
48 (* (sectionname, divname, content)
49 * for each section. *)
52 let run r (q : cgi) (dbh : Dbi.connection) hostid {hostname = hostname} user =
53 let template = get_template dbh hostid "edit.html" in
54 let template_conflict = get_template dbh hostid "edit_conflict.html" in
55 let template_email = get_template dbh hostid "edit_page_email.txt" in
57 (* Workaround bugs in IE, specifically lack of support for <button>
62 let ua = Table.get (Request.headers_in r) "User-Agent" in
63 ignore (String.find ua "MSIE"); (* Throws Invalid_string if not found. *)
66 Not_found | String.Invalid_string -> false in
67 template#conditional "msie" msie;
69 (* Build the internal model from the parameters passed to the script. *)
70 let build_internal_model () =
71 let id = int_of_string (q#param "id") in
72 let description = q#param "description" in
73 let redirect = q#param "redirect" in
74 let pt = match q#param "pt_type" with
75 "page" -> Page (q#param "pt_value")
76 | "title" -> Title (q#param "pt_value")
77 | _ -> failwith "unknown value for pt_type parameter" in
79 let contents = ref [] in
81 while q#param_exists ("content_" ^ string_of_int !i) do
82 let sectionname = q#param ("sectionname_" ^ string_of_int !i) in
83 let content = q#param ("content_" ^ string_of_int !i) in
84 let divname = q#param ("divname_" ^ string_of_int !i) in
85 contents := (sectionname, divname, content) :: !contents;
88 let contents = List.rev !contents in
92 description = description;
94 contents = contents; }
97 (* Check for errors in the model. *)
98 let check_for_errors model =
99 let errors = ref [] in
100 let add_error msg = errors := msg :: !errors in
101 let get_errors () = List.rev !errors in
103 if model.redirect = "" then (
105 if model.contents = [] then
106 add_error ("This page is empty. Use 'Insert new section here' " ^
107 "to write something!");
109 (* Description field? *)
110 if model.description = "" then
111 add_error ("The description field is very important! This field is " ^
112 "used by search engines and directories to describe " ^
113 "what's on this page.");
115 else (* it's a redirect *) (
116 (* Redirect points to a real page? *)
117 let sth = dbh#prepare_cached "select 1 from pages
122 and redirect is null" in
123 sth#execute [`Int hostid; `String model.redirect; `Int model.id];
125 let ok = try sth#fetch1 () = [`Int 1] with Not_found -> false in
127 add_error ("Redirect must point to an ordinary page " ^
128 "(ie. not to a page which is itself a redirect).")
131 (* All sections after the first one have sectionnames? The first
132 * section ONLY is allowed to have an empty title.
134 if model.contents <> [] then
135 List.iter (function (sectionnames, _, _)
136 when string_is_whitespace sectionnames ->
138 ("Every section except the first must have a title.");
140 (List.tl model.contents);
145 (* Various "actions" that can be performed on the model. *)
146 let action_insert model posn item =
147 (* posn = 0 means insert before the first element of the current list. *)
152 | n, x :: xs -> x :: (loop (n-1, xs))
154 let contents = loop (posn, model.contents) in
155 { model with contents = contents }
157 let action_moveup model posn =
158 (* posn = 1 means move up the first element, ie. do nothing
159 * posn = 2 means move up the second element to the first position
167 | 2, x :: y :: xs -> y :: x :: xs
168 | n, x :: xs -> x :: (loop (n-1, xs))
170 let contents = loop (posn, model.contents) in
171 { model with contents = contents }
173 let action_movedn model posn =
174 (* posn = 1 means move down the first element to the second position
181 | 1, x :: y :: xs -> y :: x :: xs
182 | n, x :: xs -> x :: (loop (n-1, xs))
184 let contents = loop (posn, model.contents) in
185 { model with contents = contents }
187 let action_delete model posn =
188 (* posn = 1 means delete the first element *)
194 | n, x :: xs -> x :: (loop (n-1, xs))
196 let contents = loop (posn, model.contents) in
197 { model with contents = contents }
200 (* Convert model to template. *)
201 let model_to_template model template =
202 template#set "id" (string_of_int model.id);
203 template#set "description" model.description;
207 template#set "pt_type" "page";
208 template#set "pt_value" page
210 template#set "pt_type" "title";
211 template#set "pt_value" title);
213 (* Redirects table. *)
214 let sth = dbh#prepare_cached "select url, title from pages
215 where url is not null
217 and hostid = ? and id <> ?
219 sth#execute [`Int hostid; `Int model.id];
220 let table = sth#map (function [`String url; `String title] ->
221 let selected = model.redirect = url in
222 [ "url", Template.VarString url;
223 "title", Template.VarString title;
224 "selected", Template.VarConditional selected ]
225 | _ -> assert false) in
226 template#table "redirects" table;
228 if model.id <> 0 then (
229 (* Need to go to the database to get the title of the page ... *)
230 let sth = dbh#prepare_cached "select title from pages
231 where hostid = ? and id = ?" in
232 sth#execute [`Int hostid; `Int model.id];
233 let title = sth#fetch1string () in
234 template#set "title" title;
237 Page page -> template#set "title" page
238 | Title title -> template#set "title" title
241 let ordering = ref 0 in
244 (fun (sectionname, divname, content) ->
245 incr ordering; let ordering = !ordering in
246 [ "ordering", Template.VarString (string_of_int ordering);
247 "sectionname", Template.VarString sectionname;
248 "divname", Template.VarString divname;
249 "content", Template.VarString content ]) model.contents in
250 template#table "contents" table;
252 (* Check for errors and put those into the template. *)
253 let errors = check_for_errors model in
254 let errors = List.map (fun msg ->
255 [ "error", Template.VarString msg ]) errors in
256 template#table "errors" errors;
257 template#conditional "has_errors" (errors <> [])
260 (* Check if a URL exists in the database. *)
261 let page_exists page =
263 dbh#prepare_cached "select 1 from pages where hostid = ? and url = ?" in
264 sth#execute [`Int hostid; `String page];
266 try sth#fetch1int () = 1 with Not_found -> false
269 (* Begin editing a page, pulling the page out of the database and building
272 let begin_editing page =
273 (* Pull out the page itself from the database. *)
274 let sth = dbh#prepare_cached "select id, title, description,
275 coalesce (redirect, '')
277 where hostid = ? and url = ?" in
278 sth#execute [`Int hostid; `String page];
280 let pageid, title, description, redirect =
281 match sth#fetch1 () with
282 [`Int pageid; `String title; `String description; `String redirect]->
283 pageid, title, description, redirect
284 | _ -> assert false in
286 (* Get the sections. *)
287 let sth = dbh#prepare_cached "select coalesce (sectionname, ''),
289 coalesce (divname, '')
292 order by ordering" in
293 sth#execute [`Int pageid];
297 | [`String sectionname; `String content; `String divname] ->
298 sectionname, divname, content
299 | _ -> assert false) in
301 let model = { id = pageid;
303 description = description;
305 contents = contents; } in
307 model_to_template model template
310 (* Begin editing with a blank page, typically a template. *)
311 let begin_editing_new pt =
316 match Wikilib.generate_url_of_title dbh hostid title with
317 Wikilib.GenURL_OK url -> url, title
318 | Wikilib.GenURL_Duplicate url ->
319 q#redirect ("http://" ^ hostname ^ "/" ^ url);
321 | Wikilib.GenURL_TooShort | Wikilib.GenURL_BadURL ->
322 error ~back_button:true ~title:"Bad page name"
323 q "The page name supplied is too short or invalid.";
326 let model = { id = 0;
332 model_to_template model template
335 let continue_editing () =
336 let model = ref (build_internal_model ()) in
338 (* An "action" parameter? *)
339 let is_action, get_action =
340 let actions = q#params in
341 (* Don't actually care about the value fields ... *)
342 let actions = List.map (fun (str, _) -> str) actions in
343 (* Some of our actions are imagemaps, so parameters like name.x, name.y
344 * need to be changed to name and have resulting duplicates removed.
347 List.filter (fun str ->
348 String.length str > 7 &&
349 String.sub str 0 7 = "action_" &&
350 not (String.ends_with str ".y")) actions in
353 if String.ends_with str ".x" then (
354 let str = String.sub str 0 (String.length str - 2) in
360 let action_type = String.sub str 7 6 in
362 String.sub str 14 (String.length str - 14) in
363 let action_value = int_of_string action_value in
364 action_type, action_value) actions in
366 let is_action typ = List.mem_assoc typ actions in
367 let get_value typ = List.assoc typ actions in
372 if is_action "insert" then (
373 let posn = get_action "insert" in
374 let item = "New section - change this", "", "Write some content here." in
375 model := action_insert !model posn item
376 ) else if is_action "moveup" then (
377 let posn = get_action "moveup" in
378 model := action_moveup !model posn
379 ) else if is_action "movedn" then (
380 let posn = get_action "movedn" in
381 model := action_movedn !model posn
382 ) else if is_action "delete" then (
383 let posn = get_action "delete" in
384 model := action_delete !model posn
387 model_to_template !model template
390 (* Try to save the page. Returns a boolean indicating if the
391 * page was saved successfully.
394 let model = build_internal_model () in
395 let no_errors = [] = check_for_errors model in
397 (* No errors, so we can save the page ... *)
399 (* Get the IP address of the user, if available. *)
401 try `String (Connection.remote_ip (Request.connection r))
402 with Not_found -> `Null in
406 | User (id, _, _) -> `Int id
411 if model.redirect = "" then `Null
412 else `String model.redirect in
415 (* Creating a new page (id = 0)? If so, we're just going to insert
416 * a new row, which is easy.
418 if model.id = 0 then (
419 (* Create the page title or URL. *)
424 match Wikilib.generate_url_of_title dbh hostid title with
425 Wikilib.GenURL_OK url -> url, title
426 | Wikilib.GenURL_Duplicate url ->
427 error ~back_button:true ~title:"Page exists"
428 q ("While you were editing that page, it looks " ^
429 "like another user created the same page.");
432 assert false (* This should have been detected in
436 let sth = dbh#prepare_cached "insert into pages (hostid, url, title,
437 description, logged_ip, logged_user,
439 values (?, ?, ?, ?, ?, ?, ?)" in
440 sth#execute [`Int hostid; `String url; `String title;
441 `String model.description; logged_ip; logged_user;
444 let pageid = sth#serial "pages_id_seq" in
446 (* Create the page contents. *)
447 let sth = dbh#prepare_cached "insert into contents (pageid,
448 ordering, sectionname, divname,
450 values (?, ?, ?, ?, ?)" in
451 let ordering = ref 0 in (* Creating new ordering. *)
452 List.iter (fun (sectionname, divname, content) ->
454 if string_is_whitespace divname then `Null
455 else `String divname in
457 if string_is_whitespace sectionname then `Null
458 else `String sectionname in
459 incr ordering; let ordering = !ordering in
460 sth#execute [`Int pageid; `Int ordering;
461 sectionname; divname;
467 (* Otherwise it's an old page which we're updating. *)
469 (* Pull out fields from the database. *)
470 let sth = dbh#prepare_cached "select creation_date,
471 coalesce (url, url_deleted),
474 where hostid = ? and id = ?" in
475 sth#execute [`Int hostid; `Int model.id];
477 let creation_date, url, title, css =
478 match sth#fetch1 () with
479 [ creation_date; `String url; `String title; css ] ->
480 creation_date, url, title, css
481 | _ -> assert false in
483 (* Has someone else edited this page in the meantime? *)
484 let sth = dbh#prepare_cached "select max(id) from pages
485 where hostid = ? and url = ?" in
486 sth#execute [`Int hostid; `String url];
488 let max_id = sth#fetch1int () in
489 let edited = max_id <> model.id in
492 (* Edited by someone else ... Get the other's changes. *)
494 get_diff dbh hostid url
495 ~old_version:model.id ~version:max_id () in
497 (* Synthesize our own changes. *)
498 let old_page = get_version_for_diff dbh model.id in
500 let css = match css with
501 `Null -> "" | `String css -> css
502 | _ -> assert false in
503 page_for_diff css (List.map (fun (sectionname, _, content) ->
504 sectionname, content) model.contents) in
505 let our_diff = diff_cmd old_page new_page in
507 (* Fill out the conflict template. *)
508 template_conflict#set "other_diff" other_diff;
509 template_conflict#set "our_diff" our_diff;
510 template_conflict#set "old_version" (string_of_int model.id);
511 template_conflict#set "new_version" (string_of_int max_id);
512 template_conflict#set "url" url;
514 q#template template_conflict;
518 (* Defer the pages_redirect_cn constraint because that would
519 * temporarily fail on the next UPDATE.
523 "set constraints pages_redirect_cn, sitemenu_url_cn,
524 page_emails_url_cn, links_from_cn deferred" in
527 (* Mark the old page as deleted. NB. There is a small race
528 * condition here because PostgreSQL doesn't do isolation
529 * properly. If a user tries to visit this page between the
530 * delete and the creation of the new page, then they'll get
531 * a page not found error. (XXX)
533 let sth = dbh#prepare_cached "update pages set url_deleted = url,
535 where hostid = ? and id = ?" in
536 sth#execute [`Int hostid; `Int model.id];
538 (* Create the new page. *)
539 let sth = dbh#prepare_cached "insert into pages (hostid, url, title,
540 description, creation_date, logged_ip,
541 logged_user, redirect, css)
542 values (?, ?, ?, ?, ?, ?, ?, ?, ?)" in
543 sth#execute [`Int hostid; `String url; `String title;
544 `String model.description; creation_date; logged_ip;
545 logged_user; redirect; css];
547 (* New page ID <> old page ID model.id. *)
548 let pageid = sth#serial "pages_id_seq" in
550 (* Create the page contents. *)
551 let sth = dbh#prepare_cached "insert into contents (pageid,
552 ordering, sectionname, divname,
554 values (?, ?, ?, ?, ?)" in
555 let ordering = ref 0 in (* Creating new ordering. *)
556 List.iter (fun (sectionname, divname, content) ->
558 if string_is_whitespace divname then `Null
559 else `String divname in
561 if string_is_whitespace sectionname then `Null
562 else `String sectionname in
563 incr ordering; let ordering = !ordering in
564 sth#execute [`Int pageid; `Int ordering;
565 sectionname; divname;
569 (* General email notification of page edits. Send an email to
570 * anyone in the page_emails table who has a confirmed address
571 * and who hasn't received an email already today.
573 let sth = dbh#prepare_cached "select email, opt_out from page_emails
574 where hostid = ? and url = ?
576 and last_sent < current_date" in
577 sth#execute [`Int hostid; `String url];
579 let addrs = sth#map (function [`String email; `String opt_out] ->
581 | _ -> assert false) in
583 if addrs <> [] then (
584 (* Construct the email. *)
585 template_email#set "hostname" hostname;
586 template_email#set "page" url;
589 "Site notice: " ^ hostname ^ "/" ^ url ^ " has been updated" in
591 (* Send each email individually (they all have different opt out
594 List.iter (fun (to_addr, opt_out) ->
595 template_email#set "opt_out" opt_out;
596 let body = template_email#to_string in
597 Sendmail.send_mail ~subject
598 ~to_addr:[to_addr] ~body ())
602 (* Update the database to record when these emails were sent. *)
603 let sth = dbh#prepare_cached "update page_emails
604 set last_sent = current_date
605 where hostid = ? and url = ?
606 and pending is null" in
607 sth#execute [`Int hostid; `String url];
612 (* Keep the links table in synch. *)
613 Cocanwiki_links.update_links_for_page dbh hostid url;
615 (* Commit changes to the database. *)
618 (* Email notification, if anyone is listed for this host. *)
619 let subject = "Page " ^ url ^ " has been edited" in
622 (* Prepare the diff between this version and the previous version. *)
623 let diff, _ = get_diff dbh hostid url ~version:pageid () in
624 "Page: http://" ^ hostname ^ "/" ^ url ^ "\n\n" ^
627 email_notify ~body ~subject dbh hostid;
629 (* Redirect back to the URL. *)
630 q#redirect ("http://" ^ hostname ^ "/" ^ url);
636 let sth = dbh#prepare_cached "select url from pages
637 where hostid = ? and id = ?" in
638 sth#execute [`Int hostid; `Int id];
639 let url = sth#fetch1string () in
641 q#redirect ("http://" ^ hostname ^ "/" ^ url);
645 (* This codes decides where we are in the current editing cycle.
648 * id - if set, then we are in the midst of editing a page.
649 * save - if set, then we want to save the page.
650 * cancel - if set, abandon changes and go back to viewing the page.
651 * action_* - one of the action buttons was set, eg. move up/down.
652 * page - the page URL opened newly for editing, or a template which
654 * title - page doesn't yet exist; create it.
657 try Some (int_of_string (q#param "id")) with Not_found -> None in
659 | None -> (* Begin editing the page. *)
660 if q#param_exists "page" then (
661 let page = q#param "page" in
662 let page = if page = "" then "index" else page in
663 if page_exists page then
666 begin_editing_new (Page page)
668 let title = q#param "title" in
669 begin_editing_new (Title title)
673 if q#param_true "cancel" then
675 if q#param_true "save" then
676 try_save (); (* might fail and fall through ... *)
683 register_script ~restrict:[CanEdit] run