af1a7563098150395ea5985f039abefaa9cedba0
[elisp/gnus.git-] / lisp / nnweb.el
1 ;;; nnweb.el --- retrieving articles via web search engines
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; Note: You need to have `url' and `w3' installed for this
28 ;; backend to work.
29
30 ;;; Code:
31
32 (eval-when-compile (require 'cl))
33 (eval-when-compile (require 'gnus-clfns))
34
35 (require 'nnoo)
36 (require 'message)
37 (require 'gnus-util)
38 (require 'gnus)
39 (require 'nnmail)
40 (eval-when-compile
41   (ignore-errors
42     (require 'w3)
43     (require 'url)
44     (require 'w3-forms)))
45
46 ;; Report failure to find w3 at load time if appropriate.
47 (unless noninteractive
48   (eval '(progn
49            (require 'w3)
50            (require 'url)
51            (require 'w3-forms))))
52
53 (nnoo-declare nnweb)
54
55 (defvoo nnweb-directory (nnheader-concat gnus-directory "nnweb/")
56   "Where nnweb will save its files.")
57
58 (defvoo nnweb-type 'dejanews
59   "What search engine type is being used.
60 Valid types include `dejanews', `dejanewsold', `reference',
61 and `altavista'.")
62
63 (defvar nnweb-type-definition
64   '(
65     (dejanews ;; bought by google.com
66      (article . nnweb-google-wash-article)
67      (id . "http://groups.google.com/groups?as_umsgid=%s")
68      (reference . nnweb-google-reference)
69      (map . nnweb-google-create-mapping)
70      (search . nnweb-google-search)
71      (address . "http://groups.google.com/groups")
72      (identifier . nnweb-google-identity))
73 ;;;     (dejanews
74 ;;;      (article . ignore)
75 ;;;      (id . "http://search.dejanews.com/msgid.xp?MID=%s&fmt=text")
76 ;;;      (map . nnweb-dejanews-create-mapping)
77 ;;;      (search . nnweb-dejanews-search)
78 ;;;      (address . "http://www.deja.com/=dnc/qs.xp")
79 ;;;      (identifier . nnweb-dejanews-identity))
80 ;;;     (dejanewsold
81 ;;;      (article . ignore)
82 ;;;      (map . nnweb-dejanews-create-mapping)
83 ;;;      (search . nnweb-dejanewsold-search)
84 ;;;      (address . "http://www.deja.com/dnquery.xp")
85 ;;;      (identifier . nnweb-dejanews-identity))
86     (reference
87      (article . nnweb-reference-wash-article)
88      (map . nnweb-reference-create-mapping)
89      (search . nnweb-reference-search)
90      (address . "http://www.reference.com/cgi-bin/pn/go")
91      (identifier . identity))
92     (altavista
93      (article . nnweb-altavista-wash-article)
94      (map . nnweb-altavista-create-mapping)
95      (search . nnweb-altavista-search)
96      (address . "http://www.altavista.digital.com/cgi-bin/query")
97      (id . "/cgi-bin/news?id@%s")
98      (identifier . identity)))
99   "Type-definition alist.")
100
101 (defvoo nnweb-search nil
102   "Search string to feed to DejaNews.")
103
104 (defvoo nnweb-max-hits 999
105   "Maximum number of hits to display.")
106
107 (defvoo nnweb-ephemeral-p nil
108   "Whether this nnweb server is ephemeral.")
109
110 ;;; Internal variables
111
112 (defvoo nnweb-articles nil)
113 (defvoo nnweb-buffer nil)
114 (defvoo nnweb-group-alist nil)
115 (defvoo nnweb-group nil)
116 (defvoo nnweb-hashtb nil)
117
118 ;;; Interface functions
119
120 (nnoo-define-basics nnweb)
121
122 (deffoo nnweb-retrieve-headers (articles &optional group server fetch-old)
123   (nnweb-possibly-change-server group server)
124   (save-excursion
125     (set-buffer nntp-server-buffer)
126     (erase-buffer)
127     (let (article header)
128       (mm-with-unibyte-current-buffer
129         (while (setq article (pop articles))
130           (when (setq header (cadr (assq article nnweb-articles)))
131             (nnheader-insert-nov header))))
132       'nov)))
133
134 (deffoo nnweb-request-scan (&optional group server)
135   (nnweb-possibly-change-server group server)
136   (funcall (nnweb-definition 'map))
137   (unless nnweb-ephemeral-p
138     (nnweb-write-active)
139     (nnweb-write-overview group)))
140
141 (deffoo nnweb-request-group (group &optional server dont-check)
142   (nnweb-possibly-change-server nil server)
143   (when (and group
144              (not (equal group nnweb-group))
145              (not nnweb-ephemeral-p))
146     (setq nnweb-group group
147           nnweb-articles nil)
148     (let ((info (assoc group nnweb-group-alist)))
149       (when info
150         (setq nnweb-type (nth 2 info))
151         (setq nnweb-search (nth 3 info))
152         (unless dont-check
153           (nnweb-read-overview group)))))
154   (cond
155    ((not nnweb-articles)
156     (nnheader-report 'nnweb "No matching articles"))
157    (t
158     (let ((active (if nnweb-ephemeral-p
159                       (cons (caar nnweb-articles)
160                             (caar (last nnweb-articles)))
161                     (cadr (assoc group nnweb-group-alist)))))
162       (nnheader-report 'nnweb "Opened group %s" group)
163       (nnheader-insert
164        "211 %d %d %d %s\n" (length nnweb-articles)
165        (car active) (cdr active) group)))))
166
167 (deffoo nnweb-close-group (group &optional server)
168   (nnweb-possibly-change-server group server)
169   (when (gnus-buffer-live-p nnweb-buffer)
170     (save-excursion
171       (set-buffer nnweb-buffer)
172       (set-buffer-modified-p nil)
173       (kill-buffer nnweb-buffer)))
174   t)
175
176 (deffoo nnweb-request-article (article &optional group server buffer)
177   (nnweb-possibly-change-server group server)
178   (save-excursion
179     (set-buffer (or buffer nntp-server-buffer))
180     (let* ((header (cadr (assq article nnweb-articles)))
181            (url (and header (mail-header-xref header))))
182       (when (or (and url
183                      (mm-with-unibyte-current-buffer
184                        (nnweb-fetch-url url)))
185                 (and (stringp article)
186                      (nnweb-definition 'id t)
187                      (let ((fetch (nnweb-definition 'id))
188                            art active)
189                        (when (string-match "^<\\(.*\\)>$" article)
190                          (setq art (match-string 1 article)))
191                        (when (and fetch art)
192                          (setq url (format fetch article))
193                          (mm-with-unibyte-current-buffer
194                            (nnweb-fetch-url url))
195                          (if (nnweb-definition 'reference t)
196                              (setq article
197                                    (funcall (nnweb-definition
198                                              'reference) article)))))))
199         (unless nnheader-callback-function
200           (funcall (nnweb-definition 'article))
201           (nnweb-decode-entities))
202         (nnheader-report 'nnweb "Fetched article %s" article)
203         (cons group (and (numberp article) article))))))
204
205 (deffoo nnweb-close-server (&optional server)
206   (when (and (nnweb-server-opened server)
207              (gnus-buffer-live-p nnweb-buffer))
208     (save-excursion
209       (set-buffer nnweb-buffer)
210       (set-buffer-modified-p nil)
211       (kill-buffer nnweb-buffer)))
212   (nnoo-close-server 'nnweb server))
213
214 (deffoo nnweb-request-list (&optional server)
215   (nnweb-possibly-change-server nil server)
216   (save-excursion
217     (set-buffer nntp-server-buffer)
218     (nnmail-generate-active nnweb-group-alist)
219     t))
220
221 (deffoo nnweb-request-update-info (group info &optional server)
222   (nnweb-possibly-change-server group server))
223
224 (deffoo nnweb-asynchronous-p ()
225   t)
226
227 (deffoo nnweb-request-create-group (group &optional server args)
228   (nnweb-possibly-change-server nil server)
229   (nnweb-request-delete-group group)
230   (push `(,group ,(cons 1 0) ,@args) nnweb-group-alist)
231   (nnweb-write-active)
232   t)
233
234 (deffoo nnweb-request-delete-group (group &optional force server)
235   (nnweb-possibly-change-server group server)
236   (gnus-pull group nnweb-group-alist t)
237   (nnweb-write-active)
238   (gnus-delete-file (nnweb-overview-file group))
239   t)
240
241 (nnoo-define-skeleton nnweb)
242
243 ;;; Internal functions
244
245 (defun nnweb-read-overview (group)
246   "Read the overview of GROUP and build the map."
247   (when (file-exists-p (nnweb-overview-file group))
248     (mm-with-unibyte-buffer
249       (nnheader-insert-file-contents (nnweb-overview-file group))
250       (goto-char (point-min))
251       (let (header)
252         (while (not (eobp))
253           (setq header (nnheader-parse-nov))
254           (forward-line 1)
255           (push (list (mail-header-number header)
256                       header (mail-header-xref header))
257                 nnweb-articles)
258           (nnweb-set-hashtb header (car nnweb-articles)))))))
259
260 (defun nnweb-write-overview (group)
261   "Write the overview file for GROUP."
262   (with-temp-file (nnweb-overview-file group)
263     (let ((articles nnweb-articles))
264       (while articles
265         (nnheader-insert-nov (cadr (pop articles)))))))
266
267 (defun nnweb-set-hashtb (header data)
268   (gnus-sethash (nnweb-identifier (mail-header-xref header))
269                 data nnweb-hashtb))
270
271 (defun nnweb-get-hashtb (url)
272   (gnus-gethash (nnweb-identifier url) nnweb-hashtb))
273
274 (defun nnweb-identifier (ident)
275   (funcall (nnweb-definition 'identifier) ident))
276
277 (defun nnweb-overview-file (group)
278   "Return the name of the overview file of GROUP."
279   (nnheader-concat nnweb-directory group ".overview"))
280
281 (defun nnweb-write-active ()
282   "Save the active file."
283   (gnus-make-directory nnweb-directory)
284   (with-temp-file (nnheader-concat nnweb-directory "active")
285     (prin1 `(setq nnweb-group-alist ',nnweb-group-alist) (current-buffer))))
286
287 (defun nnweb-read-active ()
288   "Read the active file."
289   (load (nnheader-concat nnweb-directory "active") t t t))
290
291 (defun nnweb-definition (type &optional noerror)
292   "Return the definition of TYPE."
293   (let ((def (cdr (assq type (assq nnweb-type nnweb-type-definition)))))
294     (when (and (not def)
295                (not noerror))
296       (error "Undefined definition %s" type))
297     def))
298
299 (defun nnweb-possibly-change-server (&optional group server)
300   (nnweb-init server)
301   (when server
302     (unless (nnweb-server-opened server)
303       (nnweb-open-server server)))
304   (unless nnweb-group-alist
305     (nnweb-read-active))
306   (when group
307     (when (and (not nnweb-ephemeral-p)
308                (not (equal group nnweb-group)))
309       (setq nnweb-hashtb (gnus-make-hashtable 4095))
310       (nnweb-request-group group nil t))))
311
312 (defun nnweb-init (server)
313   "Initialize buffers and such."
314   (unless (gnus-buffer-live-p nnweb-buffer)
315     (setq nnweb-buffer
316           (save-excursion
317             (mm-with-unibyte
318               (nnheader-set-temp-buffer
319                (format " *nnweb %s %s %s*"
320                        nnweb-type nnweb-search server))
321               (current-buffer))))))
322
323 (defun nnweb-fetch-url (url)
324   (let (buf)
325     (save-excursion
326       (if (not nnheader-callback-function)
327           (progn
328             (with-temp-buffer
329               (mm-enable-multibyte)
330               (let ((coding-system-for-read 'binary)
331                     (coding-system-for-write 'binary)
332                     (input-coding-system 'binary)
333                     (output-coding-system 'binary)
334                     (default-process-coding-system 'binary))
335                 (nnweb-insert url))
336               (setq buf (buffer-string)))
337             (erase-buffer)
338             (insert buf)
339             t)
340         (nnweb-url-retrieve-asynch
341          url 'nnweb-callback (current-buffer) nnheader-callback-function)
342         t))))
343
344 (defun nnweb-callback (buffer callback)
345   (when (gnus-buffer-live-p url-working-buffer)
346     (save-excursion
347       (set-buffer url-working-buffer)
348       (funcall (nnweb-definition 'article))
349       (nnweb-decode-entities)
350       (set-buffer buffer)
351       (goto-char (point-max))
352       (insert-buffer-substring url-working-buffer))
353     (funcall callback t)
354     (gnus-kill-buffer url-working-buffer)))
355
356 (defun nnweb-url-retrieve-asynch (url callback &rest data)
357   (let ((url-request-method "GET")
358         (old-asynch url-be-asynchronous)
359         (url-request-data nil)
360         (url-request-extra-headers nil)
361         (url-working-buffer (generate-new-buffer-name " *nnweb*")))
362     (setq-default url-be-asynchronous t)
363     (save-excursion
364       (set-buffer (get-buffer-create url-working-buffer))
365       (setq url-current-callback-data data
366             url-be-asynchronous t
367             url-current-callback-func callback)
368       (url-retrieve url nil))
369     (setq-default url-be-asynchronous old-asynch)))
370
371 (if (fboundp 'url-retrieve-synchronously)
372     (defun nnweb-url-retrieve-asynch (url callback &rest data)
373       (url-retrieve url callback data)))
374
375 ;;;
376 ;;; DejaNews functions.
377 ;;;
378
379 (defun nnweb-dejanews-create-mapping ()
380   "Perform the search and create an number-to-url alist."
381   (save-excursion
382     (set-buffer nnweb-buffer)
383     (erase-buffer)
384     (when (funcall (nnweb-definition 'search) nnweb-search)
385       (let ((i 0)
386             (more t)
387             (case-fold-search t)
388             (active (or (cadr (assoc nnweb-group nnweb-group-alist))
389                         (cons 1 0)))
390             subject date from
391             map url parse a table group text)
392         (while more
393           ;; Go through all the article hits on this page.
394           (goto-char (point-min))
395           (setq parse (w3-parse-buffer (current-buffer))
396                 table (nth 1 (nnweb-parse-find-all 'table parse)))
397           (dolist (row (nth 2 (car (nth 2 table))))
398             (setq a (nnweb-parse-find 'a row)
399                   url (cdr (assq 'href (nth 1 a)))
400                   text (nreverse (nnweb-text row)))
401             (when a
402               (setq subject (nth 4 text)
403                     group (nth 2 text)
404                     date (nth 1 text)
405                     from (nth 0 text))
406               (if (string-match "\\([0-9]+\\)/\\([0-9]+\\)/\\([0-9]+\\)" date)
407                   (setq date (format "%s %s 00:00:00 %s"
408                                      (car (rassq (string-to-number
409                                                   (match-string 2 date))
410                                                  parse-time-months))
411                                      (match-string 3 date)
412                                      (match-string 1 date)))
413                 (setq date "Jan 1 00:00:00 0000"))
414               (incf i)
415               (setq url (concat url "&fmt=text"))
416               (when (string-match "&context=[^&]+" url)
417                 (setq url (replace-match "" t t url)))
418               (unless (nnweb-get-hashtb url)
419                 (push
420                  (list
421                   (incf (cdr active))
422                   (make-full-mail-header
423                    (cdr active) (concat subject " (" group ")") from date
424                    (concat "<" (nnweb-identifier url) "@dejanews>")
425                    nil 0 0 url))
426                  map)
427                 (nnweb-set-hashtb (cadar map) (car map)))))
428           ;; See whether there is a "Get next 20 hits" button here.
429           (goto-char (point-min))
430           (if (or (not (re-search-forward
431                         "HREF=\"\\([^\"]+\\)\"[<>b]+Next result" nil t))
432                   (>= i nnweb-max-hits))
433               (setq more nil)
434             ;; Yup -- fetch it.
435             (setq more (match-string 1))
436             (erase-buffer)
437             (url-insert-file-contents more)))
438         ;; Return the articles in the right order.
439         (setq nnweb-articles
440               (sort (nconc nnweb-articles map) 'car-less-than-car))))))
441
442 (defun nnweb-dejanews-search (search)
443   (nnweb-insert
444    (concat
445     (nnweb-definition 'address)
446     "?"
447     (nnweb-encode-www-form-urlencoded
448      `(("ST" . "PS")
449        ("svcclass" . "dnyr")
450        ("QRY" . ,search)
451        ("defaultOp" . "AND")
452        ("DBS" . "1")
453        ("OP" . "dnquery.xp")
454        ("LNG" . "ALL")
455        ("maxhits" . "100")
456        ("threaded" . "0")
457        ("format" . "verbose2")
458        ("showsort" . "date")
459        ("agesign" . "1")
460        ("ageweight" . "1")))))
461   t)
462
463 (defun nnweb-dejanewsold-search (search)
464   (nnweb-fetch-form
465    (nnweb-definition 'address)
466    `(("query" . ,search)
467      ("defaultOp" . "AND")
468      ("svcclass" . "dnold")
469      ("maxhits" . "100")
470      ("format" . "verbose2")
471      ("threaded" . "0")
472      ("showsort" . "date")
473      ("agesign" . "1")
474      ("ageweight" . "1")))
475   t)
476
477 (defun nnweb-dejanews-identity (url)
478   "Return an unique identifier based on URL."
479   (if (string-match "AN=\\([0-9]+\\)" url)
480       (match-string 1 url)
481     url))
482
483 ;;;
484 ;;; InReference
485 ;;;
486
487 (defun nnweb-reference-create-mapping ()
488   "Perform the search and create an number-to-url alist."
489   (save-excursion
490     (set-buffer nnweb-buffer)
491     (erase-buffer)
492     (when (funcall (nnweb-definition 'search) nnweb-search)
493       (let ((i 0)
494             (more t)
495             (case-fold-search t)
496             (active (or (cadr (assoc nnweb-group nnweb-group-alist))
497                         (cons 1 0)))
498             Subject Score Date Newsgroups From Message-ID
499             map url)
500         (while more
501           ;; Go through all the article hits on this page.
502           (goto-char (point-min))
503           (search-forward "</pre><hr>" nil t)
504           (delete-region (point-min) (point))
505           (goto-char (point-min))
506           (while (re-search-forward "^ +[0-9]+\\." nil t)
507             (narrow-to-region
508              (point)
509              (if (re-search-forward "^$" nil t)
510                  (match-beginning 0)
511                (point-max)))
512             (goto-char (point-min))
513             (when (looking-at ".*href=\"\\([^\"]+\\)\"")
514               (setq url (match-string 1)))
515             (nnweb-remove-markup)
516             (goto-char (point-min))
517             (while (search-forward "\t" nil t)
518               (replace-match " "))
519             (goto-char (point-min))
520             (while (re-search-forward "^\\([^:]+\\): \\(.*\\)$" nil t)
521               (set (intern (match-string 1)) (match-string 2)))
522             (widen)
523             (search-forward "</pre>" nil t)
524             (incf i)
525             (unless (nnweb-get-hashtb url)
526               (push
527                (list
528                 (incf (cdr active))
529                 (make-full-mail-header
530                  (cdr active) (concat  "(" Newsgroups ") " Subject) From Date
531                  Message-ID
532                  nil 0 (string-to-int Score) url))
533                map)
534               (nnweb-set-hashtb (cadar map) (car map))))
535           (setq more nil))
536         ;; Return the articles in the right order.
537         (setq nnweb-articles
538               (sort (nconc nnweb-articles map) 'car-less-than-car))))))
539
540 (defun nnweb-reference-wash-article ()
541   (let ((case-fold-search t))
542     (goto-char (point-min))
543     (re-search-forward "^</center><hr>" nil t)
544     (delete-region (point-min) (point))
545     (search-forward "<pre>" nil t)
546     (forward-line -1)
547     (let ((body (point-marker)))
548       (search-forward "</pre>" nil t)
549       (delete-region (point) (point-max))
550       (nnweb-remove-markup)
551       (goto-char (point-min))
552       (while (looking-at " *$")
553         (gnus-delete-line))
554       (narrow-to-region (point-min) body)
555       (while (and (re-search-forward "^$" nil t)
556                   (not (eobp)))
557         (gnus-delete-line))
558       (goto-char (point-min))
559       (while (looking-at "\\(^[^ ]+:\\) *")
560         (replace-match "\\1 " t)
561         (forward-line 1))
562       (goto-char (point-min))
563       (when (re-search-forward "^References:" nil t)
564         (narrow-to-region
565          (point) (if (re-search-forward "^$\\|^[^:]+:" nil t)
566                      (match-beginning 0)
567                    (point-max)))
568         (goto-char (point-min))
569         (while (not (eobp))
570           (unless (looking-at "References")
571             (insert "\t")
572             (forward-line 1)))
573         (goto-char (point-min))
574         (while (search-forward "," nil t)
575           (replace-match " " t t)))
576       (widen)
577       (set-marker body nil))))
578
579 (defun nnweb-reference-search (search)
580   (url-insert-file-contents
581    (concat
582     (nnweb-definition 'address)
583     "?"
584     (nnweb-encode-www-form-urlencoded
585      `(("search" . "advanced")
586        ("querytext" . ,search)
587        ("subj" . "")
588        ("name" . "")
589        ("login" . "")
590        ("host" . "")
591        ("organization" . "")
592        ("groups" . "")
593        ("keywords" . "")
594        ("choice" . "Search")
595        ("startmonth" . "Jul")
596        ("startday" . "25")
597        ("startyear" . "1996")
598        ("endmonth" . "Aug")
599        ("endday" . "24")
600        ("endyear" . "1996")
601        ("mode" . "Quick")
602        ("verbosity" . "Verbose")
603        ("ranking" . "Relevance")
604        ("first" . "1")
605        ("last" . "25")
606        ("score" . "50")))))
607   (setq buffer-file-name nil)
608   t)
609
610 ;;;
611 ;;; Alta Vista
612 ;;;
613
614 (defun nnweb-altavista-create-mapping ()
615   "Perform the search and create an number-to-url alist."
616   (save-excursion
617     (set-buffer nnweb-buffer)
618     (erase-buffer)
619     (let ((part 0))
620       (when (funcall (nnweb-definition 'search) nnweb-search part)
621         (let ((i 0)
622               (more t)
623               (case-fold-search t)
624               (active (or (cadr (assoc nnweb-group nnweb-group-alist))
625                           (cons 1 0)))
626               subject date from id group
627               map url)
628           (while more
629             ;; Go through all the article hits on this page.
630             (goto-char (point-min))
631             (search-forward "<dt>" nil t)
632             (delete-region (point-min) (match-beginning 0))
633             (goto-char (point-min))
634             (while (search-forward "<dt>" nil t)
635               (replace-match "\n<blubb>"))
636             (nnweb-decode-entities)
637             (goto-char (point-min))
638             (while (re-search-forward "<blubb>.*href=\"\\([^\"]+\\)\"><strong>\\([^>]*\\)</strong></a><dd>\\([^-]+\\)- <b>\\([^<]+\\)<.*href=\"news:\\([^\"]+\\)\">.*\">\\(.+\\)</a><P>"
639                                       nil t)
640               (setq url (match-string 1)
641                     subject (match-string 2)
642                     date (match-string 3)
643                     group (match-string 4)
644                     id (concat "<" (match-string 5) ">")
645                     from (match-string 6))
646               (incf i)
647               (unless (nnweb-get-hashtb url)
648                 (push
649                  (list
650                   (incf (cdr active))
651                   (make-full-mail-header
652                    (cdr active) (concat  "(" group ") " subject) from date
653                    id nil 0 0 url))
654                  map)
655                 (nnweb-set-hashtb (cadar map) (car map))))
656             ;; See if we want more.
657             (when (or (not nnweb-articles)
658                       (>= i nnweb-max-hits)
659                       (not (funcall (nnweb-definition 'search)
660                                     nnweb-search (incf part))))
661               (setq more nil)))
662           ;; Return the articles in the right order.
663           (setq nnweb-articles
664                 (sort (nconc nnweb-articles map) 'car-less-than-car)))))))
665
666 (defun nnweb-altavista-wash-article ()
667   (goto-char (point-min))
668   (let ((case-fold-search t))
669     (when (re-search-forward "^<strong>" nil t)
670       (delete-region (point-min) (match-beginning 0)))
671     (goto-char (point-min))
672     (while (looking-at "<strong>\\([^ ]+\\) +</strong> +\\(.*\\)$")
673       (replace-match "\\1: \\2" t)
674       (forward-line 1))
675     (when (re-search-backward "^References:" nil t)
676       (narrow-to-region (point) (progn (forward-line 1) (point)))
677       (goto-char (point-min))
678       (while (re-search-forward "<A.*\\?id@\\([^\"]+\\)\">[0-9]+</A>" nil t)
679         (replace-match "&lt;\\1&gt; " t)))
680     (widen)
681     (nnweb-remove-markup)))
682
683 (defun nnweb-altavista-search (search &optional part)
684   (url-insert-file-contents
685    (concat
686     (nnweb-definition 'address)
687     "?"
688     (nnweb-encode-www-form-urlencoded
689      `(("pg" . "aq")
690        ("what" . "news")
691        ,@(when part `(("stq" . ,(int-to-string (* part 30)))))
692        ("fmt" . "d")
693        ("q" . ,search)
694        ("r" . "")
695        ("d0" . "")
696        ("d1" . "")))))
697   (setq buffer-file-name nil)
698   t)
699
700 ;;;
701 ;;; Deja bought by google.com
702 ;;;
703
704 (defun nnweb-google-wash-article ()
705   (let ((case-fold-search t) url)
706     (goto-char (point-min))
707     (re-search-forward "^<pre>" nil t)
708     (narrow-to-region (point-min) (point))
709     (search-backward "<table " nil t 2)
710     (delete-region (point-min) (point))
711     (if (re-search-forward "Search Result [0-9]+" nil t)
712         (replace-match ""))
713     (if (re-search-forward "View complete thread ([0-9]+ articles?)" nil t)
714         (replace-match ""))
715     (goto-char (point-min))
716     (while (search-forward "<br>" nil t)
717       (replace-match "\n"))
718     (nnweb-remove-markup)
719     (goto-char (point-min))
720     (while (re-search-forward "^[ \t]*\n" nil t)
721       (replace-match ""))
722     (goto-char (point-max))
723     (insert "\n")
724     (widen)
725     (narrow-to-region (point) (point-max))
726     (search-forward "</pre>" nil t)
727     (delete-region (point) (point-max))
728     (nnweb-remove-markup)
729     (widen)))
730
731 (defun nnweb-google-parse-1 (&optional Message-ID)
732   (let ((i 0)
733         (case-fold-search t)
734         (active (cadr (assoc nnweb-group nnweb-group-alist)))
735         Subject Score Date Newsgroups From
736         map url)
737     (unless active
738       (push (list nnweb-group (setq active (cons 1 0))
739                   nnweb-type nnweb-search)
740             nnweb-group-alist))
741     ;; Go through all the article hits on this page.
742     (goto-char (point-min))
743     (while (re-search-forward
744             "a href=/groups\\(\\?[^ \">]*selm=[^ \">]*\\)" nil t)
745       (setq url
746             (concat (nnweb-definition 'address)
747                     (match-string 1)))
748       (narrow-to-region (search-forward ">" nil t)
749                         (search-forward "</a>" nil t))
750       (nnweb-remove-markup)
751       (nnweb-decode-entities)
752       (setq Subject (buffer-string))
753       (goto-char (point-max))
754       (widen)
755       (forward-line 2)
756       (when (looking-at "<br><font[^>]+>")
757         (goto-char (match-end 0)))
758       (if (not (looking-at "<a[^>]+>"))
759           (skip-chars-forward " \t")
760         (narrow-to-region (point)
761                           (search-forward "</a>" nil t))
762         (nnweb-remove-markup)
763         (nnweb-decode-entities)
764         (setq Newsgroups (buffer-string))
765         (goto-char (point-max))
766         (widen)
767         (skip-chars-forward "- \t"))
768       (when (looking-at
769              "\\([0-9]+[/ ][A-Za-z]+[/ ][0-9]+\\)[ \t]*by[ \t]*\\([^<]*\\) - <a")
770         (setq From (match-string 2)
771               Date (match-string 1)))
772       (forward-line 1)
773       (incf i)
774       (unless (nnweb-get-hashtb url)
775         (push
776          (list
777           (incf (cdr active))
778           (make-full-mail-header
779            (cdr active) (if Newsgroups
780                             (concat  "(" Newsgroups ") " Subject)
781                           Subject)
782            From Date Message-ID
783            nil 0 0 url))
784          map)
785         (nnweb-set-hashtb (cadar map) (car map))))
786     map))
787
788 (defun nnweb-google-reference (id)
789   (let ((map (nnweb-google-parse-1 id)) header)
790     (setq nnweb-articles
791           (nconc nnweb-articles map))
792     (when (setq header (cadar map))
793       (mm-with-unibyte-current-buffer
794         (nnweb-fetch-url (mail-header-xref header)))
795       (caar map))))
796
797 (defun nnweb-google-create-mapping ()
798   "Perform the search and create an number-to-url alist."
799   (save-excursion
800     (set-buffer nnweb-buffer)
801     (erase-buffer)
802     (when (funcall (nnweb-definition 'search) nnweb-search)
803         (let ((more t))
804           (while more
805             (setq nnweb-articles
806                   (nconc nnweb-articles (nnweb-google-parse-1)))
807             ;; FIXME: There is more.
808             (setq more nil))
809           ;; Return the articles in the right order.
810           (setq nnweb-articles
811                 (sort nnweb-articles 'car-less-than-car))))))
812
813 (defun nnweb-google-search (search)
814   (nnweb-insert
815    (concat
816     (nnweb-definition 'address)
817     "?"
818     (nnweb-encode-www-form-urlencoded
819      `(("q" . ,search)
820        ("num". "100")
821        ("hq" . "")
822        ("hl" . "")
823        ("lr" . "")
824        ("safe" . "off")
825        ("sites" . "groups")))))
826   t)
827
828 (defun nnweb-google-identity (url)
829   "Return an unique identifier based on URL."
830   (if (string-match "seld=\\([0-9]+\\)" url)
831       (match-string 1 url)
832     url))
833
834 ;;;
835 ;;; General web/w3 interface utility functions
836 ;;;
837
838 (defun nnweb-insert-html (parse)
839   "Insert HTML based on a w3 parse tree."
840   (if (stringp parse)
841       (insert (nnheader-string-as-multibyte parse))
842     (insert "<" (symbol-name (car parse)) " ")
843     (insert (mapconcat
844              (lambda (param)
845                (concat (symbol-name (car param)) "="
846                        (prin1-to-string
847                         (if (consp (cdr param))
848                             (cadr param)
849                           (cdr param)))))
850              (nth 1 parse)
851              " "))
852     (insert ">\n")
853     (mapcar 'nnweb-insert-html (nth 2 parse))
854     (insert "</" (symbol-name (car parse)) ">\n")))
855
856 (defun nnweb-encode-www-form-urlencoded (pairs)
857   "Return PAIRS encoded for forms."
858   (mapconcat
859    (function
860     (lambda (data)
861       (concat (w3-form-encode-xwfu (car data)) "="
862               (w3-form-encode-xwfu (cdr data)))))
863    pairs "&"))
864
865 (defun nnweb-fetch-form (url pairs)
866   "Fetch a form from URL with PAIRS as the data using the POST method."
867   (let ((url-request-data (nnweb-encode-www-form-urlencoded pairs))
868         (url-request-method "POST")
869         (url-request-extra-headers
870          '(("Content-type" . "application/x-www-form-urlencoded"))))
871     (url-insert-file-contents url)
872     (setq buffer-file-name nil))
873   t)
874
875 (defun nnweb-decode-entities ()
876   "Decode all HTML entities."
877   (goto-char (point-min))
878   (while (re-search-forward "&\\(#[0-9]+\\|[a-z]+\\);" nil t)
879     (let ((elem (if (eq (aref (match-string 1) 0) ?\#)
880                         (let ((c
881                                (string-to-number (substring
882                                                   (match-string 1) 1))))
883                           (if (mm-char-or-char-int-p c) c 32))
884                       (or (cdr (assq (intern (match-string 1))
885                                      w3-html-entities))
886                           ?#))))
887       (unless (stringp elem)
888         (setq elem (char-to-string elem)))
889       (replace-match elem t t))))
890
891 (defun nnweb-decode-entities-string (string)
892   (with-temp-buffer
893     (insert string)
894     (nnweb-decode-entities)
895     (buffer-substring (point-min) (point-max))))
896
897 (defun nnweb-remove-markup ()
898   "Remove all HTML markup, leaving just plain text."
899   (goto-char (point-min))
900   (while (search-forward "<!--" nil t)
901     (delete-region (match-beginning 0)
902                    (or (search-forward "-->" nil t)
903                        (point-max))))
904   (goto-char (point-min))
905   (while (re-search-forward "<[^>]+>" nil t)
906     (replace-match "" t t)))
907
908 (defun nnweb-insert (url &optional follow-refresh)
909   "Insert the contents from an URL in the current buffer.
910 If FOLLOW-REFRESH is non-nil, redirect refresh url in META."
911   (let ((name buffer-file-name))
912     (if follow-refresh
913         (save-restriction
914           (narrow-to-region (point) (point))
915           (url-insert-file-contents url)
916           (goto-char (point-min))
917           (when (re-search-forward
918                  "<meta[ \t\r\n]*http-equiv=\"Refresh\"[^>]*URL=\\([^\"]+\\)\"" nil t)
919             (let ((url (match-string 1)))
920               (delete-region (point-min) (point-max))
921               (nnweb-insert url t))))
922       (url-insert-file-contents url))
923     (setq buffer-file-name name)))
924
925 (defun nnweb-parse-find (type parse &optional maxdepth)
926   "Find the element of TYPE in PARSE."
927   (catch 'found
928     (nnweb-parse-find-1 type parse maxdepth)))
929
930 (defun nnweb-parse-find-1 (type contents maxdepth)
931   (when (or (null maxdepth)
932             (not (zerop maxdepth)))
933     (when (consp contents)
934       (when (eq (car contents) type)
935         (throw 'found contents))
936       (when (listp (cdr contents))
937         (dolist (element contents)
938           (when (consp element)
939             (nnweb-parse-find-1 type element
940                                 (and maxdepth (1- maxdepth)))))))))
941
942 (defun nnweb-parse-find-all (type parse)
943   "Find all elements of TYPE in PARSE."
944   (catch 'found
945     (nnweb-parse-find-all-1 type parse)))
946
947 (defun nnweb-parse-find-all-1 (type contents)
948   (let (result)
949     (when (consp contents)
950       (if (eq (car contents) type)
951           (push contents result)
952         (when (listp (cdr contents))
953           (dolist (element contents)
954             (when (consp element)
955               (setq result
956                     (nconc result (nnweb-parse-find-all-1 type element))))))))
957     result))
958
959 (defvar nnweb-text)
960 (defun nnweb-text (parse)
961   "Return a list of text contents in PARSE."
962   (let ((nnweb-text nil))
963     (nnweb-text-1 parse)
964     (nreverse nnweb-text)))
965
966 (defun nnweb-text-1 (contents)
967   (dolist (element contents)
968     (if (stringp element)
969         (push element nnweb-text)
970       (when (and (consp element)
971                  (listp (cdr element)))
972         (nnweb-text-1 element)))))
973
974 (defun nnweb-replace-in-string (string match newtext)
975   (while (string-match match string)
976     (setq string (replace-match newtext t t string)))
977   string)
978
979 (provide 'nnweb)
980
981 ;;; nnweb.el ends here