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