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