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