]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
101fadb6743ed8b5ca923801e85cf1b2c470ef0a
[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         $profile = Profile::staticGet($this->profile_id);
360         $profile->blowNoticeCount();
361     }
362
363     function blowConversationCache($blowLast=false)
364     {
365         $cache = common_memcache();
366         if ($cache) {
367             $ck = common_cache_key('notice:conversation_ids:'.$this->conversation);
368             $cache->delete($ck);
369             if ($blowLast) {
370                 $cache->delete($ck.';last');
371             }
372         }
373     }
374
375     function blowGroupCache($blowLast=false)
376     {
377         $cache = common_memcache();
378         if ($cache) {
379             $group_inbox = new Group_inbox();
380             $group_inbox->notice_id = $this->id;
381             if ($group_inbox->find()) {
382                 while ($group_inbox->fetch()) {
383                     $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
384                     if ($blowLast) {
385                         $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
386                     }
387                     $member = new Group_member();
388                     $member->group_id = $group_inbox->group_id;
389                     if ($member->find()) {
390                         while ($member->fetch()) {
391                             $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
392                             if ($blowLast) {
393                                 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
394                             }
395                         }
396                     }
397                 }
398             }
399             $group_inbox->free();
400             unset($group_inbox);
401         }
402     }
403
404     function blowTagCache($blowLast=false)
405     {
406         $cache = common_memcache();
407         if ($cache) {
408             $tag = new Notice_tag();
409             $tag->notice_id = $this->id;
410             if ($tag->find()) {
411                 while ($tag->fetch()) {
412                     $tag->blowCache($blowLast);
413                     $ck = 'profile:notice_ids_tagged:' . $this->profile_id . ':' . $tag->tag;
414
415                     $cache->delete($ck);
416                     if ($blowLast) {
417                         $cache->delete($ck . ';last');
418                     }
419                 }
420             }
421             $tag->free();
422             unset($tag);
423         }
424     }
425
426     function blowSubsCache($blowLast=false)
427     {
428         $cache = common_memcache();
429         if ($cache) {
430             $user = new User();
431
432             $UT = common_config('db','type')=='pgsql'?'"user"':'user';
433             $user->query('SELECT id ' .
434
435                          "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
436                          'WHERE subscription.subscribed = ' . $this->profile_id);
437
438             while ($user->fetch()) {
439                 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
440                 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id));
441                 if ($blowLast) {
442                     $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
443                     $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id.';last'));
444                 }
445             }
446             $user->free();
447             unset($user);
448         }
449     }
450
451     function blowNoticeCache($blowLast=false)
452     {
453         if ($this->is_local) {
454             $cache = common_memcache();
455             if (!empty($cache)) {
456                 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
457                 if ($blowLast) {
458                     $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
459                 }
460             }
461         }
462     }
463
464     function blowRepliesCache($blowLast=false)
465     {
466         $cache = common_memcache();
467         if ($cache) {
468             $reply = new Reply();
469             $reply->notice_id = $this->id;
470             if ($reply->find()) {
471                 while ($reply->fetch()) {
472                     $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
473                     if ($blowLast) {
474                         $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
475                     }
476                 }
477             }
478             $reply->free();
479             unset($reply);
480         }
481     }
482
483     function blowPublicCache($blowLast=false)
484     {
485         if ($this->is_local == 1) {
486             $cache = common_memcache();
487             if ($cache) {
488                 $cache->delete(common_cache_key('public'));
489                 if ($blowLast) {
490                     $cache->delete(common_cache_key('public').';last');
491                 }
492             }
493         }
494     }
495
496     function blowFavesCache($blowLast=false)
497     {
498         $cache = common_memcache();
499         if ($cache) {
500             $fave = new Fave();
501             $fave->notice_id = $this->id;
502             if ($fave->find()) {
503                 while ($fave->fetch()) {
504                     $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
505                     $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id));
506                     if ($blowLast) {
507                         $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
508                         $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id.';last'));
509                     }
510                 }
511             }
512             $fave->free();
513             unset($fave);
514         }
515     }
516
517     # XXX: too many args; we need to move to named params or even a separate
518     # class for notice streams
519
520     static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $order=null, $since=null) {
521
522         if (common_config('memcached', 'enabled')) {
523
524             # Skip the cache if this is a since, since_id or max_id qry
525             if ($since_id > 0 || $max_id > 0 || $since) {
526                 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
527             } else {
528                 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
529             }
530         }
531
532         return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
533     }
534
535     static function getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since) {
536
537         $needAnd = false;
538         $needWhere = true;
539
540         if (preg_match('/\bWHERE\b/i', $qry)) {
541             $needWhere = false;
542             $needAnd = true;
543         }
544
545         if ($since_id > 0) {
546
547             if ($needWhere) {
548                 $qry .= ' WHERE ';
549                 $needWhere = false;
550             } else {
551                 $qry .= ' AND ';
552             }
553
554             $qry .= ' notice.id > ' . $since_id;
555         }
556
557         if ($max_id > 0) {
558
559             if ($needWhere) {
560                 $qry .= ' WHERE ';
561                 $needWhere = false;
562             } else {
563                 $qry .= ' AND ';
564             }
565
566             $qry .= ' notice.id <= ' . $max_id;
567         }
568
569         if ($since) {
570
571             if ($needWhere) {
572                 $qry .= ' WHERE ';
573                 $needWhere = false;
574             } else {
575                 $qry .= ' AND ';
576             }
577
578             $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
579         }
580
581         # Allow ORDER override
582
583         if ($order) {
584             $qry .= $order;
585         } else {
586             $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
587         }
588
589         if (common_config('db','type') == 'pgsql') {
590             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
591         } else {
592             $qry .= ' LIMIT ' . $offset . ', ' . $limit;
593         }
594
595         $notice = new Notice();
596
597         $notice->query($qry);
598
599         return $notice;
600     }
601
602     # XXX: this is pretty long and should probably be broken up into
603     # some helper functions
604
605     static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
606
607         # If outside our cache window, just go to the DB
608
609         if ($offset + $limit > NOTICE_CACHE_WINDOW) {
610             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
611         }
612
613         # Get the cache; if we can't, just go to the DB
614
615         $cache = common_memcache();
616
617         if (!$cache) {
618             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
619         }
620
621         # Get the notices out of the cache
622
623         $notices = $cache->get(common_cache_key($cachekey));
624
625         # On a cache hit, return a DB-object-like wrapper
626
627         if ($notices !== false) {
628             $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
629             return $wrapper;
630         }
631
632         # If the cache was invalidated because of new data being
633         # added, we can try and just get the new stuff. We keep an additional
634         # copy of the data at the key + ';last'
635
636         # No cache hit. Try to get the *last* cached version
637
638         $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
639
640         if ($last_notices) {
641
642             # Reverse-chron order, so last ID is last.
643
644             $last_id = $last_notices[0]->id;
645
646             # XXX: this assumes monotonically increasing IDs; a fair
647             # bet with our DB.
648
649             $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
650                                                   $last_id, null, $order, null);
651
652             if ($new_notice) {
653                 $new_notices = array();
654                 while ($new_notice->fetch()) {
655                     $new_notices[] = clone($new_notice);
656                 }
657                 $new_notice->free();
658                 $notices = array_slice(array_merge($new_notices, $last_notices),
659                                        0, NOTICE_CACHE_WINDOW);
660
661                 # Store the array in the cache for next time
662
663                 $result = $cache->set(common_cache_key($cachekey), $notices);
664                 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
665
666                 # return a wrapper of the array for use now
667
668                 return new ArrayWrapper(array_slice($notices, $offset, $limit));
669             }
670         }
671
672         # Otherwise, get the full cache window out of the DB
673
674         $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
675
676         # If there are no hits, just return the value
677
678         if (!$notice) {
679             return $notice;
680         }
681
682         # Pack results into an array
683
684         $notices = array();
685
686         while ($notice->fetch()) {
687             $notices[] = clone($notice);
688         }
689
690         $notice->free();
691
692         # Store the array in the cache for next time
693
694         $result = $cache->set(common_cache_key($cachekey), $notices);
695         $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
696
697         # return a wrapper of the array for use now
698
699         $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
700
701         return $wrapper;
702     }
703
704     function getStreamByIds($ids)
705     {
706         $cache = common_memcache();
707
708         if (!empty($cache)) {
709             $notices = array();
710             foreach ($ids as $id) {
711                 $n = Notice::staticGet('id', $id);
712                 if (!empty($n)) {
713                     $notices[] = $n;
714                 }
715             }
716             return new ArrayWrapper($notices);
717         } else {
718             $notice = new Notice();
719             $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
720             $notice->orderBy('id DESC');
721
722             $notice->find();
723             return $notice;
724         }
725     }
726
727     function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
728     {
729         $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
730                               array(),
731                               'public',
732                               $offset, $limit, $since_id, $max_id, $since);
733
734         return Notice::getStreamByIds($ids);
735     }
736
737     function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
738     {
739         $notice = new Notice();
740
741         $notice->selectAdd(); // clears it
742         $notice->selectAdd('id');
743
744         $notice->orderBy('id DESC');
745
746         if (!is_null($offset)) {
747             $notice->limit($offset, $limit);
748         }
749
750         if (common_config('public', 'localonly')) {
751             $notice->whereAdd('is_local = 1');
752         } else {
753             # -1 == blacklisted
754             $notice->whereAdd('is_local != -1');
755         }
756
757         if ($since_id != 0) {
758             $notice->whereAdd('id > ' . $since_id);
759         }
760
761         if ($max_id != 0) {
762             $notice->whereAdd('id <= ' . $max_id);
763         }
764
765         if (!is_null($since)) {
766             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
767         }
768
769         $ids = array();
770
771         if ($notice->find()) {
772             while ($notice->fetch()) {
773                 $ids[] = $notice->id;
774             }
775         }
776
777         $notice->free();
778         $notice = NULL;
779
780         return $ids;
781     }
782
783     function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
784     {
785         $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
786                               array($id),
787                               'notice:conversation_ids:'.$id,
788                               $offset, $limit, $since_id, $max_id, $since);
789
790         return Notice::getStreamByIds($ids);
791     }
792
793     function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
794     {
795         $notice = new Notice();
796
797         $notice->selectAdd(); // clears it
798         $notice->selectAdd('id');
799
800         $notice->conversation = $id;
801
802         $notice->orderBy('id DESC');
803
804         if (!is_null($offset)) {
805             $notice->limit($offset, $limit);
806         }
807
808         if ($since_id != 0) {
809             $notice->whereAdd('id > ' . $since_id);
810         }
811
812         if ($max_id != 0) {
813             $notice->whereAdd('id <= ' . $max_id);
814         }
815
816         if (!is_null($since)) {
817             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
818         }
819
820         $ids = array();
821
822         if ($notice->find()) {
823             while ($notice->fetch()) {
824                 $ids[] = $notice->id;
825             }
826         }
827
828         $notice->free();
829         $notice = NULL;
830
831         return $ids;
832     }
833
834     function addToInboxes()
835     {
836         $enabled = common_config('inboxes', 'enabled');
837
838         if ($enabled === true || $enabled === 'transitional') {
839
840             // XXX: loads constants
841
842             $inbox = new Notice_inbox();
843
844             $users = $this->getSubscribedUsers();
845
846             // FIXME: kind of ignoring 'transitional'...
847             // we'll probably stop supporting inboxless mode
848             // in 0.9.x
849
850             $ni = array();
851
852             foreach ($users as $id) {
853                 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
854             }
855
856             $groups = $this->saveGroups();
857
858             foreach ($groups as $group) {
859                 $users = $group->getUserMembers();
860                 foreach ($users as $id) {
861                     if (!array_key_exists($id, $ni)) {
862                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
863                     }
864                 }
865             }
866
867             $cnt = 0;
868
869             $qryhdr = 'INSERT INTO notice_inbox (user_id, notice_id, source, created) VALUES ';
870             $qry = $qryhdr;
871
872             foreach ($ni as $id => $source) {
873                 if ($cnt > 0) {
874                     $qry .= ', ';
875                 }
876                 $qry .= '('.$id.', '.$this->id.', '.$source.", '".$this->created. "') ";
877                 $cnt++;
878                 if (rand() % NOTICE_INBOX_SOFT_LIMIT == 0) {
879                     Notice_inbox::gc($id);
880                 }
881                 if ($cnt >= MAX_BOXCARS) {
882                     $inbox = new Notice_inbox();
883                     $inbox->query($qry);
884                     $qry = $qryhdr;
885                     $cnt = 0;
886                 }
887             }
888
889             if ($cnt > 0) {
890                 $inbox = new Notice_inbox();
891                 $inbox->query($qry);
892             }
893         }
894
895         return;
896     }
897
898     function getSubscribedUsers()
899     {
900         $user = new User();
901
902         if(common_config('db','quote_identifiers'))
903             $user_table = '"user"';
904         else $user_table = 'user';
905
906         $qry =
907           'SELECT id ' .
908           'FROM '. $user_table .' JOIN subscription '.
909           'ON '. $user_table .'.id = subscription.subscriber ' .
910           'WHERE subscription.subscribed = %d ';
911
912         $user->query(sprintf($qry, $this->profile_id));
913
914         $ids = array();
915
916         while ($user->fetch()) {
917             $ids[] = $user->id;
918         }
919
920         $user->free();
921
922         return $ids;
923     }
924
925     function saveGroups()
926     {
927         $groups = array();
928
929         $enabled = common_config('inboxes', 'enabled');
930         if ($enabled !== true && $enabled !== 'transitional') {
931             return $groups;
932         }
933
934         /* extract all !group */
935         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
936                                 strtolower($this->content),
937                                 $match);
938         if (!$count) {
939             return $groups;
940         }
941
942         $profile = $this->getProfile();
943
944         /* Add them to the database */
945
946         foreach (array_unique($match[1]) as $nickname) {
947             /* XXX: remote groups. */
948             $group = User_group::getForNickname($nickname);
949
950             if (empty($group)) {
951                 continue;
952             }
953
954             // we automatically add a tag for every group name, too
955
956             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
957                                              'notice_id' => $this->id));
958
959             if (is_null($tag)) {
960                 $this->saveTag($nickname);
961             }
962
963             if ($profile->isMember($group)) {
964
965                 $result = $this->addToGroupInbox($group);
966
967                 if (!$result) {
968                     common_log_db_error($gi, 'INSERT', __FILE__);
969                 }
970
971                 $groups[] = clone($group);
972             }
973         }
974
975         return $groups;
976     }
977
978     function addToGroupInbox($group)
979     {
980         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
981                                          'notice_id' => $this->id));
982
983         if (empty($gi)) {
984
985             $gi = new Group_inbox();
986
987             $gi->group_id  = $group->id;
988             $gi->notice_id = $this->id;
989             $gi->created   = $this->created;
990
991             return $gi->insert();
992         }
993
994         return true;
995     }
996
997     function saveReplies()
998     {
999         // Alternative reply format
1000         $tname = false;
1001         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
1002             $tname = $match[1];
1003         }
1004         // extract all @messages
1005         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
1006
1007         $names = array();
1008
1009         if ($cnt || $tname) {
1010             // XXX: is there another way to make an array copy?
1011             $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1012         }
1013
1014         $sender = Profile::staticGet($this->profile_id);
1015
1016         $replied = array();
1017
1018         // store replied only for first @ (what user/notice what the reply directed,
1019         // we assume first @ is it)
1020
1021         for ($i=0; $i<count($names); $i++) {
1022             $nickname = $names[$i];
1023             $recipient = common_relative_profile($sender, $nickname, $this->created);
1024             if (!$recipient) {
1025                 continue;
1026             }
1027             if ($i == 0 && ($recipient->id != $sender->id) && !$this->reply_to) { // Don't save reply to self
1028                 $reply_for = $recipient;
1029                 $recipient_notice = $reply_for->getCurrentNotice();
1030                 if ($recipient_notice) {
1031                     $orig = clone($this);
1032                     $this->reply_to = $recipient_notice->id;
1033                     $this->conversation = $recipient_notice->conversation;
1034                     $this->update($orig);
1035                 }
1036             }
1037             // Don't save replies from blocked profile to local user
1038             $recipient_user = User::staticGet('id', $recipient->id);
1039             if ($recipient_user && $recipient_user->hasBlocked($sender)) {
1040                 continue;
1041             }
1042             $reply = new Reply();
1043             $reply->notice_id = $this->id;
1044             $reply->profile_id = $recipient->id;
1045             $id = $reply->insert();
1046             if (!$id) {
1047                 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1048                 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1049                 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1050                 return;
1051             } else {
1052                 $replied[$recipient->id] = 1;
1053             }
1054         }
1055
1056         // Hash format replies, too
1057         $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1058         if ($cnt) {
1059             foreach ($match[1] as $tag) {
1060                 $tagged = Profile_tag::getTagged($sender->id, $tag);
1061                 foreach ($tagged as $t) {
1062                     if (!$replied[$t->id]) {
1063                         // Don't save replies from blocked profile to local user
1064                         $t_user = User::staticGet('id', $t->id);
1065                         if ($t_user && $t_user->hasBlocked($sender)) {
1066                             continue;
1067                         }
1068                         $reply = new Reply();
1069                         $reply->notice_id = $this->id;
1070                         $reply->profile_id = $t->id;
1071                         $id = $reply->insert();
1072                         if (!$id) {
1073                             common_log_db_error($reply, 'INSERT', __FILE__);
1074                             return;
1075                         } else {
1076                             $replied[$recipient->id] = 1;
1077                         }
1078                     }
1079                 }
1080             }
1081         }
1082
1083         // If it's not a reply, make it the root of a new conversation
1084
1085         if (empty($this->conversation)) {
1086             $orig = clone($this);
1087             $this->conversation = $this->id;
1088             $this->update($orig);
1089         }
1090
1091         foreach (array_keys($replied) as $recipient) {
1092             $user = User::staticGet('id', $recipient);
1093             if ($user) {
1094                 mail_notify_attn($user, $this);
1095             }
1096         }
1097     }
1098
1099     function asAtomEntry($namespace=false, $source=false)
1100     {
1101         $profile = $this->getProfile();
1102
1103         $xs = new XMLStringer(true);
1104
1105         if ($namespace) {
1106             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1107                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1108         } else {
1109             $attrs = array();
1110         }
1111
1112         $xs->elementStart('entry', $attrs);
1113
1114         if ($source) {
1115             $xs->elementStart('source');
1116             $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1117             $xs->element('link', array('href' => $profile->profileurl));
1118             $user = User::staticGet('id', $profile->id);
1119             if (!empty($user)) {
1120                 $atom_feed = common_local_url('api',
1121                                               array('apiaction' => 'statuses',
1122                                                     'method' => 'user_timeline',
1123                                                     'argument' => $profile->nickname.'.atom'));
1124                 $xs->element('link', array('rel' => 'self',
1125                                            'type' => 'application/atom+xml',
1126                                            'href' => $profile->profileurl));
1127                 $xs->element('link', array('rel' => 'license',
1128                                            'href' => common_config('license', 'url')));
1129             }
1130
1131             $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1132         }
1133
1134         $xs->elementStart('author');
1135         $xs->element('name', null, $profile->nickname);
1136         $xs->element('uri', null, $profile->profileurl);
1137         $xs->elementEnd('author');
1138
1139         if ($source) {
1140             $xs->elementEnd('source');
1141         }
1142
1143         $xs->element('title', null, $this->content);
1144         $xs->element('summary', null, $this->content);
1145
1146         $xs->element('link', array('rel' => 'alternate',
1147                                    'href' => $this->bestUrl()));
1148
1149         $xs->element('id', null, $this->uri);
1150
1151         $xs->element('published', null, common_date_w3dtf($this->created));
1152         $xs->element('updated', null, common_date_w3dtf($this->modified));
1153
1154         if ($this->reply_to) {
1155             $reply_notice = Notice::staticGet('id', $this->reply_to);
1156             if (!empty($reply_notice)) {
1157                 $xs->element('link', array('rel' => 'related',
1158                                            'href' => $reply_notice->bestUrl()));
1159                 $xs->element('thr:in-reply-to',
1160                              array('ref' => $reply_notice->uri,
1161                                    'href' => $reply_notice->bestUrl()));
1162             }
1163         }
1164
1165         $xs->element('content', array('type' => 'html'), $this->rendered);
1166
1167         $tag = new Notice_tag();
1168         $tag->notice_id = $this->id;
1169         if ($tag->find()) {
1170             while ($tag->fetch()) {
1171                 $xs->element('category', array('term' => $tag->tag));
1172             }
1173         }
1174         $tag->free();
1175
1176         # Enclosures
1177         $attachments = $this->attachments();
1178         if($attachments){
1179             foreach($attachments as $attachment){
1180                 if ($attachment->isEnclosure()) {
1181                     $attributes = array('rel'=>'enclosure','href'=>$attachment->url,'type'=>$attachment->mimetype,'length'=>$attachment->size);
1182                     if($attachment->title){
1183                         $attributes['title']=$attachment->title;
1184                     }
1185                     $xs->element('link', $attributes, null);
1186                 }
1187             }
1188         }
1189
1190         $xs->elementEnd('entry');
1191
1192         return $xs->getString();
1193     }
1194
1195     function bestUrl()
1196     {
1197         if (!empty($this->url)) {
1198             return $this->url;
1199         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1200             return $this->uri;
1201         } else {
1202             return common_local_url('shownotice',
1203                                     array('notice' => $this->id));
1204         }
1205     }
1206
1207     function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1208     {
1209         $cache = common_memcache();
1210
1211         if (empty($cache) ||
1212             $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1213             is_null($limit) ||
1214             ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1215             return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1216                                                                       $max_id, $since)));
1217         }
1218
1219         $idkey = common_cache_key($cachekey);
1220
1221         $idstr = $cache->get($idkey);
1222
1223         if (!empty($idstr)) {
1224             // Cache hit! Woohoo!
1225             $window = explode(',', $idstr);
1226             $ids = array_slice($window, $offset, $limit);
1227             return $ids;
1228         }
1229
1230         $laststr = $cache->get($idkey.';last');
1231
1232         if (!empty($laststr)) {
1233             $window = explode(',', $laststr);
1234             $last_id = $window[0];
1235             $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1236                                                                           $last_id, 0, null)));
1237
1238             $new_window = array_merge($new_ids, $window);
1239
1240             $new_windowstr = implode(',', $new_window);
1241
1242             $result = $cache->set($idkey, $new_windowstr);
1243             $result = $cache->set($idkey . ';last', $new_windowstr);
1244
1245             $ids = array_slice($new_window, $offset, $limit);
1246
1247             return $ids;
1248         }
1249
1250         $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1251                                                                      0, 0, null)));
1252
1253         $windowstr = implode(',', $window);
1254
1255         $result = $cache->set($idkey, $windowstr);
1256         $result = $cache->set($idkey . ';last', $windowstr);
1257
1258         $ids = array_slice($window, $offset, $limit);
1259
1260         return $ids;
1261     }
1262 }