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