]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
merge 0.9.x into 1.0.x
[quix0rs-gnu-social.git] / classes / Notice.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, 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  * @category Notices
20  * @package  StatusNet
21  * @author   Brenda Wallace <shiny@cpan.org>
22  * @author   Christopher Vollick <psycotica0@gmail.com>
23  * @author   CiaranG <ciaran@ciarang.com>
24  * @author   Craig Andrews <candrews@integralblue.com>
25  * @author   Evan Prodromou <evan@controlezvous.ca>
26  * @author   Gina Haeussge <osd@foosel.net>
27  * @author   Jeffery To <jeffery.to@gmail.com>
28  * @author   Mike Cochrane <mikec@mikenz.geek.nz>
29  * @author   Robin Millette <millette@controlyourself.ca>
30  * @author   Sarven Capadisli <csarven@controlyourself.ca>
31  * @author   Tom Adams <tom@holizz.com>
32  * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
33  * @license  GNU Affero General Public License http://www.gnu.org/licenses/
34  */
35
36 if (!defined('STATUSNET') && !defined('LACONICA')) {
37     exit(1);
38 }
39
40 /**
41  * Table Definition for notice
42  */
43 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
44
45 /* We keep 200 notices, the max number of notices available per API request,
46  * in the memcached cache. */
47
48 define('NOTICE_CACHE_WINDOW', CachingNoticeStream::CACHE_WINDOW);
49
50 define('MAX_BOXCARS', 128);
51
52 class Notice extends Memcached_DataObject
53 {
54     ###START_AUTOCODE
55     /* the code below is auto generated do not remove the above tag */
56
57     public $__table = 'notice';                          // table name
58     public $id;                              // int(4)  primary_key not_null
59     public $profile_id;                      // int(4)  multiple_key not_null
60     public $uri;                             // varchar(255)  unique_key
61     public $content;                         // text
62     public $rendered;                        // text
63     public $url;                             // varchar(255)
64     public $created;                         // datetime  multiple_key not_null default_0000-00-00%2000%3A00%3A00
65     public $modified;                        // timestamp   not_null default_CURRENT_TIMESTAMP
66     public $reply_to;                        // int(4)
67     public $is_local;                        // int(4)
68     public $source;                          // varchar(32)
69     public $conversation;                    // int(4)
70     public $lat;                             // decimal(10,7)
71     public $lon;                             // decimal(10,7)
72     public $location_id;                     // int(4)
73     public $location_ns;                     // int(4)
74     public $repeat_of;                       // int(4)
75     public $object_type;                     // varchar(255)
76     public $scope;                           // int(4)
77
78     /* Static get */
79     function staticGet($k,$v=NULL)
80     {
81         return Memcached_DataObject::staticGet('Notice',$k,$v);
82     }
83
84     /* the code above is auto generated do not remove the tag below */
85     ###END_AUTOCODE
86
87     /* Notice types */
88     const LOCAL_PUBLIC    =  1;
89     const REMOTE_OMB      =  0;
90     const LOCAL_NONPUBLIC = -1;
91     const GATEWAY         = -2;
92
93     const PUBLIC_SCOPE    = 0; // Useful fake constant
94     const SITE_SCOPE      = 1;
95     const ADDRESSEE_SCOPE = 2;
96     const GROUP_SCOPE     = 4;
97     const FOLLOWER_SCOPE  = 8;
98
99     protected $_profile = -1;
100
101     function getProfile()
102     {
103         if (is_int($this->_profile) && $this->_profile == -1) {
104             $this->_profile = Profile::staticGet('id', $this->profile_id);
105
106             if (empty($this->_profile)) {
107                 // TRANS: Server exception thrown when a user profile for a notice cannot be found.
108                 // TRANS: %1$d is a profile ID (number), %2$d is a notice ID (number).
109                 throw new ServerException(sprintf(_('No such profile (%1$d) for notice (%2$d).'), $this->profile_id, $this->id));
110             }
111         }
112
113         return $this->_profile;
114     }
115
116     function delete()
117     {
118         // For auditing purposes, save a record that the notice
119         // was deleted.
120
121         // @fixme we have some cases where things get re-run and so the
122         // insert fails.
123         $deleted = Deleted_notice::staticGet('id', $this->id);
124
125         if (!$deleted) {
126             $deleted = Deleted_notice::staticGet('uri', $this->uri);
127         }
128
129         if (!$deleted) {
130             $deleted = new Deleted_notice();
131
132             $deleted->id         = $this->id;
133             $deleted->profile_id = $this->profile_id;
134             $deleted->uri        = $this->uri;
135             $deleted->created    = $this->created;
136             $deleted->deleted    = common_sql_now();
137
138             $deleted->insert();
139         }
140
141         if (Event::handle('NoticeDeleteRelated', array($this))) {
142
143             // Clear related records
144
145             $this->clearReplies();
146             $this->clearRepeats();
147             $this->clearFaves();
148             $this->clearTags();
149             $this->clearGroupInboxes();
150             $this->clearFiles();
151
152             // NOTE: we don't clear inboxes
153             // NOTE: we don't clear queue items
154         }
155
156         $result = parent::delete();
157
158         $this->blowOnDelete();
159         return $result;
160     }
161
162     /**
163      * Extract #hashtags from this notice's content and save them to the database.
164      */
165     function saveTags()
166     {
167         /* extract all #hastags */
168         $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
169         if (!$count) {
170             return true;
171         }
172
173         /* Add them to the database */
174         return $this->saveKnownTags($match[1]);
175     }
176
177     /**
178      * Record the given set of hash tags in the db for this notice.
179      * Given tag strings will be normalized and checked for dupes.
180      */
181     function saveKnownTags($hashtags)
182     {
183         //turn each into their canonical tag
184         //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
185         for($i=0; $i<count($hashtags); $i++) {
186             /* elide characters we don't want in the tag */
187             $hashtags[$i] = common_canonical_tag($hashtags[$i]);
188         }
189
190         foreach(array_unique($hashtags) as $hashtag) {
191             $this->saveTag($hashtag);
192             self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
193         }
194         return true;
195     }
196
197     /**
198      * Record a single hash tag as associated with this notice.
199      * Tag format and uniqueness must be validated by caller.
200      */
201     function saveTag($hashtag)
202     {
203         $tag = new Notice_tag();
204         $tag->notice_id = $this->id;
205         $tag->tag = $hashtag;
206         $tag->created = $this->created;
207         $id = $tag->insert();
208
209         if (!$id) {
210             // TRANS: Server exception. %s are the error details.
211             throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
212                                               $last_error->message));
213             return;
214         }
215
216         // if it's saved, blow its cache
217         $tag->blowCache(false);
218     }
219
220     /**
221      * Save a new notice and push it out to subscribers' inboxes.
222      * Poster's permissions are checked before sending.
223      *
224      * @param int $profile_id Profile ID of the poster
225      * @param string $content source message text; links may be shortened
226      *                        per current user's preference
227      * @param string $source source key ('web', 'api', etc)
228      * @param array $options Associative array of optional properties:
229      *              string 'created' timestamp of notice; defaults to now
230      *              int 'is_local' source/gateway ID, one of:
231      *                  Notice::LOCAL_PUBLIC    - Local, ok to appear in public timeline
232      *                  Notice::REMOTE_OMB      - Sent from a remote OMB service;
233      *                                            hide from public timeline but show in
234      *                                            local "and friends" timelines
235      *                  Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
236      *                  Notice::GATEWAY         - From another non-OMB service;
237      *                                            will not appear in public views
238      *              float 'lat' decimal latitude for geolocation
239      *              float 'lon' decimal longitude for geolocation
240      *              int 'location_id' geoname identifier
241      *              int 'location_ns' geoname namespace to interpret location_id
242      *              int 'reply_to'; notice ID this is a reply to
243      *              int 'repeat_of'; notice ID this is a repeat of
244      *              string 'uri' unique ID for notice; defaults to local notice URL
245      *              string 'url' permalink to notice; defaults to local notice URL
246      *              string 'rendered' rendered HTML version of content
247      *              array 'replies' list of profile URIs for reply delivery in
248      *                              place of extracting @-replies from content.
249      *              array 'groups' list of group IDs to deliver to, in place of
250      *                              extracting ! tags from content
251      *              array 'tags' list of hashtag strings to save with the notice
252      *                           in place of extracting # tags from content
253      *              array 'urls' list of attached/referred URLs to save with the
254      *                           notice in place of extracting links from content
255      *              boolean 'distribute' whether to distribute the notice, default true
256      *              string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
257      *              int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
258      *
259      * @fixme tag override
260      *
261      * @return Notice
262      * @throws ClientException
263      */
264     static function saveNew($profile_id, $content, $source, $options=null) {
265         $defaults = array('uri' => null,
266                           'url' => null,
267                           'reply_to' => null,
268                           'repeat_of' => null,
269                           'scope' => null,
270                           'distribute' => true);
271
272         if (!empty($options)) {
273             $options = $options + $defaults;
274             extract($options);
275         } else {
276             extract($defaults);
277         }
278
279         if (!isset($is_local)) {
280             $is_local = Notice::LOCAL_PUBLIC;
281         }
282
283         $profile = Profile::staticGet('id', $profile_id);
284         $user = User::staticGet('id', $profile_id);
285         if ($user) {
286             // Use the local user's shortening preferences, if applicable.
287             $final = $user->shortenLinks($content);
288         } else {
289             $final = common_shorten_links($content);
290         }
291
292         if (Notice::contentTooLong($final)) {
293             // TRANS: Client exception thrown if a notice contains too many characters.
294             throw new ClientException(_('Problem saving notice. Too long.'));
295         }
296
297         if (empty($profile)) {
298             // TRANS: Client exception thrown when trying to save a notice for an unknown user.
299             throw new ClientException(_('Problem saving notice. Unknown user.'));
300         }
301
302         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
303             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
304             // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
305             throw new ClientException(_('Too many notices too fast; take a breather '.
306                                         'and post again in a few minutes.'));
307         }
308
309         if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
310             common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
311             // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
312             throw new ClientException(_('Too many duplicate messages too quickly;'.
313                                         ' take a breather and post again in a few minutes.'));
314         }
315
316         if (!$profile->hasRight(Right::NEWNOTICE)) {
317             common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
318
319             // TRANS: Client exception thrown when a user tries to post while being banned.
320             throw new ClientException(_('You are banned from posting notices on this site.'), 403);
321         }
322
323         $notice = new Notice();
324         $notice->profile_id = $profile_id;
325
326         $autosource = common_config('public', 'autosource');
327
328         // Sandboxed are non-false, but not 1, either
329
330         if (!$profile->hasRight(Right::PUBLICNOTICE) ||
331             ($source && $autosource && in_array($source, $autosource))) {
332             $notice->is_local = Notice::LOCAL_NONPUBLIC;
333         } else {
334             $notice->is_local = $is_local;
335         }
336
337         if (!empty($created)) {
338             $notice->created = $created;
339         } else {
340             $notice->created = common_sql_now();
341         }
342
343         $notice->content = $final;
344
345         $notice->source = $source;
346         $notice->uri = $uri;
347         $notice->url = $url;
348
349         // Get the groups here so we can figure out replies and such
350
351         if (!isset($groups)) {
352             $groups = self::groupsFromText($notice->content, $profile);
353         }
354
355         $reply = null;
356
357         // Handle repeat case
358
359         if (isset($repeat_of)) {
360
361             // Check for a private one
362
363             $repeat = Notice::staticGet('id', $repeat_of);
364
365             if (empty($repeat)) {
366                 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
367                 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
368             }
369
370             if ($profile->id == $repeat->profile_id) {
371                 // TRANS: Client error displayed when trying to repeat an own notice.
372                 throw new ClientException(_('You cannot repeat your own notice.'));
373             }
374
375             if ($repeat->scope != Notice::SITE_SCOPE &&
376                 $repeat->scope != Notice::PUBLIC_SCOPE) {
377                 // TRANS: Client error displayed when trying to repeat a non-public notice.
378                 throw new ClientException(_('Cannot repeat a private notice.'), 403);
379             }
380
381             if (!$repeat->inScope($profile)) {
382                 // The generic checks above should cover this, but let's be sure!
383                 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
384                 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
385             }
386
387             if ($profile->hasRepeated($repeat->id)) {
388                 // TRANS: Client error displayed when trying to repeat an already repeated notice.
389                 throw new ClientException(_('You already repeated that notice.'));
390             }
391
392             $notice->repeat_of = $repeat_of;
393         } else {
394             $reply = self::getReplyTo($reply_to, $profile_id, $source, $final);
395
396             if (!empty($reply)) {
397
398                 if (!$reply->inScope($profile)) {
399                     // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
400                     // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
401                     throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
402                                                       $profile->nickname, $reply->id), 403);
403                 }
404
405                 $notice->reply_to     = $reply->id;
406                 $notice->conversation = $reply->conversation;
407
408                 // If the original is private to a group, and notice has no group specified,
409                 // make it to the same group(s)
410
411                 if (empty($groups) && ($reply->scope | Notice::GROUP_SCOPE)) {
412                     $groups = array();
413                     $replyGroups = $reply->getGroups();
414                     foreach ($replyGroups as $group) {
415                         if ($profile->isMember($group)) {
416                             $groups[] = $group->id;
417                         }
418                     }
419                 }
420
421                 // Scope set below
422             }
423         }
424
425         if (!empty($lat) && !empty($lon)) {
426             $notice->lat = $lat;
427             $notice->lon = $lon;
428         }
429
430         if (!empty($location_ns) && !empty($location_id)) {
431             $notice->location_id = $location_id;
432             $notice->location_ns = $location_ns;
433         }
434
435         if (!empty($rendered)) {
436             $notice->rendered = $rendered;
437         } else {
438             $notice->rendered = common_render_content($final, $notice);
439         }
440
441         if (empty($object_type)) {
442             $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
443         } else {
444             $notice->object_type = $object_type;
445         }
446
447         if (is_null($scope)) { // 0 is a valid value
448             if (!empty($reply)) {
449                 $notice->scope = $reply->scope;
450             } else {
451                 $notice->scope = common_config('notice', 'defaultscope');
452             }
453         } else {
454             $notice->scope = $scope;
455         }
456
457         // For private streams
458
459         $user = $profile->getUser();
460
461         if (!empty($user)) {
462             if ($user->private_stream &&
463                 ($notice->scope == Notice::PUBLIC_SCOPE ||
464                  $notice->scope == Notice::SITE_SCOPE)) {
465                 $notice->scope |= Notice::FOLLOWER_SCOPE;
466             }
467         }
468
469         // Force the scope for private groups
470
471         foreach ($groups as $groupId) {
472             $group = User_group::staticGet('id', $groupId);
473             if (!empty($group)) {
474                 if ($group->force_scope) {
475                     $notice->scope |= Notice::GROUP_SCOPE;
476                     break;
477                 }
478             }
479         }
480
481         if (Event::handle('StartNoticeSave', array(&$notice))) {
482
483             // XXX: some of these functions write to the DB
484
485             $id = $notice->insert();
486
487             if (!$id) {
488                 common_log_db_error($notice, 'INSERT', __FILE__);
489                 // TRANS: Server exception thrown when a notice cannot be saved.
490                 throw new ServerException(_('Problem saving notice.'));
491             }
492
493             // Update ID-dependent columns: URI, conversation
494
495             $orig = clone($notice);
496
497             $changed = false;
498
499             if (empty($uri)) {
500                 $notice->uri = common_notice_uri($notice);
501                 $changed = true;
502             }
503
504             // If it's not part of a conversation, it's
505             // the beginning of a new conversation.
506
507             if (empty($notice->conversation)) {
508                 $conv = Conversation::create();
509                 $notice->conversation = $conv->id;
510                 $changed = true;
511             }
512
513             if ($changed) {
514                 if (!$notice->update($orig)) {
515                     common_log_db_error($notice, 'UPDATE', __FILE__);
516                     // TRANS: Server exception thrown when a notice cannot be updated.
517                     throw new ServerException(_('Problem saving notice.'));
518                 }
519             }
520
521         }
522
523         // Clear the cache for subscribed users, so they'll update at next request
524         // XXX: someone clever could prepend instead of clearing the cache
525
526         $notice->blowOnInsert();
527
528         // Save per-notice metadata...
529
530         if (isset($replies)) {
531             $notice->saveKnownReplies($replies);
532         } else {
533             $notice->saveReplies();
534         }
535
536         if (isset($tags)) {
537             $notice->saveKnownTags($tags);
538         } else {
539             $notice->saveTags();
540         }
541
542         // Note: groups may save tags, so must be run after tags are saved
543         // to avoid errors on duplicates.
544         // Note: groups should always be set.
545
546         $notice->saveKnownGroups($groups);
547
548         if (isset($urls)) {
549             $notice->saveKnownUrls($urls);
550         } else {
551             $notice->saveUrls();
552         }
553
554         if ($distribute) {
555             // Prepare inbox delivery, may be queued to background.
556             $notice->distribute();
557         }
558
559         return $notice;
560     }
561
562     function blowOnInsert($conversation = false)
563     {
564         $this->blowStream('profile:notice_ids:%d', $this->profile_id);
565
566         if ($this->isPublic()) {
567             $this->blowStream('public');
568         }
569
570         // XXX: Before we were blowing the casche only if the notice id
571         // was not the root of the conversation.  What to do now?
572
573         self::blow('notice:conversation_ids:%d', $this->conversation);
574         self::blow('conversation::notice_count:%d', $this->conversation);
575
576         if (!empty($this->repeat_of)) {
577             $this->blowStream('notice:repeats:%d', $this->repeat_of);
578         }
579
580         $original = Notice::staticGet('id', $this->repeat_of);
581
582         if (!empty($original)) {
583             $originalUser = User::staticGet('id', $original->profile_id);
584             if (!empty($originalUser)) {
585                 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
586             }
587         }
588
589         $profile = Profile::staticGet($this->profile_id);
590
591         if (!empty($profile)) {
592             $profile->blowNoticeCount();
593         }
594
595         $ptags = $this->getProfileTags();
596         foreach ($ptags as $ptag) {
597             $ptag->blowNoticeStreamCache();
598         }
599     }
600
601     /**
602      * Clear cache entries related to this notice at delete time.
603      * Necessary to avoid breaking paging on public, profile timelines.
604      */
605     function blowOnDelete()
606     {
607         $this->blowOnInsert();
608
609         self::blow('profile:notice_ids:%d;last', $this->profile_id);
610
611         if ($this->isPublic()) {
612             self::blow('public;last');
613         }
614
615         self::blow('fave:by_notice', $this->id);
616
617         if ($this->conversation) {
618             // In case we're the first, will need to calc a new root.
619             self::blow('notice:conversation_root:%d', $this->conversation);
620         }
621
622         $ptags = $this->getProfileTags();
623         foreach ($ptags as $ptag) {
624             $ptag->blowNoticeStreamCache(true);
625         }
626     }
627
628     function blowStream()
629     {
630         $c = self::memcache();
631
632         if (empty($c)) {
633             return false;
634         }
635
636         $args = func_get_args();
637
638         $format = array_shift($args);
639
640         $keyPart = vsprintf($format, $args);
641
642         $cacheKey = Cache::key($keyPart);
643         
644         $c->delete($cacheKey);
645
646         // delete the "last" stream, too, if this notice is
647         // older than the top of that stream
648
649         $lastKey = $cacheKey.';last';
650
651         $lastStr = $c->get($lastKey);
652
653         if ($lastStr !== false) {
654             $window     = explode(',', $lastStr);
655             $lastID     = $window[0];
656             $lastNotice = Notice::staticGet('id', $lastID);
657             if (empty($lastNotice) // just weird
658                 || strtotime($lastNotice->created) >= strtotime($this->created)) {
659                 $c->delete($lastKey);
660             }
661         }
662     }
663
664     /** save all urls in the notice to the db
665      *
666      * follow redirects and save all available file information
667      * (mimetype, date, size, oembed, etc.)
668      *
669      * @return void
670      */
671     function saveUrls() {
672         if (common_config('attachments', 'process_links')) {
673             common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
674         }
675     }
676
677     /**
678      * Save the given URLs as related links/attachments to the db
679      *
680      * follow redirects and save all available file information
681      * (mimetype, date, size, oembed, etc.)
682      *
683      * @return void
684      */
685     function saveKnownUrls($urls)
686     {
687         if (common_config('attachments', 'process_links')) {
688             // @fixme validation?
689             foreach (array_unique($urls) as $url) {
690                 File::processNew($url, $this->id);
691             }
692         }
693     }
694
695     /**
696      * @private callback
697      */
698     function saveUrl($url, $notice_id) {
699         File::processNew($url, $notice_id);
700     }
701
702     static function checkDupes($profile_id, $content) {
703         $profile = Profile::staticGet($profile_id);
704         if (empty($profile)) {
705             return false;
706         }
707         $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
708         if (!empty($notice)) {
709             $last = 0;
710             while ($notice->fetch()) {
711                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
712                     return true;
713                 } else if ($notice->content == $content) {
714                     return false;
715                 }
716             }
717         }
718         // If we get here, oldest item in cache window is not
719         // old enough for dupe limit; do direct check against DB
720         $notice = new Notice();
721         $notice->profile_id = $profile_id;
722         $notice->content = $content;
723         $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
724         $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
725
726         $cnt = $notice->count();
727         return ($cnt == 0);
728     }
729
730     static function checkEditThrottle($profile_id) {
731         $profile = Profile::staticGet($profile_id);
732         if (empty($profile)) {
733             return false;
734         }
735         // Get the Nth notice
736         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
737         if ($notice && $notice->fetch()) {
738             // If the Nth notice was posted less than timespan seconds ago
739             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
740                 // Then we throttle
741                 return false;
742             }
743         }
744         // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
745         return true;
746     }
747
748     function getUploadedAttachment() {
749         $post = clone $this;
750         $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"';
751         $post->query($query);
752         $post->fetch();
753         if (empty($post->up) || empty($post->i)) {
754             $ret = false;
755         } else {
756             $ret = array($post->up, $post->i);
757         }
758         $post->free();
759         return $ret;
760     }
761
762     function hasAttachments() {
763         $post = clone $this;
764         $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);
765         $post->query($query);
766         $post->fetch();
767         $n_attachments = intval($post->n_attachments);
768         $post->free();
769         return $n_attachments;
770     }
771
772     function attachments() {
773
774         $keypart = sprintf('notice:file_ids:%d', $this->id);
775
776         $idstr = self::cacheGet($keypart);
777
778         if ($idstr !== false) {
779             $ids = explode(',', $idstr);
780         } else {
781             $ids = array();
782             $f2p = new File_to_post;
783             $f2p->post_id = $this->id;
784             if ($f2p->find()) {
785                 while ($f2p->fetch()) {
786                     $ids[] = $f2p->file_id;
787                 }
788             }
789             self::cacheSet($keypart, implode(',', $ids));
790         }
791
792         $att = array();
793
794         foreach ($ids as $id) {
795             $f = File::staticGet('id', $id);
796             if (!empty($f)) {
797                 $att[] = clone($f);
798             }
799         }
800
801         return $att;
802     }
803
804
805     function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
806     {
807         $stream = new PublicNoticeStream();
808         return $stream->getNotices($offset, $limit, $since_id, $max_id);
809     }
810
811
812     function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
813     {
814         $stream = new ConversationNoticeStream($id);
815
816         return $stream->getNotices($offset, $limit, $since_id, $max_id);
817     }
818
819     /**
820      * Is this notice part of an active conversation?
821      *
822      * @return boolean true if other messages exist in the same
823      *                 conversation, false if this is the only one
824      */
825     function hasConversation()
826     {
827         if (!empty($this->conversation)) {
828             $conversation = Notice::conversationStream(
829                 $this->conversation,
830                 1,
831                 1
832             );
833
834             if ($conversation->N > 0) {
835                 return true;
836             }
837         }
838         return false;
839     }
840
841     /**
842      * Grab the earliest notice from this conversation.
843      *
844      * @return Notice or null
845      */
846     function conversationRoot($profile=-1)
847     {
848         // XXX: can this happen?
849
850         if (empty($this->conversation)) {
851             return null;
852         }
853
854         // Get the current profile if not specified
855
856         if (is_int($profile) && $profile == -1) {
857             $profile = Profile::current();
858         }
859
860         // If this notice is out of scope, no root for you!
861
862         if (!$this->inScope($profile)) {
863             return null;
864         }
865
866         // If this isn't a reply to anything, then it's its own
867         // root.
868
869         if (empty($this->reply_to)) {
870             return $this;
871         }
872         
873         if (is_null($profile)) {
874             $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
875         } else {
876             $keypart = sprintf('notice:conversation_root:%d:%d',
877                                $this->id,
878                                $profile->id);
879         }
880             
881         $root = self::cacheGet($keypart);
882
883         if ($root !== false && $root->inScope($profile)) {
884             return $root;
885         } else {
886             $last = $this;
887
888             do {
889                 $parent = $last->getOriginal();
890                 if (!empty($parent) && $parent->inScope($profile)) {
891                     $last = $parent;
892                     continue;
893                 } else {
894                     $root = $last;
895                     break;
896                 }
897             } while (!empty($parent));
898
899             self::cacheSet($keypart, $root);
900         }
901
902         return $root;
903     }
904
905     /**
906      * Pull up a full list of local recipients who will be getting
907      * this notice in their inbox. Results will be cached, so don't
908      * change the input data wily-nilly!
909      *
910      * @param array $groups optional list of Group objects;
911      *              if left empty, will be loaded from group_inbox records
912      * @param array $recipient optional list of reply profile ids
913      *              if left empty, will be loaded from reply records
914      * @return array associating recipient user IDs with an inbox source constant
915      */
916     function whoGets($groups=null, $recipients=null)
917     {
918         $c = self::memcache();
919
920         if (!empty($c)) {
921             $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
922             if ($ni !== false) {
923                 return $ni;
924             }
925         }
926
927         if (is_null($groups)) {
928             $groups = $this->getGroups();
929         }
930
931         if (is_null($recipients)) {
932             $recipients = $this->getReplies();
933         }
934
935         $users = $this->getSubscribedUsers();
936         $ptags = $this->getProfileTags();
937
938         // FIXME: kind of ignoring 'transitional'...
939         // we'll probably stop supporting inboxless mode
940         // in 0.9.x
941
942         $ni = array();
943
944         // Give plugins a chance to add folks in at start...
945         if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
946
947             foreach ($users as $id) {
948                 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
949             }
950
951             foreach ($groups as $group) {
952                 $users = $group->getUserMembers();
953                 foreach ($users as $id) {
954                     if (!array_key_exists($id, $ni)) {
955                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
956                     }
957                 }
958             }
959
960             foreach ($ptags as $ptag) {
961                 $users = $ptag->getUserSubscribers();
962                 foreach ($users as $id) {
963                     if (!array_key_exists($id, $ni)) {
964                         $user = User::staticGet('id', $id);
965                         if (!$user->hasBlocked($profile)) {
966                             $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
967                         }
968                     }
969                 }
970             }
971
972             foreach ($recipients as $recipient) {
973                 if (!array_key_exists($recipient, $ni)) {
974                     $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
975                 }
976
977                 // Exclude any deleted, non-local, or blocking recipients.
978                 $profile = $this->getProfile();
979                 $originalProfile = null;
980                 if ($this->repeat_of) {
981                     // Check blocks against the original notice's poster as well.
982                     $original = Notice::staticGet('id', $this->repeat_of);
983                     if ($original) {
984                         $originalProfile = $original->getProfile();
985                     }
986                 }
987                 foreach ($ni as $id => $source) {
988                     $user = User::staticGet('id', $id);
989                     if (empty($user) || $user->hasBlocked($profile) ||
990                         ($originalProfile && $user->hasBlocked($originalProfile))) {
991                         unset($ni[$id]);
992                     }
993                 }
994             }
995
996             // Give plugins a chance to filter out...
997             Event::handle('EndNoticeWhoGets', array($this, &$ni));
998         }
999
1000         if (!empty($c)) {
1001             // XXX: pack this data better
1002             $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1003         }
1004
1005         return $ni;
1006     }
1007
1008     /**
1009      * Adds this notice to the inboxes of each local user who should receive
1010      * it, based on author subscriptions, group memberships, and @-replies.
1011      *
1012      * Warning: running a second time currently will make items appear
1013      * multiple times in users' inboxes.
1014      *
1015      * @fixme make more robust against errors
1016      * @fixme break up massive deliveries to smaller background tasks
1017      *
1018      * @param array $groups optional list of Group objects;
1019      *              if left empty, will be loaded from group_inbox records
1020      * @param array $recipient optional list of reply profile ids
1021      *              if left empty, will be loaded from reply records
1022      */
1023     function addToInboxes($groups=null, $recipients=null)
1024     {
1025         $ni = $this->whoGets($groups, $recipients);
1026
1027         $ids = array_keys($ni);
1028
1029         // We remove the author (if they're a local user),
1030         // since we'll have already done this in distribute()
1031
1032         $i = array_search($this->profile_id, $ids);
1033
1034         if ($i !== false) {
1035             unset($ids[$i]);
1036         }
1037
1038         // Bulk insert
1039
1040         Inbox::bulkInsert($this->id, $ids);
1041
1042         return;
1043     }
1044
1045     function getSubscribedUsers()
1046     {
1047         $user = new User();
1048
1049         if(common_config('db','quote_identifiers'))
1050           $user_table = '"user"';
1051         else $user_table = 'user';
1052
1053         $qry =
1054           'SELECT id ' .
1055           'FROM '. $user_table .' JOIN subscription '.
1056           'ON '. $user_table .'.id = subscription.subscriber ' .
1057           'WHERE subscription.subscribed = %d ';
1058
1059         $user->query(sprintf($qry, $this->profile_id));
1060
1061         $ids = array();
1062
1063         while ($user->fetch()) {
1064             $ids[] = $user->id;
1065         }
1066
1067         $user->free();
1068
1069         return $ids;
1070     }
1071
1072     function getProfileTags()
1073     {
1074         $profile = $this->getProfile();
1075         $list    = $profile->getOtherTags($profile);
1076         $ptags   = array();
1077
1078         while($list->fetch()) {
1079             $ptags[] = clone($list);
1080         }
1081
1082         return $ptags;
1083     }
1084
1085     /**
1086      * Record this notice to the given group inboxes for delivery.
1087      * Overrides the regular parsing of !group markup.
1088      *
1089      * @param string $group_ids
1090      * @fixme might prefer URIs as identifiers, as for replies?
1091      *        best with generalizations on user_group to support
1092      *        remote groups better.
1093      */
1094     function saveKnownGroups($group_ids)
1095     {
1096         if (!is_array($group_ids)) {
1097             // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1098             throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1099         }
1100
1101         $groups = array();
1102         foreach (array_unique($group_ids) as $id) {
1103             $group = User_group::staticGet('id', $id);
1104             if ($group) {
1105                 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1106                 $result = $this->addToGroupInbox($group);
1107                 if (!$result) {
1108                     common_log_db_error($gi, 'INSERT', __FILE__);
1109                 }
1110
1111                 if (common_config('group', 'addtag')) {
1112                     // we automatically add a tag for every group name, too
1113
1114                     $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1115                                                      'notice_id' => $this->id));
1116
1117                     if (is_null($tag)) {
1118                         $this->saveTag($group->nickname);
1119                     }
1120                 }
1121
1122                 $groups[] = clone($group);
1123             } else {
1124                 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1125             }
1126         }
1127
1128         return $groups;
1129     }
1130
1131     /**
1132      * Parse !group delivery and record targets into group_inbox.
1133      * @return array of Group objects
1134      */
1135     function saveGroups()
1136     {
1137         // Don't save groups for repeats
1138
1139         if (!empty($this->repeat_of)) {
1140             return array();
1141         }
1142
1143         $profile = $this->getProfile();
1144
1145         $groups = self::groupsFromText($this->content, $profile);
1146
1147         /* Add them to the database */
1148
1149         foreach ($groups as $group) {
1150             /* XXX: remote groups. */
1151
1152             if (empty($group)) {
1153                 continue;
1154             }
1155
1156
1157             if ($profile->isMember($group)) {
1158
1159                 $result = $this->addToGroupInbox($group);
1160
1161                 if (!$result) {
1162                     common_log_db_error($gi, 'INSERT', __FILE__);
1163                 }
1164
1165                 $groups[] = clone($group);
1166             }
1167         }
1168
1169         return $groups;
1170     }
1171
1172     function addToGroupInbox($group)
1173     {
1174         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1175                                          'notice_id' => $this->id));
1176
1177         if (empty($gi)) {
1178
1179             $gi = new Group_inbox();
1180
1181             $gi->group_id  = $group->id;
1182             $gi->notice_id = $this->id;
1183             $gi->created   = $this->created;
1184
1185             $result = $gi->insert();
1186
1187             if (!$result) {
1188                 common_log_db_error($gi, 'INSERT', __FILE__);
1189                 // TRANS: Server exception thrown when an update for a group inbox fails.
1190                 throw new ServerException(_('Problem saving group inbox.'));
1191             }
1192
1193             self::blow('user_group:notice_ids:%d', $gi->group_id);
1194         }
1195
1196         return true;
1197     }
1198
1199     /**
1200      * Save reply records indicating that this notice needs to be
1201      * delivered to the local users with the given URIs.
1202      *
1203      * Since this is expected to be used when saving foreign-sourced
1204      * messages, we won't deliver to any remote targets as that's the
1205      * source service's responsibility.
1206      *
1207      * Mail notifications etc will be handled later.
1208      *
1209      * @param array of unique identifier URIs for recipients
1210      */
1211     function saveKnownReplies($uris)
1212     {
1213         if (empty($uris)) {
1214             return;
1215         }
1216
1217         $sender = Profile::staticGet($this->profile_id);
1218
1219         foreach (array_unique($uris) as $uri) {
1220
1221             $profile = Profile::fromURI($uri);
1222
1223             if (empty($profile)) {
1224                 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1225                 continue;
1226             }
1227
1228             if ($profile->hasBlocked($sender)) {
1229                 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1230                 continue;
1231             }
1232
1233             $this->saveReply($profile->id);
1234             self::blow('reply:stream:%d', $profile->id);
1235         }
1236
1237         return;
1238     }
1239
1240     /**
1241      * Pull @-replies from this message's content in StatusNet markup format
1242      * and save reply records indicating that this message needs to be
1243      * delivered to those users.
1244      *
1245      * Mail notifications to local profiles will be sent later.
1246      *
1247      * @return array of integer profile IDs
1248      */
1249
1250     function saveReplies()
1251     {
1252         // Don't save reply data for repeats
1253
1254         if (!empty($this->repeat_of)) {
1255             return array();
1256         }
1257
1258         $sender = Profile::staticGet($this->profile_id);
1259
1260         $replied = array();
1261
1262         // If it's a reply, save for the replied-to author
1263
1264         if (!empty($this->reply_to)) {
1265             $original = $this->getOriginal();
1266             if (!empty($original)) { // that'd be weird
1267                 $author = $original->getProfile();
1268                 if (!empty($author)) {
1269                     $this->saveReply($author->id);
1270                     $replied[$author->id] = 1;
1271                     self::blow('reply:stream:%d', $author->id);
1272                 }
1273             }
1274         }
1275
1276         // @todo ideally this parser information would only
1277         // be calculated once.
1278
1279         $mentions = common_find_mentions($this->content, $this);
1280
1281         // store replied only for first @ (what user/notice what the reply directed,
1282         // we assume first @ is it)
1283
1284         foreach ($mentions as $mention) {
1285
1286             foreach ($mention['mentioned'] as $mentioned) {
1287
1288                 // skip if they're already covered
1289
1290                 if (!empty($replied[$mentioned->id])) {
1291                     continue;
1292                 }
1293
1294                 // Don't save replies from blocked profile to local user
1295
1296                 $mentioned_user = User::staticGet('id', $mentioned->id);
1297                 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1298                     continue;
1299                 }
1300
1301                 $this->saveReply($mentioned->id);
1302                 $replied[$mentioned->id] = 1;
1303                 self::blow('reply:stream:%d', $mentioned->id);
1304             }
1305         }
1306
1307         $recipientIds = array_keys($replied);
1308
1309         return $recipientIds;
1310     }
1311
1312     function saveReply($profileId)
1313     {
1314         $reply = new Reply();
1315
1316         $reply->notice_id  = $this->id;
1317         $reply->profile_id = $profileId;
1318         $reply->modified   = $this->created;
1319
1320         $reply->insert();
1321
1322         return $reply;
1323     }
1324
1325     /**
1326      * Pull the complete list of @-reply targets for this notice.
1327      *
1328      * @return array of integer profile ids
1329      */
1330     function getReplies()
1331     {
1332         $keypart = sprintf('notice:reply_ids:%d', $this->id);
1333
1334         $idstr = self::cacheGet($keypart);
1335
1336         if ($idstr !== false) {
1337             $ids = explode(',', $idstr);
1338         } else {
1339             $ids = array();
1340
1341             $reply = new Reply();
1342             $reply->selectAdd();
1343             $reply->selectAdd('profile_id');
1344             $reply->notice_id = $this->id;
1345
1346             if ($reply->find()) {
1347                 while($reply->fetch()) {
1348                     $ids[] = $reply->profile_id;
1349                 }
1350             }
1351             self::cacheSet($keypart, implode(',', $ids));
1352         }
1353
1354         return $ids;
1355     }
1356
1357     /**
1358      * Pull the complete list of @-reply targets for this notice.
1359      *
1360      * @return array of Profiles
1361      */
1362     function getReplyProfiles()
1363     {
1364         $ids      = $this->getReplies();
1365         $profiles = array();
1366
1367         foreach ($ids as $id) {
1368             $profile = Profile::staticGet('id', $id);
1369             if (!empty($profile)) {
1370                 $profiles[] = $profile;
1371             }
1372         }
1373         
1374         return $profiles;
1375     }
1376
1377     /**
1378      * Send e-mail notifications to local @-reply targets.
1379      *
1380      * Replies must already have been saved; this is expected to be run
1381      * from the distrib queue handler.
1382      */
1383     function sendReplyNotifications()
1384     {
1385         // Don't send reply notifications for repeats
1386
1387         if (!empty($this->repeat_of)) {
1388             return array();
1389         }
1390
1391         $recipientIds = $this->getReplies();
1392
1393         foreach ($recipientIds as $recipientId) {
1394             $user = User::staticGet('id', $recipientId);
1395             if (!empty($user)) {
1396                 mail_notify_attn($user, $this);
1397             }
1398         }
1399     }
1400
1401     /**
1402      * Pull list of groups this notice needs to be delivered to,
1403      * as previously recorded by saveGroups() or saveKnownGroups().
1404      *
1405      * @return array of Group objects
1406      */
1407     function getGroups()
1408     {
1409         // Don't save groups for repeats
1410
1411         if (!empty($this->repeat_of)) {
1412             return array();
1413         }
1414
1415         $ids = array();
1416
1417         $keypart = sprintf('notice:groups:%d', $this->id);
1418
1419         $idstr = self::cacheGet($keypart);
1420
1421         if ($idstr !== false) {
1422             $ids = explode(',', $idstr);
1423         } else {
1424             $gi = new Group_inbox();
1425
1426             $gi->selectAdd();
1427             $gi->selectAdd('group_id');
1428
1429             $gi->notice_id = $this->id;
1430
1431             if ($gi->find()) {
1432                 while ($gi->fetch()) {
1433                     $ids[] = $gi->group_id;
1434                 }
1435             }
1436
1437             self::cacheSet($keypart, implode(',', $ids));
1438         }
1439
1440         $groups = array();
1441
1442         foreach ($ids as $id) {
1443             $group = User_group::staticGet('id', $id);
1444             if ($group) {
1445                 $groups[] = $group;
1446             }
1447         }
1448
1449         return $groups;
1450     }
1451
1452     /**
1453      * Convert a notice into an activity for export.
1454      *
1455      * @param User $cur Current user
1456      *
1457      * @return Activity activity object representing this Notice.
1458      */
1459
1460     function asActivity($cur)
1461     {
1462         $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1463
1464         if (!empty($act)) {
1465             return $act;
1466         }
1467         $act = new Activity();
1468
1469         if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1470
1471             $profile = $this->getProfile();
1472
1473             $act->actor            = ActivityObject::fromProfile($profile);
1474             $act->actor->extra[]   = $profile->profileInfo($cur);
1475             $act->verb             = ActivityVerb::POST;
1476             $act->objects[]        = ActivityObject::fromNotice($this);
1477
1478             // XXX: should this be handled by default processing for object entry?
1479
1480             $act->time    = strtotime($this->created);
1481             $act->link    = $this->bestUrl();
1482
1483             $act->content = common_xml_safe_str($this->rendered);
1484             $act->id      = $this->uri;
1485             $act->title   = common_xml_safe_str($this->content);
1486
1487             // Categories
1488
1489             $tags = $this->getTags();
1490
1491             foreach ($tags as $tag) {
1492                 $cat       = new AtomCategory();
1493                 $cat->term = $tag;
1494
1495                 $act->categories[] = $cat;
1496             }
1497
1498             // Enclosures
1499             // XXX: use Atom Media and/or File activity objects instead
1500
1501             $attachments = $this->attachments();
1502
1503             foreach ($attachments as $attachment) {
1504                 $enclosure = $attachment->getEnclosure();
1505                 if ($enclosure) {
1506                     $act->enclosures[] = $enclosure;
1507                 }
1508             }
1509
1510             $ctx = new ActivityContext();
1511
1512             if (!empty($this->reply_to)) {
1513                 $reply = Notice::staticGet('id', $this->reply_to);
1514                 if (!empty($reply)) {
1515                     $ctx->replyToID  = $reply->uri;
1516                     $ctx->replyToUrl = $reply->bestUrl();
1517                 }
1518             }
1519
1520             $ctx->location = $this->getLocation();
1521
1522             $conv = null;
1523
1524             if (!empty($this->conversation)) {
1525                 $conv = Conversation::staticGet('id', $this->conversation);
1526                 if (!empty($conv)) {
1527                     $ctx->conversation = $conv->uri;
1528                 }
1529             }
1530
1531             $reply_ids = $this->getReplies();
1532
1533             foreach ($reply_ids as $id) {
1534                 $rprofile = Profile::staticGet('id', $id);
1535                 if (!empty($rprofile)) {
1536                     $ctx->attention[] = $rprofile->getUri();
1537                 }
1538             }
1539
1540             $groups = $this->getGroups();
1541
1542             foreach ($groups as $group) {
1543                 $ctx->attention[] = $group->getUri();
1544             }
1545
1546             // XXX: deprecated; use ActivityVerb::SHARE instead
1547
1548             $repeat = null;
1549
1550             if (!empty($this->repeat_of)) {
1551                 $repeat = Notice::staticGet('id', $this->repeat_of);
1552                 $ctx->forwardID  = $repeat->uri;
1553                 $ctx->forwardUrl = $repeat->bestUrl();
1554             }
1555
1556             $act->context = $ctx;
1557
1558             // Source
1559
1560             $atom_feed = $profile->getAtomFeed();
1561
1562             if (!empty($atom_feed)) {
1563
1564                 $act->source = new ActivitySource();
1565
1566                 // XXX: we should store the actual feed ID
1567
1568                 $act->source->id = $atom_feed;
1569
1570                 // XXX: we should store the actual feed title
1571
1572                 $act->source->title = $profile->getBestName();
1573
1574                 $act->source->links['alternate'] = $profile->profileurl;
1575                 $act->source->links['self']      = $atom_feed;
1576
1577                 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1578
1579                 $notice = $profile->getCurrentNotice();
1580
1581                 if (!empty($notice)) {
1582                     $act->source->updated = self::utcDate($notice->created);
1583                 }
1584
1585                 $user = User::staticGet('id', $profile->id);
1586
1587                 if (!empty($user)) {
1588                     $act->source->links['license'] = common_config('license', 'url');
1589                 }
1590             }
1591
1592             if ($this->isLocal()) {
1593                 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1594                                                                            'format' => 'atom'));
1595                 $act->editLink = $act->selfLink;
1596             }
1597
1598             Event::handle('EndNoticeAsActivity', array($this, &$act));
1599         }
1600
1601         self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1602
1603         return $act;
1604     }
1605
1606     // This has gotten way too long. Needs to be sliced up into functional bits
1607     // or ideally exported to a utility class.
1608
1609     function asAtomEntry($namespace=false,
1610                          $source=false,
1611                          $author=true,
1612                          $cur=null)
1613     {
1614         $act = $this->asActivity($cur);
1615         $act->extra[] = $this->noticeInfo($cur);
1616         return $act->asString($namespace, $author, $source);
1617     }
1618
1619     /**
1620      * Extra notice info for atom entries
1621      *
1622      * Clients use some extra notice info in the atom stream.
1623      * This gives it to them.
1624      *
1625      * @param User $cur Current user
1626      *
1627      * @return array representation of <statusnet:notice_info> element
1628      */
1629
1630     function noticeInfo($cur)
1631     {
1632         // local notice ID (useful to clients for ordering)
1633
1634         $noticeInfoAttr = array('local_id' => $this->id);
1635
1636         // notice source
1637
1638         $ns = $this->getSource();
1639
1640         if (!empty($ns)) {
1641             $noticeInfoAttr['source'] =  $ns->code;
1642             if (!empty($ns->url)) {
1643                 $noticeInfoAttr['source_link'] = $ns->url;
1644                 if (!empty($ns->name)) {
1645                     $noticeInfoAttr['source'] =  '<a href="'
1646                         . htmlspecialchars($ns->url)
1647                         . '" rel="nofollow">'
1648                         . htmlspecialchars($ns->name)
1649                         . '</a>';
1650                 }
1651             }
1652         }
1653
1654         // favorite and repeated
1655
1656         if (!empty($cur)) {
1657             $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1658             $cp = $cur->getProfile();
1659             $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this->id)) ? "true" : "false";
1660         }
1661
1662         if (!empty($this->repeat_of)) {
1663             $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1664         }
1665
1666         return array('statusnet:notice_info', $noticeInfoAttr, null);
1667     }
1668
1669     /**
1670      * Returns an XML string fragment with a reference to a notice as an
1671      * Activity Streams noun object with the given element type.
1672      *
1673      * Assumes that 'activity' namespace has been previously defined.
1674      *
1675      * @param string $element one of 'subject', 'object', 'target'
1676      * @return string
1677      */
1678
1679     function asActivityNoun($element)
1680     {
1681         $noun = ActivityObject::fromNotice($this);
1682         return $noun->asString('activity:' . $element);
1683     }
1684
1685     function bestUrl()
1686     {
1687         if (!empty($this->url)) {
1688             return $this->url;
1689         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1690             return $this->uri;
1691         } else {
1692             return common_local_url('shownotice',
1693                                     array('notice' => $this->id));
1694         }
1695     }
1696
1697
1698     /**
1699      * Determine which notice, if any, a new notice is in reply to.
1700      *
1701      * For conversation tracking, we try to see where this notice fits
1702      * in the tree. Rough algorithm is:
1703      *
1704      * if (reply_to is set and valid) {
1705      *     return reply_to;
1706      * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1707      *     return ID of last notice by initial @name in content;
1708      * }
1709      *
1710      * Note that all @nickname instances will still be used to save "reply" records,
1711      * so the notice shows up in the mentioned users' "replies" tab.
1712      *
1713      * @param integer $reply_to   ID passed in by Web or API
1714      * @param integer $profile_id ID of author
1715      * @param string  $source     Source tag, like 'web' or 'gwibber'
1716      * @param string  $content    Final notice content
1717      *
1718      * @return integer ID of replied-to notice, or null for not a reply.
1719      */
1720
1721     static function getReplyTo($reply_to, $profile_id, $source, $content)
1722     {
1723         static $lb = array('xmpp', 'mail', 'sms', 'omb');
1724
1725         // If $reply_to is specified, we check that it exists, and then
1726         // return it if it does
1727
1728         if (!empty($reply_to)) {
1729             $reply_notice = Notice::staticGet('id', $reply_to);
1730             if (!empty($reply_notice)) {
1731                 return $reply_notice;
1732             }
1733         }
1734
1735         // If it's not a "low bandwidth" source (one where you can't set
1736         // a reply_to argument), we return. This is mostly web and API
1737         // clients.
1738
1739         if (!in_array($source, $lb)) {
1740             return null;
1741         }
1742
1743         // Is there an initial @ or T?
1744
1745         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1746             preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1747             $nickname = common_canonical_nickname($match[1]);
1748         } else {
1749             return null;
1750         }
1751
1752         // Figure out who that is.
1753
1754         $sender = Profile::staticGet('id', $profile_id);
1755         if (empty($sender)) {
1756             return null;
1757         }
1758
1759         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1760
1761         if (empty($recipient)) {
1762             return null;
1763         }
1764
1765         // Get their last notice
1766
1767         $last = $recipient->getCurrentNotice();
1768
1769         if (!empty($last)) {
1770             return $last;
1771         }
1772
1773         return null;
1774     }
1775
1776     static function maxContent()
1777     {
1778         $contentlimit = common_config('notice', 'contentlimit');
1779         // null => use global limit (distinct from 0!)
1780         if (is_null($contentlimit)) {
1781             $contentlimit = common_config('site', 'textlimit');
1782         }
1783         return $contentlimit;
1784     }
1785
1786     static function contentTooLong($content)
1787     {
1788         $contentlimit = self::maxContent();
1789         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1790     }
1791
1792     function getLocation()
1793     {
1794         $location = null;
1795
1796         if (!empty($this->location_id) && !empty($this->location_ns)) {
1797             $location = Location::fromId($this->location_id, $this->location_ns);
1798         }
1799
1800         if (is_null($location)) { // no ID, or Location::fromId() failed
1801             if (!empty($this->lat) && !empty($this->lon)) {
1802                 $location = Location::fromLatLon($this->lat, $this->lon);
1803             }
1804         }
1805
1806         return $location;
1807     }
1808
1809     /**
1810      * Convenience function for posting a repeat of an existing message.
1811      *
1812      * @param int $repeater_id: profile ID of user doing the repeat
1813      * @param string $source: posting source key, eg 'web', 'api', etc
1814      * @return Notice
1815      *
1816      * @throws Exception on failure or permission problems
1817      */
1818     function repeat($repeater_id, $source)
1819     {
1820         $author = Profile::staticGet('id', $this->profile_id);
1821
1822         // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1823         // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1824         $content = sprintf(_('RT @%1$s %2$s'),
1825                            $author->nickname,
1826                            $this->content);
1827
1828         $maxlen = common_config('site', 'textlimit');
1829         if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1830             // Web interface and current Twitter API clients will
1831             // pull the original notice's text, but some older
1832             // clients and RSS/Atom feeds will see this trimmed text.
1833             //
1834             // Unfortunately this is likely to lose tags or URLs
1835             // at the end of long notices.
1836             $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1837         }
1838
1839         // Scope is same as this one's
1840
1841         return self::saveNew($repeater_id,
1842                              $content,
1843                              $source,
1844                              array('repeat_of' => $this->id,
1845                                    'scope' => $this->scope));
1846     }
1847
1848     // These are supposed to be in chron order!
1849
1850     function repeatStream($limit=100)
1851     {
1852         $cache = Cache::instance();
1853
1854         if (empty($cache)) {
1855             $ids = $this->_repeatStreamDirect($limit);
1856         } else {
1857             $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1858             if ($idstr !== false) {
1859                 $ids = explode(',', $idstr);
1860             } else {
1861                 $ids = $this->_repeatStreamDirect(100);
1862                 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1863             }
1864             if ($limit < 100) {
1865                 // We do a max of 100, so slice down to limit
1866                 $ids = array_slice($ids, 0, $limit);
1867             }
1868         }
1869
1870         return NoticeStream::getStreamByIds($ids);
1871     }
1872
1873     function _repeatStreamDirect($limit)
1874     {
1875         $notice = new Notice();
1876
1877         $notice->selectAdd(); // clears it
1878         $notice->selectAdd('id');
1879
1880         $notice->repeat_of = $this->id;
1881
1882         $notice->orderBy('created, id'); // NB: asc!
1883
1884         if (!is_null($limit)) {
1885             $notice->limit(0, $limit);
1886         }
1887
1888         $ids = array();
1889
1890         if ($notice->find()) {
1891             while ($notice->fetch()) {
1892                 $ids[] = $notice->id;
1893             }
1894         }
1895
1896         $notice->free();
1897         $notice = NULL;
1898
1899         return $ids;
1900     }
1901
1902     function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1903     {
1904         $options = array();
1905
1906         if (!empty($location_id) && !empty($location_ns)) {
1907             $options['location_id'] = $location_id;
1908             $options['location_ns'] = $location_ns;
1909
1910             $location = Location::fromId($location_id, $location_ns);
1911
1912             if (!empty($location)) {
1913                 $options['lat'] = $location->lat;
1914                 $options['lon'] = $location->lon;
1915             }
1916
1917         } else if (!empty($lat) && !empty($lon)) {
1918             $options['lat'] = $lat;
1919             $options['lon'] = $lon;
1920
1921             $location = Location::fromLatLon($lat, $lon);
1922
1923             if (!empty($location)) {
1924                 $options['location_id'] = $location->location_id;
1925                 $options['location_ns'] = $location->location_ns;
1926             }
1927         } else if (!empty($profile)) {
1928             if (isset($profile->lat) && isset($profile->lon)) {
1929                 $options['lat'] = $profile->lat;
1930                 $options['lon'] = $profile->lon;
1931             }
1932
1933             if (isset($profile->location_id) && isset($profile->location_ns)) {
1934                 $options['location_id'] = $profile->location_id;
1935                 $options['location_ns'] = $profile->location_ns;
1936             }
1937         }
1938
1939         return $options;
1940     }
1941
1942     function clearReplies()
1943     {
1944         $replyNotice = new Notice();
1945         $replyNotice->reply_to = $this->id;
1946
1947         //Null any notices that are replies to this notice
1948
1949         if ($replyNotice->find()) {
1950             while ($replyNotice->fetch()) {
1951                 $orig = clone($replyNotice);
1952                 $replyNotice->reply_to = null;
1953                 $replyNotice->update($orig);
1954             }
1955         }
1956
1957         // Reply records
1958
1959         $reply = new Reply();
1960         $reply->notice_id = $this->id;
1961
1962         if ($reply->find()) {
1963             while($reply->fetch()) {
1964                 self::blow('reply:stream:%d', $reply->profile_id);
1965                 $reply->delete();
1966             }
1967         }
1968
1969         $reply->free();
1970     }
1971
1972     function clearFiles()
1973     {
1974         $f2p = new File_to_post();
1975
1976         $f2p->post_id = $this->id;
1977
1978         if ($f2p->find()) {
1979             while ($f2p->fetch()) {
1980                 $f2p->delete();
1981             }
1982         }
1983         // FIXME: decide whether to delete File objects
1984         // ...and related (actual) files
1985     }
1986
1987     function clearRepeats()
1988     {
1989         $repeatNotice = new Notice();
1990         $repeatNotice->repeat_of = $this->id;
1991
1992         //Null any notices that are repeats of this notice
1993
1994         if ($repeatNotice->find()) {
1995             while ($repeatNotice->fetch()) {
1996                 $orig = clone($repeatNotice);
1997                 $repeatNotice->repeat_of = null;
1998                 $repeatNotice->update($orig);
1999             }
2000         }
2001     }
2002
2003     function clearFaves()
2004     {
2005         $fave = new Fave();
2006         $fave->notice_id = $this->id;
2007
2008         if ($fave->find()) {
2009             while ($fave->fetch()) {
2010                 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2011                 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2012                 self::blow('fave:ids_by_user:%d', $fave->user_id);
2013                 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2014                 $fave->delete();
2015             }
2016         }
2017
2018         $fave->free();
2019     }
2020
2021     function clearTags()
2022     {
2023         $tag = new Notice_tag();
2024         $tag->notice_id = $this->id;
2025
2026         if ($tag->find()) {
2027             while ($tag->fetch()) {
2028                 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2029                 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2030                 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2031                 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2032                 $tag->delete();
2033             }
2034         }
2035
2036         $tag->free();
2037     }
2038
2039     function clearGroupInboxes()
2040     {
2041         $gi = new Group_inbox();
2042
2043         $gi->notice_id = $this->id;
2044
2045         if ($gi->find()) {
2046             while ($gi->fetch()) {
2047                 self::blow('user_group:notice_ids:%d', $gi->group_id);
2048                 $gi->delete();
2049             }
2050         }
2051
2052         $gi->free();
2053     }
2054
2055     function distribute()
2056     {
2057         // We always insert for the author so they don't
2058         // have to wait
2059         Event::handle('StartNoticeDistribute', array($this));
2060
2061         $user = User::staticGet('id', $this->profile_id);
2062         if (!empty($user)) {
2063             Inbox::insertNotice($user->id, $this->id);
2064         }
2065
2066         if (common_config('queue', 'inboxes')) {
2067             // If there's a failure, we want to _force_
2068             // distribution at this point.
2069             try {
2070                 $qm = QueueManager::get();
2071                 $qm->enqueue($this, 'distrib');
2072             } catch (Exception $e) {
2073                 // If the exception isn't transient, this
2074                 // may throw more exceptions as DQH does
2075                 // its own enqueueing. So, we ignore them!
2076                 try {
2077                     $handler = new DistribQueueHandler();
2078                     $handler->handle($this);
2079                 } catch (Exception $e) {
2080                     common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2081                 }
2082                 // Re-throw so somebody smarter can handle it.
2083                 throw $e;
2084             }
2085         } else {
2086             $handler = new DistribQueueHandler();
2087             $handler->handle($this);
2088         }
2089     }
2090
2091     function insert()
2092     {
2093         $result = parent::insert();
2094
2095         if ($result) {
2096             // Profile::hasRepeated() abuses pkeyGet(), so we
2097             // have to clear manually
2098             if (!empty($this->repeat_of)) {
2099                 $c = self::memcache();
2100                 if (!empty($c)) {
2101                     $ck = self::multicacheKey('Notice',
2102                                               array('profile_id' => $this->profile_id,
2103                                                     'repeat_of' => $this->repeat_of));
2104                     $c->delete($ck);
2105                 }
2106             }
2107         }
2108
2109         return $result;
2110     }
2111
2112     /**
2113      * Get the source of the notice
2114      *
2115      * @return Notice_source $ns A notice source object. 'code' is the only attribute
2116      *                           guaranteed to be populated.
2117      */
2118     function getSource()
2119     {
2120         $ns = new Notice_source();
2121         if (!empty($this->source)) {
2122             switch ($this->source) {
2123             case 'web':
2124             case 'xmpp':
2125             case 'mail':
2126             case 'omb':
2127             case 'system':
2128             case 'api':
2129                 $ns->code = $this->source;
2130                 break;
2131             default:
2132                 $ns = Notice_source::staticGet($this->source);
2133                 if (!$ns) {
2134                     $ns = new Notice_source();
2135                     $ns->code = $this->source;
2136                     $app = Oauth_application::staticGet('name', $this->source);
2137                     if ($app) {
2138                         $ns->name = $app->name;
2139                         $ns->url  = $app->source_url;
2140                     }
2141                 }
2142                 break;
2143             }
2144         }
2145         return $ns;
2146     }
2147
2148     /**
2149      * Determine whether the notice was locally created
2150      *
2151      * @return boolean locality
2152      */
2153
2154     public function isLocal()
2155     {
2156         return ($this->is_local == Notice::LOCAL_PUBLIC ||
2157                 $this->is_local == Notice::LOCAL_NONPUBLIC);
2158     }
2159
2160     /**
2161      * Get the list of hash tags saved with this notice.
2162      *
2163      * @return array of strings
2164      */
2165     public function getTags()
2166     {
2167         $tags = array();
2168
2169         $keypart = sprintf('notice:tags:%d', $this->id);
2170
2171         $tagstr = self::cacheGet($keypart);
2172
2173         if ($tagstr !== false) {
2174             $tags = explode(',', $tagstr);
2175         } else {
2176             $tag = new Notice_tag();
2177             $tag->notice_id = $this->id;
2178             if ($tag->find()) {
2179                 while ($tag->fetch()) {
2180                     $tags[] = $tag->tag;
2181                 }
2182             }
2183             self::cacheSet($keypart, implode(',', $tags));
2184         }
2185
2186         return $tags;
2187     }
2188
2189     static private function utcDate($dt)
2190     {
2191         $dateStr = date('d F Y H:i:s', strtotime($dt));
2192         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2193         return $d->format(DATE_W3C);
2194     }
2195
2196     /**
2197      * Look up the creation timestamp for a given notice ID, even
2198      * if it's been deleted.
2199      *
2200      * @param int $id
2201      * @return mixed string recorded creation timestamp, or false if can't be found
2202      */
2203     public static function getAsTimestamp($id)
2204     {
2205         if (!$id) {
2206             return false;
2207         }
2208
2209         $notice = Notice::staticGet('id', $id);
2210         if ($notice) {
2211             return $notice->created;
2212         }
2213
2214         $deleted = Deleted_notice::staticGet('id', $id);
2215         if ($deleted) {
2216             return $deleted->created;
2217         }
2218
2219         return false;
2220     }
2221
2222     /**
2223      * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2224      * parameter, matching notices posted after the given one (exclusive).
2225      *
2226      * If the referenced notice can't be found, will return false.
2227      *
2228      * @param int $id
2229      * @param string $idField
2230      * @param string $createdField
2231      * @return mixed string or false if no match
2232      */
2233     public static function whereSinceId($id, $idField='id', $createdField='created')
2234     {
2235         $since = Notice::getAsTimestamp($id);
2236         if ($since) {
2237             return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2238         }
2239         return false;
2240     }
2241
2242     /**
2243      * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2244      * parameter, matching notices posted after the given one (exclusive), and
2245      * if necessary add it to the data object's query.
2246      *
2247      * @param DB_DataObject $obj
2248      * @param int $id
2249      * @param string $idField
2250      * @param string $createdField
2251      * @return mixed string or false if no match
2252      */
2253     public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2254     {
2255         $since = self::whereSinceId($id, $idField, $createdField);
2256         if ($since) {
2257             $obj->whereAdd($since);
2258         }
2259     }
2260
2261     /**
2262      * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2263      * parameter, matching notices posted before the given one (inclusive).
2264      *
2265      * If the referenced notice can't be found, will return false.
2266      *
2267      * @param int $id
2268      * @param string $idField
2269      * @param string $createdField
2270      * @return mixed string or false if no match
2271      */
2272     public static function whereMaxId($id, $idField='id', $createdField='created')
2273     {
2274         $max = Notice::getAsTimestamp($id);
2275         if ($max) {
2276             return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2277         }
2278         return false;
2279     }
2280
2281     /**
2282      * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2283      * parameter, matching notices posted before the given one (inclusive), and
2284      * if necessary add it to the data object's query.
2285      *
2286      * @param DB_DataObject $obj
2287      * @param int $id
2288      * @param string $idField
2289      * @param string $createdField
2290      * @return mixed string or false if no match
2291      */
2292     public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2293     {
2294         $max = self::whereMaxId($id, $idField, $createdField);
2295         if ($max) {
2296             $obj->whereAdd($max);
2297         }
2298     }
2299
2300     function isPublic()
2301     {
2302         if (common_config('public', 'localonly')) {
2303             return ($this->is_local == Notice::LOCAL_PUBLIC);
2304         } else {
2305             return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2306                     ($this->is_local != Notice::GATEWAY));
2307         }
2308     }
2309
2310     /**
2311      * Check that the given profile is allowed to read, respond to, or otherwise
2312      * act on this notice.
2313      *
2314      * The $scope member is a bitmask of scopes, representing a logical AND of the
2315      * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2316      * "only visible to people who are mentioned in the notice AND are users on this site."
2317      * Users on the site who are not mentioned in the notice will not be able to see the
2318      * notice.
2319      *
2320      * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2321      *
2322      * @return boolean whether the profile is in the notice's scope
2323      */
2324     function inScope($profile)
2325     {
2326         if (is_null($profile)) {
2327             $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2328         } else {
2329             $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2330         }
2331
2332         $result = self::cacheGet($keypart);
2333
2334         if ($result === false) {
2335             $bResult = $this->_inScope($profile);
2336             $result = ($bResult) ? 1 : 0;
2337             self::cacheSet($keypart, $result, 0, 300);
2338         }
2339
2340         return ($result == 1) ? true : false;
2341     }
2342
2343     protected function _inScope($profile)
2344     {
2345         // If there's no scope, anyone (even anon) is in scope.
2346
2347         if ($this->scope == 0) {
2348             return true;
2349         }
2350
2351         // If there's scope, anon cannot be in scope
2352
2353         if (empty($profile)) {
2354             return false;
2355         }
2356
2357         // Author is always in scope
2358
2359         if ($this->profile_id == $profile->id) {
2360             return true;
2361         }
2362
2363         // Only for users on this site
2364
2365         if ($this->scope & Notice::SITE_SCOPE) {
2366             $user = $profile->getUser();
2367             if (empty($user)) {
2368                 return false;
2369             }
2370         }
2371
2372         // Only for users mentioned in the notice
2373
2374         if ($this->scope & Notice::ADDRESSEE_SCOPE) {
2375
2376             // XXX: just query for the single reply
2377
2378             $replies = $this->getReplies();
2379
2380             if (!in_array($profile->id, $replies)) {
2381                 return false;
2382             }
2383         }
2384
2385         // Only for members of the given group
2386
2387         if ($this->scope & Notice::GROUP_SCOPE) {
2388
2389             // XXX: just query for the single membership
2390
2391             $groups = $this->getGroups();
2392
2393             $foundOne = false;
2394
2395             foreach ($groups as $group) {
2396                 if ($profile->isMember($group)) {
2397                     $foundOne = true;
2398                     break;
2399                 }
2400             }
2401
2402             if (!$foundOne) {
2403                 return false;
2404             }
2405         }
2406
2407         // Only for followers of the author
2408
2409         if ($this->scope & Notice::FOLLOWER_SCOPE) {
2410             $author = $this->getProfile();
2411             if (!Subscription::exists($profile, $author)) {
2412                 return false;
2413             }
2414         }
2415
2416         return true;
2417     }
2418
2419     static function groupsFromText($text, $profile)
2420     {
2421         $groups = array();
2422
2423         /* extract all !group */
2424         $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
2425                                 strtolower($text),
2426                                 $match);
2427
2428         if (!$count) {
2429             return $groups;
2430         }
2431
2432         foreach (array_unique($match[1]) as $nickname) {
2433             $group = User_group::getForNickname($nickname, $profile);
2434             if (!empty($group) && $profile->isMember($group)) {
2435                 $groups[] = $group->id;
2436             }
2437         }
2438
2439         return $groups;
2440     }
2441
2442     protected $_original = -1;
2443
2444     function getOriginal()
2445     {
2446         if (is_int($this->_original) && $this->_original == -1) {
2447             if (empty($this->reply_to)) {
2448                 $this->_original = null;
2449             } else {
2450                 $this->_original = Notice::staticGet('id', $this->reply_to);
2451             }
2452         }
2453         return $this->_original;
2454     }
2455
2456     /**
2457      * Magic function called at serialize() time.
2458      *
2459      * We use this to drop a couple process-specific references
2460      * from DB_DataObject which can cause trouble in future
2461      * processes.
2462      *
2463      * @return array of variable names to include in serialization.
2464      */
2465
2466     function __sleep()
2467     {
2468         $vars = parent::__sleep();
2469         $skip = array('_original', '_profile');
2470         return array_diff($vars, $skip);
2471     }
2472
2473 }