]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
70036fa8fbaeb1cfb80cc3516a8776873fb576e4
[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($peopletags)) {
549             $notice->saveProfileTags($peopletags);
550         } else {
551             $notice->saveProfileTags();
552         }
553
554         if (isset($urls)) {
555             $notice->saveKnownUrls($urls);
556         } else {
557             $notice->saveUrls();
558         }
559
560         if ($distribute) {
561             // Prepare inbox delivery, may be queued to background.
562             $notice->distribute();
563         }
564
565         return $notice;
566     }
567
568     function blowOnInsert($conversation = false)
569     {
570         self::blow('profile:notice_ids:%d', $this->profile_id);
571
572         if ($this->isPublic()) {
573             self::blow('public');
574         }
575
576         // XXX: Before we were blowing the casche only if the notice id
577         // was not the root of the conversation.  What to do now?
578
579         self::blow('notice:conversation_ids:%d', $this->conversation);
580         self::blow('conversation::notice_count:%d', $this->conversation);
581
582         if (!empty($this->repeat_of)) {
583             self::blow('notice:repeats:%d', $this->repeat_of);
584         }
585
586         $original = Notice::staticGet('id', $this->repeat_of);
587
588         if (!empty($original)) {
589             $originalUser = User::staticGet('id', $original->profile_id);
590             if (!empty($originalUser)) {
591                 self::blow('user:repeats_of_me:%d', $originalUser->id);
592             }
593         }
594
595         $profile = Profile::staticGet($this->profile_id);
596         if (!empty($profile)) {
597             $profile->blowNoticeCount();
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
623     /** save all urls in the notice to the db
624      *
625      * follow redirects and save all available file information
626      * (mimetype, date, size, oembed, etc.)
627      *
628      * @return void
629      */
630     function saveUrls() {
631         if (common_config('attachments', 'process_links')) {
632             common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
633         }
634     }
635
636     /**
637      * Save the given URLs as related links/attachments to the db
638      *
639      * follow redirects and save all available file information
640      * (mimetype, date, size, oembed, etc.)
641      *
642      * @return void
643      */
644     function saveKnownUrls($urls)
645     {
646         if (common_config('attachments', 'process_links')) {
647             // @fixme validation?
648             foreach (array_unique($urls) as $url) {
649                 File::processNew($url, $this->id);
650             }
651         }
652     }
653
654     /**
655      * @private callback
656      */
657     function saveUrl($url, $notice_id) {
658         File::processNew($url, $notice_id);
659     }
660
661     static function checkDupes($profile_id, $content) {
662         $profile = Profile::staticGet($profile_id);
663         if (empty($profile)) {
664             return false;
665         }
666         $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
667         if (!empty($notice)) {
668             $last = 0;
669             while ($notice->fetch()) {
670                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
671                     return true;
672                 } else if ($notice->content == $content) {
673                     return false;
674                 }
675             }
676         }
677         // If we get here, oldest item in cache window is not
678         // old enough for dupe limit; do direct check against DB
679         $notice = new Notice();
680         $notice->profile_id = $profile_id;
681         $notice->content = $content;
682         $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
683         $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
684
685         $cnt = $notice->count();
686         return ($cnt == 0);
687     }
688
689     static function checkEditThrottle($profile_id) {
690         $profile = Profile::staticGet($profile_id);
691         if (empty($profile)) {
692             return false;
693         }
694         // Get the Nth notice
695         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
696         if ($notice && $notice->fetch()) {
697             // If the Nth notice was posted less than timespan seconds ago
698             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
699                 // Then we throttle
700                 return false;
701             }
702         }
703         // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
704         return true;
705     }
706
707     function getUploadedAttachment() {
708         $post = clone $this;
709         $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"';
710         $post->query($query);
711         $post->fetch();
712         if (empty($post->up) || empty($post->i)) {
713             $ret = false;
714         } else {
715             $ret = array($post->up, $post->i);
716         }
717         $post->free();
718         return $ret;
719     }
720
721     function hasAttachments() {
722         $post = clone $this;
723         $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);
724         $post->query($query);
725         $post->fetch();
726         $n_attachments = intval($post->n_attachments);
727         $post->free();
728         return $n_attachments;
729     }
730
731     function attachments() {
732
733         $keypart = sprintf('notice:file_ids:%d', $this->id);
734
735         $idstr = self::cacheGet($keypart);
736
737         if ($idstr !== false) {
738             $ids = explode(',', $idstr);
739         } else {
740             $ids = array();
741             $f2p = new File_to_post;
742             $f2p->post_id = $this->id;
743             if ($f2p->find()) {
744                 while ($f2p->fetch()) {
745                     $ids[] = $f2p->file_id;
746                 }
747             }
748             self::cacheSet($keypart, implode(',', $ids));
749         }
750
751         $att = array();
752
753         foreach ($ids as $id) {
754             $f = File::staticGet('id', $id);
755             if (!empty($f)) {
756                 $att[] = clone($f);
757             }
758         }
759
760         return $att;
761     }
762
763
764     function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
765     {
766         $stream = new PublicNoticeStream();
767         return $stream->getNotices($offset, $limit, $since_id, $max_id);
768     }
769
770
771     function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
772     {
773         $stream = new ConversationNoticeStream($id);
774
775         return $stream->getNotices($offset, $limit, $since_id, $max_id);
776     }
777
778     /**
779      * Is this notice part of an active conversation?
780      *
781      * @return boolean true if other messages exist in the same
782      *                 conversation, false if this is the only one
783      */
784     function hasConversation()
785     {
786         if (!empty($this->conversation)) {
787             $conversation = Notice::conversationStream(
788                 $this->conversation,
789                 1,
790                 1
791             );
792
793             if ($conversation->N > 0) {
794                 return true;
795             }
796         }
797         return false;
798     }
799
800     /**
801      * Grab the earliest notice from this conversation.
802      *
803      * @return Notice or null
804      */
805     function conversationRoot($profile=-1)
806     {
807         // XXX: can this happen?
808
809         if (empty($this->conversation)) {
810             return null;
811         }
812
813         // Get the current profile if not specified
814
815         if (is_int($profile) && $profile == -1) {
816             $profile = Profile::current();
817         }
818
819         // If this notice is out of scope, no root for you!
820
821         if (!$this->inScope($profile)) {
822             return null;
823         }
824
825         // If this isn't a reply to anything, then it's its own
826         // root.
827
828         if (empty($this->reply_to)) {
829             return $this;
830         }
831         
832         if (is_null($profile)) {
833             $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
834         } else {
835             $keypart = sprintf('notice:conversation_root:%d:%d',
836                                $this->id,
837                                $profile->id);
838         }
839             
840         $root = self::cacheGet($keypart);
841
842         if ($root !== false && $root->inScope($profile)) {
843             return $root;
844         } else {
845             $last = $this;
846
847             do {
848                 $parent = $last->getOriginal();
849                 if (!empty($parent) && $parent->inScope($profile)) {
850                     $last = $parent;
851                     continue;
852                 } else {
853                     $root = $last;
854                     break;
855                 }
856             } while (!empty($parent));
857
858             self::cacheSet($keypart, $root);
859         }
860
861         return $root;
862     }
863
864     /**
865      * Pull up a full list of local recipients who will be getting
866      * this notice in their inbox. Results will be cached, so don't
867      * change the input data wily-nilly!
868      *
869      * @param array $groups optional list of Group objects;
870      *              if left empty, will be loaded from group_inbox records
871      * @param array $recipient optional list of reply profile ids
872      *              if left empty, will be loaded from reply records
873      * @return array associating recipient user IDs with an inbox source constant
874      */
875     function whoGets($groups=null, $recipients=null)
876     {
877         $c = self::memcache();
878
879         if (!empty($c)) {
880             $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
881             if ($ni !== false) {
882                 return $ni;
883             }
884         }
885
886         if (is_null($groups)) {
887             $groups = $this->getGroups();
888         }
889
890         if (is_null($recipients)) {
891             $recipients = $this->getReplies();
892         }
893
894         $users = $this->getSubscribedUsers();
895         $ptags = $this->getProfileTags();
896
897         // FIXME: kind of ignoring 'transitional'...
898         // we'll probably stop supporting inboxless mode
899         // in 0.9.x
900
901         $ni = array();
902
903         // Give plugins a chance to add folks in at start...
904         if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
905
906             foreach ($users as $id) {
907                 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
908             }
909
910             foreach ($groups as $group) {
911                 $users = $group->getUserMembers();
912                 foreach ($users as $id) {
913                     if (!array_key_exists($id, $ni)) {
914                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
915                     }
916                 }
917             }
918
919             foreach ($ptags as $ptag) {
920                 $users = $ptag->getUserSubscribers();
921                 foreach ($users as $id) {
922                     if (!array_key_exists($id, $ni)) {
923                         $user = User::staticGet('id', $id);
924                         if (!$user->hasBlocked($profile)) {
925                             $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
926                         }
927                     }
928                 }
929             }
930
931             foreach ($recipients as $recipient) {
932                 if (!array_key_exists($recipient, $ni)) {
933                     $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
934                 }
935
936                 // Exclude any deleted, non-local, or blocking recipients.
937                 $profile = $this->getProfile();
938                 $originalProfile = null;
939                 if ($this->repeat_of) {
940                     // Check blocks against the original notice's poster as well.
941                     $original = Notice::staticGet('id', $this->repeat_of);
942                     if ($original) {
943                         $originalProfile = $original->getProfile();
944                     }
945                 }
946                 foreach ($ni as $id => $source) {
947                     $user = User::staticGet('id', $id);
948                     if (empty($user) || $user->hasBlocked($profile) ||
949                         ($originalProfile && $user->hasBlocked($originalProfile))) {
950                         unset($ni[$id]);
951                     }
952                 }
953             }
954
955             // Give plugins a chance to filter out...
956             Event::handle('EndNoticeWhoGets', array($this, &$ni));
957         }
958
959         if (!empty($c)) {
960             // XXX: pack this data better
961             $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
962         }
963
964         return $ni;
965     }
966
967     /**
968      * Adds this notice to the inboxes of each local user who should receive
969      * it, based on author subscriptions, group memberships, and @-replies.
970      *
971      * Warning: running a second time currently will make items appear
972      * multiple times in users' inboxes.
973      *
974      * @fixme make more robust against errors
975      * @fixme break up massive deliveries to smaller background tasks
976      *
977      * @param array $groups optional list of Group objects;
978      *              if left empty, will be loaded from group_inbox records
979      * @param array $recipient optional list of reply profile ids
980      *              if left empty, will be loaded from reply records
981      */
982     function addToInboxes($groups=null, $recipients=null)
983     {
984         $ni = $this->whoGets($groups, $recipients);
985
986         $ids = array_keys($ni);
987
988         // We remove the author (if they're a local user),
989         // since we'll have already done this in distribute()
990
991         $i = array_search($this->profile_id, $ids);
992
993         if ($i !== false) {
994             unset($ids[$i]);
995         }
996
997         // Bulk insert
998
999         Inbox::bulkInsert($this->id, $ids);
1000
1001         return;
1002     }
1003
1004     function getSubscribedUsers()
1005     {
1006         $user = new User();
1007
1008         if(common_config('db','quote_identifiers'))
1009           $user_table = '"user"';
1010         else $user_table = 'user';
1011
1012         $qry =
1013           'SELECT id ' .
1014           'FROM '. $user_table .' JOIN subscription '.
1015           'ON '. $user_table .'.id = subscription.subscriber ' .
1016           'WHERE subscription.subscribed = %d ';
1017
1018         $user->query(sprintf($qry, $this->profile_id));
1019
1020         $ids = array();
1021
1022         while ($user->fetch()) {
1023             $ids[] = $user->id;
1024         }
1025
1026         $user->free();
1027
1028         return $ids;
1029     }
1030
1031     function getProfileTags()
1032     {
1033         // Don't save ptags for repeats, for now.
1034
1035         if (!empty($this->repeat_of)) {
1036             return array();
1037         }
1038
1039         // XXX: cache me
1040
1041         $ptags = array();
1042
1043         $ptagi = new Profile_tag_inbox();
1044
1045         $ptagi->selectAdd();
1046         $ptagi->selectAdd('profile_tag_id');
1047
1048         $ptagi->notice_id = $this->id;
1049
1050         if ($ptagi->find()) {
1051             while ($ptagi->fetch()) {
1052                 $profile_list = Profile_list::staticGet('id', $ptagi->profile_tag_id);
1053                 if ($profile_list) {
1054                     $ptags[] = $profile_list;
1055                 }
1056             }
1057         }
1058
1059         $ptagi->free();
1060
1061         return $ptags;
1062     }
1063
1064     /**
1065      * Record this notice to the given group inboxes for delivery.
1066      * Overrides the regular parsing of !group markup.
1067      *
1068      * @param string $group_ids
1069      * @fixme might prefer URIs as identifiers, as for replies?
1070      *        best with generalizations on user_group to support
1071      *        remote groups better.
1072      */
1073     function saveKnownGroups($group_ids)
1074     {
1075         if (!is_array($group_ids)) {
1076             // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1077             throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1078         }
1079
1080         $groups = array();
1081         foreach (array_unique($group_ids) as $id) {
1082             $group = User_group::staticGet('id', $id);
1083             if ($group) {
1084                 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1085                 $result = $this->addToGroupInbox($group);
1086                 if (!$result) {
1087                     common_log_db_error($gi, 'INSERT', __FILE__);
1088                 }
1089
1090                 // we automatically add a tag for every group name, too
1091
1092                 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1093                                                  'notice_id' => $this->id));
1094
1095                 if (is_null($tag)) {
1096                     $this->saveTag($group->nickname);
1097                 }
1098
1099                 $groups[] = clone($group);
1100             } else {
1101                 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1102             }
1103         }
1104
1105         return $groups;
1106     }
1107
1108     /**
1109      * Parse !group delivery and record targets into group_inbox.
1110      * @return array of Group objects
1111      */
1112     function saveGroups()
1113     {
1114         // Don't save groups for repeats
1115
1116         if (!empty($this->repeat_of)) {
1117             return array();
1118         }
1119
1120         $profile = $this->getProfile();
1121
1122         $groups = self::groupsFromText($this->content, $profile);
1123
1124         /* Add them to the database */
1125
1126         foreach ($groups as $group) {
1127             /* XXX: remote groups. */
1128
1129             if (empty($group)) {
1130                 continue;
1131             }
1132
1133
1134             if ($profile->isMember($group)) {
1135
1136                 $result = $this->addToGroupInbox($group);
1137
1138                 if (!$result) {
1139                     common_log_db_error($gi, 'INSERT', __FILE__);
1140                 }
1141
1142                 $groups[] = clone($group);
1143             }
1144         }
1145
1146         return $groups;
1147     }
1148
1149     function addToGroupInbox($group)
1150     {
1151         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1152                                          'notice_id' => $this->id));
1153
1154         if (empty($gi)) {
1155
1156             $gi = new Group_inbox();
1157
1158             $gi->group_id  = $group->id;
1159             $gi->notice_id = $this->id;
1160             $gi->created   = $this->created;
1161
1162             $result = $gi->insert();
1163
1164             if (!$result) {
1165                 common_log_db_error($gi, 'INSERT', __FILE__);
1166                 // TRANS: Server exception thrown when an update for a group inbox fails.
1167                 throw new ServerException(_('Problem saving group inbox.'));
1168             }
1169
1170             self::blow('user_group:notice_ids:%d', $gi->group_id);
1171         }
1172
1173         return true;
1174     }
1175
1176     /**
1177      * record targets into profile_tag_inbox.
1178      * @return array of Profile_list objects
1179      */
1180     function saveProfileTags($known=array())
1181     {
1182         // Don't save ptags for repeats, for now
1183
1184         if (!empty($this->repeat_of)) {
1185             return array();
1186         }
1187
1188         if (is_array($known)) {
1189             $ptags = $known;
1190         } else {
1191             $ptags = array();
1192         }
1193
1194         $ptag = new Profile_tag();
1195         $ptag->tagged = $this->profile_id;
1196
1197         if($ptag->find()) {
1198             while($ptag->fetch()) {
1199                 $plist = Profile_list::getByTaggerAndTag($ptag->tagger, $ptag->tag);
1200                 if (!empty($plist)) {
1201                     $ptags[] = clone($plist);
1202                 }
1203             }
1204         }
1205
1206         foreach ($ptags as $target) {
1207             $this->addToProfileTagInbox($target);
1208         }
1209
1210         return $ptags;
1211     }
1212
1213     function addToProfileTagInbox($plist)
1214     {
1215         $ptagi = Profile_tag_inbox::pkeyGet(array('profile_tag_id' => $plist->id,
1216                                          'notice_id' => $this->id));
1217
1218         if (empty($ptagi)) {
1219
1220             $ptagi = new Profile_tag_inbox();
1221
1222             $ptagi->query('BEGIN');
1223             $ptagi->profile_tag_id  = $plist->id;
1224             $ptagi->notice_id = $this->id;
1225             $ptagi->created   = $this->created;
1226
1227             $result = $ptagi->insert();
1228             if (!$result) {
1229                 common_log_db_error($ptagi, 'INSERT', __FILE__);
1230                 // TRANS: Server exception thrown when saving profile_tag inbox fails.
1231                 throw new ServerException(_('Problem saving profile_tag inbox.'));
1232             }
1233
1234             $ptagi->query('COMMIT');
1235
1236             self::blow('profile_tag:notice_ids:%d', $ptagi->profile_tag_id);
1237         }
1238
1239         return true;
1240     }
1241
1242     /**
1243      * Save reply records indicating that this notice needs to be
1244      * delivered to the local users with the given URIs.
1245      *
1246      * Since this is expected to be used when saving foreign-sourced
1247      * messages, we won't deliver to any remote targets as that's the
1248      * source service's responsibility.
1249      *
1250      * Mail notifications etc will be handled later.
1251      *
1252      * @param array of unique identifier URIs for recipients
1253      */
1254     function saveKnownReplies($uris)
1255     {
1256         if (empty($uris)) {
1257             return;
1258         }
1259
1260         $sender = Profile::staticGet($this->profile_id);
1261
1262         foreach (array_unique($uris) as $uri) {
1263
1264             $profile = Profile::fromURI($uri);
1265
1266             if (empty($profile)) {
1267                 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1268                 continue;
1269             }
1270
1271             if ($profile->hasBlocked($sender)) {
1272                 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1273                 continue;
1274             }
1275
1276             $reply = new Reply();
1277
1278             $reply->notice_id  = $this->id;
1279             $reply->profile_id = $profile->id;
1280             $reply->modified   = $this->created;
1281
1282             common_log(LOG_INFO, __METHOD__ . ": saving reply: notice $this->id to profile $profile->id");
1283
1284             $id = $reply->insert();
1285         }
1286
1287         return;
1288     }
1289
1290     /**
1291      * Pull @-replies from this message's content in StatusNet markup format
1292      * and save reply records indicating that this message needs to be
1293      * delivered to those users.
1294      *
1295      * Mail notifications to local profiles will be sent later.
1296      *
1297      * @return array of integer profile IDs
1298      */
1299
1300     function saveReplies()
1301     {
1302         // Don't save reply data for repeats
1303
1304         if (!empty($this->repeat_of)) {
1305             return array();
1306         }
1307
1308         $sender = Profile::staticGet($this->profile_id);
1309
1310         // @todo ideally this parser information would only
1311         // be calculated once.
1312
1313         $mentions = common_find_mentions($this->content, $this);
1314
1315         $replied = array();
1316
1317         // store replied only for first @ (what user/notice what the reply directed,
1318         // we assume first @ is it)
1319
1320         foreach ($mentions as $mention) {
1321
1322             foreach ($mention['mentioned'] as $mentioned) {
1323
1324                 // skip if they're already covered
1325
1326                 if (!empty($replied[$mentioned->id])) {
1327                     continue;
1328                 }
1329
1330                 // Don't save replies from blocked profile to local user
1331
1332                 $mentioned_user = User::staticGet('id', $mentioned->id);
1333                 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1334                     continue;
1335                 }
1336
1337                 $reply = new Reply();
1338
1339                 $reply->notice_id  = $this->id;
1340                 $reply->profile_id = $mentioned->id;
1341                 $reply->modified   = $this->created;
1342
1343                 $id = $reply->insert();
1344
1345                 if (!$id) {
1346                     common_log_db_error($reply, 'INSERT', __FILE__);
1347                     // TRANS: Server exception thrown when a reply cannot be saved.
1348                     // TRANS: %1$d is a notice ID, %2$d is the ID of the mentioned user.
1349                     throw new ServerException(sprintf(_('Could not save reply for %1$d, %2$d.'), $this->id, $mentioned->id));
1350                 } else {
1351                     $replied[$mentioned->id] = 1;
1352                     self::blow('reply:stream:%d', $mentioned->id);
1353                 }
1354             }
1355         }
1356
1357         $recipientIds = array_keys($replied);
1358
1359         return $recipientIds;
1360     }
1361
1362     /**
1363      * Pull the complete list of @-reply targets for this notice.
1364      *
1365      * @return array of integer profile ids
1366      */
1367     function getReplies()
1368     {
1369         $keypart = sprintf('notice:reply_ids:%d', $this->id);
1370
1371         $idstr = self::cacheGet($keypart);
1372
1373         if ($idstr !== false) {
1374             $ids = explode(',', $idstr);
1375         } else {
1376             $ids = array();
1377
1378             $reply = new Reply();
1379             $reply->selectAdd();
1380             $reply->selectAdd('profile_id');
1381             $reply->notice_id = $this->id;
1382
1383             if ($reply->find()) {
1384                 while($reply->fetch()) {
1385                     $ids[] = $reply->profile_id;
1386                 }
1387             }
1388             self::cacheSet($keypart, implode(',', $ids));
1389         }
1390
1391         return $ids;
1392     }
1393
1394     /**
1395      * Send e-mail notifications to local @-reply targets.
1396      *
1397      * Replies must already have been saved; this is expected to be run
1398      * from the distrib queue handler.
1399      */
1400     function sendReplyNotifications()
1401     {
1402         // Don't send reply notifications for repeats
1403
1404         if (!empty($this->repeat_of)) {
1405             return array();
1406         }
1407
1408         $recipientIds = $this->getReplies();
1409
1410         foreach ($recipientIds as $recipientId) {
1411             $user = User::staticGet('id', $recipientId);
1412             if (!empty($user)) {
1413                 mail_notify_attn($user, $this);
1414             }
1415         }
1416     }
1417
1418     /**
1419      * Pull list of groups this notice needs to be delivered to,
1420      * as previously recorded by saveGroups() or saveKnownGroups().
1421      *
1422      * @return array of Group objects
1423      */
1424     function getGroups()
1425     {
1426         // Don't save groups for repeats
1427
1428         if (!empty($this->repeat_of)) {
1429             return array();
1430         }
1431
1432         $ids = array();
1433
1434         $keypart = sprintf('notice:groups:%d', $this->id);
1435
1436         $idstr = self::cacheGet($keypart);
1437
1438         if ($idstr !== false) {
1439             $ids = explode(',', $idstr);
1440         } else {
1441             $gi = new Group_inbox();
1442
1443             $gi->selectAdd();
1444             $gi->selectAdd('group_id');
1445
1446             $gi->notice_id = $this->id;
1447
1448             if ($gi->find()) {
1449                 while ($gi->fetch()) {
1450                     $ids[] = $gi->group_id;
1451                 }
1452             }
1453
1454             self::cacheSet($keypart, implode(',', $ids));
1455         }
1456
1457         $groups = array();
1458
1459         foreach ($ids as $id) {
1460             $group = User_group::staticGet('id', $id);
1461             if ($group) {
1462                 $groups[] = $group;
1463             }
1464         }
1465
1466         return $groups;
1467     }
1468
1469     /**
1470      * Convert a notice into an activity for export.
1471      *
1472      * @param User $cur Current user
1473      *
1474      * @return Activity activity object representing this Notice.
1475      */
1476
1477     function asActivity($cur)
1478     {
1479         $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1480
1481         if (!empty($act)) {
1482             return $act;
1483         }
1484         $act = new Activity();
1485
1486         if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1487
1488             $profile = $this->getProfile();
1489
1490             $act->actor            = ActivityObject::fromProfile($profile);
1491             $act->actor->extra[]   = $profile->profileInfo($cur);
1492             $act->verb             = ActivityVerb::POST;
1493             $act->objects[]        = ActivityObject::fromNotice($this);
1494
1495             // XXX: should this be handled by default processing for object entry?
1496
1497             $act->time    = strtotime($this->created);
1498             $act->link    = $this->bestUrl();
1499
1500             $act->content = common_xml_safe_str($this->rendered);
1501             $act->id      = $this->uri;
1502             $act->title   = common_xml_safe_str($this->content);
1503
1504             // Categories
1505
1506             $tags = $this->getTags();
1507
1508             foreach ($tags as $tag) {
1509                 $cat       = new AtomCategory();
1510                 $cat->term = $tag;
1511
1512                 $act->categories[] = $cat;
1513             }
1514
1515             // Enclosures
1516             // XXX: use Atom Media and/or File activity objects instead
1517
1518             $attachments = $this->attachments();
1519
1520             foreach ($attachments as $attachment) {
1521                 $enclosure = $attachment->getEnclosure();
1522                 if ($enclosure) {
1523                     $act->enclosures[] = $enclosure;
1524                 }
1525             }
1526
1527             $ctx = new ActivityContext();
1528
1529             if (!empty($this->reply_to)) {
1530                 $reply = Notice::staticGet('id', $this->reply_to);
1531                 if (!empty($reply)) {
1532                     $ctx->replyToID  = $reply->uri;
1533                     $ctx->replyToUrl = $reply->bestUrl();
1534                 }
1535             }
1536
1537             $ctx->location = $this->getLocation();
1538
1539             $conv = null;
1540
1541             if (!empty($this->conversation)) {
1542                 $conv = Conversation::staticGet('id', $this->conversation);
1543                 if (!empty($conv)) {
1544                     $ctx->conversation = $conv->uri;
1545                 }
1546             }
1547
1548             $reply_ids = $this->getReplies();
1549
1550             foreach ($reply_ids as $id) {
1551                 $rprofile = Profile::staticGet('id', $id);
1552                 if (!empty($rprofile)) {
1553                     $ctx->attention[] = $rprofile->getUri();
1554                 }
1555             }
1556
1557             $groups = $this->getGroups();
1558
1559             foreach ($groups as $group) {
1560                 $ctx->attention[] = $group->getUri();
1561             }
1562
1563             // XXX: deprecated; use ActivityVerb::SHARE instead
1564
1565             $repeat = null;
1566
1567             if (!empty($this->repeat_of)) {
1568                 $repeat = Notice::staticGet('id', $this->repeat_of);
1569                 $ctx->forwardID  = $repeat->uri;
1570                 $ctx->forwardUrl = $repeat->bestUrl();
1571             }
1572
1573             $act->context = $ctx;
1574
1575             // Source
1576
1577             $atom_feed = $profile->getAtomFeed();
1578
1579             if (!empty($atom_feed)) {
1580
1581                 $act->source = new ActivitySource();
1582
1583                 // XXX: we should store the actual feed ID
1584
1585                 $act->source->id = $atom_feed;
1586
1587                 // XXX: we should store the actual feed title
1588
1589                 $act->source->title = $profile->getBestName();
1590
1591                 $act->source->links['alternate'] = $profile->profileurl;
1592                 $act->source->links['self']      = $atom_feed;
1593
1594                 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1595
1596                 $notice = $profile->getCurrentNotice();
1597
1598                 if (!empty($notice)) {
1599                     $act->source->updated = self::utcDate($notice->created);
1600                 }
1601
1602                 $user = User::staticGet('id', $profile->id);
1603
1604                 if (!empty($user)) {
1605                     $act->source->links['license'] = common_config('license', 'url');
1606                 }
1607             }
1608
1609             if ($this->isLocal()) {
1610                 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1611                                                                            'format' => 'atom'));
1612                 $act->editLink = $act->selfLink;
1613             }
1614
1615             Event::handle('EndNoticeAsActivity', array($this, &$act));
1616         }
1617
1618         self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1619
1620         return $act;
1621     }
1622
1623     // This has gotten way too long. Needs to be sliced up into functional bits
1624     // or ideally exported to a utility class.
1625
1626     function asAtomEntry($namespace=false,
1627                          $source=false,
1628                          $author=true,
1629                          $cur=null)
1630     {
1631         $act = $this->asActivity($cur);
1632         $act->extra[] = $this->noticeInfo($cur);
1633         return $act->asString($namespace, $author, $source);
1634     }
1635
1636     /**
1637      * Extra notice info for atom entries
1638      *
1639      * Clients use some extra notice info in the atom stream.
1640      * This gives it to them.
1641      *
1642      * @param User $cur Current user
1643      *
1644      * @return array representation of <statusnet:notice_info> element
1645      */
1646
1647     function noticeInfo($cur)
1648     {
1649         // local notice ID (useful to clients for ordering)
1650
1651         $noticeInfoAttr = array('local_id' => $this->id);
1652
1653         // notice source
1654
1655         $ns = $this->getSource();
1656
1657         if (!empty($ns)) {
1658             $noticeInfoAttr['source'] =  $ns->code;
1659             if (!empty($ns->url)) {
1660                 $noticeInfoAttr['source_link'] = $ns->url;
1661                 if (!empty($ns->name)) {
1662                     $noticeInfoAttr['source'] =  '<a href="'
1663                         . htmlspecialchars($ns->url)
1664                         . '" rel="nofollow">'
1665                         . htmlspecialchars($ns->name)
1666                         . '</a>';
1667                 }
1668             }
1669         }
1670
1671         // favorite and repeated
1672
1673         if (!empty($cur)) {
1674             $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1675             $cp = $cur->getProfile();
1676             $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this->id)) ? "true" : "false";
1677         }
1678
1679         if (!empty($this->repeat_of)) {
1680             $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1681         }
1682
1683         return array('statusnet:notice_info', $noticeInfoAttr, null);
1684     }
1685
1686     /**
1687      * Returns an XML string fragment with a reference to a notice as an
1688      * Activity Streams noun object with the given element type.
1689      *
1690      * Assumes that 'activity' namespace has been previously defined.
1691      *
1692      * @param string $element one of 'subject', 'object', 'target'
1693      * @return string
1694      */
1695
1696     function asActivityNoun($element)
1697     {
1698         $noun = ActivityObject::fromNotice($this);
1699         return $noun->asString('activity:' . $element);
1700     }
1701
1702     function bestUrl()
1703     {
1704         if (!empty($this->url)) {
1705             return $this->url;
1706         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1707             return $this->uri;
1708         } else {
1709             return common_local_url('shownotice',
1710                                     array('notice' => $this->id));
1711         }
1712     }
1713
1714
1715     /**
1716      * Determine which notice, if any, a new notice is in reply to.
1717      *
1718      * For conversation tracking, we try to see where this notice fits
1719      * in the tree. Rough algorithm is:
1720      *
1721      * if (reply_to is set and valid) {
1722      *     return reply_to;
1723      * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1724      *     return ID of last notice by initial @name in content;
1725      * }
1726      *
1727      * Note that all @nickname instances will still be used to save "reply" records,
1728      * so the notice shows up in the mentioned users' "replies" tab.
1729      *
1730      * @param integer $reply_to   ID passed in by Web or API
1731      * @param integer $profile_id ID of author
1732      * @param string  $source     Source tag, like 'web' or 'gwibber'
1733      * @param string  $content    Final notice content
1734      *
1735      * @return integer ID of replied-to notice, or null for not a reply.
1736      */
1737
1738     static function getReplyTo($reply_to, $profile_id, $source, $content)
1739     {
1740         static $lb = array('xmpp', 'mail', 'sms', 'omb');
1741
1742         // If $reply_to is specified, we check that it exists, and then
1743         // return it if it does
1744
1745         if (!empty($reply_to)) {
1746             $reply_notice = Notice::staticGet('id', $reply_to);
1747             if (!empty($reply_notice)) {
1748                 return $reply_notice;
1749             }
1750         }
1751
1752         // If it's not a "low bandwidth" source (one where you can't set
1753         // a reply_to argument), we return. This is mostly web and API
1754         // clients.
1755
1756         if (!in_array($source, $lb)) {
1757             return null;
1758         }
1759
1760         // Is there an initial @ or T?
1761
1762         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1763             preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1764             $nickname = common_canonical_nickname($match[1]);
1765         } else {
1766             return null;
1767         }
1768
1769         // Figure out who that is.
1770
1771         $sender = Profile::staticGet('id', $profile_id);
1772         if (empty($sender)) {
1773             return null;
1774         }
1775
1776         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1777
1778         if (empty($recipient)) {
1779             return null;
1780         }
1781
1782         // Get their last notice
1783
1784         $last = $recipient->getCurrentNotice();
1785
1786         if (!empty($last)) {
1787             return $last;
1788         }
1789
1790         return null;
1791     }
1792
1793     static function maxContent()
1794     {
1795         $contentlimit = common_config('notice', 'contentlimit');
1796         // null => use global limit (distinct from 0!)
1797         if (is_null($contentlimit)) {
1798             $contentlimit = common_config('site', 'textlimit');
1799         }
1800         return $contentlimit;
1801     }
1802
1803     static function contentTooLong($content)
1804     {
1805         $contentlimit = self::maxContent();
1806         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1807     }
1808
1809     function getLocation()
1810     {
1811         $location = null;
1812
1813         if (!empty($this->location_id) && !empty($this->location_ns)) {
1814             $location = Location::fromId($this->location_id, $this->location_ns);
1815         }
1816
1817         if (is_null($location)) { // no ID, or Location::fromId() failed
1818             if (!empty($this->lat) && !empty($this->lon)) {
1819                 $location = Location::fromLatLon($this->lat, $this->lon);
1820             }
1821         }
1822
1823         return $location;
1824     }
1825
1826     /**
1827      * Convenience function for posting a repeat of an existing message.
1828      *
1829      * @param int $repeater_id: profile ID of user doing the repeat
1830      * @param string $source: posting source key, eg 'web', 'api', etc
1831      * @return Notice
1832      *
1833      * @throws Exception on failure or permission problems
1834      */
1835     function repeat($repeater_id, $source)
1836     {
1837         $author = Profile::staticGet('id', $this->profile_id);
1838
1839         // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1840         // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1841         $content = sprintf(_('RT @%1$s %2$s'),
1842                            $author->nickname,
1843                            $this->content);
1844
1845         $maxlen = common_config('site', 'textlimit');
1846         if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1847             // Web interface and current Twitter API clients will
1848             // pull the original notice's text, but some older
1849             // clients and RSS/Atom feeds will see this trimmed text.
1850             //
1851             // Unfortunately this is likely to lose tags or URLs
1852             // at the end of long notices.
1853             $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1854         }
1855
1856         // Scope is same as this one's
1857
1858         return self::saveNew($repeater_id,
1859                              $content,
1860                              $source,
1861                              array('repeat_of' => $this->id,
1862                                    'scope' => $this->scope));
1863     }
1864
1865     // These are supposed to be in chron order!
1866
1867     function repeatStream($limit=100)
1868     {
1869         $cache = Cache::instance();
1870
1871         if (empty($cache)) {
1872             $ids = $this->_repeatStreamDirect($limit);
1873         } else {
1874             $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1875             if ($idstr !== false) {
1876                 $ids = explode(',', $idstr);
1877             } else {
1878                 $ids = $this->_repeatStreamDirect(100);
1879                 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1880             }
1881             if ($limit < 100) {
1882                 // We do a max of 100, so slice down to limit
1883                 $ids = array_slice($ids, 0, $limit);
1884             }
1885         }
1886
1887         return NoticeStream::getStreamByIds($ids);
1888     }
1889
1890     function _repeatStreamDirect($limit)
1891     {
1892         $notice = new Notice();
1893
1894         $notice->selectAdd(); // clears it
1895         $notice->selectAdd('id');
1896
1897         $notice->repeat_of = $this->id;
1898
1899         $notice->orderBy('created, id'); // NB: asc!
1900
1901         if (!is_null($limit)) {
1902             $notice->limit(0, $limit);
1903         }
1904
1905         $ids = array();
1906
1907         if ($notice->find()) {
1908             while ($notice->fetch()) {
1909                 $ids[] = $notice->id;
1910             }
1911         }
1912
1913         $notice->free();
1914         $notice = NULL;
1915
1916         return $ids;
1917     }
1918
1919     function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1920     {
1921         $options = array();
1922
1923         if (!empty($location_id) && !empty($location_ns)) {
1924             $options['location_id'] = $location_id;
1925             $options['location_ns'] = $location_ns;
1926
1927             $location = Location::fromId($location_id, $location_ns);
1928
1929             if (!empty($location)) {
1930                 $options['lat'] = $location->lat;
1931                 $options['lon'] = $location->lon;
1932             }
1933
1934         } else if (!empty($lat) && !empty($lon)) {
1935             $options['lat'] = $lat;
1936             $options['lon'] = $lon;
1937
1938             $location = Location::fromLatLon($lat, $lon);
1939
1940             if (!empty($location)) {
1941                 $options['location_id'] = $location->location_id;
1942                 $options['location_ns'] = $location->location_ns;
1943             }
1944         } else if (!empty($profile)) {
1945             if (isset($profile->lat) && isset($profile->lon)) {
1946                 $options['lat'] = $profile->lat;
1947                 $options['lon'] = $profile->lon;
1948             }
1949
1950             if (isset($profile->location_id) && isset($profile->location_ns)) {
1951                 $options['location_id'] = $profile->location_id;
1952                 $options['location_ns'] = $profile->location_ns;
1953             }
1954         }
1955
1956         return $options;
1957     }
1958
1959     function clearReplies()
1960     {
1961         $replyNotice = new Notice();
1962         $replyNotice->reply_to = $this->id;
1963
1964         //Null any notices that are replies to this notice
1965
1966         if ($replyNotice->find()) {
1967             while ($replyNotice->fetch()) {
1968                 $orig = clone($replyNotice);
1969                 $replyNotice->reply_to = null;
1970                 $replyNotice->update($orig);
1971             }
1972         }
1973
1974         // Reply records
1975
1976         $reply = new Reply();
1977         $reply->notice_id = $this->id;
1978
1979         if ($reply->find()) {
1980             while($reply->fetch()) {
1981                 self::blow('reply:stream:%d', $reply->profile_id);
1982                 $reply->delete();
1983             }
1984         }
1985
1986         $reply->free();
1987     }
1988
1989     function clearFiles()
1990     {
1991         $f2p = new File_to_post();
1992
1993         $f2p->post_id = $this->id;
1994
1995         if ($f2p->find()) {
1996             while ($f2p->fetch()) {
1997                 $f2p->delete();
1998             }
1999         }
2000         // FIXME: decide whether to delete File objects
2001         // ...and related (actual) files
2002     }
2003
2004     function clearRepeats()
2005     {
2006         $repeatNotice = new Notice();
2007         $repeatNotice->repeat_of = $this->id;
2008
2009         //Null any notices that are repeats of this notice
2010
2011         if ($repeatNotice->find()) {
2012             while ($repeatNotice->fetch()) {
2013                 $orig = clone($repeatNotice);
2014                 $repeatNotice->repeat_of = null;
2015                 $repeatNotice->update($orig);
2016             }
2017         }
2018     }
2019
2020     function clearFaves()
2021     {
2022         $fave = new Fave();
2023         $fave->notice_id = $this->id;
2024
2025         if ($fave->find()) {
2026             while ($fave->fetch()) {
2027                 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2028                 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2029                 self::blow('fave:ids_by_user:%d', $fave->user_id);
2030                 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2031                 $fave->delete();
2032             }
2033         }
2034
2035         $fave->free();
2036     }
2037
2038     function clearTags()
2039     {
2040         $tag = new Notice_tag();
2041         $tag->notice_id = $this->id;
2042
2043         if ($tag->find()) {
2044             while ($tag->fetch()) {
2045                 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2046                 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2047                 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2048                 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2049                 $tag->delete();
2050             }
2051         }
2052
2053         $tag->free();
2054     }
2055
2056     function clearGroupInboxes()
2057     {
2058         $gi = new Group_inbox();
2059
2060         $gi->notice_id = $this->id;
2061
2062         if ($gi->find()) {
2063             while ($gi->fetch()) {
2064                 self::blow('user_group:notice_ids:%d', $gi->group_id);
2065                 $gi->delete();
2066             }
2067         }
2068
2069         $gi->free();
2070     }
2071
2072     function distribute()
2073     {
2074         // We always insert for the author so they don't
2075         // have to wait
2076         Event::handle('StartNoticeDistribute', array($this));
2077
2078         $user = User::staticGet('id', $this->profile_id);
2079         if (!empty($user)) {
2080             Inbox::insertNotice($user->id, $this->id);
2081         }
2082
2083         if (common_config('queue', 'inboxes')) {
2084             // If there's a failure, we want to _force_
2085             // distribution at this point.
2086             try {
2087                 $qm = QueueManager::get();
2088                 $qm->enqueue($this, 'distrib');
2089             } catch (Exception $e) {
2090                 // If the exception isn't transient, this
2091                 // may throw more exceptions as DQH does
2092                 // its own enqueueing. So, we ignore them!
2093                 try {
2094                     $handler = new DistribQueueHandler();
2095                     $handler->handle($this);
2096                 } catch (Exception $e) {
2097                     common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2098                 }
2099                 // Re-throw so somebody smarter can handle it.
2100                 throw $e;
2101             }
2102         } else {
2103             $handler = new DistribQueueHandler();
2104             $handler->handle($this);
2105         }
2106     }
2107
2108     function insert()
2109     {
2110         $result = parent::insert();
2111
2112         if ($result) {
2113             // Profile::hasRepeated() abuses pkeyGet(), so we
2114             // have to clear manually
2115             if (!empty($this->repeat_of)) {
2116                 $c = self::memcache();
2117                 if (!empty($c)) {
2118                     $ck = self::multicacheKey('Notice',
2119                                               array('profile_id' => $this->profile_id,
2120                                                     'repeat_of' => $this->repeat_of));
2121                     $c->delete($ck);
2122                 }
2123             }
2124         }
2125
2126         return $result;
2127     }
2128
2129     /**
2130      * Get the source of the notice
2131      *
2132      * @return Notice_source $ns A notice source object. 'code' is the only attribute
2133      *                           guaranteed to be populated.
2134      */
2135     function getSource()
2136     {
2137         $ns = new Notice_source();
2138         if (!empty($this->source)) {
2139             switch ($this->source) {
2140             case 'web':
2141             case 'xmpp':
2142             case 'mail':
2143             case 'omb':
2144             case 'system':
2145             case 'api':
2146                 $ns->code = $this->source;
2147                 break;
2148             default:
2149                 $ns = Notice_source::staticGet($this->source);
2150                 if (!$ns) {
2151                     $ns = new Notice_source();
2152                     $ns->code = $this->source;
2153                     $app = Oauth_application::staticGet('name', $this->source);
2154                     if ($app) {
2155                         $ns->name = $app->name;
2156                         $ns->url  = $app->source_url;
2157                     }
2158                 }
2159                 break;
2160             }
2161         }
2162         return $ns;
2163     }
2164
2165     /**
2166      * Determine whether the notice was locally created
2167      *
2168      * @return boolean locality
2169      */
2170
2171     public function isLocal()
2172     {
2173         return ($this->is_local == Notice::LOCAL_PUBLIC ||
2174                 $this->is_local == Notice::LOCAL_NONPUBLIC);
2175     }
2176
2177     /**
2178      * Get the list of hash tags saved with this notice.
2179      *
2180      * @return array of strings
2181      */
2182     public function getTags()
2183     {
2184         $tags = array();
2185
2186         $keypart = sprintf('notice:tags:%d', $this->id);
2187
2188         $tagstr = self::cacheGet($keypart);
2189
2190         if ($tagstr !== false) {
2191             $tags = explode(',', $tagstr);
2192         } else {
2193             $tag = new Notice_tag();
2194             $tag->notice_id = $this->id;
2195             if ($tag->find()) {
2196                 while ($tag->fetch()) {
2197                     $tags[] = $tag->tag;
2198                 }
2199             }
2200             self::cacheSet($keypart, implode(',', $tags));
2201         }
2202
2203         return $tags;
2204     }
2205
2206     static private function utcDate($dt)
2207     {
2208         $dateStr = date('d F Y H:i:s', strtotime($dt));
2209         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2210         return $d->format(DATE_W3C);
2211     }
2212
2213     /**
2214      * Look up the creation timestamp for a given notice ID, even
2215      * if it's been deleted.
2216      *
2217      * @param int $id
2218      * @return mixed string recorded creation timestamp, or false if can't be found
2219      */
2220     public static function getAsTimestamp($id)
2221     {
2222         if (!$id) {
2223             return false;
2224         }
2225
2226         $notice = Notice::staticGet('id', $id);
2227         if ($notice) {
2228             return $notice->created;
2229         }
2230
2231         $deleted = Deleted_notice::staticGet('id', $id);
2232         if ($deleted) {
2233             return $deleted->created;
2234         }
2235
2236         return false;
2237     }
2238
2239     /**
2240      * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2241      * parameter, matching notices posted after the given one (exclusive).
2242      *
2243      * If the referenced notice can't be found, will return false.
2244      *
2245      * @param int $id
2246      * @param string $idField
2247      * @param string $createdField
2248      * @return mixed string or false if no match
2249      */
2250     public static function whereSinceId($id, $idField='id', $createdField='created')
2251     {
2252         $since = Notice::getAsTimestamp($id);
2253         if ($since) {
2254             return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2255         }
2256         return false;
2257     }
2258
2259     /**
2260      * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2261      * parameter, matching notices posted after the given one (exclusive), and
2262      * if necessary add it to the data object's query.
2263      *
2264      * @param DB_DataObject $obj
2265      * @param int $id
2266      * @param string $idField
2267      * @param string $createdField
2268      * @return mixed string or false if no match
2269      */
2270     public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2271     {
2272         $since = self::whereSinceId($id, $idField, $createdField);
2273         if ($since) {
2274             $obj->whereAdd($since);
2275         }
2276     }
2277
2278     /**
2279      * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2280      * parameter, matching notices posted before the given one (inclusive).
2281      *
2282      * If the referenced notice can't be found, will return false.
2283      *
2284      * @param int $id
2285      * @param string $idField
2286      * @param string $createdField
2287      * @return mixed string or false if no match
2288      */
2289     public static function whereMaxId($id, $idField='id', $createdField='created')
2290     {
2291         $max = Notice::getAsTimestamp($id);
2292         if ($max) {
2293             return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2294         }
2295         return false;
2296     }
2297
2298     /**
2299      * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2300      * parameter, matching notices posted before the given one (inclusive), and
2301      * if necessary add it to the data object's query.
2302      *
2303      * @param DB_DataObject $obj
2304      * @param int $id
2305      * @param string $idField
2306      * @param string $createdField
2307      * @return mixed string or false if no match
2308      */
2309     public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2310     {
2311         $max = self::whereMaxId($id, $idField, $createdField);
2312         if ($max) {
2313             $obj->whereAdd($max);
2314         }
2315     }
2316
2317     function isPublic()
2318     {
2319         if (common_config('public', 'localonly')) {
2320             return ($this->is_local == Notice::LOCAL_PUBLIC);
2321         } else {
2322             return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2323                     ($this->is_local != Notice::GATEWAY));
2324         }
2325     }
2326
2327     /**
2328      * Check that the given profile is allowed to read, respond to, or otherwise
2329      * act on this notice.
2330      *
2331      * The $scope member is a bitmask of scopes, representing a logical AND of the
2332      * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2333      * "only visible to people who are mentioned in the notice AND are users on this site."
2334      * Users on the site who are not mentioned in the notice will not be able to see the
2335      * notice.
2336      *
2337      * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2338      *
2339      * @return boolean whether the profile is in the notice's scope
2340      */
2341     function inScope($profile)
2342     {
2343         if (is_null($profile)) {
2344             $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2345         } else {
2346             $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2347         }
2348
2349         $result = self::cacheGet($keypart);
2350
2351         if ($result === false) {
2352             $bResult = $this->_inScope($profile);
2353             $result = ($bResult) ? 1 : 0;
2354             self::cacheSet($keypart, $result, 0, 300);
2355         }
2356
2357         return ($result == 1) ? true : false;
2358     }
2359
2360     protected function _inScope($profile)
2361     {
2362         // If there's no scope, anyone (even anon) is in scope.
2363
2364         if ($this->scope == 0) {
2365             return true;
2366         }
2367
2368         // If there's scope, anon cannot be in scope
2369
2370         if (empty($profile)) {
2371             return false;
2372         }
2373
2374         // Author is always in scope
2375
2376         if ($this->profile_id == $profile->id) {
2377             return true;
2378         }
2379
2380         // Only for users on this site
2381
2382         if ($this->scope & Notice::SITE_SCOPE) {
2383             $user = $profile->getUser();
2384             if (empty($user)) {
2385                 return false;
2386             }
2387         }
2388
2389         // Only for users mentioned in the notice
2390
2391         if ($this->scope & Notice::ADDRESSEE_SCOPE) {
2392
2393             // XXX: just query for the single reply
2394
2395             $replies = $this->getReplies();
2396
2397             if (!in_array($profile->id, $replies)) {
2398                 return false;
2399             }
2400         }
2401
2402         // Only for members of the given group
2403
2404         if ($this->scope & Notice::GROUP_SCOPE) {
2405
2406             // XXX: just query for the single membership
2407
2408             $groups = $this->getGroups();
2409
2410             $foundOne = false;
2411
2412             foreach ($groups as $group) {
2413                 if ($profile->isMember($group)) {
2414                     $foundOne = true;
2415                     break;
2416                 }
2417             }
2418
2419             if (!$foundOne) {
2420                 return false;
2421             }
2422         }
2423
2424         // Only for followers of the author
2425
2426         if ($this->scope & Notice::FOLLOWER_SCOPE) {
2427             $author = $this->getProfile();
2428             if (!Subscription::exists($profile, $author)) {
2429                 return false;
2430             }
2431         }
2432
2433         return true;
2434     }
2435
2436     static function groupsFromText($text, $profile)
2437     {
2438         $groups = array();
2439
2440         /* extract all !group */
2441         $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
2442                                 strtolower($text),
2443                                 $match);
2444
2445         if (!$count) {
2446             return $groups;
2447         }
2448
2449         foreach (array_unique($match[1]) as $nickname) {
2450             $group = User_group::getForNickname($nickname, $profile);
2451             if (!empty($group) && $profile->isMember($group)) {
2452                 $groups[] = $group->id;
2453             }
2454         }
2455
2456         return $groups;
2457     }
2458
2459     protected $_original = -1;
2460
2461     function getOriginal()
2462     {
2463         if (is_int($this->_original) && $this->_original == -1) {
2464             if (empty($this->reply_to)) {
2465                 $this->_original = null;
2466             } else {
2467                 $this->_original = Notice::staticGet('id', $this->reply_to);
2468             }
2469         }
2470         return $this->_original;
2471     }
2472 }