]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
*** Privacy Leak fixed: ***
[quix0rs-gnu-social.git] / classes / Notice.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008-2011 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  * @author   Mikael Nordfeldth <mmn@hethane.se>
33  * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
34  * @license  GNU Affero General Public License http://www.gnu.org/licenses/
35  */
36
37 if (!defined('GNUSOCIAL')) { exit(1); }
38
39 /**
40  * Table Definition for notice
41  */
42
43 /* We keep 200 notices, the max number of notices available per API request,
44  * in the memcached cache. */
45
46 define('NOTICE_CACHE_WINDOW', CachingNoticeStream::CACHE_WINDOW);
47
48 define('MAX_BOXCARS', 128);
49
50 class Notice extends Managed_DataObject
51 {
52     ###START_AUTOCODE
53     /* the code below is auto generated do not remove the above tag */
54
55     public $__table = 'notice';                          // table name
56     public $id;                              // int(4)  primary_key not_null
57     public $profile_id;                      // int(4)  multiple_key not_null
58     public $uri;                             // varchar(191)  unique_key   not 255 because utf8mb4 takes more space
59     public $content;                         // text
60     public $rendered;                        // text
61     public $url;                             // varchar(191)   not 255 because utf8mb4 takes more space
62     public $created;                         // datetime  multiple_key not_null default_0000-00-00%2000%3A00%3A00
63     public $modified;                        // timestamp   not_null default_CURRENT_TIMESTAMP
64     public $reply_to;                        // int(4)
65     public $is_local;                        // int(4)
66     public $source;                          // varchar(32)
67     public $conversation;                    // int(4)
68     public $lat;                             // decimal(10,7)
69     public $lon;                             // decimal(10,7)
70     public $location_id;                     // int(4)
71     public $location_ns;                     // int(4)
72     public $repeat_of;                       // int(4)
73     public $verb;                            // varchar(191)   not 255 because utf8mb4 takes more space
74     public $object_type;                     // varchar(191)   not 255 because utf8mb4 takes more space
75     public $scope;                           // int(4)
76
77     /* the code above is auto generated do not remove the tag below */
78     ###END_AUTOCODE
79
80     public static function schemaDef()
81     {
82         $def = array(
83             'fields' => array(
84                 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
85                 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'who made the update'),
86                 'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universally unique identifier, usually a tag URI'),
87                 'content' => array('type' => 'text', 'description' => 'update content', 'collate' => 'utf8_general_ci'),
88                 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
89                 'url' => array('type' => 'varchar', 'length' => 191, 'description' => 'URL of any attachment (image, video, bookmark, whatever)'),
90                 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
91                 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
92                 'reply_to' => array('type' => 'int', 'description' => 'notice replied to (usually a guess)'),
93                 'is_local' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'notice was generated by a user'),
94                 'source' => array('type' => 'varchar', 'length' => 32, 'description' => 'source of comment, like "web", "im", or "clientname"'),
95                 'conversation' => array('type' => 'int', 'description' => 'id of root notice in this conversation'),
96                 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
97                 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
98                 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
99                 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
100                 'repeat_of' => array('type' => 'int', 'description' => 'notice this is a repeat of'),
101                 'object_type' => array('type' => 'varchar', 'length' => 191, 'description' => 'URI representing activity streams object type', 'default' => 'http://activitystrea.ms/schema/1.0/note'),
102                 'verb' => array('type' => 'varchar', 'length' => 191, 'description' => 'URI representing activity streams verb', 'default' => 'http://activitystrea.ms/schema/1.0/post'),
103                 'scope' => array('type' => 'int',
104                                  'description' => 'bit map for distribution scope; 0 = everywhere; 1 = this server only; 2 = addressees; 4 = followers; null = default'),
105             ),
106             'primary key' => array('id'),
107             'unique keys' => array(
108                 'notice_uri_key' => array('uri'),
109             ),
110             'foreign keys' => array(
111                 'notice_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
112                 'notice_reply_to_fkey' => array('notice', array('reply_to' => 'id')),
113                 'notice_conversation_fkey' => array('conversation', array('conversation' => 'id')), # note... used to refer to notice.id
114                 'notice_repeat_of_fkey' => array('notice', array('repeat_of' => 'id')), # @fixme: what about repeats of deleted notices?
115             ),
116             'indexes' => array(
117                 'notice_created_id_is_local_idx' => array('created', 'id', 'is_local'),
118                 'notice_profile_id_idx' => array('profile_id', 'created', 'id'),
119                 'notice_repeat_of_created_id_idx' => array('repeat_of', 'created', 'id'),
120                 'notice_conversation_created_id_idx' => array('conversation', 'created', 'id'),
121                 'notice_replyto_idx' => array('reply_to')
122             )
123         );
124
125         if (common_config('search', 'type') == 'fulltext') {
126             $def['fulltext indexes'] = array('content' => array('content'));
127         }
128
129         return $def;
130     }
131
132     /* Notice types */
133     const LOCAL_PUBLIC    =  1;
134     const REMOTE          =  0;
135     const LOCAL_NONPUBLIC = -1;
136     const GATEWAY         = -2;
137
138     const PUBLIC_SCOPE    = 0; // Useful fake constant
139     const SITE_SCOPE      = 1;
140     const ADDRESSEE_SCOPE = 2;
141     const GROUP_SCOPE     = 4;
142     const FOLLOWER_SCOPE  = 8;
143
144     protected $_profile = array();
145
146     /**
147      * Will always return a profile, if anything fails it will
148      * (through _setProfile) throw a NoProfileException.
149      */
150     public function getProfile()
151     {
152         if (!isset($this->_profile[$this->profile_id])) {
153             // We could've sent getKV directly to _setProfile, but occasionally we get
154             // a "false" (instead of null), likely because it indicates a cache miss.
155             $profile = Profile::getKV('id', $this->profile_id);
156             $this->_setProfile($profile instanceof Profile ? $profile : null);
157         }
158         return $this->_profile[$this->profile_id];
159     }
160
161     public function _setProfile(Profile $profile=null)
162     {
163         if (!$profile instanceof Profile) {
164             throw new NoProfileException($this->profile_id);
165         }
166         $this->_profile[$this->profile_id] = $profile;
167     }
168
169     function delete($useWhere=false)
170     {
171         // For auditing purposes, save a record that the notice
172         // was deleted.
173
174         // @fixme we have some cases where things get re-run and so the
175         // insert fails.
176         $deleted = Deleted_notice::getKV('id', $this->id);
177
178         if (!$deleted instanceof Deleted_notice) {
179             $deleted = Deleted_notice::getKV('uri', $this->uri);
180         }
181
182         if (!$deleted instanceof Deleted_notice) {
183             $deleted = new Deleted_notice();
184
185             $deleted->id         = $this->id;
186             $deleted->profile_id = $this->profile_id;
187             $deleted->uri        = $this->uri;
188             $deleted->created    = $this->created;
189             $deleted->deleted    = common_sql_now();
190
191             $deleted->insert();
192         }
193
194         if (Event::handle('NoticeDeleteRelated', array($this))) {
195
196             // Clear related records
197
198             $this->clearReplies();
199             $this->clearRepeats();
200             $this->clearTags();
201             $this->clearGroupInboxes();
202             $this->clearFiles();
203             $this->clearAttentions();
204
205             // NOTE: we don't clear queue items
206         }
207
208         $result = parent::delete($useWhere);
209
210         $this->blowOnDelete();
211         return $result;
212     }
213
214     public function getUri()
215     {
216         return $this->uri;
217     }
218
219     /*
220      * Get a Notice object by URI. Will call external plugins for help
221      * using the event StartGetNoticeFromURI.
222      *
223      * @param string $uri A unique identifier for a resource (notice in this case)
224      */
225     static function fromUri($uri)
226     {
227         $notice = null;
228
229         if (Event::handle('StartGetNoticeFromUri', array($uri, &$notice))) {
230             $notice = Notice::getKV('uri', $uri);
231             Event::handle('EndGetNoticeFromUri', array($uri, $notice));
232         }
233
234         if (!$notice instanceof Notice) {
235             throw new UnknownUriException($uri);
236         }
237
238         return $notice;
239     }
240
241     /*
242      * @param $root boolean If true, link to just the conversation root.
243      *
244      * @return URL to conversation
245      */
246     public function getConversationUrl($anchor=true)
247     {
248         return Conversation::getUrlFromNotice($this, $anchor);
249     }
250
251     /*
252      * Get the local representation URL of this notice.
253      */
254     public function getLocalUrl()
255     {
256         return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
257     }
258
259     public function getTitle()
260     {
261         $title = null;
262         if (Event::handle('GetNoticeTitle', array($this, &$title))) {
263             // TRANS: Title of a notice posted without a title value.
264             // TRANS: %1$s is a user name, %2$s is the notice creation date/time.
265             $title = sprintf(_('%1$s\'s status on %2$s'),
266                              $this->getProfile()->getFancyName(),
267                              common_exact_date($this->created));
268         }
269         return $title;
270     }
271
272     public function getContent()
273     {
274         return $this->content;
275     }
276
277     /*
278      * Get the original representation URL of this notice.
279      *
280      * @param boolean $fallback     Whether to fall back to generate a local URL or throw InvalidUrlException
281      */
282     public function getUrl($fallback=false)
283     {
284         // The risk is we start having empty urls and non-http uris...
285         // and we can't really handle any other protocol right now.
286         switch (true) {
287         case common_valid_http_url($this->url): // should we allow non-http/https URLs?
288             return $this->url;
289         case !$this->isLocal() && common_valid_http_url($this->uri): // Sometimes we only have the URI for remote posts.
290             return $this->uri;
291         case $this->isLocal() || $fallback:
292             // let's generate a valid link to our locally available notice on demand
293             return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
294         default:
295             common_debug('No URL available for notice: id='.$this->id);
296             throw new InvalidUrlException($this->url);
297         }
298     }
299
300     public function get_object_type($canonical=false) {
301         return $canonical
302                 ? ActivityObject::canonicalType($this->object_type)
303                 : $this->object_type;
304     }
305
306     public static function getByUri($uri)
307     {
308         $notice = new Notice();
309         $notice->uri = $uri;
310         if (!$notice->find(true)) {
311             throw new NoResultException($notice);
312         }
313         return $notice;
314     }
315
316     public static function getById($id)
317     {
318         $notice = new Notice();
319         $notice->id = $id;
320         if (!$notice->find(true)) {
321             throw new NoResultException($notice);
322         }
323         return $notice;
324     }
325
326     /**
327      * Extract #hashtags from this notice's content and save them to the database.
328      */
329     function saveTags()
330     {
331         /* extract all #hastags */
332         $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
333         if (!$count) {
334             return true;
335         }
336
337         /* Add them to the database */
338         return $this->saveKnownTags($match[1]);
339     }
340
341     /**
342      * Record the given set of hash tags in the db for this notice.
343      * Given tag strings will be normalized and checked for dupes.
344      */
345     function saveKnownTags(array $hashtags)
346     {
347         //turn each into their canonical tag
348         //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
349         for($i=0; $i<count($hashtags); $i++) {
350             /* elide characters we don't want in the tag */
351             $hashtags[$i] = common_canonical_tag($hashtags[$i]);
352         }
353
354         foreach(array_unique($hashtags) as $hashtag) {
355             $this->saveTag($hashtag);
356             self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
357         }
358         return true;
359     }
360
361     /**
362      * Record a single hash tag as associated with this notice.
363      * Tag format and uniqueness must be validated by caller.
364      */
365     function saveTag($hashtag)
366     {
367         $tag = new Notice_tag();
368         $tag->notice_id = $this->id;
369         $tag->tag = $hashtag;
370         $tag->created = $this->created;
371         $id = $tag->insert();
372
373         if (!$id) {
374             // TRANS: Server exception. %s are the error details.
375             throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
376                                               $last_error->message));
377             return;
378         }
379
380         // if it's saved, blow its cache
381         $tag->blowCache(false);
382     }
383
384     /**
385      * Save a new notice and push it out to subscribers' inboxes.
386      * Poster's permissions are checked before sending.
387      *
388      * @param int $profile_id Profile ID of the poster
389      * @param string $content source message text; links may be shortened
390      *                        per current user's preference
391      * @param string $source source key ('web', 'api', etc)
392      * @param array $options Associative array of optional properties:
393      *              string 'created' timestamp of notice; defaults to now
394      *              int 'is_local' source/gateway ID, one of:
395      *                  Notice::LOCAL_PUBLIC    - Local, ok to appear in public timeline
396      *                  Notice::REMOTE          - Sent from a remote service;
397      *                                            hide from public timeline but show in
398      *                                            local "and friends" timelines
399      *                  Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
400      *                  Notice::GATEWAY         - From another non-OStatus service;
401      *                                            will not appear in public views
402      *              float 'lat' decimal latitude for geolocation
403      *              float 'lon' decimal longitude for geolocation
404      *              int 'location_id' geoname identifier
405      *              int 'location_ns' geoname namespace to interpret location_id
406      *              int 'reply_to'; notice ID this is a reply to
407      *              int 'repeat_of'; notice ID this is a repeat of
408      *              string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
409      *              string 'url' permalink to notice; defaults to local notice URL
410      *              string 'rendered' rendered HTML version of content
411      *              array 'replies' list of profile URIs for reply delivery in
412      *                              place of extracting @-replies from content.
413      *              array 'groups' list of group IDs to deliver to, in place of
414      *                              extracting ! tags from content
415      *              array 'tags' list of hashtag strings to save with the notice
416      *                           in place of extracting # tags from content
417      *              array 'urls' list of attached/referred URLs to save with the
418      *                           notice in place of extracting links from content
419      *              boolean 'distribute' whether to distribute the notice, default true
420      *              string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
421      *              string 'verb' URL of the associated verb (default ActivityVerb::POST)
422      *              int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
423      *
424      * @fixme tag override
425      *
426      * @return Notice
427      * @throws ClientException
428      */
429     static function saveNew($profile_id, $content, $source, array $options=array()) {
430         $defaults = array('uri' => null,
431                           'url' => null,
432                           'conversation' => null,   // URI of conversation
433                           'reply_to' => null,       // This will override convo URI if the parent is known
434                           'repeat_of' => null,      // This will override convo URI if the repeated notice is known
435                           'scope' => null,
436                           'distribute' => true,
437                           'object_type' => null,
438                           'verb' => null);
439
440         /*
441          * Above type-hint is already array, so simply count it, this saves
442          * "some" CPU cycles.
443          */
444         if (count($options) > 0) {
445             $options = array_merge($defaults, $options);
446         }
447
448         extract($options);
449
450         if (!isset($is_local)) {
451             $is_local = Notice::LOCAL_PUBLIC;
452         }
453
454         $profile = Profile::getKV('id', $profile_id);
455         if (!$profile instanceof Profile) {
456             // TRANS: Client exception thrown when trying to save a notice for an unknown user.
457             throw new ClientException(_('Problem saving notice. Unknown user.'));
458         }
459
460         $user = User::getKV('id', $profile_id);
461         if ($user instanceof User) {
462             // Use the local user's shortening preferences, if applicable.
463             $final = $user->shortenLinks($content);
464         } else {
465             $final = common_shorten_links($content);
466         }
467
468         if (Notice::contentTooLong($final)) {
469             // TRANS: Client exception thrown if a notice contains too many characters.
470             throw new ClientException(_('Problem saving notice. Too long.'));
471         }
472
473         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
474             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
475             // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
476             throw new ClientException(_('Too many notices too fast; take a breather '.
477                                         'and post again in a few minutes.'));
478         }
479
480         if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
481             common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
482             // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
483             throw new ClientException(_('Too many duplicate messages too quickly;'.
484                                         ' take a breather and post again in a few minutes.'));
485         }
486
487         if (!$profile->hasRight(Right::NEWNOTICE)) {
488             common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
489
490             // TRANS: Client exception thrown when a user tries to post while being banned.
491             throw new ClientException(_('You are banned from posting notices on this site.'), 403);
492         }
493
494         $notice = new Notice();
495         $notice->profile_id = $profile_id;
496
497         $autosource = common_config('public', 'autosource');
498
499         // Sandboxed are non-false, but not 1, either
500
501         if (!$profile->hasRight(Right::PUBLICNOTICE) ||
502             ($source && $autosource && in_array($source, $autosource))) {
503             $notice->is_local = Notice::LOCAL_NONPUBLIC;
504         } else {
505             $notice->is_local = $is_local;
506         }
507
508         if (!empty($created)) {
509             $notice->created = $created;
510         } else {
511             $notice->created = common_sql_now();
512         }
513
514         if (!$notice->isLocal()) {
515             // Only do these checks for non-local notices. Local notices will generate these values later.
516             if (!common_valid_http_url($url)) {
517                 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
518             }
519             if (empty($uri)) {
520                 throw new ServerException('No URI for remote notice. Cannot accept that.');
521             }
522         }
523
524         $notice->content = $final;
525
526         $notice->source = $source;
527         $notice->uri = $uri;
528         $notice->url = $url;
529
530         // Get the groups here so we can figure out replies and such
531         if (!isset($groups)) {
532             $groups = User_group::idsFromText($notice->content, $profile);
533         }
534
535         $reply = null;
536
537         // Handle repeat case
538
539         if (isset($repeat_of)) {
540
541             // Check for a private one
542
543             $repeat = Notice::getKV('id', $repeat_of);
544
545             if (!($repeat instanceof Notice)) {
546                 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
547                 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
548             }
549
550             if ($profile->id == $repeat->profile_id) {
551                 // TRANS: Client error displayed when trying to repeat an own notice.
552                 throw new ClientException(_('You cannot repeat your own notice.'));
553             }
554
555             if ($repeat->isPrivateScope()) {
556                 // TRANS: Client error displayed when trying to repeat a non-public notice.
557                 throw new ClientException(_('Cannot repeat a private notice.'), 403);
558             }
559
560             if (!$repeat->inScope($profile)) {
561                 // The generic checks above should cover this, but let's be sure!
562                 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
563                 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
564             }
565
566             if ($profile->hasRepeated($repeat)) {
567                 // TRANS: Client error displayed when trying to repeat an already repeated notice.
568                 throw new ClientException(_('You already repeated that notice.'));
569             }
570
571             $notice->repeat_of = $repeat->id;
572             $notice->conversation = $repeat->conversation;
573         } else {
574             $reply = null;
575
576             // If $reply_to is specified, we check that it exists, and then
577             // return it if it does
578             if (!empty($reply_to)) {
579                 $reply = Notice::getKV('id', $reply_to);
580             } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
581                 // If the source lacks capability of sending the "reply_to"
582                 // metadata, let's try to find an inline replyto-reference.
583                 $reply = self::getInlineReplyTo($profile, $final);
584             }
585
586             if ($reply instanceof Notice) {
587                 if (!$reply->inScope($profile)) {
588                     // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
589                     // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
590                     throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
591                                                       $profile->nickname, $reply->id), 403);
592                 }
593
594                 // If it's a repeat, the reply_to should be to the original
595                 if ($reply->isRepeat()) {
596                     $notice->reply_to = $reply->repeat_of;
597                 } else {
598                     $notice->reply_to = $reply->id;
599                 }
600                 // But the conversation ought to be the same :)
601                 $notice->conversation = $reply->conversation;
602
603                 // If the original is private to a group, and notice has
604                 // no group specified, make it to the same group(s)
605
606                 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
607                     $groups = array();
608                     $replyGroups = $reply->getGroups();
609                     foreach ($replyGroups as $group) {
610                         if ($profile->isMember($group)) {
611                             $groups[] = $group->id;
612                         }
613                     }
614                 }
615
616                 // Scope set below
617             }
618
619             // If we don't know the reply, we might know the conversation!
620             // This will happen if a known remote user replies to an
621             // unknown remote user - within a known conversation.
622             if (empty($notice->conversation) and !empty($options['conversation'])) {
623                 $conv = Conversation::getKV('uri', $options['conversation']);
624                 if ($conv instanceof Conversation) {
625                     common_debug('Conversation stitched together from (probably) reply to unknown remote user. Activity creation time ('.$notice->created.') should maybe be compared to conversation creation time ('.$conv->created.').');
626                     $notice->conversation = $conv->id;
627                 } else {
628                     // Conversation URI was not found, so we must create it. But we can't create it
629                     // until we have a Notice ID because of the database layout...
630                     $notice->tmp_conv_uri = $options['conversation'];
631                 }
632             } else {
633                 // If we're not using the attached conversation URI let's remove it
634                 // so we don't mistake ourselves later, when creating our own Conversation.
635                 // This implies that the notice knows which conversation it belongs to.
636                 $options['conversation'] = null;
637             }
638         }
639
640         if (!empty($lat) && !empty($lon)) {
641             $notice->lat = $lat;
642             $notice->lon = $lon;
643         }
644
645         if (!empty($location_ns) && !empty($location_id)) {
646             $notice->location_id = $location_id;
647             $notice->location_ns = $location_ns;
648         }
649
650         if (!empty($rendered)) {
651             $notice->rendered = $rendered;
652         } else {
653             $notice->rendered = common_render_content($final, $notice);
654         }
655
656         if (empty($verb)) {
657             if ($notice->isRepeat()) {
658                 $notice->verb        = ActivityVerb::SHARE;
659                 $notice->object_type = ActivityObject::ACTIVITY;
660             } else {
661                 $notice->verb        = ActivityVerb::POST;
662             }
663         } else {
664             $notice->verb = $verb;
665         }
666
667         if (empty($object_type)) {
668             $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
669         } else {
670             $notice->object_type = $object_type;
671         }
672
673         if (is_null($scope) && $reply instanceof Notice) {
674             $notice->scope = $reply->scope;
675         } else {
676             $notice->scope = $scope;
677         }
678
679         $notice->scope = self::figureOutScope($profile, $groups, $notice->scope);
680
681         if (Event::handle('StartNoticeSave', array(&$notice))) {
682
683             // XXX: some of these functions write to the DB
684
685             try {
686                 $notice->insert();  // throws exception on failure
687                 // If it's not part of a conversation, it's
688                 // the beginning of a new conversation.
689                 if (empty($notice->conversation)) {
690                     $orig = clone($notice);
691                     // $act->context->conversation will be null if it was not provided
692                     $conv = Conversation::create($notice, $options['conversation']);
693                     $notice->conversation = $conv->id;
694                     $notice->update($orig);
695                 }
696             } catch (Exception $e) {
697                 // Let's test if we managed initial insert, which would imply
698                 // failing on some update-part (check 'insert()'). Delete if
699                 // something had been stored to the database.
700                 if (!empty($notice->id)) {
701                     $notice->delete();
702                 }
703                 throw $e;
704             }
705         }
706
707         // Clear the cache for subscribed users, so they'll update at next request
708         // XXX: someone clever could prepend instead of clearing the cache
709
710         // Save per-notice metadata...
711
712         if (isset($replies)) {
713             $notice->saveKnownReplies($replies);
714         } else {
715             $notice->saveReplies();
716         }
717
718         if (isset($tags)) {
719             $notice->saveKnownTags($tags);
720         } else {
721             $notice->saveTags();
722         }
723
724         // Note: groups may save tags, so must be run after tags are saved
725         // to avoid errors on duplicates.
726         // Note: groups should always be set.
727
728         $notice->saveKnownGroups($groups);
729
730         if (isset($urls)) {
731             $notice->saveKnownUrls($urls);
732         } else {
733             $notice->saveUrls();
734         }
735
736         if ($distribute) {
737             // Prepare inbox delivery, may be queued to background.
738             $notice->distribute();
739         }
740
741         return $notice;
742     }
743
744     static function saveActivity(Activity $act, Profile $actor, array $options=array())
745     {
746         // First check if we're going to let this Activity through from the specific actor
747         if (!$actor->hasRight(Right::NEWNOTICE)) {
748             common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $actor->getNickname());
749
750             // TRANS: Client exception thrown when a user tries to post while being banned.
751             throw new ClientException(_m('You are banned from posting notices on this site.'), 403);
752         }
753         if (common_config('throttle', 'enabled') && !self::checkEditThrottle($actor->id)) {
754             common_log(LOG_WARNING, 'Excessive posting by profile #' . $actor->id . '; throttled.');
755             // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
756             throw new ClientException(_m('Too many notices too fast; take a breather '.
757                                         'and post again in a few minutes.'));
758         }
759
760         // Get ActivityObject properties
761         if (!empty($act->id)) {
762             // implied object
763             $options['uri'] = $act->id;
764             $options['url'] = $act->link;
765         } else {
766             $actobj = count($act->objects)==1 ? $act->objects[0] : null;
767             if (!is_null($actobj) && !empty($actobj->id)) {
768                 $options['uri'] = $actobj->id;
769                 if ($actobj->link) {
770                     $options['url'] = $actobj->link;
771                 } elseif (preg_match('!^https?://!', $actobj->id)) {
772                     $options['url'] = $actobj->id;
773                 }
774             }
775         }
776
777         $defaults = array(
778                           'groups'   => array(),
779                           'is_local' => self::LOCAL_PUBLIC,
780                           'mentions' => array(),
781                           'reply_to' => null,
782                           'repeat_of' => null,
783                           'scope' => null,
784                           'source' => 'unknown',
785                           'tags' => array(),
786                           'uri' => null,
787                           'url' => null,
788                           'urls' => array(),
789                           'distribute' => true);
790
791         // options will have default values when nothing has been supplied
792         $options = array_merge($defaults, $options);
793         foreach (array_keys($defaults) as $key) {
794             // Only convert the keynames we specify ourselves from 'defaults' array into variables
795             $$key = $options[$key];
796         }
797         extract($options, EXTR_SKIP);
798
799         $stored = new Notice();
800         if (!empty($uri)) {
801             $stored->uri = $uri;
802             if ($stored->find()) {
803                 common_debug('cannot create duplicate Notice URI: '.$stored->uri);
804                 throw new Exception('Notice URI already exists');
805             }
806         }
807
808         $stored->profile_id = $actor->id;
809         $stored->source = $source;
810         $stored->uri = $uri;
811         $stored->url = $url;
812         $stored->verb = $act->verb;
813
814         // Use the local user's shortening preferences, if applicable.
815         $stored->rendered = $actor->isLocal()
816                                 ? $actor->shortenLinks($act->content)
817                                 : $act->content;
818         $stored->content = common_strip_html($stored->rendered);
819
820         $autosource = common_config('public', 'autosource');
821
822         // Sandboxed are non-false, but not 1, either
823         if (!$actor->hasRight(Right::PUBLICNOTICE) ||
824             ($source && $autosource && in_array($source, $autosource))) {
825             $stored->is_local = Notice::LOCAL_NONPUBLIC;
826         }
827
828         // Maybe a missing act-time should be fatal if the actor is not local?
829         if (!empty($act->time)) {
830             $stored->created = common_sql_date($act->time);
831         } else {
832             $stored->created = common_sql_now();
833         }
834
835         $reply = null;
836         if ($act->context instanceof ActivityContext && !empty($act->context->replyToID)) {
837             $reply = self::getKV('uri', $act->context->replyToID);
838         }
839         if (!$reply instanceof Notice && $act->target instanceof ActivityObject) {
840             $reply = self::getKV('uri', $act->target->id);
841         }
842
843         if ($reply instanceof Notice) {
844             if (!$reply->inScope($actor)) {
845                 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
846                 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
847                 throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $actor->getNickname(), $reply->id), 403);
848             }
849
850             $stored->reply_to     = $reply->id;
851             $stored->conversation = $reply->conversation;
852
853             // If the original is private to a group, and notice has no group specified,
854             // make it to the same group(s)
855             if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
856                 $groups = array();
857                 $replyGroups = $reply->getGroups();
858                 foreach ($replyGroups as $group) {
859                     if ($actor->isMember($group)) {
860                         $groups[] = $group->id;
861                     }
862                 }
863             }
864
865             if (is_null($scope)) {
866                 $scope = $reply->scope;
867             }
868         }
869
870         if ($act->context instanceof ActivityContext) {
871             $location = $act->context->location;
872             if ($location) {
873                 $stored->lat = $location->lat;
874                 $stored->lon = $location->lon;
875                 if ($location->location_id) {
876                     $stored->location_ns = $location->location_ns;
877                     $stored->location_id = $location->location_id;
878                 }
879             }
880         } else {
881             $act->context = new ActivityContext();
882         }
883
884         $stored->scope = self::figureOutScope($actor, $groups, $scope);
885
886         foreach ($act->categories as $cat) {
887             if ($cat->term) {
888                 $term = common_canonical_tag($cat->term);
889                 if (!empty($term)) {
890                     $tags[] = $term;
891                 }
892             }
893         }
894
895         foreach ($act->enclosures as $href) {
896             // @todo FIXME: Save these locally or....?
897             $urls[] = $href;
898         }
899
900         if (Event::handle('StartNoticeSave', array(&$stored))) {
901             // XXX: some of these functions write to the DB
902
903             try {
904                 $stored->insert();    // throws exception on error
905                 $orig = clone($stored); // for updating later in this try clause
906
907                 $object = null;
908                 Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
909                 if (empty($object)) {
910                     throw new ServerException('Unsuccessful call to StoreActivityObject '.$stored->uri . ': '.$act->asString());
911                 }
912
913                 // If it's not part of a conversation, it's
914                 // the beginning of a new conversation.
915                 if (empty($stored->conversation)) {
916                     // $act->context->conversation will be null if it was not provided
917                     $conv = Conversation::create($stored, $act->context->conversation);
918                     $stored->conversation = $conv->id;
919                 }
920
921                 $stored->update($orig);
922             } catch (Exception $e) {
923                 if (empty($stored->id)) {
924                     common_debug('Failed to save stored object entry in database ('.$e->getMessage().')');
925                 } else {
926                     common_debug('Failed to store activity object in database ('.$e->getMessage().'), deleting notice id '.$stored->id);
927                     $stored->delete();
928                 }
929                 throw $e;
930             }
931         }
932         if (!$stored instanceof Notice) {
933             throw new ServerException('StartNoticeSave did not give back a Notice');
934         }
935
936         // Save per-notice metadata...
937         $mentions = array();
938         $groups   = array();
939
940         // This event lets plugins filter out non-local recipients (attentions we don't care about)
941         // Used primarily for OStatus (and if we don't federate, all attentions would be local anyway)
942         Event::handle('GetLocalAttentions', array($actor, $act->context->attention, &$mentions, &$groups));
943
944         if (!empty($mentions)) {
945             $stored->saveKnownReplies($mentions);
946         } else {
947             $stored->saveReplies();
948         }
949
950         if (!empty($tags)) {
951             $stored->saveKnownTags($tags);
952         } else {
953             $stored->saveTags();
954         }
955
956         // Note: groups may save tags, so must be run after tags are saved
957         // to avoid errors on duplicates.
958         // Note: groups should always be set.
959
960         $stored->saveKnownGroups($groups);
961
962         if (!empty($urls)) {
963             $stored->saveKnownUrls($urls);
964         } else {
965             $stored->saveUrls();
966         }
967
968         if ($distribute) {
969             // Prepare inbox delivery, may be queued to background.
970             $stored->distribute();
971         }
972
973         return $stored;
974     }
975
976     static public function figureOutScope(Profile $actor, array $groups, $scope=null) {
977         if (is_null($scope)) {
978             $scope = self::defaultScope();
979         }
980
981         // For private streams
982         try {
983             $user = $actor->getUser();
984             // FIXME: We can't do bit comparison with == (Legacy StatusNet thing. Let's keep it for now.)
985             if ($user->private_stream && ($scope == Notice::PUBLIC_SCOPE || $scope == Notice::SITE_SCOPE)) {
986                 $scope |= Notice::FOLLOWER_SCOPE;
987             }
988         } catch (NoSuchUserException $e) {
989             // TODO: Not a local user, so we don't know about scope preferences... yet!
990         }
991
992         // Force the scope for private groups
993         foreach ($groups as $group_id) {
994             $group = User_group::staticGet('id', $group_id);
995             if ($group instanceof User_group) {
996                 if ($group->force_scope) {
997                     $scope |= Notice::GROUP_SCOPE;
998                     break;
999                 }
1000             }
1001         }
1002
1003         return $scope;
1004     }
1005
1006     function blowOnInsert($conversation = false)
1007     {
1008         $this->blowStream('profile:notice_ids:%d', $this->profile_id);
1009
1010         if ($this->isPublic()) {
1011             $this->blowStream('public');
1012             $this->blowStream('networkpublic');
1013         }
1014
1015         self::blow('notice:list-ids:conversation:%s', $this->conversation);
1016         self::blow('conversation:notice_count:%d', $this->conversation);
1017
1018         if ($this->isRepeat()) {
1019             // XXX: we should probably only use one of these
1020             $this->blowStream('notice:repeats:%d', $this->repeat_of);
1021             self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
1022         }
1023
1024         $original = Notice::getKV('id', $this->repeat_of);
1025
1026         if ($original instanceof Notice) {
1027             $originalUser = User::getKV('id', $original->profile_id);
1028             if ($originalUser instanceof User) {
1029                 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
1030             }
1031         }
1032
1033         $profile = Profile::getKV($this->profile_id);
1034
1035         if ($profile instanceof Profile) {
1036             $profile->blowNoticeCount();
1037         }
1038
1039         $ptags = $this->getProfileTags();
1040         foreach ($ptags as $ptag) {
1041             $ptag->blowNoticeStreamCache();
1042         }
1043     }
1044
1045     /**
1046      * Clear cache entries related to this notice at delete time.
1047      * Necessary to avoid breaking paging on public, profile timelines.
1048      */
1049     function blowOnDelete()
1050     {
1051         $this->blowOnInsert();
1052
1053         self::blow('profile:notice_ids:%d;last', $this->profile_id);
1054
1055         if ($this->isPublic()) {
1056             self::blow('public;last');
1057             self::blow('networkpublic;last');
1058         }
1059
1060         self::blow('fave:by_notice', $this->id);
1061
1062         if ($this->conversation) {
1063             // In case we're the first, will need to calc a new root.
1064             self::blow('notice:conversation_root:%d', $this->conversation);
1065         }
1066
1067         $ptags = $this->getProfileTags();
1068         foreach ($ptags as $ptag) {
1069             $ptag->blowNoticeStreamCache(true);
1070         }
1071     }
1072
1073     function blowStream()
1074     {
1075         $c = self::memcache();
1076
1077         if (empty($c)) {
1078             return false;
1079         }
1080
1081         $args = func_get_args();
1082         $format = array_shift($args);
1083         $keyPart = vsprintf($format, $args);
1084         $cacheKey = Cache::key($keyPart);
1085         $c->delete($cacheKey);
1086
1087         // delete the "last" stream, too, if this notice is
1088         // older than the top of that stream
1089
1090         $lastKey = $cacheKey.';last';
1091
1092         $lastStr = $c->get($lastKey);
1093
1094         if ($lastStr !== false) {
1095             $window     = explode(',', $lastStr);
1096             $lastID     = $window[0];
1097             $lastNotice = Notice::getKV('id', $lastID);
1098             if (!$lastNotice instanceof Notice // just weird
1099                 || strtotime($lastNotice->created) >= strtotime($this->created)) {
1100                 $c->delete($lastKey);
1101             }
1102         }
1103     }
1104
1105     /** save all urls in the notice to the db
1106      *
1107      * follow redirects and save all available file information
1108      * (mimetype, date, size, oembed, etc.)
1109      *
1110      * @return void
1111      */
1112     function saveUrls() {
1113         if (common_config('attachments', 'process_links')) {
1114             common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
1115         }
1116     }
1117
1118     /**
1119      * Save the given URLs as related links/attachments to the db
1120      *
1121      * follow redirects and save all available file information
1122      * (mimetype, date, size, oembed, etc.)
1123      *
1124      * @return void
1125      */
1126     function saveKnownUrls(array $urls)
1127     {
1128         if (common_config('attachments', 'process_links')) {
1129             // @fixme validation?
1130             foreach (array_unique($urls) as $url) {
1131                 try {
1132                     File::processNew($url, $this->id);
1133                 } catch (ServerException $e) {
1134                     // Could not save URL. Log it?
1135                 }
1136             }
1137         }
1138     }
1139
1140     /**
1141      * @private callback
1142      */
1143     function saveUrl($url, $notice_id) {
1144         try {
1145             File::processNew($url, $notice_id);
1146         } catch (ServerException $e) {
1147             // Could not save URL. Log it?
1148         }
1149     }
1150
1151     static function checkDupes($profile_id, $content) {
1152         $profile = Profile::getKV($profile_id);
1153         if (!$profile instanceof Profile) {
1154             return false;
1155         }
1156         $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
1157         if (!empty($notice)) {
1158             $last = 0;
1159             while ($notice->fetch()) {
1160                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
1161                     return true;
1162                 } else if ($notice->content == $content) {
1163                     return false;
1164                 }
1165             }
1166         }
1167         // If we get here, oldest item in cache window is not
1168         // old enough for dupe limit; do direct check against DB
1169         $notice = new Notice();
1170         $notice->profile_id = $profile_id;
1171         $notice->content = $content;
1172         $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
1173         $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
1174
1175         $cnt = $notice->count();
1176         return ($cnt == 0);
1177     }
1178
1179     static function checkEditThrottle($profile_id) {
1180         $profile = Profile::getKV($profile_id);
1181         if (!$profile instanceof Profile) {
1182             return false;
1183         }
1184         // Get the Nth notice
1185         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
1186         if ($notice && $notice->fetch()) {
1187             // If the Nth notice was posted less than timespan seconds ago
1188             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
1189                 // Then we throttle
1190                 return false;
1191             }
1192         }
1193         // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
1194         return true;
1195     }
1196
1197         protected $_attachments = array();
1198
1199     function attachments() {
1200                 if (isset($this->_attachments[$this->id])) {
1201             return $this->_attachments[$this->id];
1202         }
1203
1204         $f2ps = File_to_post::listGet('post_id', array($this->id));
1205                 $ids = array();
1206                 foreach ($f2ps[$this->id] as $f2p) {
1207             $ids[] = $f2p->file_id;
1208         }
1209
1210                 $files = File::multiGet('id', $ids);
1211                 $this->_attachments[$this->id] = $files->fetchAll();
1212         return $this->_attachments[$this->id];
1213     }
1214
1215         function _setAttachments($attachments)
1216         {
1217             $this->_attachments[$this->id] = $attachments;
1218         }
1219
1220     function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
1221     {
1222         $stream = new PublicNoticeStream();
1223         return $stream->getNotices($offset, $limit, $since_id, $max_id);
1224     }
1225
1226
1227     function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
1228     {
1229         $stream = new ConversationNoticeStream($id);
1230
1231         return $stream->getNotices($offset, $limit, $since_id, $max_id);
1232     }
1233
1234     /**
1235      * Is this notice part of an active conversation?
1236      *
1237      * @return boolean true if other messages exist in the same
1238      *                 conversation, false if this is the only one
1239      */
1240     function hasConversation()
1241     {
1242         if (!empty($this->conversation)) {
1243             $conversation = Notice::conversationStream(
1244                 $this->conversation,
1245                 1,
1246                 1
1247             );
1248
1249             if ($conversation->N > 0) {
1250                 return true;
1251             }
1252         }
1253         return false;
1254     }
1255
1256     /**
1257      * Grab the earliest notice from this conversation.
1258      *
1259      * @return Notice or null
1260      */
1261     function conversationRoot($profile=-1)
1262     {
1263         // XXX: can this happen?
1264
1265         if (empty($this->conversation)) {
1266             return null;
1267         }
1268
1269         // Get the current profile if not specified
1270
1271         if (is_int($profile) && $profile == -1) {
1272             $profile = Profile::current();
1273         }
1274
1275         // If this notice is out of scope, no root for you!
1276
1277         if (!$this->inScope($profile)) {
1278             return null;
1279         }
1280
1281         // If this isn't a reply to anything, then it's its own
1282         // root if it's the earliest notice in the conversation:
1283
1284         if (empty($this->reply_to)) {
1285             $root = new Notice;
1286             $root->conversation = $this->conversation;
1287             $root->orderBy('notice.created ASC');
1288             $root->find();
1289             $root->fetch();
1290             $root->free();
1291             return $root;
1292         }
1293
1294         if (is_null($profile)) {
1295             $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1296         } else {
1297             $keypart = sprintf('notice:conversation_root:%d:%d',
1298                                $this->id,
1299                                $profile->id);
1300         }
1301
1302         $root = self::cacheGet($keypart);
1303
1304         if ($root !== false && $root->inScope($profile)) {
1305             return $root;
1306         }
1307
1308         $last = $this;
1309         while (true) {
1310             try {
1311                 $parent = $last->getParent();
1312                 if ($parent->inScope($profile)) {
1313                     $last = $parent;
1314                     continue;
1315                 }
1316             } catch (Exception $e) {
1317                 // Latest notice has no parent
1318             }
1319             // No parent, or parent out of scope
1320             $root = $last;
1321             break;
1322         }
1323
1324         self::cacheSet($keypart, $root);
1325
1326         return $root;
1327     }
1328
1329     /**
1330      * Pull up a full list of local recipients who will be getting
1331      * this notice in their inbox. Results will be cached, so don't
1332      * change the input data wily-nilly!
1333      *
1334      * @param array $groups optional list of Group objects;
1335      *              if left empty, will be loaded from group_inbox records
1336      * @param array $recipient optional list of reply profile ids
1337      *              if left empty, will be loaded from reply records
1338      * @return array associating recipient user IDs with an inbox source constant
1339      */
1340     function whoGets(array $groups=null, array $recipients=null)
1341     {
1342         $c = self::memcache();
1343
1344         if (!empty($c)) {
1345             $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1346             if ($ni !== false) {
1347                 return $ni;
1348             }
1349         }
1350
1351         if (is_null($recipients)) {
1352             $recipients = $this->getReplies();
1353         }
1354
1355         $ni = array();
1356
1357         // Give plugins a chance to add folks in at start...
1358         if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1359
1360             $users = $this->getSubscribedUsers();
1361             foreach ($users as $id) {
1362                 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1363             }
1364
1365             if (is_null($groups)) {
1366                 $groups = $this->getGroups();
1367             }
1368             foreach ($groups as $group) {
1369                 $users = $group->getUserMembers();
1370                 foreach ($users as $id) {
1371                     if (!array_key_exists($id, $ni)) {
1372                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1373                     }
1374                 }
1375             }
1376
1377             $ptAtts = $this->getAttentionsFromProfileTags();
1378             foreach ($ptAtts as $key=>$val) {
1379                 if (!array_key_exists($key, $ni)) {
1380                     $ni[$key] = $val;
1381                 }
1382             }
1383
1384             foreach ($recipients as $recipient) {
1385                 if (!array_key_exists($recipient, $ni)) {
1386                     $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1387                 }
1388             }
1389
1390             // Exclude any deleted, non-local, or blocking recipients.
1391             $profile = $this->getProfile();
1392             $originalProfile = null;
1393             if ($this->isRepeat()) {
1394                 // Check blocks against the original notice's poster as well.
1395                 $original = Notice::getKV('id', $this->repeat_of);
1396                 if ($original instanceof Notice) {
1397                     $originalProfile = $original->getProfile();
1398                 }
1399             }
1400
1401             foreach ($ni as $id => $source) {
1402                 try {
1403                     $user = User::getKV('id', $id);
1404                     if (!$user instanceof User ||
1405                         $user->hasBlocked($profile) ||
1406                         ($originalProfile && $user->hasBlocked($originalProfile))) {
1407                         unset($ni[$id]);
1408                     }
1409                 } catch (UserNoProfileException $e) {
1410                     // User doesn't have a profile; invalid; skip them.
1411                     unset($ni[$id]);
1412                 }
1413             }
1414
1415             // Give plugins a chance to filter out...
1416             Event::handle('EndNoticeWhoGets', array($this, &$ni));
1417         }
1418
1419         if (!empty($c)) {
1420             // XXX: pack this data better
1421             $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1422         }
1423
1424         return $ni;
1425     }
1426
1427     function getSubscribedUsers()
1428     {
1429         $user = new User();
1430
1431         if(common_config('db','quote_identifiers'))
1432           $user_table = '"user"';
1433         else $user_table = 'user';
1434
1435         $qry =
1436           'SELECT id ' .
1437           'FROM '. $user_table .' JOIN subscription '.
1438           'ON '. $user_table .'.id = subscription.subscriber ' .
1439           'WHERE subscription.subscribed = %d ';
1440
1441         $user->query(sprintf($qry, $this->profile_id));
1442
1443         $ids = array();
1444
1445         while ($user->fetch()) {
1446             $ids[] = $user->id;
1447         }
1448
1449         $user->free();
1450
1451         return $ids;
1452     }
1453
1454     function getProfileTags()
1455     {
1456         $profile = $this->getProfile();
1457         $list    = $profile->getOtherTags($profile);
1458         $ptags   = array();
1459
1460         while($list->fetch()) {
1461             $ptags[] = clone($list);
1462         }
1463
1464         return $ptags;
1465     }
1466
1467     public function getAttentionsFromProfileTags()
1468     {
1469         $ni = array();
1470         $ptags = $this->getProfileTags();
1471         foreach ($ptags as $ptag) {
1472             $users = $ptag->getUserSubscribers();
1473             foreach ($users as $id) {
1474                 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1475             }
1476         }
1477         return $ni;
1478     }
1479
1480     /**
1481      * Record this notice to the given group inboxes for delivery.
1482      * Overrides the regular parsing of !group markup.
1483      *
1484      * @param string $group_ids
1485      * @fixme might prefer URIs as identifiers, as for replies?
1486      *        best with generalizations on user_group to support
1487      *        remote groups better.
1488      */
1489     function saveKnownGroups($group_ids)
1490     {
1491         if (!is_array($group_ids)) {
1492             // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1493             throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1494         }
1495
1496         $groups = array();
1497         foreach (array_unique($group_ids) as $id) {
1498             $group = User_group::getKV('id', $id);
1499             if ($group instanceof User_group) {
1500                 common_log(LOG_DEBUG, "Local delivery to group id $id, $group->nickname");
1501                 $result = $this->addToGroupInbox($group);
1502                 if (!$result) {
1503                     common_log_db_error($gi, 'INSERT', __FILE__);
1504                 }
1505
1506                 if (common_config('group', 'addtag')) {
1507                     // we automatically add a tag for every group name, too
1508
1509                     $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1510                                                      'notice_id' => $this->id));
1511
1512                     if (is_null($tag)) {
1513                         $this->saveTag($group->nickname);
1514                     }
1515                 }
1516
1517                 $groups[] = clone($group);
1518             } else {
1519                 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1520             }
1521         }
1522
1523         return $groups;
1524     }
1525
1526     function addToGroupInbox(User_group $group)
1527     {
1528         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1529                                          'notice_id' => $this->id));
1530
1531         if (!$gi instanceof Group_inbox) {
1532
1533             $gi = new Group_inbox();
1534
1535             $gi->group_id  = $group->id;
1536             $gi->notice_id = $this->id;
1537             $gi->created   = $this->created;
1538
1539             $result = $gi->insert();
1540
1541             if (!$result) {
1542                 common_log_db_error($gi, 'INSERT', __FILE__);
1543                 // TRANS: Server exception thrown when an update for a group inbox fails.
1544                 throw new ServerException(_('Problem saving group inbox.'));
1545             }
1546
1547             self::blow('user_group:notice_ids:%d', $gi->group_id);
1548         }
1549
1550         return true;
1551     }
1552
1553     /**
1554      * Save reply records indicating that this notice needs to be
1555      * delivered to the local users with the given URIs.
1556      *
1557      * Since this is expected to be used when saving foreign-sourced
1558      * messages, we won't deliver to any remote targets as that's the
1559      * source service's responsibility.
1560      *
1561      * Mail notifications etc will be handled later.
1562      *
1563      * @param array  $uris   Array of unique identifier URIs for recipients
1564      */
1565     function saveKnownReplies(array $uris)
1566     {
1567         if (empty($uris)) {
1568             return;
1569         }
1570
1571         $sender = Profile::getKV($this->profile_id);
1572
1573         foreach (array_unique($uris) as $uri) {
1574             try {
1575                 $profile = Profile::fromUri($uri);
1576             } catch (UnknownUriException $e) {
1577                 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1578                 continue;
1579             }
1580
1581             if ($profile->hasBlocked($sender)) {
1582                 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1583                 continue;
1584             }
1585
1586             $this->saveReply($profile->id);
1587             self::blow('reply:stream:%d', $profile->id);
1588         }
1589
1590         return;
1591     }
1592
1593     /**
1594      * Pull @-replies from this message's content in StatusNet markup format
1595      * and save reply records indicating that this message needs to be
1596      * delivered to those users.
1597      *
1598      * Mail notifications to local profiles will be sent later.
1599      *
1600      * @return array of integer profile IDs
1601      */
1602
1603     function saveReplies()
1604     {
1605         // Don't save reply data for repeats
1606
1607         if ($this->isRepeat()) {
1608             return array();
1609         }
1610
1611         $sender = $this->getProfile();
1612
1613         $replied = array();
1614
1615         // If it's a reply, save for the replied-to author
1616         try {
1617             $parent = $this->getParent();
1618             $parentauthor = $parent->getProfile();
1619             $this->saveReply($parentauthor->id);
1620             $replied[$parentauthor->id] = 1;
1621             self::blow('reply:stream:%d', $parentauthor->id);
1622         } catch (Exception $e) {
1623             // Not a reply, since it has no parent!
1624         }
1625
1626         // @todo ideally this parser information would only
1627         // be calculated once.
1628
1629         $mentions = common_find_mentions($this->content, $this);
1630
1631         // store replied only for first @ (what user/notice what the reply directed,
1632         // we assume first @ is it)
1633
1634         foreach ($mentions as $mention) {
1635
1636             foreach ($mention['mentioned'] as $mentioned) {
1637
1638                 // skip if they're already covered
1639
1640                 if (!empty($replied[$mentioned->id])) {
1641                     continue;
1642                 }
1643
1644                 // Don't save replies from blocked profile to local user
1645
1646                 $mentioned_user = User::getKV('id', $mentioned->id);
1647                 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1648                     continue;
1649                 }
1650
1651                 $this->saveReply($mentioned->id);
1652                 $replied[$mentioned->id] = 1;
1653                 self::blow('reply:stream:%d', $mentioned->id);
1654             }
1655         }
1656
1657         $recipientIds = array_keys($replied);
1658
1659         return $recipientIds;
1660     }
1661
1662     function saveReply($profileId)
1663     {
1664         $reply = new Reply();
1665
1666         $reply->notice_id  = $this->id;
1667         $reply->profile_id = $profileId;
1668         $reply->modified   = $this->created;
1669
1670         $reply->insert();
1671
1672         return $reply;
1673     }
1674
1675     protected $_replies = array();
1676
1677     /**
1678      * Pull the complete list of @-reply targets for this notice.
1679      *
1680      * @return array of integer profile ids
1681      */
1682     function getReplies()
1683     {
1684         if (isset($this->_replies[$this->id])) {
1685             return $this->_replies[$this->id];
1686         }
1687
1688         $replyMap = Reply::listGet('notice_id', array($this->id));
1689
1690         $ids = array();
1691
1692         foreach ($replyMap[$this->id] as $reply) {
1693             $ids[] = $reply->profile_id;
1694         }
1695
1696         $this->_setReplies($ids);
1697
1698         return $ids;
1699     }
1700
1701     function _setReplies(array $replies)
1702     {
1703         $this->_replies[$this->id] = $replies;
1704     }
1705
1706     /**
1707      * Pull the complete list of @-reply targets for this notice.
1708      *
1709      * @return array of Profiles
1710      */
1711     function getReplyProfiles()
1712     {
1713         $ids = $this->getReplies();
1714
1715         $profiles = Profile::multiGet('id', $ids);
1716
1717         return $profiles->fetchAll();
1718     }
1719
1720     /**
1721      * Send e-mail notifications to local @-reply targets.
1722      *
1723      * Replies must already have been saved; this is expected to be run
1724      * from the distrib queue handler.
1725      */
1726     function sendReplyNotifications()
1727     {
1728         // Don't send reply notifications for repeats
1729
1730         if ($this->isRepeat()) {
1731             return array();
1732         }
1733
1734         $recipientIds = $this->getReplies();
1735         if (Event::handle('StartNotifyMentioned', array($this, &$recipientIds))) {
1736             require_once INSTALLDIR.'/lib/mail.php';
1737
1738             foreach ($recipientIds as $recipientId) {
1739                 $user = User::getKV('id', $recipientId);
1740                 if ($user instanceof User) {
1741                     mail_notify_attn($user, $this);
1742                 }
1743             }
1744             Event::handle('EndNotifyMentioned', array($this, $recipientIds));
1745         }
1746     }
1747
1748     /**
1749      * Pull list of groups this notice needs to be delivered to,
1750      * as previously recorded by saveKnownGroups().
1751      *
1752      * @return array of Group objects
1753      */
1754
1755     protected $_groups = array();
1756
1757     function getGroups()
1758     {
1759         // Don't save groups for repeats
1760
1761         if (!empty($this->repeat_of)) {
1762             return array();
1763         }
1764
1765         if (isset($this->_groups[$this->id])) {
1766             return $this->_groups[$this->id];
1767         }
1768
1769         $gis = Group_inbox::listGet('notice_id', array($this->id));
1770
1771         $ids = array();
1772
1773                 foreach ($gis[$this->id] as $gi) {
1774                     $ids[] = $gi->group_id;
1775                 }
1776
1777                 $groups = User_group::multiGet('id', $ids);
1778                 $this->_setGroups($groups->fetchAll());
1779                 return $this->_groups[$this->id];
1780     }
1781
1782     function _setGroups(array $groups)
1783     {
1784         $this->_groups[$this->id] = $groups;
1785     }
1786
1787     /**
1788      * Convert a notice into an activity for export.
1789      *
1790      * @param Profile $scoped   The currently logged in/scoped profile
1791      *
1792      * @return Activity activity object representing this Notice.
1793      */
1794
1795     function asActivity(Profile $scoped=null)
1796     {
1797         $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1798
1799         if ($act instanceof Activity) {
1800             return $act;
1801         }
1802         $act = new Activity();
1803
1804         if (Event::handle('StartNoticeAsActivity', array($this, $act, $scoped))) {
1805
1806             $act->id      = $this->uri;
1807             $act->time    = strtotime($this->created);
1808             try {
1809                 $act->link    = $this->getUrl();
1810             } catch (InvalidUrlException $e) {
1811                 // The notice is probably a share or similar, which don't
1812                 // have a representational URL of their own.
1813             }
1814             $act->content = common_xml_safe_str($this->rendered);
1815
1816             $profile = $this->getProfile();
1817
1818             $act->actor            = $profile->asActivityObject();
1819             $act->actor->extra[]   = $profile->profileInfo($scoped);
1820
1821             $act->verb = $this->verb;
1822
1823             if (!$this->repeat_of) {
1824                 $act->objects[] = $this->asActivityObject();
1825             }
1826
1827             // XXX: should this be handled by default processing for object entry?
1828
1829             // Categories
1830
1831             $tags = $this->getTags();
1832
1833             foreach ($tags as $tag) {
1834                 $cat       = new AtomCategory();
1835                 $cat->term = $tag;
1836
1837                 $act->categories[] = $cat;
1838             }
1839
1840             // Enclosures
1841             // XXX: use Atom Media and/or File activity objects instead
1842
1843             $attachments = $this->attachments();
1844
1845             foreach ($attachments as $attachment) {
1846                 // Include local attachments in Activity
1847                 if (!empty($attachment->filename)) {
1848                     $act->enclosures[] = $attachment->getEnclosure();
1849                 }
1850             }
1851
1852             $ctx = new ActivityContext();
1853
1854             try {
1855                 $reply = $this->getParent();
1856                 $ctx->replyToID  = $reply->getUri();
1857                 $ctx->replyToUrl = $reply->getUrl();
1858             } catch (Exception $e) {
1859                 // This is not a reply to something
1860             }
1861
1862             $ctx->location = $this->getLocation();
1863
1864             $conv = null;
1865
1866             if (!empty($this->conversation)) {
1867                 $conv = Conversation::getKV('id', $this->conversation);
1868                 if ($conv instanceof Conversation) {
1869                     $ctx->conversation = $conv->uri;
1870                 }
1871             }
1872
1873             $reply_ids = $this->getReplies();
1874
1875             foreach ($reply_ids as $id) {
1876                 $rprofile = Profile::getKV('id', $id);
1877                 if ($rprofile instanceof Profile) {
1878                     $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1879                 }
1880             }
1881
1882             $groups = $this->getGroups();
1883
1884             foreach ($groups as $group) {
1885                 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1886             }
1887
1888             switch ($this->scope) {
1889             case Notice::PUBLIC_SCOPE:
1890                 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1891                 break;
1892             case Notice::FOLLOWER_SCOPE:
1893                 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1894                 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1895                 break;
1896             }
1897
1898             $act->context = $ctx;
1899
1900             $source = $this->getSource();
1901
1902             if ($source instanceof Notice_source) {
1903                 $act->generator = ActivityObject::fromNoticeSource($source);
1904             }
1905
1906             // Source
1907
1908             $atom_feed = $profile->getAtomFeed();
1909
1910             if (!empty($atom_feed)) {
1911
1912                 $act->source = new ActivitySource();
1913
1914                 // XXX: we should store the actual feed ID
1915
1916                 $act->source->id = $atom_feed;
1917
1918                 // XXX: we should store the actual feed title
1919
1920                 $act->source->title = $profile->getBestName();
1921
1922                 $act->source->links['alternate'] = $profile->profileurl;
1923                 $act->source->links['self']      = $atom_feed;
1924
1925                 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1926
1927                 $notice = $profile->getCurrentNotice();
1928
1929                 if ($notice instanceof Notice) {
1930                     $act->source->updated = self::utcDate($notice->created);
1931                 }
1932
1933                 $user = User::getKV('id', $profile->id);
1934
1935                 if ($user instanceof User) {
1936                     $act->source->links['license'] = common_config('license', 'url');
1937                 }
1938             }
1939
1940             if ($this->isLocal()) {
1941                 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1942                                                                            'format' => 'atom'));
1943                 $act->editLink = $act->selfLink;
1944             }
1945
1946             Event::handle('EndNoticeAsActivity', array($this, $act, $scoped));
1947         }
1948
1949         self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1950
1951         return $act;
1952     }
1953
1954     // This has gotten way too long. Needs to be sliced up into functional bits
1955     // or ideally exported to a utility class.
1956
1957     function asAtomEntry($namespace=false,
1958                          $source=false,
1959                          $author=true,
1960                          Profile $scoped=null)
1961     {
1962         $act = $this->asActivity($scoped);
1963         $act->extra[] = $this->noticeInfo($scoped);
1964         return $act->asString($namespace, $author, $source);
1965     }
1966
1967     /**
1968      * Extra notice info for atom entries
1969      *
1970      * Clients use some extra notice info in the atom stream.
1971      * This gives it to them.
1972      *
1973      * @param Profile $scoped   The currently logged in/scoped profile
1974      *
1975      * @return array representation of <statusnet:notice_info> element
1976      */
1977
1978     function noticeInfo(Profile $scoped=null)
1979     {
1980         // local notice ID (useful to clients for ordering)
1981
1982         $noticeInfoAttr = array('local_id' => $this->id);
1983
1984         // notice source
1985
1986         $ns = $this->getSource();
1987
1988         if ($ns instanceof Notice_source) {
1989             $noticeInfoAttr['source'] =  $ns->code;
1990             if (!empty($ns->url)) {
1991                 $noticeInfoAttr['source_link'] = $ns->url;
1992                 if (!empty($ns->name)) {
1993                     $noticeInfoAttr['source'] =  '<a href="'
1994                         . htmlspecialchars($ns->url)
1995                         . '" rel="nofollow">'
1996                         . htmlspecialchars($ns->name)
1997                         . '</a>';
1998                 }
1999             }
2000         }
2001
2002         // favorite and repeated
2003
2004         if ($scoped instanceof Profile) {
2005             $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
2006         }
2007
2008         if (!empty($this->repeat_of)) {
2009             $noticeInfoAttr['repeat_of'] = $this->repeat_of;
2010         }
2011
2012         Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
2013
2014         return array('statusnet:notice_info', $noticeInfoAttr, null);
2015     }
2016
2017     /**
2018      * Returns an XML string fragment with a reference to a notice as an
2019      * Activity Streams noun object with the given element type.
2020      *
2021      * Assumes that 'activity' namespace has been previously defined.
2022      *
2023      * @param string $element one of 'subject', 'object', 'target'
2024      * @return string
2025      */
2026
2027     function asActivityNoun($element)
2028     {
2029         $noun = $this->asActivityObject();
2030         return $noun->asString('activity:' . $element);
2031     }
2032
2033     public function asActivityObject()
2034     {
2035         $object = new ActivityObject();
2036
2037         if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
2038             $object->type    = $this->object_type ?: ActivityObject::NOTE;
2039             $object->id      = $this->getUri();
2040             $object->title   = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
2041             $object->content = $this->rendered;
2042             $object->link    = $this->getUrl();
2043
2044             $object->extra[] = array('status_net', array('notice_id' => $this->id));
2045
2046             Event::handle('EndActivityObjectFromNotice', array($this, &$object));
2047         }
2048
2049         return $object;
2050     }
2051
2052     /**
2053      * Determine which notice, if any, a new notice is in reply to.
2054      *
2055      * For conversation tracking, we try to see where this notice fits
2056      * in the tree. Beware that this may very well give false positives
2057      * and add replies to wrong threads (if there have been newer posts
2058      * by the same user as we're replying to).
2059      *
2060      * @param Profile $sender     Author profile
2061      * @param string  $content    Final notice content
2062      *
2063      * @return integer ID of replied-to notice, or null for not a reply.
2064      */
2065
2066     static function getInlineReplyTo(Profile $sender, $content)
2067     {
2068         // Is there an initial @ or T?
2069         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
2070                 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
2071             $nickname = common_canonical_nickname($match[1]);
2072         } else {
2073             return null;
2074         }
2075
2076         // Figure out who that is.
2077         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
2078
2079         if ($recipient instanceof Profile) {
2080             // Get their last notice
2081             $last = $recipient->getCurrentNotice();
2082             if ($last instanceof Notice) {
2083                 return $last;
2084             }
2085             // Maybe in the future we want to handle something else below
2086             // so don't return getCurrentNotice() immediately.
2087         }
2088
2089         return null;
2090     }
2091
2092     static function maxContent()
2093     {
2094         $contentlimit = common_config('notice', 'contentlimit');
2095         // null => use global limit (distinct from 0!)
2096         if (is_null($contentlimit)) {
2097             $contentlimit = common_config('site', 'textlimit');
2098         }
2099         return $contentlimit;
2100     }
2101
2102     static function contentTooLong($content)
2103     {
2104         $contentlimit = self::maxContent();
2105         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
2106     }
2107
2108     function getLocation()
2109     {
2110         $location = null;
2111
2112         if (!empty($this->location_id) && !empty($this->location_ns)) {
2113             $location = Location::fromId($this->location_id, $this->location_ns);
2114         }
2115
2116         if (is_null($location)) { // no ID, or Location::fromId() failed
2117             if (!empty($this->lat) && !empty($this->lon)) {
2118                 $location = Location::fromLatLon($this->lat, $this->lon);
2119             }
2120         }
2121
2122         return $location;
2123     }
2124
2125     /**
2126      * Convenience function for posting a repeat of an existing message.
2127      *
2128      * @param Profile $repeater Profile which is doing the repeat
2129      * @param string $source: posting source key, eg 'web', 'api', etc
2130      * @return Notice
2131      *
2132      * @throws Exception on failure or permission problems
2133      */
2134     function repeat(Profile $repeater, $source)
2135     {
2136         $author = $this->getProfile();
2137
2138         // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
2139         // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
2140         $content = sprintf(_('RT @%1$s %2$s'),
2141                            $author->getNickname(),
2142                            $this->content);
2143
2144         $maxlen = self::maxContent();
2145         if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
2146             // Web interface and current Twitter API clients will
2147             // pull the original notice's text, but some older
2148             // clients and RSS/Atom feeds will see this trimmed text.
2149             //
2150             // Unfortunately this is likely to lose tags or URLs
2151             // at the end of long notices.
2152             $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
2153         }
2154
2155
2156         // Scope is same as this one's
2157         return self::saveNew($repeater->id,
2158                              $content,
2159                              $source,
2160                              array('repeat_of' => $this->id,
2161                                    'scope' => $this->scope));
2162     }
2163
2164     // These are supposed to be in chron order!
2165
2166     function repeatStream($limit=100)
2167     {
2168         $cache = Cache::instance();
2169
2170         if (empty($cache)) {
2171             $ids = $this->_repeatStreamDirect($limit);
2172         } else {
2173             $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
2174             if ($idstr !== false) {
2175                 if (empty($idstr)) {
2176                         $ids = array();
2177                 } else {
2178                         $ids = explode(',', $idstr);
2179                 }
2180             } else {
2181                 $ids = $this->_repeatStreamDirect(100);
2182                 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
2183             }
2184             if ($limit < 100) {
2185                 // We do a max of 100, so slice down to limit
2186                 $ids = array_slice($ids, 0, $limit);
2187             }
2188         }
2189
2190         return NoticeStream::getStreamByIds($ids);
2191     }
2192
2193     function _repeatStreamDirect($limit)
2194     {
2195         $notice = new Notice();
2196
2197         $notice->selectAdd(); // clears it
2198         $notice->selectAdd('id');
2199
2200         $notice->repeat_of = $this->id;
2201
2202         $notice->orderBy('created, id'); // NB: asc!
2203
2204         if (!is_null($limit)) {
2205             $notice->limit(0, $limit);
2206         }
2207
2208         return $notice->fetchAll('id');
2209     }
2210
2211     function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
2212     {
2213         $options = array();
2214
2215         if (!empty($location_id) && !empty($location_ns)) {
2216             $options['location_id'] = $location_id;
2217             $options['location_ns'] = $location_ns;
2218
2219             $location = Location::fromId($location_id, $location_ns);
2220
2221             if ($location instanceof Location) {
2222                 $options['lat'] = $location->lat;
2223                 $options['lon'] = $location->lon;
2224             }
2225
2226         } else if (!empty($lat) && !empty($lon)) {
2227             $options['lat'] = $lat;
2228             $options['lon'] = $lon;
2229
2230             $location = Location::fromLatLon($lat, $lon);
2231
2232             if ($location instanceof Location) {
2233                 $options['location_id'] = $location->location_id;
2234                 $options['location_ns'] = $location->location_ns;
2235             }
2236         } else if (!empty($profile)) {
2237             if (isset($profile->lat) && isset($profile->lon)) {
2238                 $options['lat'] = $profile->lat;
2239                 $options['lon'] = $profile->lon;
2240             }
2241
2242             if (isset($profile->location_id) && isset($profile->location_ns)) {
2243                 $options['location_id'] = $profile->location_id;
2244                 $options['location_ns'] = $profile->location_ns;
2245             }
2246         }
2247
2248         return $options;
2249     }
2250
2251     function clearAttentions()
2252     {
2253         $att = new Attention();
2254         $att->notice_id = $this->getID();
2255
2256         if ($att->find()) {
2257             while ($att->fetch()) {
2258                 // Can't do delete() on the object directly since it won't remove all of it
2259                 $other = clone($att);
2260                 $other->delete();
2261             }
2262         }
2263     }
2264
2265     function clearReplies()
2266     {
2267         $replyNotice = new Notice();
2268         $replyNotice->reply_to = $this->id;
2269
2270         //Null any notices that are replies to this notice
2271
2272         if ($replyNotice->find()) {
2273             while ($replyNotice->fetch()) {
2274                 $orig = clone($replyNotice);
2275                 $replyNotice->reply_to = null;
2276                 $replyNotice->update($orig);
2277             }
2278         }
2279
2280         // Reply records
2281
2282         $reply = new Reply();
2283         $reply->notice_id = $this->id;
2284
2285         if ($reply->find()) {
2286             while($reply->fetch()) {
2287                 self::blow('reply:stream:%d', $reply->profile_id);
2288                 $reply->delete();
2289             }
2290         }
2291
2292         $reply->free();
2293     }
2294
2295     function clearFiles()
2296     {
2297         $f2p = new File_to_post();
2298
2299         $f2p->post_id = $this->id;
2300
2301         if ($f2p->find()) {
2302             while ($f2p->fetch()) {
2303                 $f2p->delete();
2304             }
2305         }
2306         // FIXME: decide whether to delete File objects
2307         // ...and related (actual) files
2308     }
2309
2310     function clearRepeats()
2311     {
2312         $repeatNotice = new Notice();
2313         $repeatNotice->repeat_of = $this->id;
2314
2315         //Null any notices that are repeats of this notice
2316
2317         if ($repeatNotice->find()) {
2318             while ($repeatNotice->fetch()) {
2319                 $orig = clone($repeatNotice);
2320                 $repeatNotice->repeat_of = null;
2321                 $repeatNotice->update($orig);
2322             }
2323         }
2324     }
2325
2326     function clearTags()
2327     {
2328         $tag = new Notice_tag();
2329         $tag->notice_id = $this->id;
2330
2331         if ($tag->find()) {
2332             while ($tag->fetch()) {
2333                 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2334                 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2335                 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2336                 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2337                 $tag->delete();
2338             }
2339         }
2340
2341         $tag->free();
2342     }
2343
2344     function clearGroupInboxes()
2345     {
2346         $gi = new Group_inbox();
2347
2348         $gi->notice_id = $this->id;
2349
2350         if ($gi->find()) {
2351             while ($gi->fetch()) {
2352                 self::blow('user_group:notice_ids:%d', $gi->group_id);
2353                 $gi->delete();
2354             }
2355         }
2356
2357         $gi->free();
2358     }
2359
2360     function distribute()
2361     {
2362         // We always insert for the author so they don't
2363         // have to wait
2364         Event::handle('StartNoticeDistribute', array($this));
2365
2366         // If there's a failure, we want to _force_
2367         // distribution at this point.
2368         try {
2369             $qm = QueueManager::get();
2370             $qm->enqueue($this, 'distrib');
2371         } catch (Exception $e) {
2372             // If the exception isn't transient, this
2373             // may throw more exceptions as DQH does
2374             // its own enqueueing. So, we ignore them!
2375             try {
2376                 $handler = new DistribQueueHandler();
2377                 $handler->handle($this);
2378             } catch (Exception $e) {
2379                 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2380             }
2381             // Re-throw so somebody smarter can handle it.
2382             throw $e;
2383         }
2384     }
2385
2386     function insert()
2387     {
2388         $result = parent::insert();
2389
2390         if ($result === false) {
2391             common_log_db_error($this, 'INSERT', __FILE__);
2392             // TRANS: Server exception thrown when a stored object entry cannot be saved.
2393             throw new ServerException('Could not save Notice');
2394         }
2395
2396         // Profile::hasRepeated() abuses pkeyGet(), so we
2397         // have to clear manually
2398         if (!empty($this->repeat_of)) {
2399             $c = self::memcache();
2400             if (!empty($c)) {
2401                 $ck = self::multicacheKey('Notice',
2402                                           array('profile_id' => $this->profile_id,
2403                                                 'repeat_of' => $this->repeat_of));
2404                 $c->delete($ck);
2405             }
2406         }
2407
2408         // Update possibly ID-dependent columns: URI, conversation
2409         // (now that INSERT has added the notice's local id)
2410         $orig = clone($this);
2411         $changed = false;
2412
2413         // We can only get here if it's a local notice, since remote notices
2414         // should've bailed out earlier due to lacking a URI.
2415         if (empty($this->uri)) {
2416             $this->uri = sprintf('%s%s=%d:%s=%s',
2417                                 TagURI::mint(),
2418                                 'noticeId', $this->id,
2419                                 'objectType', $this->get_object_type(true));
2420             $changed = true;
2421         }
2422
2423         if ($changed && $this->update($orig) === false) {
2424             common_log_db_error($notice, 'UPDATE', __FILE__);
2425             // TRANS: Server exception thrown when a notice cannot be updated.
2426             throw new ServerException(_('Problem saving notice.'));
2427         }
2428
2429         $this->blowOnInsert();
2430
2431         return $result;
2432     }
2433
2434     /**
2435      * Get the source of the notice
2436      *
2437      * @return Notice_source $ns A notice source object. 'code' is the only attribute
2438      *                           guaranteed to be populated.
2439      */
2440     function getSource()
2441     {
2442         if (empty($this->source)) {
2443             return false;
2444         }
2445
2446         $ns = new Notice_source();
2447         switch ($this->source) {
2448         case 'web':
2449         case 'xmpp':
2450         case 'mail':
2451         case 'omb':
2452         case 'system':
2453         case 'api':
2454             $ns->code = $this->source;
2455             break;
2456         default:
2457             $ns = Notice_source::getKV($this->source);
2458             if (!$ns) {
2459                 $ns = new Notice_source();
2460                 $ns->code = $this->source;
2461                 $app = Oauth_application::getKV('name', $this->source);
2462                 if ($app) {
2463                     $ns->name = $app->name;
2464                     $ns->url  = $app->source_url;
2465                 }
2466             }
2467             break;
2468         }
2469
2470         return $ns;
2471     }
2472
2473     /**
2474      * Determine whether the notice was locally created
2475      *
2476      * @return boolean locality
2477      */
2478
2479     public function isLocal()
2480     {
2481         return ($this->is_local == Notice::LOCAL_PUBLIC ||
2482                 $this->is_local == Notice::LOCAL_NONPUBLIC);
2483     }
2484
2485     public function isRepeat()
2486     {
2487         return !empty($this->repeat_of);
2488     }
2489
2490     /**
2491      * Get the list of hash tags saved with this notice.
2492      *
2493      * @return array of strings
2494      */
2495     public function getTags()
2496     {
2497         // Check default scope (non-private notices)
2498         $inScope = (!$this->isPrivateScope());
2499
2500         // Get current profile
2501         $profile = Profile::current();
2502
2503         // Is the general scope check okay and the user in logged in?
2504         //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . ']: inScope=' . intval($inScope) . ',profile[]=' . gettype($profile));
2505         if (($inScope === TRUE) && ($profile instanceof Profile)) {
2506             /*
2507              * Check scope, else a privacy leaks happens this way:
2508              *
2509              * 1) Bob and Alice follow each other and write private notices
2510              *    (this->scope=2) to each other.
2511              * 2) Bob uses tags in his private notice to alice (which she can
2512              *    read from him).
2513              * 3) Alice adds that notice (with tags) to her favorites
2514              *    ("faving") it.
2515              * 4) The tags from Bob's private notice becomes visible in Alice's
2516              *    profile.
2517              *
2518              * This has the simple background that the scope is not being
2519              * re-checked. This has to be done here at this point because given
2520              * above scenario is a privacy leak as the tags may be *really*
2521              * private (nobody else shall see them) such as initmate words or
2522              * very political words.
2523              */
2524             $inScope = $this->inScope($profile);
2525             //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . ']: inScope=' . intval($inScope) . ' - After inScope() has been called.');
2526         }
2527
2528         $tags = array();
2529
2530         $keypart = sprintf('notice:tags:%d', $this->id);
2531
2532         $tagstr = self::cacheGet($keypart);
2533
2534         if ($tagstr !== false) {
2535             $tags = explode(',', $tagstr);
2536         } else {
2537             $tag = new Notice_tag();
2538             $tag->notice_id = $this->id;
2539
2540             // Check scope for privacy-leak protection (see some lines above why)
2541             if (($inScope === TRUE) && ($tag->find())) {
2542                 while ($tag->fetch()) {
2543                     $tags[] = $tag->tag;
2544                 }
2545             }
2546             self::cacheSet($keypart, implode(',', $tags));
2547         }
2548
2549         return $tags;
2550     }
2551
2552     static private function utcDate($dt)
2553     {
2554         $dateStr = date('d F Y H:i:s', strtotime($dt));
2555         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2556         return $d->format(DATE_W3C);
2557     }
2558
2559     /**
2560      * Look up the creation timestamp for a given notice ID, even
2561      * if it's been deleted.
2562      *
2563      * @param int $id
2564      * @return mixed string recorded creation timestamp, or false if can't be found
2565      */
2566     public static function getAsTimestamp($id)
2567     {
2568         if (!$id) {
2569             return false;
2570         }
2571
2572         $notice = Notice::getKV('id', $id);
2573         if ($notice) {
2574             return $notice->created;
2575         }
2576
2577         $deleted = Deleted_notice::getKV('id', $id);
2578         if ($deleted) {
2579             return $deleted->created;
2580         }
2581
2582         return false;
2583     }
2584
2585     /**
2586      * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2587      * parameter, matching notices posted after the given one (exclusive).
2588      *
2589      * If the referenced notice can't be found, will return false.
2590      *
2591      * @param int $id
2592      * @param string $idField
2593      * @param string $createdField
2594      * @return mixed string or false if no match
2595      */
2596     public static function whereSinceId($id, $idField='id', $createdField='created')
2597     {
2598         $since = Notice::getAsTimestamp($id);
2599         if ($since) {
2600             return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2601         }
2602         return false;
2603     }
2604
2605     /**
2606      * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2607      * parameter, matching notices posted after the given one (exclusive), and
2608      * if necessary add it to the data object's query.
2609      *
2610      * @param DB_DataObject $obj
2611      * @param int $id
2612      * @param string $idField
2613      * @param string $createdField
2614      * @return mixed string or false if no match
2615      */
2616     public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2617     {
2618         $since = self::whereSinceId($id, $idField, $createdField);
2619         if ($since) {
2620             $obj->whereAdd($since);
2621         }
2622     }
2623
2624     /**
2625      * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2626      * parameter, matching notices posted before the given one (inclusive).
2627      *
2628      * If the referenced notice can't be found, will return false.
2629      *
2630      * @param int $id
2631      * @param string $idField
2632      * @param string $createdField
2633      * @return mixed string or false if no match
2634      */
2635     public static function whereMaxId($id, $idField='id', $createdField='created')
2636     {
2637         $max = Notice::getAsTimestamp($id);
2638         if ($max) {
2639             return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2640         }
2641         return false;
2642     }
2643
2644     /**
2645      * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2646      * parameter, matching notices posted before the given one (inclusive), and
2647      * if necessary add it to the data object's query.
2648      *
2649      * @param DB_DataObject $obj
2650      * @param int $id
2651      * @param string $idField
2652      * @param string $createdField
2653      * @return mixed string or false if no match
2654      */
2655     public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2656     {
2657         $max = self::whereMaxId($id, $idField, $createdField);
2658         if ($max) {
2659             $obj->whereAdd($max);
2660         }
2661     }
2662
2663     function isPublic()
2664     {
2665         return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2666                 ($this->is_local != Notice::GATEWAY));
2667     }
2668
2669     public function isPrivateScope () {
2670         return (
2671             ($this->is_local === Notice::LOCAL_NONPUBLIC) ||
2672             ($this->is_local === Notice::GATEWAY) ||
2673             ($this->is_local === Notice::REMOTE)
2674         );
2675     }
2676
2677     /**
2678      * Check that the given profile is allowed to read, respond to, or otherwise
2679      * act on this notice.
2680      *
2681      * The $scope member is a bitmask of scopes, representing a logical AND of the
2682      * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2683      * "only visible to people who are mentioned in the notice AND are users on this site."
2684      * Users on the site who are not mentioned in the notice will not be able to see the
2685      * notice.
2686      *
2687      * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2688      *
2689      * @return boolean whether the profile is in the notice's scope
2690      */
2691     function inScope(Profile $profile=null)
2692     {
2693         if (is_null($profile)) {
2694             $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2695         } else {
2696             $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2697         }
2698
2699         $result = self::cacheGet($keypart);
2700
2701         if ($result === false) {
2702             $bResult = false;
2703             if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2704                 $bResult = $this->_inScope($profile);
2705                 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2706             }
2707             $result = ($bResult) ? 1 : 0;
2708             self::cacheSet($keypart, $result, 0, 300);
2709         }
2710
2711         return ($result == 1) ? true : false;
2712     }
2713
2714     protected function _inScope(Profile $profile=null)
2715     {
2716         if (!is_null($this->scope)) {
2717             $scope = $this->scope;
2718         } else {
2719             $scope = self::defaultScope();
2720         }
2721
2722         if ($scope == 0 && !$this->getProfile()->isPrivateStream()) { // Not scoping, so it is public.
2723             return !$this->isHiddenSpam($profile);
2724         }
2725
2726         // If there's scope, anon cannot be in scope
2727         if (empty($profile)) {
2728             return false;
2729         }
2730
2731         // Author is always in scope
2732         if ($this->profile_id == $profile->id) {
2733             return true;
2734         }
2735
2736         // Only for users on this site
2737         if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2738             return false;
2739         }
2740
2741         // Only for users mentioned in the notice
2742         if ($scope & Notice::ADDRESSEE_SCOPE) {
2743
2744             $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2745                                          'profile_id' => $profile->id));
2746
2747             if (!$reply instanceof Reply) {
2748                 return false;
2749             }
2750         }
2751
2752         // Only for members of the given group
2753         if ($scope & Notice::GROUP_SCOPE) {
2754
2755             // XXX: just query for the single membership
2756
2757             $groups = $this->getGroups();
2758
2759             $foundOne = false;
2760
2761             foreach ($groups as $group) {
2762                 if ($profile->isMember($group)) {
2763                     $foundOne = true;
2764                     break;
2765                 }
2766             }
2767
2768             if (!$foundOne) {
2769                 return false;
2770             }
2771         }
2772
2773         if ($scope & Notice::FOLLOWER_SCOPE || $this->getProfile()->isPrivateStream()) {
2774
2775             if (!Subscription::exists($profile, $this->getProfile())) {
2776                 return false;
2777             }
2778         }
2779
2780         return !$this->isHiddenSpam($profile);
2781     }
2782
2783     function isHiddenSpam(Profile $profile=null) {
2784
2785         // Hide posts by silenced users from everyone but moderators.
2786
2787         if (common_config('notice', 'hidespam')) {
2788
2789             try {
2790                 $author = $this->getProfile();
2791             } catch(Exception $e) {
2792                 // If we can't get an author, keep it hidden.
2793                 // XXX: technically not spam, but, whatever.
2794                 return true;
2795             }
2796
2797             if ($author->hasRole(Profile_role::SILENCED)) {
2798                 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2799                     return true;
2800                 }
2801             }
2802         }
2803
2804         return false;
2805     }
2806
2807     public function getParent()
2808     {
2809         $parent = Notice::getKV('id', $this->reply_to);
2810
2811         if (!$parent instanceof Notice) {
2812             throw new ServerException('Notice has no parent');
2813         }
2814
2815         return $parent;
2816     }
2817
2818     /**
2819      * Magic function called at serialize() time.
2820      *
2821      * We use this to drop a couple process-specific references
2822      * from DB_DataObject which can cause trouble in future
2823      * processes.
2824      *
2825      * @return array of variable names to include in serialization.
2826      */
2827
2828     function __sleep()
2829     {
2830         $vars = parent::__sleep();
2831         $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2832         return array_diff($vars, $skip);
2833     }
2834
2835     static function defaultScope()
2836     {
2837         $scope = common_config('notice', 'defaultscope');
2838         if (is_null($scope)) {
2839                 if (common_config('site', 'private')) {
2840                         $scope = 1;
2841                 } else {
2842                         $scope = 0;
2843                 }
2844         }
2845         return $scope;
2846     }
2847
2848         static function fillProfiles(array $notices)
2849         {
2850                 $map = self::getProfiles($notices);
2851                 foreach ($notices as $entry=>$notice) {
2852             try {
2853                         if (array_key_exists($notice->profile_id, $map)) {
2854                                 $notice->_setProfile($map[$notice->profile_id]);
2855                         }
2856             } catch (NoProfileException $e) {
2857                 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2858                 unset($notices[$entry]);
2859             }
2860                 }
2861
2862                 return array_values($map);
2863         }
2864
2865         static function getProfiles(array &$notices)
2866         {
2867                 $ids = array();
2868                 foreach ($notices as $notice) {
2869                         $ids[] = $notice->profile_id;
2870                 }
2871                 $ids = array_unique($ids);
2872                 return Profile::pivotGet('id', $ids);
2873         }
2874
2875         static function fillGroups(array &$notices)
2876         {
2877         $ids = self::_idsOf($notices);
2878         $gis = Group_inbox::listGet('notice_id', $ids);
2879         $gids = array();
2880
2881                 foreach ($gis as $id => $gi) {
2882                     foreach ($gi as $g)
2883                     {
2884                         $gids[] = $g->group_id;
2885                     }
2886                 }
2887
2888                 $gids = array_unique($gids);
2889                 $group = User_group::pivotGet('id', $gids);
2890                 foreach ($notices as $notice)
2891                 {
2892                         $grps = array();
2893                         $gi = $gis[$notice->id];
2894                         foreach ($gi as $g) {
2895                             $grps[] = $group[$g->group_id];
2896                         }
2897                     $notice->_setGroups($grps);
2898                 }
2899         }
2900
2901     static function _idsOf(array &$notices)
2902     {
2903                 $ids = array();
2904                 foreach ($notices as $notice) {
2905                         $ids[$notice->id] = true;
2906                 }
2907                 return array_keys($ids);
2908     }
2909
2910     static function fillAttachments(array &$notices)
2911     {
2912         $ids = self::_idsOf($notices);
2913         $f2pMap = File_to_post::listGet('post_id', $ids);
2914                 $fileIds = array();
2915                 foreach ($f2pMap as $noticeId => $f2ps) {
2916             foreach ($f2ps as $f2p) {
2917                 $fileIds[] = $f2p->file_id;
2918             }
2919         }
2920
2921         $fileIds = array_unique($fileIds);
2922                 $fileMap = File::pivotGet('id', $fileIds);
2923                 foreach ($notices as $notice)
2924                 {
2925                         $files = array();
2926                         $f2ps = $f2pMap[$notice->id];
2927                         foreach ($f2ps as $f2p) {
2928                             $files[] = $fileMap[$f2p->file_id];
2929                         }
2930                     $notice->_setAttachments($files);
2931                 }
2932     }
2933
2934     static function fillReplies(array &$notices)
2935     {
2936         $ids = self::_idsOf($notices);
2937         $replyMap = Reply::listGet('notice_id', $ids);
2938         foreach ($notices as $notice) {
2939             $replies = $replyMap[$notice->id];
2940             $ids = array();
2941             foreach ($replies as $reply) {
2942                 $ids[] = $reply->profile_id;
2943             }
2944             $notice->_setReplies($ids);
2945         }
2946     }
2947
2948     /**
2949      * Checks whether the current profile is allowed (in scope) to see this notice.
2950      *
2951      * @return $inScope Whether the current profile is allowed to see this notice
2952      */
2953     function isCurrentProfileInScope () {
2954         // Check scope, default is allowed
2955         $inScope = TRUE;
2956
2957         //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . '] this->tag=' . $this->tag . ',this->id=' . $this->id . ',this->scope=' . $this->scope);
2958
2959         // Is it private scope?
2960         if ($this->isPrivateScope()) {
2961             // 2) Get current profile
2962             $profile = Profile::current();
2963
2964             // Is the profile not set?
2965             if (!$profile instanceof Profile) {
2966                 // Public viewer shall not see a tag from a private dent (privacy leak)
2967                 //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . '] Not logged in (public view).');
2968                 $inScope = FALSE;
2969             } elseif (!$this->inScope($profile)) {
2970                 // Current profile is not in scope (not allowed to see) of notice
2971                 //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . '] profile->id=' . $profile->id . ' is not allowed to see this notice.');
2972                 $inScope = FALSE;
2973             }
2974         }
2975
2976         // Return result
2977         //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . '] this->tag=' . $this->tag . ',this->weight=' . $this->weight . ',inScope=' . intval($inScope) . ' - EXIT!');
2978         return $inScope;
2979     }
2980 }