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