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