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