]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
Merge branch '0.8.x' into group-rss-empty
[quix0rs-gnu-social.git] / classes / Notice.php
1 <?php
2 /*
3  * Laconica - a distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, Control Yourself, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 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 Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.     If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('LACONICA')) { exit(1); }
21
22 /**
23  * Table Definition for notice
24  */
25 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
26
27 /* We keep the first three 20-notice pages, plus one for pagination check,
28  * in the memcached cache. */
29
30 define('NOTICE_CACHE_WINDOW', 61);
31
32 define('NOTICE_LOCAL_PUBLIC', 1);
33 define('NOTICE_REMOTE_OMB', 0);
34 define('NOTICE_LOCAL_NONPUBLIC', -1);
35 define('NOTICE_GATEWAY', -2);
36
37 class Notice extends Memcached_DataObject
38 {
39     ###START_AUTOCODE
40     /* the code below is auto generated do not remove the above tag */
41
42     public $__table = 'notice';                          // table name
43     public $id;                              // int(4)  primary_key not_null
44     public $profile_id;                      // int(4)   not_null
45     public $uri;                             // varchar(255)  unique_key
46     public $content;                         // varchar(140)
47     public $rendered;                        // text()
48     public $url;                             // varchar(255)
49     public $created;                         // datetime()   not_null
50     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
51     public $reply_to;                        // int(4)
52     public $is_local;                        // tinyint(1)
53     public $source;                          // varchar(32)
54     public $conversation;                    // int(4)
55
56     /* Static get */
57     function staticGet($k,$v=NULL) {
58         return Memcached_DataObject::staticGet('Notice',$k,$v);
59     }
60
61     /* the code above is auto generated do not remove the tag below */
62     ###END_AUTOCODE
63
64     function getProfile()
65     {
66         return Profile::staticGet('id', $this->profile_id);
67     }
68
69     function delete()
70     {
71         $this->blowCaches(true);
72         $this->blowFavesCache(true);
73         $this->blowSubsCache(true);
74
75         $this->query('BEGIN');
76         //Null any notices that are replies to this notice
77         $this->query(sprintf("UPDATE notice set reply_to = null WHERE reply_to = %d", $this->id));
78         $related = array('Reply',
79                          'Fave',
80                          'Notice_tag',
81                          'Group_inbox',
82                          'Queue_item');
83         if (common_config('inboxes', 'enabled')) {
84             $related[] = 'Notice_inbox';
85         }
86         foreach ($related as $cls) {
87             $inst = new $cls();
88             $inst->notice_id = $this->id;
89             $inst->delete();
90         }
91         $result = parent::delete();
92         $this->query('COMMIT');
93     }
94
95     function saveTags()
96     {
97         /* extract all #hastags */
98         $count = preg_match_all('/(?:^|\s)#([A-Za-z0-9_\-\.]{1,64})/', strtolower($this->content), $match);
99         if (!$count) {
100             return true;
101         }
102
103         /* Add them to the database */
104         foreach(array_unique($match[1]) as $hashtag) {
105             /* elide characters we don't want in the tag */
106             $this->saveTag($hashtag);
107         }
108         return true;
109     }
110
111     function saveTag($hashtag)
112     {
113         $hashtag = common_canonical_tag($hashtag);
114
115         $tag = new Notice_tag();
116         $tag->notice_id = $this->id;
117         $tag->tag = $hashtag;
118         $tag->created = $this->created;
119         $id = $tag->insert();
120
121         if (!$id) {
122             throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
123                                               $last_error->message));
124             return;
125         }
126     }
127
128     static function saveNew($profile_id, $content, $source=null,
129                             $is_local=1, $reply_to=null, $uri=null, $created=null) {
130
131         $profile = Profile::staticGet($profile_id);
132
133         $final = common_shorten_links($content);
134
135         if (mb_strlen($final) > 140) {
136             common_log(LOG_INFO, 'Rejecting notice that is too long.');
137             return _('Problem saving notice. Too long.');
138         }
139
140         if (!$profile) {
141             common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
142             return _('Problem saving notice. Unknown user.');
143         }
144
145         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
146             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
147             return _('Too many notices too fast; take a breather and post again in a few minutes.');
148         }
149
150         if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
151             common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
152                         return _('Too many duplicate messages too quickly; take a breather and post again in a few minutes.');
153         }
154
155                 $banned = common_config('profile', 'banned');
156
157         if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
158             common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
159             return _('You are banned from posting notices on this site.');
160         }
161
162         $notice = new Notice();
163         $notice->profile_id = $profile_id;
164
165         $blacklist = common_config('public', 'blacklist');
166         $autosource = common_config('public', 'autosource');
167
168         # Blacklisted are non-false, but not 1, either
169
170         if (($blacklist && in_array($profile_id, $blacklist)) ||
171             ($source && $autosource && in_array($source, $autosource))) {
172             $notice->is_local = -1;
173         } else {
174             $notice->is_local = $is_local;
175         }
176
177                 $notice->query('BEGIN');
178
179                 $notice->reply_to = $reply_to;
180         if (!empty($created)) {
181             $notice->created = $created;
182         } else {
183             $notice->created = common_sql_now();
184         }
185                 $notice->content = $final;
186                 $notice->rendered = common_render_content($final, $notice);
187                 $notice->source = $source;
188                 $notice->uri = $uri;
189
190         if (!empty($reply_to)) {
191             $reply_notice = Notice::staticGet('id', $reply_to);
192             if (!empty($reply_notice)) {
193                 $notice->reply_to = $reply_to;
194                 $notice->conversation = $reply_notice->conversation;
195             }
196         }
197
198         if (Event::handle('StartNoticeSave', array(&$notice))) {
199
200             $id = $notice->insert();
201
202             if (!$id) {
203                 common_log_db_error($notice, 'INSERT', __FILE__);
204                 return _('Problem saving notice.');
205             }
206
207             # Update the URI after the notice is in the database
208             if (!$uri) {
209                 $orig = clone($notice);
210                 $notice->uri = common_notice_uri($notice);
211
212                 if (!$notice->update($orig)) {
213                     common_log_db_error($notice, 'UPDATE', __FILE__);
214                     return _('Problem saving notice.');
215                 }
216             }
217
218             # XXX: do we need to change this for remote users?
219
220             $notice->saveReplies();
221             $notice->saveTags();
222
223             $notice->addToInboxes();
224             $notice->saveGroups();
225             $notice->saveUrls();
226             $orig2 = clone($notice);
227                 $notice->rendered = common_render_content($final, $notice);
228             if (!$notice->update($orig2)) {
229                 common_log_db_error($notice, 'UPDATE', __FILE__);
230                 return _('Problem saving notice.');
231             }
232
233             $notice->query('COMMIT');
234
235             Event::handle('EndNoticeSave', array($notice));
236         }
237
238         # Clear the cache for subscribed users, so they'll update at next request
239         # XXX: someone clever could prepend instead of clearing the cache
240
241         $notice->blowCaches();
242
243         return $notice;
244     }
245
246     /** save all urls in the notice to the db
247      *
248      * follow redirects and save all available file information
249      * (mimetype, date, size, oembed, etc.)
250      *
251      * @return void
252      */
253     function saveUrls() {
254         common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
255     }
256
257     function saveUrl($data) {
258         list($url, $notice_id) = $data;
259         File::processNew($url, $notice_id);
260     }
261
262     static function checkDupes($profile_id, $content) {
263         $profile = Profile::staticGet($profile_id);
264         if (!$profile) {
265             return false;
266         }
267         $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
268         if ($notice) {
269             $last = 0;
270             while ($notice->fetch()) {
271                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
272                     return true;
273                 } else if ($notice->content == $content) {
274                     return false;
275                 }
276             }
277         }
278         # If we get here, oldest item in cache window is not
279         # old enough for dupe limit; do direct check against DB
280         $notice = new Notice();
281         $notice->profile_id = $profile_id;
282         $notice->content = $content;
283         if (common_config('db','type') == 'pgsql')
284             $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
285         else
286             $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
287
288         $cnt = $notice->count();
289         return ($cnt == 0);
290     }
291
292     static function checkEditThrottle($profile_id) {
293         $profile = Profile::staticGet($profile_id);
294         if (!$profile) {
295             return false;
296         }
297         # Get the Nth notice
298         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
299         if ($notice && $notice->fetch()) {
300             # If the Nth notice was posted less than timespan seconds ago
301             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
302                 # Then we throttle
303                 return false;
304             }
305         }
306         # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
307         return true;
308     }
309
310     function getUploadedAttachment() {
311         $post = clone $this;
312         $query = 'select file.url as up, file.id as i from file join file_to_post on file.id = file_id where post_id=' . $post->escape($post->id) . ' and url like "%/notice/%/file"';
313         $post->query($query);
314         $post->fetch();
315         if (empty($post->up) || empty($post->i)) {
316             $ret = false;
317         } else {
318             $ret = array($post->up, $post->i);
319         }
320         $post->free();
321         return $ret;
322     }
323
324     function hasAttachments() {
325         $post = clone $this;
326         $query = "select count(file_id) as n_attachments from file join file_to_post on (file_id = file.id) join notice on (post_id = notice.id) where post_id = " . $post->escape($post->id);
327         $post->query($query);
328         $post->fetch();
329         $n_attachments = intval($post->n_attachments);
330         $post->free();
331         return $n_attachments;
332     }
333
334     function attachments() {
335         // XXX: cache this
336         $att = array();
337         $f2p = new File_to_post;
338         $f2p->post_id = $this->id;
339         if ($f2p->find()) {
340             while ($f2p->fetch()) {
341                 $f = File::staticGet($f2p->file_id);
342                 $att[] = clone($f);
343             }
344         }
345         return $att;
346     }
347
348     function blowCaches($blowLast=false)
349     {
350         $this->blowSubsCache($blowLast);
351         $this->blowNoticeCache($blowLast);
352         $this->blowRepliesCache($blowLast);
353         $this->blowPublicCache($blowLast);
354         $this->blowTagCache($blowLast);
355         $this->blowGroupCache($blowLast);
356         $this->blowConversationCache($blowLast);
357     }
358
359     function blowConversationCache($blowLast=false)
360     {
361         $cache = common_memcache();
362         if ($cache) {
363             $ck = common_cache_key('notice:conversation_ids:'.$this->conversation);
364             $cache->delete($ck);
365             if ($blowLast) {
366                 $cache->delete($ck.';last');
367             }
368         }
369     }
370
371     function blowGroupCache($blowLast=false)
372     {
373         $cache = common_memcache();
374         if ($cache) {
375             $group_inbox = new Group_inbox();
376             $group_inbox->notice_id = $this->id;
377             if ($group_inbox->find()) {
378                 while ($group_inbox->fetch()) {
379                     $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
380                     if ($blowLast) {
381                         $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
382                     }
383                     $member = new Group_member();
384                     $member->group_id = $group_inbox->group_id;
385                     if ($member->find()) {
386                         while ($member->fetch()) {
387                             $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
388                             if ($blowLast) {
389                                 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
390                             }
391                         }
392                     }
393                 }
394             }
395             $group_inbox->free();
396             unset($group_inbox);
397         }
398     }
399
400     function blowTagCache($blowLast=false)
401     {
402         $cache = common_memcache();
403         if ($cache) {
404             $tag = new Notice_tag();
405             $tag->notice_id = $this->id;
406             if ($tag->find()) {
407                 while ($tag->fetch()) {
408                     $tag->blowCache($blowLast);
409                     $ck = 'profile:notice_ids_tagged:' . $this->profile_id . ':' . $tag->tag;
410
411                     $cache->delete($ck);
412                     if ($blowLast) {
413                         $cache->delete($ck . ';last');
414                     }
415                 }
416             }
417             $tag->free();
418             unset($tag);
419         }
420     }
421
422     function blowSubsCache($blowLast=false)
423     {
424         $cache = common_memcache();
425         if ($cache) {
426             $user = new User();
427
428             $UT = common_config('db','type')=='pgsql'?'"user"':'user';
429             $user->query('SELECT id ' .
430
431                          "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
432                          'WHERE subscription.subscribed = ' . $this->profile_id);
433
434             while ($user->fetch()) {
435                 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
436                 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id));
437                 if ($blowLast) {
438                     $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
439                     $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id.';last'));
440                 }
441             }
442             $user->free();
443             unset($user);
444         }
445     }
446
447     function blowNoticeCache($blowLast=false)
448     {
449         if ($this->is_local) {
450             $cache = common_memcache();
451             if (!empty($cache)) {
452                 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
453                 if ($blowLast) {
454                     $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
455                 }
456             }
457         }
458     }
459
460     function blowRepliesCache($blowLast=false)
461     {
462         $cache = common_memcache();
463         if ($cache) {
464             $reply = new Reply();
465             $reply->notice_id = $this->id;
466             if ($reply->find()) {
467                 while ($reply->fetch()) {
468                     $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
469                     if ($blowLast) {
470                         $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
471                     }
472                 }
473             }
474             $reply->free();
475             unset($reply);
476         }
477     }
478
479     function blowPublicCache($blowLast=false)
480     {
481         if ($this->is_local == 1) {
482             $cache = common_memcache();
483             if ($cache) {
484                 $cache->delete(common_cache_key('public'));
485                 if ($blowLast) {
486                     $cache->delete(common_cache_key('public').';last');
487                 }
488             }
489         }
490     }
491
492     function blowFavesCache($blowLast=false)
493     {
494         $cache = common_memcache();
495         if ($cache) {
496             $fave = new Fave();
497             $fave->notice_id = $this->id;
498             if ($fave->find()) {
499                 while ($fave->fetch()) {
500                     $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
501                     $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id));
502                     if ($blowLast) {
503                         $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
504                         $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id.';last'));
505                     }
506                 }
507             }
508             $fave->free();
509             unset($fave);
510         }
511     }
512
513     # XXX: too many args; we need to move to named params or even a separate
514     # class for notice streams
515
516     static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $order=null, $since=null) {
517
518         if (common_config('memcached', 'enabled')) {
519
520             # Skip the cache if this is a since, since_id or max_id qry
521             if ($since_id > 0 || $max_id > 0 || $since) {
522                 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
523             } else {
524                 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
525             }
526         }
527
528         return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
529     }
530
531     static function getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since) {
532
533         $needAnd = false;
534         $needWhere = true;
535
536         if (preg_match('/\bWHERE\b/i', $qry)) {
537             $needWhere = false;
538             $needAnd = true;
539         }
540
541         if ($since_id > 0) {
542
543             if ($needWhere) {
544                 $qry .= ' WHERE ';
545                 $needWhere = false;
546             } else {
547                 $qry .= ' AND ';
548             }
549
550             $qry .= ' notice.id > ' . $since_id;
551         }
552
553         if ($max_id > 0) {
554
555             if ($needWhere) {
556                 $qry .= ' WHERE ';
557                 $needWhere = false;
558             } else {
559                 $qry .= ' AND ';
560             }
561
562             $qry .= ' notice.id <= ' . $max_id;
563         }
564
565         if ($since) {
566
567             if ($needWhere) {
568                 $qry .= ' WHERE ';
569                 $needWhere = false;
570             } else {
571                 $qry .= ' AND ';
572             }
573
574             $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
575         }
576
577         # Allow ORDER override
578
579         if ($order) {
580             $qry .= $order;
581         } else {
582             $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
583         }
584
585         if (common_config('db','type') == 'pgsql') {
586             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
587         } else {
588             $qry .= ' LIMIT ' . $offset . ', ' . $limit;
589         }
590
591         $notice = new Notice();
592
593         $notice->query($qry);
594
595         return $notice;
596     }
597
598     # XXX: this is pretty long and should probably be broken up into
599     # some helper functions
600
601     static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
602
603         # If outside our cache window, just go to the DB
604
605         if ($offset + $limit > NOTICE_CACHE_WINDOW) {
606             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
607         }
608
609         # Get the cache; if we can't, just go to the DB
610
611         $cache = common_memcache();
612
613         if (!$cache) {
614             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
615         }
616
617         # Get the notices out of the cache
618
619         $notices = $cache->get(common_cache_key($cachekey));
620
621         # On a cache hit, return a DB-object-like wrapper
622
623         if ($notices !== false) {
624             $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
625             return $wrapper;
626         }
627
628         # If the cache was invalidated because of new data being
629         # added, we can try and just get the new stuff. We keep an additional
630         # copy of the data at the key + ';last'
631
632         # No cache hit. Try to get the *last* cached version
633
634         $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
635
636         if ($last_notices) {
637
638             # Reverse-chron order, so last ID is last.
639
640             $last_id = $last_notices[0]->id;
641
642             # XXX: this assumes monotonically increasing IDs; a fair
643             # bet with our DB.
644
645             $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
646                                                   $last_id, null, $order, null);
647
648             if ($new_notice) {
649                 $new_notices = array();
650                 while ($new_notice->fetch()) {
651                     $new_notices[] = clone($new_notice);
652                 }
653                 $new_notice->free();
654                 $notices = array_slice(array_merge($new_notices, $last_notices),
655                                        0, NOTICE_CACHE_WINDOW);
656
657                 # Store the array in the cache for next time
658
659                 $result = $cache->set(common_cache_key($cachekey), $notices);
660                 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
661
662                 # return a wrapper of the array for use now
663
664                 return new ArrayWrapper(array_slice($notices, $offset, $limit));
665             }
666         }
667
668         # Otherwise, get the full cache window out of the DB
669
670         $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
671
672         # If there are no hits, just return the value
673
674         if (!$notice) {
675             return $notice;
676         }
677
678         # Pack results into an array
679
680         $notices = array();
681
682         while ($notice->fetch()) {
683             $notices[] = clone($notice);
684         }
685
686         $notice->free();
687
688         # Store the array in the cache for next time
689
690         $result = $cache->set(common_cache_key($cachekey), $notices);
691         $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
692
693         # return a wrapper of the array for use now
694
695         $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
696
697         return $wrapper;
698     }
699
700     function getStreamByIds($ids)
701     {
702         $cache = common_memcache();
703
704         if (!empty($cache)) {
705             $notices = array();
706             foreach ($ids as $id) {
707                 $n = Notice::staticGet('id', $id);
708                 if (!empty($n)) {
709                     $notices[] = $n;
710                 }
711             }
712             return new ArrayWrapper($notices);
713         } else {
714             $notice = new Notice();
715             $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
716             $notice->orderBy('id DESC');
717
718             $notice->find();
719             return $notice;
720         }
721     }
722
723     function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
724     {
725         $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
726                               array(),
727                               'public',
728                               $offset, $limit, $since_id, $max_id, $since);
729
730         return Notice::getStreamByIds($ids);
731     }
732
733     function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
734     {
735         $notice = new Notice();
736
737         $notice->selectAdd(); // clears it
738         $notice->selectAdd('id');
739
740         $notice->orderBy('id DESC');
741
742         if (!is_null($offset)) {
743             $notice->limit($offset, $limit);
744         }
745
746         if (common_config('public', 'localonly')) {
747             $notice->whereAdd('is_local = 1');
748         } else {
749             # -1 == blacklisted
750             $notice->whereAdd('is_local != -1');
751         }
752
753         if ($since_id != 0) {
754             $notice->whereAdd('id > ' . $since_id);
755         }
756
757         if ($max_id != 0) {
758             $notice->whereAdd('id <= ' . $max_id);
759         }
760
761         if (!is_null($since)) {
762             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
763         }
764
765         $ids = array();
766
767         if ($notice->find()) {
768             while ($notice->fetch()) {
769                 $ids[] = $notice->id;
770             }
771         }
772
773         $notice->free();
774         $notice = NULL;
775
776         return $ids;
777     }
778
779     function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
780     {
781         $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
782                               array($id),
783                               'notice:conversation_ids:'.$id,
784                               $offset, $limit, $since_id, $max_id, $since);
785
786         return Notice::getStreamByIds($ids);
787     }
788
789     function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
790     {
791         $notice = new Notice();
792
793         $notice->selectAdd(); // clears it
794         $notice->selectAdd('id');
795
796         $notice->whereAdd('conversation = '.$id);
797
798         $notice->orderBy('id DESC');
799
800         if (!is_null($offset)) {
801             $notice->limit($offset, $limit);
802         }
803
804         if ($since_id != 0) {
805             $notice->whereAdd('id > ' . $since_id);
806         }
807
808         if ($max_id != 0) {
809             $notice->whereAdd('id <= ' . $max_id);
810         }
811
812         if (!is_null($since)) {
813             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
814         }
815
816         $ids = array();
817
818         if ($notice->find()) {
819             while ($notice->fetch()) {
820                 $ids[] = $notice->id;
821             }
822         }
823
824         $notice->free();
825         $notice = NULL;
826
827         return $ids;
828     }
829
830     function addToInboxes()
831     {
832         $enabled = common_config('inboxes', 'enabled');
833
834         if ($enabled === true || $enabled === 'transitional') {
835
836             $users = $this->getSubscribedUsers();
837
838             // FIXME: kind of ignoring 'transitional'...
839             // we'll probably stop supporting inboxless mode
840             // in 0.9.x
841
842             foreach ($users as $id) {
843                 $this->addToUserInbox($id, NOTICE_INBOX_SOURCE_SUB);
844             }
845         }
846
847         return;
848     }
849
850     function getSubscribedUsers()
851     {
852         $user = new User();
853
854         $qry =
855           'SELECT id ' .
856           'FROM user JOIN subscription '.
857           'ON user.id = subscription.subscriber ' .
858           'WHERE subscription.subscribed = %d ';
859
860         $user->query(sprintf($qry, $this->profile_id));
861
862         $ids = array();
863
864         while ($user->fetch()) {
865             $ids[] = $user->id;
866         }
867
868         $user->free();
869
870         return $ids;
871     }
872
873     function addToUserInbox($user_id, $source)
874     {
875         $inbox = Notice_inbox::pkeyGet(array('user_id' => $user_id,
876                                              'notice_id' => $this->id));
877         if (empty($inbox)) {
878             $inbox = new Notice_inbox();
879             $inbox->user_id   = $user_id;
880             $inbox->notice_id = $this->id;
881             $inbox->source    = $source;
882             $inbox->created   = $this->created;
883             return $inbox->insert();
884         }
885
886         return true;
887     }
888
889     function saveGroups()
890     {
891         $enabled = common_config('inboxes', 'enabled');
892         if ($enabled !== true && $enabled !== 'transitional') {
893             return;
894         }
895
896         /* extract all !group */
897         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
898                                 strtolower($this->content),
899                                 $match);
900         if (!$count) {
901             return true;
902         }
903
904         $profile = $this->getProfile();
905
906         /* Add them to the database */
907
908         foreach (array_unique($match[1]) as $nickname) {
909             /* XXX: remote groups. */
910             $group = User_group::getForNickname($nickname);
911
912             if (empty($group)) {
913                 continue;
914             }
915
916             // we automatically add a tag for every group name, too
917
918             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
919                                              'notice_id' => $this->id));
920
921             if (is_null($tag)) {
922                 $this->saveTag($nickname);
923             }
924
925             if ($profile->isMember($group)) {
926
927                 $result = $this->addToGroupInbox($group);
928
929                 if (!$result) {
930                     common_log_db_error($gi, 'INSERT', __FILE__);
931                 }
932
933                 // FIXME: do this in an offline daemon
934
935                 $this->addToGroupMemberInboxes($group);
936             }
937         }
938     }
939
940     function addToGroupInbox($group)
941     {
942         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
943                                          'notice_id' => $this->id));
944
945         if (empty($gi)) {
946
947             $gi = new Group_inbox();
948
949             $gi->group_id  = $group->id;
950             $gi->notice_id = $this->id;
951             $gi->created   = $this->created;
952
953             return $gi->insert();
954         }
955
956         return true;
957     }
958
959     function addToGroupMemberInboxes($group)
960     {
961         $users = $group->getUserMembers();
962
963         foreach ($users as $id) {
964             $this->addToUserInbox($id, NOTICE_INBOX_SOURCE_GROUP);
965         }
966     }
967
968     function saveReplies()
969     {
970         // Alternative reply format
971         $tname = false;
972         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
973             $tname = $match[1];
974         }
975         // extract all @messages
976         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
977
978         $names = array();
979
980         if ($cnt || $tname) {
981             // XXX: is there another way to make an array copy?
982             $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
983         }
984
985         $sender = Profile::staticGet($this->profile_id);
986
987         $replied = array();
988
989         // store replied only for first @ (what user/notice what the reply directed,
990         // we assume first @ is it)
991
992         for ($i=0; $i<count($names); $i++) {
993             $nickname = $names[$i];
994             $recipient = common_relative_profile($sender, $nickname, $this->created);
995             if (!$recipient) {
996                 continue;
997             }
998             if ($i == 0 && ($recipient->id != $sender->id) && !$this->reply_to) { // Don't save reply to self
999                 $reply_for = $recipient;
1000                 $recipient_notice = $reply_for->getCurrentNotice();
1001                 if ($recipient_notice) {
1002                     $orig = clone($this);
1003                     $this->reply_to = $recipient_notice->id;
1004                     $this->conversation = $recipient_notice->conversation;
1005                     $this->update($orig);
1006                 }
1007             }
1008             // Don't save replies from blocked profile to local user
1009             $recipient_user = User::staticGet('id', $recipient->id);
1010             if ($recipient_user && $recipient_user->hasBlocked($sender)) {
1011                 continue;
1012             }
1013             $reply = new Reply();
1014             $reply->notice_id = $this->id;
1015             $reply->profile_id = $recipient->id;
1016             $id = $reply->insert();
1017             if (!$id) {
1018                 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1019                 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1020                 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1021                 return;
1022             } else {
1023                 $replied[$recipient->id] = 1;
1024             }
1025         }
1026
1027         // Hash format replies, too
1028         $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1029         if ($cnt) {
1030             foreach ($match[1] as $tag) {
1031                 $tagged = Profile_tag::getTagged($sender->id, $tag);
1032                 foreach ($tagged as $t) {
1033                     if (!$replied[$t->id]) {
1034                         // Don't save replies from blocked profile to local user
1035                         $t_user = User::staticGet('id', $t->id);
1036                         if ($t_user && $t_user->hasBlocked($sender)) {
1037                             continue;
1038                         }
1039                         $reply = new Reply();
1040                         $reply->notice_id = $this->id;
1041                         $reply->profile_id = $t->id;
1042                         $id = $reply->insert();
1043                         if (!$id) {
1044                             common_log_db_error($reply, 'INSERT', __FILE__);
1045                             return;
1046                         } else {
1047                             $replied[$recipient->id] = 1;
1048                         }
1049                     }
1050                 }
1051             }
1052         }
1053
1054         // If it's not a reply, make it the root of a new conversation
1055
1056         if (empty($this->conversation)) {
1057             $orig = clone($this);
1058             $this->conversation = $this->id;
1059             $this->update($orig);
1060         }
1061
1062         foreach (array_keys($replied) as $recipient) {
1063             $user = User::staticGet('id', $recipient);
1064             if ($user) {
1065                 mail_notify_attn($user, $this);
1066             }
1067         }
1068     }
1069
1070     function asAtomEntry($namespace=false, $source=false)
1071     {
1072         $profile = $this->getProfile();
1073
1074         $xs = new XMLStringer(true);
1075
1076         if ($namespace) {
1077             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1078                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1079         } else {
1080             $attrs = array();
1081         }
1082
1083         $xs->elementStart('entry', $attrs);
1084
1085         if ($source) {
1086             $xs->elementStart('source');
1087             $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1088             $xs->element('link', array('href' => $profile->profileurl));
1089             $user = User::staticGet('id', $profile->id);
1090             if (!empty($user)) {
1091                 $atom_feed = common_local_url('api',
1092                                               array('apiaction' => 'statuses',
1093                                                     'method' => 'user_timeline',
1094                                                     'argument' => $profile->nickname.'.atom'));
1095                 $xs->element('link', array('rel' => 'self',
1096                                            'type' => 'application/atom+xml',
1097                                            'href' => $profile->profileurl));
1098                 $xs->element('link', array('rel' => 'license',
1099                                            'href' => common_config('license', 'url')));
1100             }
1101
1102             $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1103         }
1104
1105         $xs->elementStart('author');
1106         $xs->element('name', null, $profile->nickname);
1107         $xs->element('uri', null, $profile->profileurl);
1108         $xs->elementEnd('author');
1109
1110         if ($source) {
1111             $xs->elementEnd('source');
1112         }
1113
1114         $xs->element('title', null, $this->content);
1115         $xs->element('summary', null, $this->content);
1116
1117         $xs->element('link', array('rel' => 'alternate',
1118                                    'href' => $this->bestUrl()));
1119
1120         $xs->element('id', null, $this->uri);
1121
1122         $xs->element('published', null, common_date_w3dtf($this->created));
1123         $xs->element('updated', null, common_date_w3dtf($this->modified));
1124
1125         if ($this->reply_to) {
1126             $reply_notice = Notice::staticGet('id', $this->reply_to);
1127             if (!empty($reply_notice)) {
1128                 $xs->element('link', array('rel' => 'related',
1129                                            'href' => $reply_notice->bestUrl()));
1130                 $xs->element('thr:in-reply-to',
1131                              array('ref' => $reply_notice->uri,
1132                                    'href' => $reply_notice->bestUrl()));
1133             }
1134         }
1135
1136         $xs->element('content', array('type' => 'html'), $this->rendered);
1137
1138         $tag = new Notice_tag();
1139         $tag->notice_id = $this->id;
1140         if ($tag->find()) {
1141             while ($tag->fetch()) {
1142                 $xs->element('category', array('term' => $tag->tag));
1143             }
1144         }
1145         $tag->free();
1146
1147         $xs->elementEnd('entry');
1148
1149         return $xs->getString();
1150     }
1151
1152     function bestUrl()
1153     {
1154         if (!empty($this->url)) {
1155             return $this->url;
1156         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1157             return $this->uri;
1158         } else {
1159             return common_local_url('shownotice',
1160                                     array('notice' => $this->id));
1161         }
1162     }
1163
1164     function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1165     {
1166         $cache = common_memcache();
1167
1168         if (empty($cache) ||
1169             $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1170             ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1171             return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1172                                                                       $max_id, $since)));
1173         }
1174
1175         $idkey = common_cache_key($cachekey);
1176
1177         $idstr = $cache->get($idkey);
1178
1179         if (!empty($idstr)) {
1180             // Cache hit! Woohoo!
1181             $window = explode(',', $idstr);
1182             $ids = array_slice($window, $offset, $limit);
1183             return $ids;
1184         }
1185
1186         $laststr = $cache->get($idkey.';last');
1187
1188         if (!empty($laststr)) {
1189             $window = explode(',', $laststr);
1190             $last_id = $window[0];
1191             $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1192                                                                           $last_id, 0, null, $tag)));
1193
1194             $new_window = array_merge($new_ids, $window);
1195
1196             $new_windowstr = implode(',', $new_window);
1197
1198             $result = $cache->set($idkey, $new_windowstr);
1199             $result = $cache->set($idkey . ';last', $new_windowstr);
1200
1201             $ids = array_slice($new_window, $offset, $limit);
1202
1203             return $ids;
1204         }
1205
1206         $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1207                                                                      0, 0, null, $tag)));
1208
1209         $windowstr = implode(',', $window);
1210
1211         $result = $cache->set($idkey, $windowstr);
1212         $result = $cache->set($idkey . ';last', $windowstr);
1213
1214         $ids = array_slice($window, $offset, $limit);
1215
1216         return $ids;
1217     }
1218 }