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