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