b6355b8f126140ae65ede94b1001d23308aeb233
[banana.git] / banana / spool.inc.php
1 <?php
2 /********************************************************************************
3 * include/spool.inc.php : spool subroutines
4 * -----------------------
5 *
6 * This file is part of the banana distribution
7 * Copyright: See COPYING files that comes with this distribution
8 ********************************************************************************/
9
10 require_once dirname(__FILE__) . '/banana.inc.php';
11 require_once dirname(__FILE__) . '/tree.inc.php';
12
13 define('BANANA_SPOOL_VERSION', '0.5.14');
14
15 /** Class spoolhead
16 * class used in thread overviews
17 */
18 class BananaSpoolHead
19 {
20 public $id;
21 public $msgid;
22
23 /** date (timestamp) */
24 public $date;
25 /** subject */
26 public $subject;
27 /** author */
28 public $from;
29 public $name;
30 public $color;
31 /** reference of parent */
32 public $parent = null;
33 /** array of children */
34 public $children = Array();
35 /** true if post is read */
36 public $isread;
37 /** number of posts deeper in this branch of tree */
38 public $desc;
39 /** same as desc, but counts only unread posts */
40 public $descunread;
41 /** last time the number of children has been updated */
42 public $time = 0;
43
44 /** storage data */
45 public $storage = array();
46
47 /** constructor
48 * @param $_date INTEGER timestamp of post
49 * @param $_subject STRING subject of post
50 * @param $_from STRING author of post
51 * @param $_desc INTEGER desc value (1 for a new post)
52 * @param $_read BOOLEAN true if read
53 * @param $_descunread INTEGER descunread value (0 for a new post)
54 */
55 public function __construct($id, array &$message)
56 {
57 $this->id = $id;
58 $this->msgid = @$message['message-id'];
59 $this->date = $message['date'];
60 $this->subject = @$message['subject'];
61 $this->from = $message['from'];
62 $this->color = sprintf('#%06x', abs(crc32($this->from) % 0xffffff));
63 $this->desc = 1;
64 $this->isread = true;
65 $this->descunread = 0;
66 if (preg_match("/^([^ ]+@[^ ]+) \((.*)\)$/", $this->from, $regs)) {
67 $this->name = $regs[2];
68 }
69 if (preg_match("/^\"?([^<>\"]+)\"? +<(.+@.+)>$/", $this->from, $regs)) {
70 $this->name = preg_replace("/^'(.*)'$/", '\1', $regs[1]);
71 $this->name = stripslashes($this->name);
72 }
73 if ($this->name) {
74 $this->name = preg_replace("/\\\(\(|\))/","\\1", $this->name);
75 } else if (preg_match("/([^< ]+)@([^> ]+)/", $this->from, $regs)) {
76 $this->name = $regs[1];
77 } else {
78 $this->name = 'Anonymous';
79 }
80 }
81 }
82
83
84 class BananaSpool
85 {
86 private $version;
87 private $mode;
88
89 /** group name */
90 public $group;
91 /** spool */
92 public $overview = array();
93 /** array msgid => msgnum */
94 public $ids = array();
95 /** thread starts */
96 public $roots = array();
97
98 /** protocole specific data */
99 public $storage = array();
100
101 private $unreadnb = 0;
102
103 /** constructor
104 * @param $_group STRING group name
105 * @param $_display INTEGER 1 => all posts, 2 => only threads with new posts
106 * @param $_since INTEGER time stamp (used for read/unread)
107 */
108 protected function __construct($group)
109 {
110 $this->version = BANANA_SPOOL_VERSION;
111 $this->mode = Banana::SPOOL_ALL;
112 $this->group = $group;
113 }
114
115 public static function &getSpool($group, $since = 0, $clean = false)
116 {
117 if (!is_null(Banana::$spool) && Banana::$spool->group == $group) {
118 $spool =& Banana::$spool;
119 } else {
120 $spool =& BananaSpool::readFromFile($group);
121 }
122 if (is_null($spool)) {
123 $spool = new BananaSpool($group);
124 }
125 Banana::$spool =& $spool;
126 $spool->build();
127 if ($clean) {
128 $spool->markAllAsRead();
129 }
130 $spool->updateUnread($since);
131 return $spool;
132 }
133
134 public static function getPath($file = null)
135 {
136 $path = Banana::$spool_root . '/' . Banana::$protocole->name() . '/' . Banana::$protocole->filename();
137 if (!is_dir($path)) {
138 if (file_exists($path)) {
139 @unlink($path);
140 }
141 mkdir($path, 0777, true);
142 }
143 return $path . '/' . $file;
144 }
145
146 private static function spoolFilename()
147 {
148 return BananaSpool::getPath('spool');
149 }
150
151 private static function &readFromFile($group)
152 {
153 $spool = null;
154 $file = BananaSpool::spoolFilename();
155 if (!file_exists($file)) {
156 return $spool;
157 }
158 $spool = unserialize(file_get_contents($file));
159 if ($spool->version != BANANA_SPOOL_VERSION || $spool->mode != Banana::SPOOL_ALL) {
160 $spool = null;
161 return $spool;
162 }
163 $spool->markAllAsRead();
164 return $spool;
165 }
166
167 private function compare(&$a, &$b)
168 {
169 return ($b->date - $a->date);
170 }
171
172 private function saveToFile()
173 {
174 $file = BananaSpool::spoolFilename();
175
176 $this->roots = Array();
177 foreach($this->overview as &$msg) {
178 if (is_null($msg->parent)) {
179 $this->roots[] =& $msg;
180 }
181 }
182 usort($this->roots, array($this, 'compare'));
183
184 if ($this->mode == Banana::SPOOL_ALL) {
185 file_put_contents($file, serialize($this));
186 }
187 }
188
189 private function build()
190 {
191 $threshold = 0;
192
193 // Compute the range of indexes
194 list($msgnum, $first, $last) = Banana::$protocole->getIndexes();
195 if ($last < $first) {
196 $threshold = $first + $msgnum - $last;
197 $threshold = (int)(log($threshold)/log(2));
198 $threshold = (2 ^ ($threshold + 1)) - 1;
199 }
200 if (Banana::$spool_max && Banana::$spool_max < $msgnum) {
201 $first = $last - Banana::$spool_max;
202 if ($first < 0) {
203 $first += $threshold;
204 }
205 }
206 $clean = $this->clean($first, $last, $msgnum);
207 $update = $this->update($first, $last, $msgnum);
208
209 if ($clean || $update) {
210 $this->saveToFile();
211 }
212 }
213
214 private function clean(&$first, &$last, $msgnum)
215 {
216 $do_save = false;
217 if (!empty($this->overview)) {
218 $mids = array_keys($this->overview);
219 foreach ($mids as $id) {
220 if (($first <= $last && ($id < $first || $id > $last))
221 || ($first > $last && $id < $first && $id > $last)) {
222 $this->delid($id, false);
223 $do_save = true;
224 }
225 }
226 if (!empty($this->overview)) {
227 $first = max(array_keys($this->overview))+1;
228 }
229 }
230 return $do_save;
231 }
232
233 private function update(&$first, &$last, $msgnum)
234 {
235 if ($first > $last || !$msgnum) {
236 return false;
237 }
238
239 $messages =& Banana::$protocole->getMessageHeaders($first, $last,
240 array('Date', 'Subject', 'From', 'Message-ID', 'References', 'In-Reply-To'));
241
242 // Build all the new Spool Heads
243 $time = time();
244 foreach ($messages as $id=>&$message) {
245 if (!isset($this->overview[$id])) {
246 $this->overview[$id] = new BananaSpoolHead($id, $message);
247 $head =& $this->overview[$id];
248 $this->ids[$head->msgid] =& $head;
249 $head->time = $time;
250 }
251 }
252
253 // Build tree
254 $null = null;
255 foreach ($messages as $id=>&$message) {
256 $msg =& $this->overview[$id];
257 $parents =& $this->getReferences($message);
258 while (!empty($parents) && ($msg->parent === $msg || is_null($msg->parent))) {
259 @$msg->parent =& array_pop($parents);
260 }
261
262 if (!is_null($msg->parent)) {
263 $parent =& $msg->parent;
264 $parent->children[] =& $msg;
265 while (!is_null($parent)) {
266 $parent->desc += $msg->desc;
267 $parent->time = $time;
268 $prev =& $parent;
269 if ($parent !== $parent->parent) {
270 $parent =& $parent->parent;
271 } else {
272 $parent =& $null;
273 }
274 }
275 }
276 }
277 Banana::$protocole->updateSpool($messages);
278 return true;
279 }
280
281 public function updateUnread($since)
282 {
283 if (empty($since)) {
284 return;
285 }
286
287 $newpostsids = Banana::$protocole->getNewIndexes($since);
288
289 if (empty($newpostsids)) {
290 return;
291 }
292
293 $newpostsids = array_intersect($newpostsids, array_keys($this->ids));
294 foreach ($newpostsids as $mid) {
295 $overview =& $this->ids[$mid];
296 if ($overview->isread) {
297 $overview->isread = false;
298 while (!is_null($overview)) {
299 $overview->descunread++;
300 $overview =& $overview->parent;
301 }
302 }
303 }
304 $this->unreadnb += count($newpostsids);
305 }
306
307 public function setMode($mode)
308 {
309 $this->mode = $mode;
310 switch ($mode) {
311 case Banana::SPOOL_UNREAD:
312 $num = max(array_keys($this->overview));
313 if ($this->overview[$num]->isread) {
314 break;
315 }
316 foreach ($this->roots as &$root) {
317 if ($root->descunread == 0) {
318 $this->killdesc($root->id);
319 }
320 }
321 break;
322 }
323 }
324
325 /** Fetch list of references
326 */
327 public function &getReferences(array &$refs)
328 {
329 $references = array();
330 if (isset($refs['references'])) {
331 $text = preg_split('/\s/', str_replace('><', '> <', $refs['references']));
332 foreach ($text as $id=>&$value) {
333 if (isset($this->ids[$value])) {
334 $references[] =& $this->ids[$value];
335 }
336 }
337 } elseif (isset($refs['in-reply-to']) && isset($this->ids[$refs['in-reply-to']])) {
338 $references[] =& $this->ids[$refs['in-reply-to']];
339 }
340 return $references;
341 }
342
343 /** Get the tree associated to a given id
344 */
345 public function &getTree($id)
346 {
347 return BananaTree::build($id)->data;
348 }
349
350 /** Mark the given id as read
351 * @param id MSGNUM of post
352 */
353 public function markAsRead($id)
354 {
355 if (!$this->overview[$id]->isread) {
356 $this->overview[$id]->isread = true;
357 $this->unreadnb--;
358 while (isset($id)) {
359 $this->overview[$id]->descunread--;
360 $id = $this->overview[$id]->parent;
361 }
362 }
363 }
364
365 /** Mark all unread messages as read
366 */
367 public function markAllAsRead(array &$array = null)
368 {
369 if (!$this->unreadnb) {
370 return;
371 }
372 if (is_null($array) && !empty($this->roots)) {
373 $array =& $this->roots;
374 } elseif (is_null($array)) {
375 return;
376 }
377 foreach ($array as &$msg) {
378 if (!$msg->isread) {
379 $this->markAsRead($msg->id);
380 if (!$this->unreadnb) {
381 return;
382 }
383 }
384 if ($msg->descunread) {
385 $this->markAllAsRead($msg->children);
386 }
387 }
388 }
389
390 /** kill post and childrens
391 * @param $_id MSGNUM of post
392 */
393 private function killdesc($_id)
394 {
395 $overview =& $this->overview[$_id];
396 $children =& $overview->children;
397 if (sizeof($children)) {
398 foreach ($children as &$c) {
399 $this->killdesc($c->id);
400 }
401 }
402 unset($this->overview[$_id]);
403 foreach ($this->roots as $k=>&$root) {
404 if ($root === $overview) {
405 unset($this->roots[$k]);
406 break;
407 }
408 }
409 unset($this->ids[$overview->msgid]);
410 $overview = null;
411 }
412
413 /** delete a post from overview
414 * @param $_id MSGNUM of post
415 */
416 public function delid($_id, $write = true)
417 {
418 if (!isset($this->overview[$_id])) {
419 return;
420 }
421
422 $overview =& $this->overview[$_id];
423 // Be sure it is not counted as unread
424 if (!$overview->isread) {
425 $this->markAsRead($_id);
426 }
427
428 $parent =& $overview->parent;
429
430 // Remove from the message tree
431 if (!is_null($parent)) {
432 foreach ($parent->children as $key=>&$child) {
433 if ($child === $overview) {
434 unset($parent->children[$key]);
435 break;
436 }
437 }
438 if (sizeof($overview->children)) {
439 $parent->children = array_merge($parent->children, $overview->children);
440 foreach ($overview->children as &$child) {
441 $child->parent =& $parent;
442 }
443 }
444 $time = time();
445 while (!is_null($parent)) {
446 $parent->desc--;
447 $parent->time = $time;
448 $parent =& $parent->parent;
449 }
450 }
451
452 // Remove all refenrences and assign null to the object
453 unset($this->ids[$overview->msgid]);
454 unset($this->overview[$_id]);
455 BananaTree::kill($_id);
456 foreach ($this->roots as $k=>&$root) {
457 if ($root === $overview) {
458 unset($this->roots[$k]);
459 break;
460 }
461 }
462 $overview = null;
463
464 if ($write) {
465 $this->saveToFile();
466 }
467 }
468
469 public function formatDate(BananaSpoolHead &$head)
470 {
471 $stamp = $head->date;
472 $today = intval(time() / (24*3600));
473 $dday = intval($stamp / (24*3600));
474
475 if ($today == $dday) {
476 $format = "%H:%M";
477 } elseif ($today == 1 + $dday) {
478 $format = _b_('hier')." %H:%M";
479 } elseif ($today < 7 + $dday) {
480 $format = '%a %H:%M';
481 } elseif ($today < 90 + $dday) {
482 $format = '%a %e %b';
483 } else {
484 $format = '%a %e %b %Y';
485 }
486 return strftime($format, $stamp);
487 }
488
489 public function formatSubject(BananaSpoolHead &$head)
490 {
491 $subject = $popup = $head->subject;
492 $popup = $subject;
493 if (function_exists('hook_formatDisplayHeader')) {
494 list($subject, $link) = hook_formatDisplayHeader('subject', $subject, true);
495 } else {
496 $subject = banana_catchFormats(banana_entities(stripslashes($subject)));
497 $link = null;
498 }
499 if (empty($subject)) {
500 $subject = _b_('(pas de sujet)');
501 }
502 if ($head->id != Banana::$artid) {
503 $subject = Banana::$page->makeLink(Array('group' => $this->group, 'artid' => $head->id,
504 'text' => $subject, 'popup' => $popup));
505 }
506 return $subject . $link;
507 }
508
509 public function formatFrom(BananaSpoolHead &$head)
510 {
511 return BananaMessage::formatFrom($head->from);
512 }
513
514 public function start()
515 {
516 if (Banana::$first) {
517 return Banana::$first;
518 } else {
519 $first = array_search(Banana::$artid, $this->roots);
520 return max(0, $first - Banana::$spool_tbefore);
521 }
522 }
523
524 public function context()
525 {
526 return Banana::$first ? Banana::$spool_tmax : Banana::$spool_tcontext;
527 }
528
529
530 /** computes linear post index
531 * @param $_id INTEGER MSGNUM of post
532 * @return INTEGER linear index of post
533 */
534 public function getNdX($_id)
535 {
536 $ndx = 1;
537 $id_cur = $_id;
538 while (true) {
539 $id_parent = $this->overview[$id_cur]->parent;
540 if (is_null($id_parent)) break;
541 $pos = array_search($id_cur, $this->overview[$id_parent]->children);
542
543 for ($i = 0; $i < $pos ; $i++) {
544 $ndx += $this->overview[$this->overview[$id_parent]->children[$i]]->desc;
545 }
546 $ndx++; //noeud père
547
548 $id_cur = $id_parent;
549 }
550
551 foreach ($this->roots as $i) {
552 if ($i==$id_cur) {
553 break;
554 }
555 $ndx += $this->overview[$i]->desc;
556 }
557 return $ndx;
558 }
559
560 /** Return root message of the given thread
561 * @param id INTEGER id of a message
562 */
563 public function &root($id)
564 {
565 $parent =& $this->overview[$id];
566 while (!is_null($parent->parent)) {
567 $parent =& $parent->parent;
568 }
569 return $parent;
570 }
571
572 /** Return the last post id with the given subject
573 * @param subject
574 */
575 public function getPostId($subject)
576 {
577 $subject = trim($subject);
578 $id = max(array_keys($this->overview));
579 while (isset($this->overview[$id])) {
580 $test = $this->overview[$id]->subject;
581 if (function_exists('hook_formatDisplayHeader')) {
582 $val = hook_formatDisplayHeader('subject', $test, true);
583 if (is_array($val)) {
584 $test = banana_html_entity_decode($val[0]);
585 } else {
586 $test = banana_html_entity_decode($val);
587 }
588 }
589 $test = trim($test);
590 if ($test == $subject) {
591 return $id;
592 }
593 $id--;
594 }
595 return -1;
596 }
597
598 /** Returns previous thread root index
599 * @param id INTEGER message number
600 */
601 public function prevThread($id)
602 {
603 $root =& $this->root($id);
604 $last = null;
605 foreach ($this->roots as &$i) {
606 if ($i === $root) {
607 return $last;
608 }
609 $last = $i->id;
610 }
611 return $last;
612 }
613
614 /** Returns next thread root index
615 * @param id INTEGER message number
616 */
617 public function nextThread($id)
618 {
619 $root =& $this->root($id);
620 $ok = false;
621 foreach ($this->roots as &$i) {
622 if ($ok) {
623 return $i->id;
624 }
625 if ($i === $root) {
626 $ok = true;
627 }
628 }
629 return null;
630 }
631
632 /** Return prev post in the thread
633 * @param id INTEGER message number
634 */
635 public function prevPost($id)
636 {
637 $parent =& $this->overview[$id]->parent;
638 if (is_null($parent)) {
639 return null;
640 }
641 $last = $parent->id;
642 foreach ($parent->children as &$child) {
643 if ($child->id == $id) {
644 return $last;
645 }
646 $last = $child->id;
647 }
648 return null;
649 }
650
651 /** Return next post in the thread
652 * @param id INTEGER message number
653 */
654 public function nextPost($id)
655 {
656 $cur =& $this->overview[$id];
657 if (count($cur->children) != 0) {
658 return $cur->children[0]->id;
659 }
660
661 $parent =& $cur;
662 while (true) {
663 $parent =& $cur->parent;
664 if (is_null($parent)) {
665 return null;
666 }
667 $ok = false;
668 foreach ($parent->children as &$child) {
669 if ($ok) {
670 return $child->id;
671 }
672 if ($child === $cur) {
673 $ok = true;
674 }
675 }
676 $cur =& $parent;
677 }
678 return null;
679 }
680
681 /** Look for an unread message in the thread rooted by the message
682 * @param id INTEGER message number
683 */
684 private function _nextUnread(BananaSpoolHead &$cur)
685 {
686 if (!$cur->isread) {
687 return $cur->id;
688 }
689 foreach ($cur->children as &$child) {
690 $unread = $this->_nextUnread($child);
691 if (!is_null($unread)) {
692 return $unread;
693 }
694 }
695 return null;
696 }
697
698 /** Find next unread message
699 * @param id INTEGER message number
700 */
701 public function nextUnread($id = null)
702 {
703 if (!$this->unreadnb) {
704 return null;
705 }
706
707 if (!is_null($id)) {
708 // Look in message children
709 foreach ($this->overview[$id]->children as &$child) {
710 $next = $this->_nextUnread($child);
711 if (!is_null($next)) {
712 return $next;
713 }
714 }
715 }
716
717 // Look in current thread
718 if (is_null($id)) {
719 $cur = null;
720 } else {
721 $cur =& $this->overview[$id];
722 }
723 do {
724 if (is_null($cur)) {
725 $parent =& $cur;
726 $ok = true;
727 } else {
728 $parent =& $cur->parent;
729 $ok = false;
730 }
731 if (!is_null($parent)) {
732 $array =& $parent->children;
733 } else {
734 $array =& $this->roots;
735 }
736 foreach ($array as &$child) {
737 if ($ok) {
738 $next = $this->_nextUnread($child);
739 if (!is_null($next)) {
740 return $next;
741 }
742 }
743 if ($child === $cur) {
744 $ok = true;
745 }
746 }
747 $cur =& $parent;
748 } while(!is_null($cur));
749 return null;
750 }
751 }
752 // vim:set et sw=4 sts=4 ts=4 enc=utf-8:
753 ?>