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