Script for rebuilding the links table from scratch.
[cocanwiki.git] / scripts / cocanwiki_links.ml
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: cocanwiki_links.ml,v 1.1 2004/09/28 10:56:39 rich Exp $
5  *
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.
10  *
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.
15  *
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.
20  *)
21
22 open ExtString
23
24 let split_tags_re = Pcre.regexp ~flags:[`DOTALL] "<.*?>|[^<]+"
25 let internal_re = Pcre.regexp "class=\"internal\""
26 let href_re = Pcre.regexp "href=\"/(.*?)\""
27
28 let get_links_from_section dbh hostid content =
29   let html = Wikilib.xhtml_of_content dbh hostid content in
30
31   (* Split into attrs and non-attrs.  We end up with a list like this:
32    * [ "<ul>"; "<li>"; "Some text"; "</li>"; ... ]
33    *)
34   let html =
35     try
36       let html = Pcre.extract_all ~rex:split_tags_re html in
37       let html = Array.to_list html in
38       List.map (function [| a |] -> a | _ -> assert false) html
39     with
40         Not_found -> [] in
41
42   (* Only interested in the <a> tags. *)
43   let html = List.filter (fun str -> String.starts_with str "<a ") html in
44
45   (* Only interested in the tags with class="internal". *)
46   let html =
47     List.filter (fun str ->
48                    Pcre.pmatch ~rex:internal_re str
49                    && Pcre.pmatch ~rex:href_re str)
50       html in
51
52   (* Extract the URL names. *)
53   let links = List.map (fun str ->
54                           let subs =
55                             try Pcre.exec ~rex:href_re str
56                             with Not_found -> assert false in
57                           Pcre.get_substring subs 1) html in
58
59   (* Return the list of links. *)
60   links