]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
Removed Inbox from core (unused since 4b2a66ed29091209c05d74755e42f96265c846ce)
[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     function getSubscribedUsers()
1068     {
1069         $user = new User();
1070
1071         if(common_config('db','quote_identifiers'))
1072           $user_table = '"user"';
1073         else $user_table = 'user';
1074
1075         $qry =
1076           'SELECT id ' .
1077           'FROM '. $user_table .' JOIN subscription '.
1078           'ON '. $user_table .'.id = subscription.subscriber ' .
1079           'WHERE subscription.subscribed = %d ';
1080
1081         $user->query(sprintf($qry, $this->profile_id));
1082
1083         $ids = array();
1084
1085         while ($user->fetch()) {
1086             $ids[] = $user->id;
1087         }
1088
1089         $user->free();
1090
1091         return $ids;
1092     }
1093
1094     function getProfileTags()
1095     {
1096         $profile = $this->getProfile();
1097         $list    = $profile->getOtherTags($profile);
1098         $ptags   = array();
1099
1100         while($list->fetch()) {
1101             $ptags[] = clone($list);
1102         }
1103
1104         return $ptags;
1105     }
1106
1107     /**
1108      * Record this notice to the given group inboxes for delivery.
1109      * Overrides the regular parsing of !group markup.
1110      *
1111      * @param string $group_ids
1112      * @fixme might prefer URIs as identifiers, as for replies?
1113      *        best with generalizations on user_group to support
1114      *        remote groups better.
1115      */
1116     function saveKnownGroups($group_ids)
1117     {
1118         if (!is_array($group_ids)) {
1119             // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1120             throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1121         }
1122
1123         $groups = array();
1124         foreach (array_unique($group_ids) as $id) {
1125             $group = User_group::getKV('id', $id);
1126             if ($group instanceof User_group) {
1127                 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1128                 $result = $this->addToGroupInbox($group);
1129                 if (!$result) {
1130                     common_log_db_error($gi, 'INSERT', __FILE__);
1131                 }
1132
1133                 if (common_config('group', 'addtag')) {
1134                     // we automatically add a tag for every group name, too
1135
1136                     $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1137                                                      'notice_id' => $this->id));
1138
1139                     if (is_null($tag)) {
1140                         $this->saveTag($group->nickname);
1141                     }
1142                 }
1143
1144                 $groups[] = clone($group);
1145             } else {
1146                 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1147             }
1148         }
1149
1150         return $groups;
1151     }
1152
1153     function addToGroupInbox(User_group $group)
1154     {
1155         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1156                                          'notice_id' => $this->id));
1157
1158         if (!$gi instanceof Group_inbox) {
1159
1160             $gi = new Group_inbox();
1161
1162             $gi->group_id  = $group->id;
1163             $gi->notice_id = $this->id;
1164             $gi->created   = $this->created;
1165
1166             $result = $gi->insert();
1167
1168             if (!$result) {
1169                 common_log_db_error($gi, 'INSERT', __FILE__);
1170                 // TRANS: Server exception thrown when an update for a group inbox fails.
1171                 throw new ServerException(_('Problem saving group inbox.'));
1172             }
1173
1174             self::blow('user_group:notice_ids:%d', $gi->group_id);
1175         }
1176
1177         return true;
1178     }
1179
1180     /**
1181      * Save reply records indicating that this notice needs to be
1182      * delivered to the local users with the given URIs.
1183      *
1184      * Since this is expected to be used when saving foreign-sourced
1185      * messages, we won't deliver to any remote targets as that's the
1186      * source service's responsibility.
1187      *
1188      * Mail notifications etc will be handled later.
1189      *
1190      * @param array  $uris   Array of unique identifier URIs for recipients
1191      */
1192     function saveKnownReplies(array $uris)
1193     {
1194         if (empty($uris)) {
1195             return;
1196         }
1197
1198         $sender = Profile::getKV($this->profile_id);
1199
1200         foreach (array_unique($uris) as $uri) {
1201
1202             $profile = Profile::fromURI($uri);
1203
1204             if (!$profile instanceof Profile) {
1205                 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1206                 continue;
1207             }
1208
1209             if ($profile->hasBlocked($sender)) {
1210                 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1211                 continue;
1212             }
1213
1214             $this->saveReply($profile->id);
1215             self::blow('reply:stream:%d', $profile->id);
1216         }
1217
1218         return;
1219     }
1220
1221     /**
1222      * Pull @-replies from this message's content in StatusNet markup format
1223      * and save reply records indicating that this message needs to be
1224      * delivered to those users.
1225      *
1226      * Mail notifications to local profiles will be sent later.
1227      *
1228      * @return array of integer profile IDs
1229      */
1230
1231     function saveReplies()
1232     {
1233         // Don't save reply data for repeats
1234
1235         if (!empty($this->repeat_of)) {
1236             return array();
1237         }
1238
1239         $sender = Profile::getKV($this->profile_id);
1240
1241         $replied = array();
1242
1243         // If it's a reply, save for the replied-to author
1244         try {
1245             $parent = $this->getParent();
1246             $author = $parent->getProfile();
1247             if ($author instanceof Profile) {
1248                 $this->saveReply($author->id);
1249                 $replied[$author->id] = 1;
1250                 self::blow('reply:stream:%d', $author->id);
1251             }
1252         } catch (Exception $e) {
1253             // Not a reply, since it has no parent!
1254         }
1255
1256         // @todo ideally this parser information would only
1257         // be calculated once.
1258
1259         $mentions = common_find_mentions($this->content, $this);
1260
1261         // store replied only for first @ (what user/notice what the reply directed,
1262         // we assume first @ is it)
1263
1264         foreach ($mentions as $mention) {
1265
1266             foreach ($mention['mentioned'] as $mentioned) {
1267
1268                 // skip if they're already covered
1269
1270                 if (!empty($replied[$mentioned->id])) {
1271                     continue;
1272                 }
1273
1274                 // Don't save replies from blocked profile to local user
1275
1276                 $mentioned_user = User::getKV('id', $mentioned->id);
1277                 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1278                     continue;
1279                 }
1280
1281                 $this->saveReply($mentioned->id);
1282                 $replied[$mentioned->id] = 1;
1283                 self::blow('reply:stream:%d', $mentioned->id);
1284             }
1285         }
1286
1287         $recipientIds = array_keys($replied);
1288
1289         return $recipientIds;
1290     }
1291
1292     function saveReply($profileId)
1293     {
1294         $reply = new Reply();
1295
1296         $reply->notice_id  = $this->id;
1297         $reply->profile_id = $profileId;
1298         $reply->modified   = $this->created;
1299
1300         $reply->insert();
1301
1302         return $reply;
1303     }
1304
1305     protected $_replies = -1;
1306
1307     /**
1308      * Pull the complete list of @-reply targets for this notice.
1309      *
1310      * @return array of integer profile ids
1311      */
1312     function getReplies()
1313     {
1314         if ($this->_replies != -1) {
1315             return $this->_replies;
1316         }
1317
1318         $replyMap = Reply::listGet('notice_id', array($this->id));
1319
1320         $ids = array();
1321
1322         foreach ($replyMap[$this->id] as $reply) {
1323             $ids[] = $reply->profile_id;
1324         }
1325
1326         $this->_replies = $ids;
1327
1328         return $ids;
1329     }
1330
1331     function _setReplies($replies)
1332     {
1333         $this->_replies = $replies;
1334     }
1335
1336     /**
1337      * Pull the complete list of @-reply targets for this notice.
1338      *
1339      * @return array of Profiles
1340      */
1341     function getReplyProfiles()
1342     {
1343         $ids = $this->getReplies();
1344         
1345         $profiles = Profile::multiGet('id', $ids);
1346         
1347         return $profiles->fetchAll();
1348     }
1349
1350     /**
1351      * Send e-mail notifications to local @-reply targets.
1352      *
1353      * Replies must already have been saved; this is expected to be run
1354      * from the distrib queue handler.
1355      */
1356     function sendReplyNotifications()
1357     {
1358         // Don't send reply notifications for repeats
1359
1360         if (!empty($this->repeat_of)) {
1361             return array();
1362         }
1363
1364         $recipientIds = $this->getReplies();
1365
1366         foreach ($recipientIds as $recipientId) {
1367             $user = User::getKV('id', $recipientId);
1368             if ($user instanceof User) {
1369                 mail_notify_attn($user, $this);
1370             }
1371         }
1372     }
1373
1374     /**
1375      * Pull list of groups this notice needs to be delivered to,
1376      * as previously recorded by saveKnownGroups().
1377      *
1378      * @return array of Group objects
1379      */
1380     
1381     protected $_groups = -1;
1382     
1383     function getGroups()
1384     {
1385         // Don't save groups for repeats
1386
1387         if (!empty($this->repeat_of)) {
1388             return array();
1389         }
1390         
1391         if ($this->_groups != -1)
1392         {
1393             return $this->_groups;
1394         }
1395         
1396         $gis = Group_inbox::listGet('notice_id', array($this->id));
1397
1398         $ids = array();
1399
1400                 foreach ($gis[$this->id] as $gi)
1401                 {
1402                     $ids[] = $gi->group_id;
1403                 }
1404                 
1405                 $groups = User_group::multiGet('id', $ids);
1406                 
1407                 $this->_groups = $groups->fetchAll();
1408                 
1409                 return $this->_groups;
1410     }
1411     
1412     function _setGroups($groups)
1413     {
1414         $this->_groups = $groups;
1415     }
1416
1417     /**
1418      * Convert a notice into an activity for export.
1419      *
1420      * @param User $cur Current user
1421      *
1422      * @return Activity activity object representing this Notice.
1423      */
1424
1425     function asActivity($cur=null)
1426     {
1427         $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1428
1429         if ($act instanceof Activity) {
1430             return $act;
1431         }
1432         $act = new Activity();
1433
1434         if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1435
1436             $act->id      = $this->uri;
1437             $act->time    = strtotime($this->created);
1438             $act->link    = $this->bestUrl();
1439             $act->content = common_xml_safe_str($this->rendered);
1440
1441             $profile = $this->getProfile();
1442
1443             $act->actor            = ActivityObject::fromProfile($profile);
1444             $act->actor->extra[]   = $profile->profileInfo($cur);
1445
1446             $act->verb = $this->verb;
1447
1448             if ($this->repeat_of) {
1449                 $repeated = Notice::getKV('id', $this->repeat_of);
1450                 if ($repeated instanceof Notice) {
1451                     $act->objects[] = $repeated->asActivity($cur);
1452                 }
1453             } else {
1454                 $act->objects[] = ActivityObject::fromNotice($this);
1455             }
1456
1457             // XXX: should this be handled by default processing for object entry?
1458
1459             // Categories
1460
1461             $tags = $this->getTags();
1462
1463             foreach ($tags as $tag) {
1464                 $cat       = new AtomCategory();
1465                 $cat->term = $tag;
1466
1467                 $act->categories[] = $cat;
1468             }
1469
1470             // Enclosures
1471             // XXX: use Atom Media and/or File activity objects instead
1472
1473             $attachments = $this->attachments();
1474
1475             foreach ($attachments as $attachment) {
1476                 // Save local attachments
1477                 if (!empty($attachment->filename)) {
1478                     $act->attachments[] = ActivityObject::fromFile($attachment);
1479                 }
1480             }
1481
1482             $ctx = new ActivityContext();
1483
1484             try {
1485                 $reply = $this->getParent();
1486                 $ctx->replyToID  = $reply->uri;
1487                 $ctx->replyToUrl = $reply->bestUrl();
1488             } catch (Exception $e) {
1489                 // This is not a reply to something
1490             }
1491
1492             $ctx->location = $this->getLocation();
1493
1494             $conv = null;
1495
1496             if (!empty($this->conversation)) {
1497                 $conv = Conversation::getKV('id', $this->conversation);
1498                 if ($conv instanceof Conversation) {
1499                     $ctx->conversation = $conv->uri;
1500                 }
1501             }
1502
1503             $reply_ids = $this->getReplies();
1504
1505             foreach ($reply_ids as $id) {
1506                 $rprofile = Profile::getKV('id', $id);
1507                 if ($rprofile instanceof Profile) {
1508                     $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1509                 }
1510             }
1511
1512             $groups = $this->getGroups();
1513
1514             foreach ($groups as $group) {
1515                 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1516             }
1517
1518             switch ($this->scope) {
1519             case Notice::PUBLIC_SCOPE:
1520                 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1521                 break;
1522             case Notice::FOLLOWER_SCOPE:
1523                 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1524                 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1525                 break;
1526             }
1527
1528             $act->context = $ctx;
1529
1530             $source = $this->getSource();
1531
1532             if ($source instanceof Notice_source) {
1533                 $act->generator = ActivityObject::fromNoticeSource($source);
1534             }
1535
1536             // Source
1537
1538             $atom_feed = $profile->getAtomFeed();
1539
1540             if (!empty($atom_feed)) {
1541
1542                 $act->source = new ActivitySource();
1543
1544                 // XXX: we should store the actual feed ID
1545
1546                 $act->source->id = $atom_feed;
1547
1548                 // XXX: we should store the actual feed title
1549
1550                 $act->source->title = $profile->getBestName();
1551
1552                 $act->source->links['alternate'] = $profile->profileurl;
1553                 $act->source->links['self']      = $atom_feed;
1554
1555                 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1556
1557                 $notice = $profile->getCurrentNotice();
1558
1559                 if ($notice instanceof Notice) {
1560                     $act->source->updated = self::utcDate($notice->created);
1561                 }
1562
1563                 $user = User::getKV('id', $profile->id);
1564
1565                 if ($user instanceof User) {
1566                     $act->source->links['license'] = common_config('license', 'url');
1567                 }
1568             }
1569
1570             if ($this->isLocal()) {
1571                 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1572                                                                            'format' => 'atom'));
1573                 $act->editLink = $act->selfLink;
1574             }
1575
1576             Event::handle('EndNoticeAsActivity', array($this, &$act));
1577         }
1578
1579         self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1580
1581         return $act;
1582     }
1583
1584     // This has gotten way too long. Needs to be sliced up into functional bits
1585     // or ideally exported to a utility class.
1586
1587     function asAtomEntry($namespace=false,
1588                          $source=false,
1589                          $author=true,
1590                          $cur=null)
1591     {
1592         $act = $this->asActivity($cur);
1593         $act->extra[] = $this->noticeInfo($cur);
1594         return $act->asString($namespace, $author, $source);
1595     }
1596
1597     /**
1598      * Extra notice info for atom entries
1599      *
1600      * Clients use some extra notice info in the atom stream.
1601      * This gives it to them.
1602      *
1603      * @param User $cur Current user
1604      *
1605      * @return array representation of <statusnet:notice_info> element
1606      */
1607
1608     function noticeInfo($cur)
1609     {
1610         // local notice ID (useful to clients for ordering)
1611
1612         $noticeInfoAttr = array('local_id' => $this->id);
1613
1614         // notice source
1615
1616         $ns = $this->getSource();
1617
1618         if ($ns instanceof Notice_source) {
1619             $noticeInfoAttr['source'] =  $ns->code;
1620             if (!empty($ns->url)) {
1621                 $noticeInfoAttr['source_link'] = $ns->url;
1622                 if (!empty($ns->name)) {
1623                     $noticeInfoAttr['source'] =  '<a href="'
1624                         . htmlspecialchars($ns->url)
1625                         . '" rel="nofollow">'
1626                         . htmlspecialchars($ns->name)
1627                         . '</a>';
1628                 }
1629             }
1630         }
1631
1632         // favorite and repeated
1633
1634         if (!empty($cur)) {
1635             $cp = $cur->getProfile();
1636             $noticeInfoAttr['favorite'] = ($cp->hasFave($this)) ? "true" : "false";
1637             $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this)) ? "true" : "false";
1638         }
1639
1640         if (!empty($this->repeat_of)) {
1641             $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1642         }
1643
1644         return array('statusnet:notice_info', $noticeInfoAttr, null);
1645     }
1646
1647     /**
1648      * Returns an XML string fragment with a reference to a notice as an
1649      * Activity Streams noun object with the given element type.
1650      *
1651      * Assumes that 'activity' namespace has been previously defined.
1652      *
1653      * @param string $element one of 'subject', 'object', 'target'
1654      * @return string
1655      */
1656
1657     function asActivityNoun($element)
1658     {
1659         $noun = ActivityObject::fromNotice($this);
1660         return $noun->asString('activity:' . $element);
1661     }
1662
1663     function bestUrl()
1664     {
1665         if (!empty($this->url)) {
1666             return $this->url;
1667         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1668             return $this->uri;
1669         } else {
1670             return common_local_url('shownotice',
1671                                     array('notice' => $this->id));
1672         }
1673     }
1674
1675
1676     /**
1677      * Determine which notice, if any, a new notice is in reply to.
1678      *
1679      * For conversation tracking, we try to see where this notice fits
1680      * in the tree. Rough algorithm is:
1681      *
1682      * if (reply_to is set and valid) {
1683      *     return reply_to;
1684      * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1685      *     return ID of last notice by initial @name in content;
1686      * }
1687      *
1688      * Note that all @nickname instances will still be used to save "reply" records,
1689      * so the notice shows up in the mentioned users' "replies" tab.
1690      *
1691      * @param integer $reply_to   ID passed in by Web or API
1692      * @param integer $profile_id ID of author
1693      * @param string  $source     Source tag, like 'web' or 'gwibber'
1694      * @param string  $content    Final notice content
1695      *
1696      * @return integer ID of replied-to notice, or null for not a reply.
1697      */
1698
1699     static function getReplyTo($reply_to, $profile_id, $source, $content)
1700     {
1701         static $lb = array('xmpp', 'mail', 'sms', 'omb');
1702
1703         // If $reply_to is specified, we check that it exists, and then
1704         // return it if it does
1705
1706         if (!empty($reply_to)) {
1707             $reply_notice = Notice::getKV('id', $reply_to);
1708             if ($reply_notice instanceof Notice) {
1709                 return $reply_notice;
1710             }
1711         }
1712
1713         // If it's not a "low bandwidth" source (one where you can't set
1714         // a reply_to argument), we return. This is mostly web and API
1715         // clients.
1716
1717         if (!in_array($source, $lb)) {
1718             return null;
1719         }
1720
1721         // Is there an initial @ or T?
1722
1723         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1724             preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1725             $nickname = common_canonical_nickname($match[1]);
1726         } else {
1727             return null;
1728         }
1729
1730         // Figure out who that is.
1731
1732         $sender = Profile::getKV('id', $profile_id);
1733         if (!$sender instanceof Profile) {
1734             return null;
1735         }
1736
1737         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1738
1739         if (!$recipient instanceof Profile) {
1740             return null;
1741         }
1742
1743         // Get their last notice
1744
1745         $last = $recipient->getCurrentNotice();
1746
1747         if ($last instanceof Notice) {
1748             return $last;
1749         }
1750
1751         return null;
1752     }
1753
1754     static function maxContent()
1755     {
1756         $contentlimit = common_config('notice', 'contentlimit');
1757         // null => use global limit (distinct from 0!)
1758         if (is_null($contentlimit)) {
1759             $contentlimit = common_config('site', 'textlimit');
1760         }
1761         return $contentlimit;
1762     }
1763
1764     static function contentTooLong($content)
1765     {
1766         $contentlimit = self::maxContent();
1767         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1768     }
1769
1770     function getLocation()
1771     {
1772         $location = null;
1773
1774         if (!empty($this->location_id) && !empty($this->location_ns)) {
1775             $location = Location::fromId($this->location_id, $this->location_ns);
1776         }
1777
1778         if (is_null($location)) { // no ID, or Location::fromId() failed
1779             if (!empty($this->lat) && !empty($this->lon)) {
1780                 $location = Location::fromLatLon($this->lat, $this->lon);
1781             }
1782         }
1783
1784         return $location;
1785     }
1786
1787     /**
1788      * Convenience function for posting a repeat of an existing message.
1789      *
1790      * @param int $repeater_id: profile ID of user doing the repeat
1791      * @param string $source: posting source key, eg 'web', 'api', etc
1792      * @return Notice
1793      *
1794      * @throws Exception on failure or permission problems
1795      */
1796     function repeat($repeater_id, $source)
1797     {
1798         $author = Profile::getKV('id', $this->profile_id);
1799
1800         // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1801         // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1802         $content = sprintf(_('RT @%1$s %2$s'),
1803                            $author->nickname,
1804                            $this->content);
1805
1806         $maxlen = common_config('site', 'textlimit');
1807         if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1808             // Web interface and current Twitter API clients will
1809             // pull the original notice's text, but some older
1810             // clients and RSS/Atom feeds will see this trimmed text.
1811             //
1812             // Unfortunately this is likely to lose tags or URLs
1813             // at the end of long notices.
1814             $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1815         }
1816
1817         // Scope is same as this one's
1818
1819         return self::saveNew($repeater_id,
1820                              $content,
1821                              $source,
1822                              array('repeat_of' => $this->id,
1823                                    'scope' => $this->scope));
1824     }
1825
1826     // These are supposed to be in chron order!
1827
1828     function repeatStream($limit=100)
1829     {
1830         $cache = Cache::instance();
1831
1832         if (empty($cache)) {
1833             $ids = $this->_repeatStreamDirect($limit);
1834         } else {
1835             $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1836             if ($idstr !== false) {
1837                 if (empty($idstr)) {
1838                         $ids = array();
1839                 } else {
1840                         $ids = explode(',', $idstr);
1841                 }
1842             } else {
1843                 $ids = $this->_repeatStreamDirect(100);
1844                 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1845             }
1846             if ($limit < 100) {
1847                 // We do a max of 100, so slice down to limit
1848                 $ids = array_slice($ids, 0, $limit);
1849             }
1850         }
1851
1852         return NoticeStream::getStreamByIds($ids);
1853     }
1854
1855     function _repeatStreamDirect($limit)
1856     {
1857         $notice = new Notice();
1858
1859         $notice->selectAdd(); // clears it
1860         $notice->selectAdd('id');
1861
1862         $notice->repeat_of = $this->id;
1863
1864         $notice->orderBy('created, id'); // NB: asc!
1865
1866         if (!is_null($limit)) {
1867             $notice->limit(0, $limit);
1868         }
1869
1870         return $notice->fetchAll('id');
1871     }
1872
1873     function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1874     {
1875         $options = array();
1876
1877         if (!empty($location_id) && !empty($location_ns)) {
1878             $options['location_id'] = $location_id;
1879             $options['location_ns'] = $location_ns;
1880
1881             $location = Location::fromId($location_id, $location_ns);
1882
1883             if ($location instanceof Location) {
1884                 $options['lat'] = $location->lat;
1885                 $options['lon'] = $location->lon;
1886             }
1887
1888         } else if (!empty($lat) && !empty($lon)) {
1889             $options['lat'] = $lat;
1890             $options['lon'] = $lon;
1891
1892             $location = Location::fromLatLon($lat, $lon);
1893
1894             if ($location instanceof Location) {
1895                 $options['location_id'] = $location->location_id;
1896                 $options['location_ns'] = $location->location_ns;
1897             }
1898         } else if (!empty($profile)) {
1899             if (isset($profile->lat) && isset($profile->lon)) {
1900                 $options['lat'] = $profile->lat;
1901                 $options['lon'] = $profile->lon;
1902             }
1903
1904             if (isset($profile->location_id) && isset($profile->location_ns)) {
1905                 $options['location_id'] = $profile->location_id;
1906                 $options['location_ns'] = $profile->location_ns;
1907             }
1908         }
1909
1910         return $options;
1911     }
1912
1913     function clearReplies()
1914     {
1915         $replyNotice = new Notice();
1916         $replyNotice->reply_to = $this->id;
1917
1918         //Null any notices that are replies to this notice
1919
1920         if ($replyNotice->find()) {
1921             while ($replyNotice->fetch()) {
1922                 $orig = clone($replyNotice);
1923                 $replyNotice->reply_to = null;
1924                 $replyNotice->update($orig);
1925             }
1926         }
1927
1928         // Reply records
1929
1930         $reply = new Reply();
1931         $reply->notice_id = $this->id;
1932
1933         if ($reply->find()) {
1934             while($reply->fetch()) {
1935                 self::blow('reply:stream:%d', $reply->profile_id);
1936                 $reply->delete();
1937             }
1938         }
1939
1940         $reply->free();
1941     }
1942
1943     function clearFiles()
1944     {
1945         $f2p = new File_to_post();
1946
1947         $f2p->post_id = $this->id;
1948
1949         if ($f2p->find()) {
1950             while ($f2p->fetch()) {
1951                 $f2p->delete();
1952             }
1953         }
1954         // FIXME: decide whether to delete File objects
1955         // ...and related (actual) files
1956     }
1957
1958     function clearRepeats()
1959     {
1960         $repeatNotice = new Notice();
1961         $repeatNotice->repeat_of = $this->id;
1962
1963         //Null any notices that are repeats of this notice
1964
1965         if ($repeatNotice->find()) {
1966             while ($repeatNotice->fetch()) {
1967                 $orig = clone($repeatNotice);
1968                 $repeatNotice->repeat_of = null;
1969                 $repeatNotice->update($orig);
1970             }
1971         }
1972     }
1973
1974     function clearFaves()
1975     {
1976         $fave = new Fave();
1977         $fave->notice_id = $this->id;
1978
1979         if ($fave->find()) {
1980             while ($fave->fetch()) {
1981                 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1982                 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1983                 self::blow('fave:ids_by_user:%d', $fave->user_id);
1984                 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1985                 $fave->delete();
1986             }
1987         }
1988
1989         $fave->free();
1990     }
1991
1992     function clearTags()
1993     {
1994         $tag = new Notice_tag();
1995         $tag->notice_id = $this->id;
1996
1997         if ($tag->find()) {
1998             while ($tag->fetch()) {
1999                 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2000                 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2001                 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2002                 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2003                 $tag->delete();
2004             }
2005         }
2006
2007         $tag->free();
2008     }
2009
2010     function clearGroupInboxes()
2011     {
2012         $gi = new Group_inbox();
2013
2014         $gi->notice_id = $this->id;
2015
2016         if ($gi->find()) {
2017             while ($gi->fetch()) {
2018                 self::blow('user_group:notice_ids:%d', $gi->group_id);
2019                 $gi->delete();
2020             }
2021         }
2022
2023         $gi->free();
2024     }
2025
2026     function distribute()
2027     {
2028         // We always insert for the author so they don't
2029         // have to wait
2030         Event::handle('StartNoticeDistribute', array($this));
2031
2032         // If there's a failure, we want to _force_
2033         // distribution at this point.
2034         try {
2035             $qm = QueueManager::get();
2036             $qm->enqueue($this, 'distrib');
2037         } catch (Exception $e) {
2038             // If the exception isn't transient, this
2039             // may throw more exceptions as DQH does
2040             // its own enqueueing. So, we ignore them!
2041             try {
2042                 $handler = new DistribQueueHandler();
2043                 $handler->handle($this);
2044             } catch (Exception $e) {
2045                 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2046             }
2047             // Re-throw so somebody smarter can handle it.
2048             throw $e;
2049         }
2050     }
2051
2052     function insert()
2053     {
2054         $result = parent::insert();
2055
2056         if ($result !== false) {
2057             // Profile::hasRepeated() abuses pkeyGet(), so we
2058             // have to clear manually
2059             if (!empty($this->repeat_of)) {
2060                 $c = self::memcache();
2061                 if (!empty($c)) {
2062                     $ck = self::multicacheKey('Notice',
2063                                               array('profile_id' => $this->profile_id,
2064                                                     'repeat_of' => $this->repeat_of));
2065                     $c->delete($ck);
2066                 }
2067             }
2068         }
2069
2070         return $result;
2071     }
2072
2073     /**
2074      * Get the source of the notice
2075      *
2076      * @return Notice_source $ns A notice source object. 'code' is the only attribute
2077      *                           guaranteed to be populated.
2078      */
2079     function getSource()
2080     {
2081         $ns = new Notice_source();
2082         if (!empty($this->source)) {
2083             switch ($this->source) {
2084             case 'web':
2085             case 'xmpp':
2086             case 'mail':
2087             case 'omb':
2088             case 'system':
2089             case 'api':
2090                 $ns->code = $this->source;
2091                 break;
2092             default:
2093                 $ns = Notice_source::getKV($this->source);
2094                 if (!$ns) {
2095                     $ns = new Notice_source();
2096                     $ns->code = $this->source;
2097                     $app = Oauth_application::getKV('name', $this->source);
2098                     if ($app) {
2099                         $ns->name = $app->name;
2100                         $ns->url  = $app->source_url;
2101                     }
2102                 }
2103                 break;
2104             }
2105         }
2106         return $ns;
2107     }
2108
2109     /**
2110      * Determine whether the notice was locally created
2111      *
2112      * @return boolean locality
2113      */
2114
2115     public function isLocal()
2116     {
2117         return ($this->is_local == Notice::LOCAL_PUBLIC ||
2118                 $this->is_local == Notice::LOCAL_NONPUBLIC);
2119     }
2120
2121     /**
2122      * Get the list of hash tags saved with this notice.
2123      *
2124      * @return array of strings
2125      */
2126     public function getTags()
2127     {
2128         $tags = array();
2129
2130         $keypart = sprintf('notice:tags:%d', $this->id);
2131
2132         $tagstr = self::cacheGet($keypart);
2133
2134         if ($tagstr !== false) {
2135             $tags = explode(',', $tagstr);
2136         } else {
2137             $tag = new Notice_tag();
2138             $tag->notice_id = $this->id;
2139             if ($tag->find()) {
2140                 while ($tag->fetch()) {
2141                     $tags[] = $tag->tag;
2142                 }
2143             }
2144             self::cacheSet($keypart, implode(',', $tags));
2145         }
2146
2147         return $tags;
2148     }
2149
2150     static private function utcDate($dt)
2151     {
2152         $dateStr = date('d F Y H:i:s', strtotime($dt));
2153         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2154         return $d->format(DATE_W3C);
2155     }
2156
2157     /**
2158      * Look up the creation timestamp for a given notice ID, even
2159      * if it's been deleted.
2160      *
2161      * @param int $id
2162      * @return mixed string recorded creation timestamp, or false if can't be found
2163      */
2164     public static function getAsTimestamp($id)
2165     {
2166         if (!$id) {
2167             return false;
2168         }
2169
2170         $notice = Notice::getKV('id', $id);
2171         if ($notice) {
2172             return $notice->created;
2173         }
2174
2175         $deleted = Deleted_notice::getKV('id', $id);
2176         if ($deleted) {
2177             return $deleted->created;
2178         }
2179
2180         return false;
2181     }
2182
2183     /**
2184      * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2185      * parameter, matching notices posted after the given one (exclusive).
2186      *
2187      * If the referenced notice can't be found, will return false.
2188      *
2189      * @param int $id
2190      * @param string $idField
2191      * @param string $createdField
2192      * @return mixed string or false if no match
2193      */
2194     public static function whereSinceId($id, $idField='id', $createdField='created')
2195     {
2196         $since = Notice::getAsTimestamp($id);
2197         if ($since) {
2198             return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2199         }
2200         return false;
2201     }
2202
2203     /**
2204      * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2205      * parameter, matching notices posted after the given one (exclusive), and
2206      * if necessary add it to the data object's query.
2207      *
2208      * @param DB_DataObject $obj
2209      * @param int $id
2210      * @param string $idField
2211      * @param string $createdField
2212      * @return mixed string or false if no match
2213      */
2214     public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2215     {
2216         $since = self::whereSinceId($id, $idField, $createdField);
2217         if ($since) {
2218             $obj->whereAdd($since);
2219         }
2220     }
2221
2222     /**
2223      * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2224      * parameter, matching notices posted before the given one (inclusive).
2225      *
2226      * If the referenced notice can't be found, will return false.
2227      *
2228      * @param int $id
2229      * @param string $idField
2230      * @param string $createdField
2231      * @return mixed string or false if no match
2232      */
2233     public static function whereMaxId($id, $idField='id', $createdField='created')
2234     {
2235         $max = Notice::getAsTimestamp($id);
2236         if ($max) {
2237             return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2238         }
2239         return false;
2240     }
2241
2242     /**
2243      * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2244      * parameter, matching notices posted before the given one (inclusive), and
2245      * if necessary add it to the data object's query.
2246      *
2247      * @param DB_DataObject $obj
2248      * @param int $id
2249      * @param string $idField
2250      * @param string $createdField
2251      * @return mixed string or false if no match
2252      */
2253     public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2254     {
2255         $max = self::whereMaxId($id, $idField, $createdField);
2256         if ($max) {
2257             $obj->whereAdd($max);
2258         }
2259     }
2260
2261     function isPublic()
2262     {
2263         if (common_config('public', 'localonly')) {
2264             return ($this->is_local == Notice::LOCAL_PUBLIC);
2265         } else {
2266             return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2267                     ($this->is_local != Notice::GATEWAY));
2268         }
2269     }
2270
2271     /**
2272      * Check that the given profile is allowed to read, respond to, or otherwise
2273      * act on this notice.
2274      *
2275      * The $scope member is a bitmask of scopes, representing a logical AND of the
2276      * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2277      * "only visible to people who are mentioned in the notice AND are users on this site."
2278      * Users on the site who are not mentioned in the notice will not be able to see the
2279      * notice.
2280      *
2281      * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2282      *
2283      * @return boolean whether the profile is in the notice's scope
2284      */
2285     function inScope($profile)
2286     {
2287         if (is_null($profile)) {
2288             $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2289         } else {
2290             $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2291         }
2292
2293         $result = self::cacheGet($keypart);
2294
2295         if ($result === false) {
2296             $bResult = false;
2297             if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2298                 $bResult = $this->_inScope($profile);
2299                 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2300             }
2301             $result = ($bResult) ? 1 : 0;
2302             self::cacheSet($keypart, $result, 0, 300);
2303         }
2304
2305         return ($result == 1) ? true : false;
2306     }
2307
2308     protected function _inScope($profile)
2309     {
2310         if (!is_null($this->scope)) {
2311             $scope = $this->scope;
2312         } else {
2313             $scope = self::defaultScope();
2314         }
2315
2316         // If there's no scope, anyone (even anon) is in scope.
2317
2318         if ($scope == 0) { // Not private
2319
2320             return !$this->isHiddenSpam($profile);
2321
2322         } else { // Private, somehow
2323
2324             // If there's scope, anon cannot be in scope
2325
2326             if (empty($profile)) {
2327                 return false;
2328             }
2329
2330             // Author is always in scope
2331
2332             if ($this->profile_id == $profile->id) {
2333                 return true;
2334             }
2335
2336             // Only for users on this site
2337
2338             if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2339                 return false;
2340             }
2341
2342             // Only for users mentioned in the notice
2343
2344             if ($scope & Notice::ADDRESSEE_SCOPE) {
2345
2346                 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2347                                              'profile_id' => $profile->id));
2348                                                                                  
2349                 if (!$reply instanceof Reply) {
2350                     return false;
2351                 }
2352             }
2353
2354             // Only for members of the given group
2355
2356             if ($scope & Notice::GROUP_SCOPE) {
2357
2358                 // XXX: just query for the single membership
2359
2360                 $groups = $this->getGroups();
2361
2362                 $foundOne = false;
2363
2364                 foreach ($groups as $group) {
2365                     if ($profile->isMember($group)) {
2366                         $foundOne = true;
2367                         break;
2368                     }
2369                 }
2370
2371                 if (!$foundOne) {
2372                     return false;
2373                 }
2374             }
2375
2376             // Only for followers of the author
2377
2378             $author = null;
2379
2380             if ($scope & Notice::FOLLOWER_SCOPE) {
2381
2382                 try {
2383                     $author = $this->getProfile();
2384                 } catch (Exception $e) {
2385                     return false;
2386                 }
2387         
2388                 if (!Subscription::exists($profile, $author)) {
2389                     return false;
2390                 }
2391             }
2392
2393             return !$this->isHiddenSpam($profile);
2394         }
2395     }
2396
2397     function isHiddenSpam($profile) {
2398         
2399         // Hide posts by silenced users from everyone but moderators.
2400
2401         if (common_config('notice', 'hidespam')) {
2402
2403             try {
2404                 $author = $this->getProfile();
2405             } catch(Exception $e) {
2406                 // If we can't get an author, keep it hidden.
2407                 // XXX: technically not spam, but, whatever.
2408                 return true;
2409             }
2410
2411             if ($author->hasRole(Profile_role::SILENCED)) {
2412                 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2413                     return true;
2414                 }
2415             }
2416         }
2417
2418         return false;
2419     }
2420
2421     public function getParent()
2422     {
2423         $parent = Notice::getKV('id', $this->reply_to);
2424
2425         if (!$parent instanceof Notice) {
2426             throw new ServerException('Notice has no parent');
2427         }
2428
2429         return $parent;
2430     }
2431
2432     /**
2433      * Magic function called at serialize() time.
2434      *
2435      * We use this to drop a couple process-specific references
2436      * from DB_DataObject which can cause trouble in future
2437      * processes.
2438      *
2439      * @return array of variable names to include in serialization.
2440      */
2441
2442     function __sleep()
2443     {
2444         $vars = parent::__sleep();
2445         $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2446         return array_diff($vars, $skip);
2447     }
2448     
2449     static function defaultScope()
2450     {
2451         $scope = common_config('notice', 'defaultscope');
2452         if (is_null($scope)) {
2453                 if (common_config('site', 'private')) {
2454                         $scope = 1;
2455                 } else {
2456                         $scope = 0;
2457                 }
2458         }
2459         return $scope;
2460     }
2461
2462         static function fillProfiles($notices)
2463         {
2464                 $map = self::getProfiles($notices);
2465                 
2466                 foreach ($notices as $entry=>$notice) {
2467             try {
2468                         if (array_key_exists($notice->profile_id, $map)) {
2469                                 $notice->_setProfile($map[$notice->profile_id]);
2470                         }
2471             } catch (NoProfileException $e) {
2472                 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->id}");
2473                 unset($notices[$entry]);
2474             }
2475                 }
2476                 
2477                 return array_values($map);
2478         }
2479         
2480         static function getProfiles(&$notices)
2481         {
2482                 $ids = array();
2483                 foreach ($notices as $notice) {
2484                         $ids[] = $notice->profile_id;
2485                 }
2486                 
2487                 $ids = array_unique($ids);
2488                 
2489                 return Profile::pivotGet('id', $ids); 
2490         }
2491         
2492         static function fillGroups(&$notices)
2493         {
2494         $ids = self::_idsOf($notices);
2495                 
2496         $gis = Group_inbox::listGet('notice_id', $ids);
2497                 
2498         $gids = array();
2499
2500                 foreach ($gis as $id => $gi)
2501                 {
2502                     foreach ($gi as $g)
2503                     {
2504                         $gids[] = $g->group_id;
2505                     }
2506                 }
2507                 
2508                 $gids = array_unique($gids);
2509                 
2510                 $group = User_group::pivotGet('id', $gids);
2511                 
2512                 foreach ($notices as $notice)
2513                 {
2514                         $grps = array();
2515                         $gi = $gis[$notice->id];
2516                         foreach ($gi as $g) {
2517                             $grps[] = $group[$g->group_id];
2518                         }
2519                     $notice->_setGroups($grps);
2520                 }
2521         }
2522
2523     static function _idsOf(&$notices)
2524     {
2525                 $ids = array();
2526                 foreach ($notices as $notice) {
2527                         $ids[] = $notice->id;
2528                 }
2529                 $ids = array_unique($ids);
2530         return $ids;
2531     }
2532
2533     static function fillAttachments(&$notices)
2534     {
2535         $ids = self::_idsOf($notices);
2536
2537         $f2pMap = File_to_post::listGet('post_id', $ids);
2538                 
2539                 $fileIds = array();
2540                 
2541                 foreach ($f2pMap as $noticeId => $f2ps) {
2542             foreach ($f2ps as $f2p) {
2543                 $fileIds[] = $f2p->file_id;    
2544             }
2545         }
2546
2547         $fileIds = array_unique($fileIds);
2548
2549                 $fileMap = File::pivotGet('id', $fileIds);
2550
2551                 foreach ($notices as $notice)
2552                 {
2553                         $files = array();
2554                         $f2ps = $f2pMap[$notice->id];
2555                         foreach ($f2ps as $f2p) {
2556                             $files[] = $fileMap[$f2p->file_id];
2557                         }
2558                     $notice->_setAttachments($files);
2559                 }
2560     }
2561
2562     protected $_faves;
2563
2564     /**
2565      * All faves of this notice
2566      *
2567      * @return array Array of Fave objects
2568      */
2569
2570     function getFaves()
2571     {
2572         if (isset($this->_faves) && is_array($this->_faves)) {
2573             return $this->_faves;
2574         }
2575         $faveMap = Fave::listGet('notice_id', array($this->id));
2576         $this->_faves = $faveMap[$this->id];
2577         return $this->_faves;
2578     }
2579
2580     function _setFaves($faves)
2581     {
2582         $this->_faves = $faves;
2583     }
2584
2585     static function fillFaves(&$notices)
2586     {
2587         $ids = self::_idsOf($notices);
2588         $faveMap = Fave::listGet('notice_id', $ids);
2589         $cnt = 0;
2590         $faved = array();
2591         foreach ($faveMap as $id => $faves) {
2592             $cnt += count($faves);
2593             if (count($faves) > 0) {
2594                 $faved[] = $id;
2595             }
2596         }
2597         foreach ($notices as $notice) {
2598                 $faves = $faveMap[$notice->id];
2599             $notice->_setFaves($faves);
2600         }
2601     }
2602
2603     static function fillReplies(&$notices)
2604     {
2605         $ids = self::_idsOf($notices);
2606         $replyMap = Reply::listGet('notice_id', $ids);
2607         foreach ($notices as $notice) {
2608             $replies = $replyMap[$notice->id];
2609             $ids = array();
2610             foreach ($replies as $reply) {
2611                 $ids[] = $reply->profile_id;
2612             }
2613             $notice->_setReplies($ids);
2614         }
2615     }
2616
2617     protected $_repeats;
2618
2619     function getRepeats()
2620     {
2621         if (isset($this->_repeats) && is_array($this->_repeats)) {
2622             return $this->_repeats;
2623         }
2624         $repeatMap = Notice::listGet('repeat_of', array($this->id));
2625         $this->_repeats = $repeatMap[$this->id];
2626         return $this->_repeats;
2627     }
2628
2629     function _setRepeats($repeats)
2630     {
2631         $this->_repeats = $repeats;
2632     }
2633
2634     static function fillRepeats(&$notices)
2635     {
2636         $ids = self::_idsOf($notices);
2637         $repeatMap = Notice::listGet('repeat_of', $ids);
2638         foreach ($notices as $notice) {
2639                 $repeats = $repeatMap[$notice->id];
2640             $notice->_setRepeats($repeats);
2641         }
2642     }
2643 }