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