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