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