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