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