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