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