]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
Output selfLink from notice asActivity[Object]
[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(191)  unique_key   not 255 because utf8mb4 takes more space
59     public $content;                         // text
60     public $rendered;                        // text
61     public $url;                             // varchar(191)   not 255 because utf8mb4 takes more space
62     public $self;                            // varchar(191)   not 255 because utf8mb4 takes more space
63     public $created;                         // datetime  multiple_key not_null default_0000-00-00%2000%3A00%3A00
64     public $modified;                        // timestamp   not_null default_CURRENT_TIMESTAMP
65     public $reply_to;                        // int(4)
66     public $is_local;                        // int(4)
67     public $source;                          // varchar(32)
68     public $conversation;                    // int(4)
69     public $repeat_of;                       // int(4)
70     public $verb;                            // varchar(191)   not 255 because utf8mb4 takes more space
71     public $object_type;                     // varchar(191)   not 255 because utf8mb4 takes more space
72     public $scope;                           // int(4)
73
74     /* the code above is auto generated do not remove the tag below */
75     ###END_AUTOCODE
76
77     public static function schemaDef()
78     {
79         $def = array(
80             'fields' => array(
81                 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
82                 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'who made the update'),
83                 'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universally unique identifier, usually a tag URI'),
84                 'content' => array('type' => 'text', 'description' => 'update content', 'collate' => 'utf8mb4_general_ci'),
85                 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
86                 'url' => array('type' => 'varchar', 'length' => 191, 'description' => 'URL of any attachment (image, video, bookmark, whatever)'),
87                 'self' => array('type' => 'varchar', 'length' => 191, 'description' => 'Resolvable URL to the (remote) Atom entry representation'),
88                 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
89                 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
90                 'reply_to' => array('type' => 'int', 'description' => 'notice replied to (usually a guess)'),
91                 'is_local' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'notice was generated by a user'),
92                 'source' => array('type' => 'varchar', 'length' => 32, 'description' => 'source of comment, like "web", "im", or "clientname"'),
93                 'conversation' => array('type' => 'int', 'description' => 'the local numerical conversation id'),
94                 'repeat_of' => array('type' => 'int', 'description' => 'notice this is a repeat of'),
95                 'object_type' => array('type' => 'varchar', 'length' => 191, 'description' => 'URI representing activity streams object type', 'default' => null),
96                 'verb' => array('type' => 'varchar', 'length' => 191, 'description' => 'URI representing activity streams verb', 'default' => 'http://activitystrea.ms/schema/1.0/post'),
97                 'scope' => array('type' => 'int',
98                                  'description' => 'bit map for distribution scope; 0 = everywhere; 1 = this server only; 2 = addressees; 4 = followers; null = default'),
99             ),
100             'primary key' => array('id'),
101             'unique keys' => array(
102                 'notice_uri_key' => array('uri'),
103             ),
104             'foreign keys' => array(
105                 'notice_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
106                 'notice_reply_to_fkey' => array('notice', array('reply_to' => 'id')),
107                 'notice_conversation_fkey' => array('conversation', array('conversation' => 'id')), # note... used to refer to notice.id
108                 'notice_repeat_of_fkey' => array('notice', array('repeat_of' => 'id')), # @fixme: what about repeats of deleted notices?
109             ),
110             'indexes' => array(
111                 'notice_created_id_is_local_idx' => array('created', 'id', 'is_local'),
112                 'notice_profile_id_idx' => array('profile_id', 'created', 'id'),
113                 'notice_repeat_of_created_id_idx' => array('repeat_of', 'created', 'id'),
114                 'notice_conversation_created_id_idx' => array('conversation', 'created', 'id'),
115                 'notice_object_type_idx' => array('object_type'),
116                 'notice_verb_idx' => array('verb'),
117                 'notice_profile_id_verb_idx' => array('profile_id', 'verb'),
118                 'notice_url_idx' => array('url'),   // Qvitter wants this
119                 'notice_replyto_idx' => array('reply_to')
120             )
121         );
122
123         if (common_config('search', 'type') == 'fulltext') {
124             $def['fulltext indexes'] = array('content' => array('content'));
125         }
126
127         return $def;
128     }
129
130     /* Notice types */
131     const LOCAL_PUBLIC    =  1;
132     const REMOTE          =  0;
133     const LOCAL_NONPUBLIC = -1;
134     const GATEWAY         = -2;
135
136     const PUBLIC_SCOPE    = 0; // Useful fake constant
137     const SITE_SCOPE      = 1;
138     const ADDRESSEE_SCOPE = 2;
139     const GROUP_SCOPE     = 4;
140     const FOLLOWER_SCOPE  = 8;
141
142     protected $_profile = array();
143
144     /**
145      * Will always return a profile, if anything fails it will
146      * (through _setProfile) throw a NoProfileException.
147      */
148     public function getProfile()
149     {
150         if (!isset($this->_profile[$this->profile_id])) {
151             // We could've sent getKV directly to _setProfile, but occasionally we get
152             // a "false" (instead of null), likely because it indicates a cache miss.
153             $profile = Profile::getKV('id', $this->profile_id);
154             $this->_setProfile($profile instanceof Profile ? $profile : null);
155         }
156         return $this->_profile[$this->profile_id];
157     }
158
159     public function _setProfile(Profile $profile=null)
160     {
161         if (!$profile instanceof Profile) {
162             throw new NoProfileException($this->profile_id);
163         }
164         $this->_profile[$this->profile_id] = $profile;
165     }
166
167     public function deleteAs(Profile $actor, $delete_event=true)
168     {
169         if (!$this->getProfile()->sameAs($actor) && !$actor->hasRight(Right::DELETEOTHERSNOTICE)) {
170             throw new AuthorizationException(_('You are not allowed to delete another user\'s notice.'));
171         }
172
173         $result = null;
174         if (!$delete_event || Event::handle('DeleteNoticeAsProfile', array($this, $actor, &$result))) {
175             // If $delete_event is true, we run the event. If the Event then 
176             // returns false it is assumed everything was handled properly 
177             // and the notice was deleted.
178             $result = $this->delete();
179         }
180         return $result;
181     }
182
183     protected function deleteRelated()
184     {
185         if (Event::handle('NoticeDeleteRelated', array($this))) {
186             // Clear related records
187             $this->clearReplies();
188             $this->clearLocation();
189             $this->clearRepeats();
190             $this->clearTags();
191             $this->clearGroupInboxes();
192             $this->clearFiles();
193             $this->clearAttentions();
194             // NOTE: we don't clear queue items
195         }
196     }
197
198     public function delete($useWhere=false)
199     {
200         $this->deleteRelated();
201
202         $result = parent::delete($useWhere);
203
204         $this->blowOnDelete();
205         return $result;
206     }
207
208     public function getUri()
209     {
210         return $this->uri;
211     }
212
213     /*
214      * Get a Notice object by URI. Will call external plugins for help
215      * using the event StartGetNoticeFromURI.
216      *
217      * @param string $uri A unique identifier for a resource (notice in this case)
218      */
219     static function fromUri($uri)
220     {
221         $notice = null;
222
223         if (Event::handle('StartGetNoticeFromUri', array($uri, &$notice))) {
224             $notice = Notice::getKV('uri', $uri);
225             Event::handle('EndGetNoticeFromUri', array($uri, $notice));
226         }
227
228         if (!$notice instanceof Notice) {
229             throw new UnknownUriException($uri);
230         }
231
232         return $notice;
233     }
234
235     /*
236      * @param $root boolean If true, link to just the conversation root.
237      *
238      * @return URL to conversation
239      */
240     public function getConversationUrl($anchor=true)
241     {
242         return Conversation::getUrlFromNotice($this, $anchor);
243     }
244
245     /*
246      * Get the local representation URL of this notice.
247      */
248     public function getLocalUrl()
249     {
250         return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
251     }
252
253     public function getTitle($imply=true)
254     {
255         $title = null;
256         if (Event::handle('GetNoticeTitle', array($this, &$title)) && $imply) {
257             // TRANS: Title of a notice posted without a title value.
258             // TRANS: %1$s is a user name, %2$s is the notice creation date/time.
259             $title = sprintf(_('%1$s\'s status on %2$s'),
260                              $this->getProfile()->getFancyName(),
261                              common_exact_date($this->created));
262         }
263         return $title;
264     }
265
266     public function getContent()
267     {
268         return $this->content;
269     }
270
271     public function getRendered()
272     {
273         // we test $this->id because if it's not inserted yet, we can't update the field
274         if (!empty($this->id) && (is_null($this->rendered) || $this->rendered === '')) {
275             // update to include rendered content on-the-fly, so we don't have to have a fix-up script in upgrade.php
276             common_debug('Rendering notice '.$this->getID().' as it had no rendered HTML content.');
277             $orig = clone($this);
278             $this->rendered = common_render_content($this->getContent(),
279                                                     $this->getProfile(),
280                                                     $this->hasParent() ? $this->getParent() : null);
281             $this->update($orig);
282         }
283         return $this->rendered;
284     }
285
286     public function getCreated()
287     {
288         return $this->created;
289     }
290
291     public function getVerb($make_relative=false)
292     {
293         return ActivityUtils::resolveUri($this->verb, $make_relative);
294     }
295
296     public function isVerb(array $verbs)
297     {
298         return ActivityUtils::compareVerbs($this->getVerb(), $verbs);
299     }
300
301     /*
302      * Get the original representation URL of this notice.
303      *
304      * @param boolean $fallback     Whether to fall back to generate a local URL or throw InvalidUrlException
305      */
306     public function getUrl($fallback=false)
307     {
308         // The risk is we start having empty urls and non-http uris...
309         // and we can't really handle any other protocol right now.
310         switch (true) {
311         case $this->isLocal():
312             return common_local_url('shownotice', array('notice' => $this->getID()), null, null, false);
313         case common_valid_http_url($this->url): // should we allow non-http/https URLs?
314             return $this->url;
315         case common_valid_http_url($this->uri): // Sometimes we only have the URI for remote posts.
316             return $this->uri;
317         case $fallback:
318             // let's generate a valid link to our locally available notice on demand
319             return common_local_url('shownotice', array('notice' => $this->getID()), null, null, false);
320         default:
321             throw new InvalidUrlException($this->url);
322         }
323     }
324
325     public function getSelfLink()
326     {
327         if ($this->isLocal()) {
328             return common_local_url('ApiStatusesShow', array('id' => $this->getID(), 'format' => 'atom'));
329         }
330
331         if (!common_valid_http_url($this->self)) {
332             throw new InvalidUrlException($this->url);
333         }
334
335         return $this->self;
336     }
337
338     public function getObjectType($canonical=false) {
339         if (is_null($this->object_type) || $this->object_type==='') {
340             throw new NoObjectTypeException($this);
341         }
342         return ActivityUtils::resolveUri($this->object_type, $canonical);
343     }
344
345     public function isObjectType(array $types)
346     {
347         try {
348             return ActivityUtils::compareTypes($this->getObjectType(), $types);
349         } catch (NoObjectTypeException $e) {
350             return false;
351         }
352     }
353
354     /**
355      * Extract #hashtags from this notice's content and save them to the database.
356      */
357     function saveTags()
358     {
359         /* extract all #hastags */
360         $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
361         if (!$count) {
362             return true;
363         }
364
365         /* Add them to the database */
366         return $this->saveKnownTags($match[1]);
367     }
368
369     /**
370      * Record the given set of hash tags in the db for this notice.
371      * Given tag strings will be normalized and checked for dupes.
372      */
373     function saveKnownTags($hashtags)
374     {
375         //turn each into their canonical tag
376         //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
377         for($i=0; $i<count($hashtags); $i++) {
378             /* elide characters we don't want in the tag */
379             $hashtags[$i] = common_canonical_tag($hashtags[$i]);
380         }
381
382         foreach(array_unique($hashtags) as $hashtag) {
383             $this->saveTag($hashtag);
384             self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
385         }
386         return true;
387     }
388
389     /**
390      * Record a single hash tag as associated with this notice.
391      * Tag format and uniqueness must be validated by caller.
392      */
393     function saveTag($hashtag)
394     {
395         $tag = new Notice_tag();
396         $tag->notice_id = $this->id;
397         $tag->tag = $hashtag;
398         $tag->created = $this->created;
399         $id = $tag->insert();
400
401         if (!$id) {
402             // TRANS: Server exception. %s are the error details.
403             throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
404                                               $last_error->message));
405             return;
406         }
407
408         // if it's saved, blow its cache
409         $tag->blowCache(false);
410     }
411
412     /**
413      * Save a new notice and push it out to subscribers' inboxes.
414      * Poster's permissions are checked before sending.
415      *
416      * @param int $profile_id Profile ID of the poster
417      * @param string $content source message text; links may be shortened
418      *                        per current user's preference
419      * @param string $source source key ('web', 'api', etc)
420      * @param array $options Associative array of optional properties:
421      *              string 'created' timestamp of notice; defaults to now
422      *              int 'is_local' source/gateway ID, one of:
423      *                  Notice::LOCAL_PUBLIC    - Local, ok to appear in public timeline
424      *                  Notice::REMOTE          - Sent from a remote service;
425      *                                            hide from public timeline but show in
426      *                                            local "and friends" timelines
427      *                  Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
428      *                  Notice::GATEWAY         - From another non-OStatus service;
429      *                                            will not appear in public views
430      *              float 'lat' decimal latitude for geolocation
431      *              float 'lon' decimal longitude for geolocation
432      *              int 'location_id' geoname identifier
433      *              int 'location_ns' geoname namespace to interpret location_id
434      *              int 'reply_to'; notice ID this is a reply to
435      *              int 'repeat_of'; notice ID this is a repeat of
436      *              string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
437      *              string 'url' permalink to notice; defaults to local notice URL
438      *              string 'rendered' rendered HTML version of content
439      *              array 'replies' list of profile URIs for reply delivery in
440      *                              place of extracting @-replies from content.
441      *              array 'groups' list of group IDs to deliver to, in place of
442      *                              extracting ! tags from content
443      *              array 'tags' list of hashtag strings to save with the notice
444      *                           in place of extracting # tags from content
445      *              array 'urls' list of attached/referred URLs to save with the
446      *                           notice in place of extracting links from content
447      *              boolean 'distribute' whether to distribute the notice, default true
448      *              string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
449      *              string 'verb' URL of the associated verb (default ActivityVerb::POST)
450      *              int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
451      *
452      * @fixme tag override
453      *
454      * @return Notice
455      * @throws ClientException
456      */
457     static function saveNew($profile_id, $content, $source, array $options=null) {
458         $defaults = array('uri' => null,
459                           'url' => null,
460                           'self' => null,
461                           'conversation' => null,   // URI of conversation
462                           'reply_to' => null,       // This will override convo URI if the parent is known
463                           'repeat_of' => null,      // This will override convo URI if the repeated notice is known
464                           'scope' => null,
465                           'distribute' => true,
466                           'object_type' => null,
467                           'verb' => null);
468
469         if (!empty($options) && is_array($options)) {
470             $options = array_merge($defaults, $options);
471             extract($options);
472         } else {
473             extract($defaults);
474         }
475
476         if (!isset($is_local)) {
477             $is_local = Notice::LOCAL_PUBLIC;
478         }
479
480         $profile = Profile::getKV('id', $profile_id);
481         if (!$profile instanceof Profile) {
482             // TRANS: Client exception thrown when trying to save a notice for an unknown user.
483             throw new ClientException(_('Problem saving notice. Unknown user.'));
484         }
485
486         $user = User::getKV('id', $profile_id);
487         if ($user instanceof User) {
488             // Use the local user's shortening preferences, if applicable.
489             $final = $user->shortenLinks($content);
490         } else {
491             $final = common_shorten_links($content);
492         }
493
494         if (Notice::contentTooLong($final)) {
495             // TRANS: Client exception thrown if a notice contains too many characters.
496             throw new ClientException(_('Problem saving notice. Too long.'));
497         }
498
499         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
500             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
501             // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
502             throw new ClientException(_('Too many notices too fast; take a breather '.
503                                         'and post again in a few minutes.'));
504         }
505
506         if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
507             common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
508             // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
509             throw new ClientException(_('Too many duplicate messages too quickly;'.
510                                         ' take a breather and post again in a few minutes.'));
511         }
512
513         if (!$profile->hasRight(Right::NEWNOTICE)) {
514             common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
515
516             // TRANS: Client exception thrown when a user tries to post while being banned.
517             throw new ClientException(_('You are banned from posting notices on this site.'), 403);
518         }
519
520         $notice = new Notice();
521         $notice->profile_id = $profile_id;
522
523         if ($source && in_array($source, common_config('public', 'autosource'))) {
524             $notice->is_local = Notice::LOCAL_NONPUBLIC;
525         } else {
526             $notice->is_local = $is_local;
527         }
528
529         if (!empty($created)) {
530             $notice->created = $created;
531         } else {
532             $notice->created = common_sql_now();
533         }
534
535         if (!$notice->isLocal()) {
536             // Only do these checks for non-local notices. Local notices will generate these values later.
537             if (empty($uri)) {
538                 throw new ServerException('No URI for remote notice. Cannot accept that.');
539             }
540         }
541
542         $notice->content = $final;
543
544         $notice->source = $source;
545         $notice->uri = $uri;
546         $notice->url = $url;
547         if ($self && common_valid_http_url($self)) {
548             $notice->self = $self;
549         }
550
551         // Get the groups here so we can figure out replies and such
552         if (!isset($groups)) {
553             $groups = User_group::idsFromText($notice->content, $profile);
554         }
555
556         $reply = null;
557
558         // Handle repeat case
559
560         if (!empty($options['repeat_of'])) {
561
562             // Check for a private one
563
564             $repeat = Notice::getByID($options['repeat_of']);
565
566             if ($profile->sameAs($repeat->getProfile())) {
567                 // TRANS: Client error displayed when trying to repeat an own notice.
568                 throw new ClientException(_('You cannot repeat your own notice.'));
569             }
570
571             if ($repeat->scope != Notice::SITE_SCOPE &&
572                 $repeat->scope != Notice::PUBLIC_SCOPE) {
573                 // TRANS: Client error displayed when trying to repeat a non-public notice.
574                 throw new ClientException(_('Cannot repeat a private notice.'), 403);
575             }
576
577             if (!$repeat->inScope($profile)) {
578                 // The generic checks above should cover this, but let's be sure!
579                 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
580                 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
581             }
582
583             if ($profile->hasRepeated($repeat)) {
584                 // TRANS: Client error displayed when trying to repeat an already repeated notice.
585                 throw new ClientException(_('You already repeated that notice.'));
586             }
587
588             $notice->repeat_of = $repeat->id;
589             $notice->conversation = $repeat->conversation;
590         } else {
591             $reply = null;
592
593             // If $reply_to is specified, we check that it exists, and then
594             // return it if it does
595             if (!empty($reply_to)) {
596                 $reply = Notice::getKV('id', $reply_to);
597             } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
598                 // If the source lacks capability of sending the "reply_to"
599                 // metadata, let's try to find an inline replyto-reference.
600                 $reply = self::getInlineReplyTo($profile, $final);
601             }
602
603             if ($reply instanceof Notice) {
604                 if (!$reply->inScope($profile)) {
605                     // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
606                     // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
607                     throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
608                                                       $profile->nickname, $reply->id), 403);
609                 }
610
611                 // If it's a repeat, the reply_to should be to the original
612                 if ($reply->isRepeat()) {
613                     $notice->reply_to = $reply->repeat_of;
614                 } else {
615                     $notice->reply_to = $reply->id;
616                 }
617                 // But the conversation ought to be the same :)
618                 $notice->conversation = $reply->conversation;
619
620                 // If the original is private to a group, and notice has
621                 // no group specified, make it to the same group(s)
622
623                 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
624                     $groups = array();
625                     $replyGroups = $reply->getGroups();
626                     foreach ($replyGroups as $group) {
627                         if ($profile->isMember($group)) {
628                             $groups[] = $group->id;
629                         }
630                     }
631                 }
632
633                 // Scope set below
634             }
635
636             // If we don't know the reply, we might know the conversation!
637             // This will happen if a known remote user replies to an
638             // unknown remote user - within a known conversation.
639             if (empty($notice->conversation) and !empty($options['conversation'])) {
640                 $conv = Conversation::getKV('uri', $options['conversation']);
641                 if ($conv instanceof Conversation) {
642                     common_debug('Conversation stitched together from (probably) a reply to unknown remote user. Activity creation time ('.$notice->created.') should maybe be compared to conversation creation time ('.$conv->created.').');
643                 } else {
644                     // Conversation entry with specified URI was not found, so we must create it.
645                     common_debug('Conversation URI not found, so we will create it with the URI given in the options to Notice::saveNew: '.$options['conversation']);
646                     $convctx = new ActivityContext();
647                     $convctx->conversation = $options['conversation'];
648                     if (array_key_exists('conversation_url', $options)) {
649                         $convctx->conversation_url = $options['conversation_url'];
650                     }
651                     // The insert in Conversation::create throws exception on failure
652                     $conv = Conversation::create($convctx, $notice->created);
653                 }
654                 $notice->conversation = $conv->getID();
655                 unset($conv);
656             }
657         }
658
659         // If it's not part of a conversation, it's the beginning of a new conversation.
660         if (empty($notice->conversation)) {
661             $conv = Conversation::create();
662             $notice->conversation = $conv->getID();
663             unset($conv);
664         }
665
666
667         $notloc = new Notice_location();
668         if (!empty($lat) && !empty($lon)) {
669             $notloc->lat = $lat;
670             $notloc->lon = $lon;
671         }
672
673         if (!empty($location_ns) && !empty($location_id)) {
674             $notloc->location_id = $location_id;
675             $notloc->location_ns = $location_ns;
676         }
677
678         if (!empty($rendered)) {
679             $notice->rendered = $rendered;
680         } else {
681             $notice->rendered = common_render_content($final,
682                                                       $notice->getProfile(),
683                                                       $notice->hasParent() ? $notice->getParent() : null);
684         }
685
686         if (empty($verb)) {
687             if ($notice->isRepeat()) {
688                 $notice->verb        = ActivityVerb::SHARE;
689                 $notice->object_type = ActivityObject::ACTIVITY;
690             } else {
691                 $notice->verb        = ActivityVerb::POST;
692             }
693         } else {
694             $notice->verb = $verb;
695         }
696
697         if (empty($object_type)) {
698             $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
699         } else {
700             $notice->object_type = $object_type;
701         }
702
703         if (is_null($scope) && $reply instanceof Notice) {
704             $notice->scope = $reply->scope;
705         } else {
706             $notice->scope = $scope;
707         }
708
709         $notice->scope = self::figureOutScope($profile, $groups, $notice->scope);
710
711         if (Event::handle('StartNoticeSave', array(&$notice))) {
712
713             // XXX: some of these functions write to the DB
714
715             try {
716                 $notice->insert();  // throws exception on failure, if successful we have an ->id
717
718                 if (($notloc->lat && $notloc->lon) || ($notloc->location_id && $notloc->location_ns)) {
719                     $notloc->notice_id = $notice->getID();
720                     $notloc->insert();  // store the notice location if it had any information
721                 }
722             } catch (Exception $e) {
723                 // Let's test if we managed initial insert, which would imply
724                 // failing on some update-part (check 'insert()'). Delete if
725                 // something had been stored to the database.
726                 if (!empty($notice->id)) {
727                     $notice->delete();
728                 }
729                 throw $e;
730             }
731         }
732
733         // Only save 'attention' and metadata stuff (URLs, tags...) stuff if
734         // the activityverb is a POST (since stuff like repeat, favorite etc.
735         // reasonably handle notifications themselves.
736         if (ActivityUtils::compareVerbs($notice->verb, array(ActivityVerb::POST))) {
737             if (isset($replies)) {
738                 $notice->saveKnownReplies($replies);
739             } else {
740                 $notice->saveReplies();
741             }
742
743             if (isset($tags)) {
744                 $notice->saveKnownTags($tags);
745             } else {
746                 $notice->saveTags();
747             }
748
749             // Note: groups may save tags, so must be run after tags are saved
750             // to avoid errors on duplicates.
751             // Note: groups should always be set.
752
753             $notice->saveKnownGroups($groups);
754
755             if (isset($urls)) {
756                 $notice->saveKnownUrls($urls);
757             } else {
758                 $notice->saveUrls();
759             }
760         }
761
762         if ($distribute) {
763             // Prepare inbox delivery, may be queued to background.
764             $notice->distribute();
765         }
766
767         return $notice;
768     }
769
770     static function saveActivity(Activity $act, Profile $actor, array $options=array())
771     {
772         // First check if we're going to let this Activity through from the specific actor
773         if (!$actor->hasRight(Right::NEWNOTICE)) {
774             common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $actor->getNickname());
775
776             // TRANS: Client exception thrown when a user tries to post while being banned.
777             throw new ClientException(_m('You are banned from posting notices on this site.'), 403);
778         }
779         if (common_config('throttle', 'enabled') && !self::checkEditThrottle($actor->id)) {
780             common_log(LOG_WARNING, 'Excessive posting by profile #' . $actor->id . '; throttled.');
781             // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
782             throw new ClientException(_m('Too many notices too fast; take a breather '.
783                                         'and post again in a few minutes.'));
784         }
785
786         // Get ActivityObject properties
787         $actobj = null;
788         if (!empty($act->id)) {
789             // implied object
790             $options['uri'] = $act->id;
791             $options['url'] = $act->link;
792             if ($act->selfLink) {
793                 $options['self'] = $act->selfLink;
794             }
795         } else {
796             $actobj = count($act->objects)===1 ? $act->objects[0] : null;
797             if (!is_null($actobj) && !empty($actobj->id)) {
798                 $options['uri'] = $actobj->id;
799                 if ($actobj->link) {
800                     $options['url'] = $actobj->link;
801                 } elseif (preg_match('!^https?://!', $actobj->id)) {
802                     $options['url'] = $actobj->id;
803                 }
804             }
805             if ($actobj->selfLink) {
806                 $options['self'] = $actobj->selfLink;
807             }
808         }
809
810         $defaults = array(
811                           'groups'   => array(),
812                           'is_local' => $actor->isLocal() ? self::LOCAL_PUBLIC : self::REMOTE,
813                           'mentions' => array(),
814                           'reply_to' => null,
815                           'repeat_of' => null,
816                           'scope' => null,
817                           'self' => null,
818                           'source' => 'unknown',
819                           'tags' => array(),
820                           'uri' => null,
821                           'url' => null,
822                           'urls' => array(),
823                           'distribute' => true);
824
825         // options will have default values when nothing has been supplied
826         $options = array_merge($defaults, $options);
827         foreach (array_keys($defaults) as $key) {
828             // Only convert the keynames we specify ourselves from 'defaults' array into variables
829             $$key = $options[$key];
830         }
831         extract($options, EXTR_SKIP);
832
833         // dupe check
834         $stored = new Notice();
835         if (!empty($uri) && !ActivityUtils::compareVerbs($act->verb, array(ActivityVerb::DELETE))) {
836             $stored->uri = $uri;
837             if ($stored->find()) {
838                 common_debug('cannot create duplicate Notice URI: '.$stored->uri);
839                 // I _assume_ saving a Notice with a colliding URI means we're really trying to
840                 // save the same notice again...
841                 throw new AlreadyFulfilledException('Notice URI already exists');
842             }
843         }
844
845         // NOTE: Sandboxed users previously got all the notices _during_
846         // sandbox period set to to is_local=Notice::LOCAL_NONPUBLIC here.
847         // Since then we have started just filtering _when_ it gets shown
848         // instead of creating a mixed jumble of differently scoped notices.
849
850         if ($source && in_array($source, common_config('public', 'autosource'))) {
851             $stored->is_local = Notice::LOCAL_NONPUBLIC;
852         } else {
853             $stored->is_local = intval($is_local);
854         }
855
856         if (!$stored->isLocal()) {
857             // Only do these checks for non-local notices. Local notices will generate these values later.
858             if (!common_valid_http_url($url)) {
859                 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
860             }
861             if (empty($uri)) {
862                 throw new ServerException('No URI for remote notice. Cannot accept that.');
863             }
864         }
865
866         $stored->profile_id = $actor->getID();
867         $stored->source = $source;
868         $stored->uri = $uri;
869         $stored->url = $url;
870         if (common_valid_http_url($stored->self)) {
871             $stored->self = $self;
872         }
873         $stored->verb = $act->verb;
874
875         // we use mb_strlen because it _might_ be that the content is just the string "0"...
876         $content = mb_strlen($act->content) ? $act->content : $act->summary;
877         if (mb_strlen($content)===0 && !is_null($actobj)) {
878             $content = mb_strlen($actobj->content) ? $actobj->content : $actobj->summary;
879         }
880         // Strip out any bad HTML from $content. URI.Base is used to sort out relative URLs.
881         $stored->rendered = common_purify($content, ['URI.Base' => $stored->url ?: null]);
882         $stored->content  = common_strip_html($stored->getRendered(), true, true);
883         if (trim($stored->content) === '') {
884             // TRANS: Error message when the plain text content of a notice has zero length.
885             throw new ClientException(_('Empty notice content, will not save this.'));
886         }
887         unset($content);    // garbage collect
888
889         // Maybe a missing act-time should be fatal if the actor is not local?
890         if (!empty($act->time)) {
891             $stored->created = common_sql_date($act->time);
892         } else {
893             $stored->created = common_sql_now();
894         }
895
896         $reply = null;  // this will store the in-reply-to Notice if found
897         $replyUris = [];    // this keeps a list of possible URIs to look up
898         if ($act->context instanceof ActivityContext && !empty($act->context->replyToID)) {
899             $replyUris[] = $act->context->replyToID;
900         }
901         if ($act->target instanceof ActivityObject && !empty($act->target->id)) {
902             $replyUris[] = $act->target->id;
903         }
904         foreach (array_unique($replyUris) as $replyUri) {
905             $reply = self::getKV('uri', $replyUri);
906             // Only do remote fetching if we're not a private site
907             if (!common_config('site', 'private') && !$reply instanceof Notice) {
908                 // the URI is the object we're looking for, $actor is a
909                 // Profile that surely knows of it and &$reply where it
910                 // will be stored when fetched
911                 Event::handle('FetchRemoteNotice', array($replyUri, $actor, &$reply));
912             }
913             // we got what we're in-reply-to now, so let's move on
914             if ($reply instanceof Notice) {
915                 break;
916             }
917             // otherwise reset whatever we might've gotten from the event
918             $reply = null;
919         }
920         unset($replyUris);  // garbage collect
921
922         if ($reply instanceof Notice) {
923             if (!$reply->inScope($actor)) {
924                 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
925                 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
926                 throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $actor->getNickname(), $reply->id), 403);
927             }
928
929             $stored->reply_to     = $reply->id;
930             $stored->conversation = $reply->conversation;
931
932             // If the original is private to a group, and notice has no group specified,
933             // make it to the same group(s)
934             if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
935                 $replyGroups = $reply->getGroups();
936                 foreach ($replyGroups as $group) {
937                     if ($actor->isMember($group)) {
938                         $groups[] = $group->id;
939                     }
940                 }
941             }
942
943             if (is_null($scope)) {
944                 $scope = $reply->scope;
945             }
946         } else {
947             // If we don't know the reply, we might know the conversation!
948             // This will happen if a known remote user replies to an
949             // unknown remote user - within a known conversation.
950             if (empty($stored->conversation) and !empty($act->context->conversation)) {
951                 $conv = Conversation::getKV('uri', $act->context->conversation);
952                 if ($conv instanceof Conversation) {
953                     common_debug('Conversation stitched together from (probably) a reply activity to unknown remote user. Activity creation time ('.$stored->created.') should maybe be compared to conversation creation time ('.$conv->created.').');
954                 } else {
955                     // Conversation entry with specified URI was not found, so we must create it.
956                     common_debug('Conversation URI not found, so we will create it with the URI given in the context of the activity: '.$act->context->conversation);
957                     // The insert in Conversation::create throws exception on failure
958                     $conv = Conversation::create($act->context, $stored->created);
959                 }
960                 $stored->conversation = $conv->getID();
961                 unset($conv);
962             }
963         }
964         unset($reply);  // garbage collect
965
966         // If it's not part of a conversation, it's the beginning of a new conversation.
967         if (empty($stored->conversation)) {
968             $conv = Conversation::create();
969             $stored->conversation = $conv->getID();
970             unset($conv);
971         }
972
973         $notloc = null;
974         if ($act->context instanceof ActivityContext) {
975             if ($act->context->location instanceof Location) {
976                 $notloc = Notice_location::fromLocation($act->context->location);
977             }
978         } else {
979             $act->context = new ActivityContext();
980         }
981
982         if (array_key_exists(ActivityContext::ATTN_PUBLIC, $act->context->attention)) {
983             $stored->scope = Notice::PUBLIC_SCOPE;
984             // TODO: maybe we should actually keep this? if the saveAttentions thing wants to use it...
985             unset($act->context->attention[ActivityContext::ATTN_PUBLIC]);
986         } else {
987             $stored->scope = self::figureOutScope($actor, $groups, $scope);
988         }
989
990         foreach ($act->categories as $cat) {
991             if ($cat->term) {
992                 $term = common_canonical_tag($cat->term);
993                 if (!empty($term)) {
994                     $tags[] = $term;
995                 }
996             }
997         }
998
999         foreach ($act->enclosures as $href) {
1000             // @todo FIXME: Save these locally or....?
1001             $urls[] = $href;
1002         }
1003
1004         if (ActivityUtils::compareVerbs($stored->verb, array(ActivityVerb::POST))) {
1005             if (empty($act->objects[0]->type)) {
1006                 // Default type for the post verb is 'note', but we know it's
1007                 // a 'comment' if it is in reply to something.
1008                 $stored->object_type = empty($stored->reply_to) ? ActivityObject::NOTE : ActivityObject::COMMENT;
1009             } else {
1010                 //TODO: Is it safe to always return a relative URI? The
1011                 // JSON version of ActivityStreams always use it, so we
1012                 // should definitely be able to handle it...
1013                 $stored->object_type = ActivityUtils::resolveUri($act->objects[0]->type, true);
1014             }
1015         }
1016
1017         if (Event::handle('StartNoticeSave', array(&$stored))) {
1018             // XXX: some of these functions write to the DB
1019
1020             try {
1021                 $result = $stored->insert();    // throws exception on error
1022
1023                 if ($notloc instanceof Notice_location) {
1024                     $notloc->notice_id = $stored->getID();
1025                     $notloc->insert();
1026                 }
1027
1028                 $orig = clone($stored); // for updating later in this try clause
1029
1030                 $object = null;
1031                 Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
1032                 if (empty($object)) {
1033                     throw new NoticeSaveException('Unsuccessful call to StoreActivityObject '._ve($stored->getUri()) . ': '._ve($act->asString()));
1034                 }
1035                 unset($object);
1036
1037                 // If something changed in the Notice during StoreActivityObject
1038                 $stored->update($orig);
1039             } catch (Exception $e) {
1040                 if (empty($stored->id)) {
1041                     common_debug('Failed to save stored object entry in database ('.$e->getMessage().')');
1042                 } else {
1043                     common_debug('Failed to store activity object in database ('.$e->getMessage().'), deleting notice id '.$stored->id);
1044                     $stored->delete();
1045                 }
1046                 throw $e;
1047             }
1048         }
1049         unset($notloc); // garbage collect
1050
1051         if (!$stored instanceof Notice) {
1052             throw new ServerException('StartNoticeSave did not give back a Notice.');
1053         } elseif (empty($stored->id)) {
1054             throw new ServerException('Supposedly saved Notice has no ID.');
1055         }
1056
1057         // Only save 'attention' and metadata stuff (URLs, tags...) stuff if
1058         // the activityverb is a POST (since stuff like repeat, favorite etc.
1059         // reasonably handle notifications themselves.
1060         if (ActivityUtils::compareVerbs($stored->verb, array(ActivityVerb::POST))) {
1061
1062             if (!empty($tags)) {
1063                 $stored->saveKnownTags($tags);
1064             } else {
1065                 $stored->saveTags();
1066             }
1067
1068             // Note: groups may save tags, so must be run after tags are saved
1069             // to avoid errors on duplicates.
1070             $stored->saveAttentions($act->context->attention);
1071
1072             if (!empty($urls)) {
1073                 $stored->saveKnownUrls($urls);
1074             } else {
1075                 $stored->saveUrls();
1076             }
1077         }
1078
1079         if ($distribute) {
1080             // Prepare inbox delivery, may be queued to background.
1081             $stored->distribute();
1082         }
1083
1084         return $stored;
1085     }
1086
1087     static public function figureOutScope(Profile $actor, array $groups, $scope=null) {
1088         $scope = is_null($scope) ? self::defaultScope() : intval($scope);
1089
1090         // For private streams
1091         try {
1092             $user = $actor->getUser();
1093             // FIXME: We can't do bit comparison with == (Legacy StatusNet thing. Let's keep it for now.)
1094             if ($user->private_stream && ($scope === Notice::PUBLIC_SCOPE || $scope === Notice::SITE_SCOPE)) {
1095                 $scope |= Notice::FOLLOWER_SCOPE;
1096             }
1097         } catch (NoSuchUserException $e) {
1098             // TODO: Not a local user, so we don't know about scope preferences... yet!
1099         }
1100
1101         // Force the scope for private groups
1102         foreach ($groups as $group_id) {
1103             try {
1104                 $group = User_group::getByID($group_id);
1105                 if ($group->force_scope) {
1106                     $scope |= Notice::GROUP_SCOPE;
1107                     break;
1108                 }
1109             } catch (Exception $e) {
1110                 common_log(LOG_ERR, 'Notice figureOutScope threw exception: '.$e->getMessage());
1111             }
1112         }
1113
1114         return $scope;
1115     }
1116
1117     function blowOnInsert($conversation = false)
1118     {
1119         $this->blowStream('profile:notice_ids:%d', $this->profile_id);
1120
1121         if ($this->isPublic()) {
1122             $this->blowStream('public');
1123             $this->blowStream('networkpublic');
1124         }
1125
1126         if ($this->conversation) {
1127             self::blow('notice:list-ids:conversation:%s', $this->conversation);
1128             self::blow('conversation:notice_count:%d', $this->conversation);
1129         }
1130
1131         if ($this->isRepeat()) {
1132             // XXX: we should probably only use one of these
1133             $this->blowStream('notice:repeats:%d', $this->repeat_of);
1134             self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
1135         }
1136
1137         $original = Notice::getKV('id', $this->repeat_of);
1138
1139         if ($original instanceof Notice) {
1140             $originalUser = User::getKV('id', $original->profile_id);
1141             if ($originalUser instanceof User) {
1142                 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
1143             }
1144         }
1145
1146         $profile = Profile::getKV($this->profile_id);
1147
1148         if ($profile instanceof Profile) {
1149             $profile->blowNoticeCount();
1150         }
1151
1152         $ptags = $this->getProfileTags();
1153         foreach ($ptags as $ptag) {
1154             $ptag->blowNoticeStreamCache();
1155         }
1156     }
1157
1158     /**
1159      * Clear cache entries related to this notice at delete time.
1160      * Necessary to avoid breaking paging on public, profile timelines.
1161      */
1162     function blowOnDelete()
1163     {
1164         $this->blowOnInsert();
1165
1166         self::blow('profile:notice_ids:%d;last', $this->profile_id);
1167
1168         if ($this->isPublic()) {
1169             self::blow('public;last');
1170             self::blow('networkpublic;last');
1171         }
1172
1173         self::blow('fave:by_notice', $this->id);
1174
1175         if ($this->conversation) {
1176             // In case we're the first, will need to calc a new root.
1177             self::blow('notice:conversation_root:%d', $this->conversation);
1178         }
1179
1180         $ptags = $this->getProfileTags();
1181         foreach ($ptags as $ptag) {
1182             $ptag->blowNoticeStreamCache(true);
1183         }
1184     }
1185
1186     function blowStream()
1187     {
1188         $c = self::memcache();
1189
1190         if (empty($c)) {
1191             return false;
1192         }
1193
1194         $args = func_get_args();
1195         $format = array_shift($args);
1196         $keyPart = vsprintf($format, $args);
1197         $cacheKey = Cache::key($keyPart);
1198         $c->delete($cacheKey);
1199
1200         // delete the "last" stream, too, if this notice is
1201         // older than the top of that stream
1202
1203         $lastKey = $cacheKey.';last';
1204
1205         $lastStr = $c->get($lastKey);
1206
1207         if ($lastStr !== false) {
1208             $window     = explode(',', $lastStr);
1209             $lastID     = $window[0];
1210             $lastNotice = Notice::getKV('id', $lastID);
1211             if (!$lastNotice instanceof Notice // just weird
1212                 || strtotime($lastNotice->created) >= strtotime($this->created)) {
1213                 $c->delete($lastKey);
1214             }
1215         }
1216     }
1217
1218     /** save all urls in the notice to the db
1219      *
1220      * follow redirects and save all available file information
1221      * (mimetype, date, size, oembed, etc.)
1222      *
1223      * @return void
1224      */
1225     function saveUrls() {
1226         if (common_config('attachments', 'process_links')) {
1227             common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this);
1228         }
1229     }
1230
1231     /**
1232      * Save the given URLs as related links/attachments to the db
1233      *
1234      * follow redirects and save all available file information
1235      * (mimetype, date, size, oembed, etc.)
1236      *
1237      * @return void
1238      */
1239     function saveKnownUrls($urls)
1240     {
1241         if (common_config('attachments', 'process_links')) {
1242             // @fixme validation?
1243             foreach (array_unique($urls) as $url) {
1244                 $this->saveUrl($url, $this);
1245             }
1246         }
1247     }
1248
1249     /**
1250      * @private callback
1251      */
1252     function saveUrl($url, Notice $notice) {
1253         try {
1254             File::processNew($url, $notice);
1255         } catch (ServerException $e) {
1256             // Could not save URL. Log it?
1257         }
1258     }
1259
1260     static function checkDupes($profile_id, $content) {
1261         $profile = Profile::getKV($profile_id);
1262         if (!$profile instanceof Profile) {
1263             return false;
1264         }
1265         $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
1266         if (!empty($notice)) {
1267             $last = 0;
1268             while ($notice->fetch()) {
1269                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
1270                     return true;
1271                 } else if ($notice->content == $content) {
1272                     return false;
1273                 }
1274             }
1275         }
1276         // If we get here, oldest item in cache window is not
1277         // old enough for dupe limit; do direct check against DB
1278         $notice = new Notice();
1279         $notice->profile_id = $profile_id;
1280         $notice->content = $content;
1281         $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
1282         $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
1283
1284         $cnt = $notice->count();
1285         return ($cnt == 0);
1286     }
1287
1288     static function checkEditThrottle($profile_id) {
1289         $profile = Profile::getKV($profile_id);
1290         if (!$profile instanceof Profile) {
1291             return false;
1292         }
1293         // Get the Nth notice
1294         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
1295         if ($notice && $notice->fetch()) {
1296             // If the Nth notice was posted less than timespan seconds ago
1297             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
1298                 // Then we throttle
1299                 return false;
1300             }
1301         }
1302         // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
1303         return true;
1304     }
1305
1306         protected $_attachments = array();
1307
1308     function attachments() {
1309                 if (isset($this->_attachments[$this->id])) {
1310             return $this->_attachments[$this->id];
1311         }
1312
1313         $f2ps = File_to_post::listGet('post_id', array($this->id));
1314                 $ids = array();
1315                 foreach ($f2ps[$this->id] as $f2p) {
1316             $ids[] = $f2p->file_id;
1317         }
1318
1319         return $this->_setAttachments(File::multiGet('id', $ids)->fetchAll());
1320     }
1321
1322         public function _setAttachments(array $attachments)
1323         {
1324             return $this->_attachments[$this->id] = $attachments;
1325         }
1326
1327     static function publicStream($offset=0, $limit=20, $since_id=null, $max_id=null)
1328     {
1329         $stream = new PublicNoticeStream();
1330         return $stream->getNotices($offset, $limit, $since_id, $max_id);
1331     }
1332
1333     static function conversationStream($id, $offset=0, $limit=20, $since_id=null, $max_id=null, Profile $scoped=null)
1334     {
1335         $stream = new ConversationNoticeStream($id, $scoped);
1336         return $stream->getNotices($offset, $limit, $since_id, $max_id);
1337     }
1338
1339     /**
1340      * Is this notice part of an active conversation?
1341      *
1342      * @return boolean true if other messages exist in the same
1343      *                 conversation, false if this is the only one
1344      */
1345     function hasConversation()
1346     {
1347         if (empty($this->conversation)) {
1348             // this notice is not part of a conversation apparently
1349             // FIXME: all notices should have a conversation value, right?
1350             return false;
1351         }
1352
1353         //FIXME: Get the Profile::current() stuff some other way
1354         // to avoid confusion between queue processing and session.
1355         $notice = self::conversationStream($this->conversation, 1, 1, null, null, Profile::current());
1356
1357         // if our "offset 1, limit 1" query got a result, return true else false
1358         return $notice->N > 0;
1359     }
1360
1361     /**
1362      * Grab the earliest notice from this conversation.
1363      *
1364      * @return Notice or null
1365      */
1366     function conversationRoot($profile=-1)
1367     {
1368         // XXX: can this happen?
1369
1370         if (empty($this->conversation)) {
1371             return null;
1372         }
1373
1374         // Get the current profile if not specified
1375
1376         if (is_int($profile) && $profile == -1) {
1377             $profile = Profile::current();
1378         }
1379
1380         // If this notice is out of scope, no root for you!
1381
1382         if (!$this->inScope($profile)) {
1383             return null;
1384         }
1385
1386         // If this isn't a reply to anything, then it's its own
1387         // root if it's the earliest notice in the conversation:
1388
1389         if (empty($this->reply_to)) {
1390             $root = new Notice;
1391             $root->conversation = $this->conversation;
1392             $root->orderBy('notice.created ASC');
1393             $root->find(true);  // true means "fetch first result"
1394             $root->free();
1395             return $root;
1396         }
1397
1398         if (is_null($profile)) {
1399             $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1400         } else {
1401             $keypart = sprintf('notice:conversation_root:%d:%d',
1402                                $this->id,
1403                                $profile->id);
1404         }
1405
1406         $root = self::cacheGet($keypart);
1407
1408         if ($root !== false && $root->inScope($profile)) {
1409             return $root;
1410         }
1411
1412         $last = $this;
1413         while (true) {
1414             try {
1415                 $parent = $last->getParent();
1416                 if ($parent->inScope($profile)) {
1417                     $last = $parent;
1418                     continue;
1419                 }
1420             } catch (NoParentNoticeException $e) {
1421                 // Latest notice has no parent
1422             } catch (NoResultException $e) {
1423                 // Notice was not found, so we can't go further up in the tree.
1424                 // FIXME: Maybe we should do this in a more stable way where deleted
1425                 // notices won't break conversation chains?
1426             }
1427             // No parent, or parent out of scope
1428             $root = $last;
1429             break;
1430         }
1431
1432         self::cacheSet($keypart, $root);
1433
1434         return $root;
1435     }
1436
1437     /**
1438      * Pull up a full list of local recipients who will be getting
1439      * this notice in their inbox. Results will be cached, so don't
1440      * change the input data wily-nilly!
1441      *
1442      * @param array $groups optional list of Group objects;
1443      *              if left empty, will be loaded from group_inbox records
1444      * @param array $recipient optional list of reply profile ids
1445      *              if left empty, will be loaded from reply records
1446      * @return array associating recipient user IDs with an inbox source constant
1447      */
1448     function whoGets(array $groups=null, array $recipients=null)
1449     {
1450         $c = self::memcache();
1451
1452         if (!empty($c)) {
1453             $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1454             if ($ni !== false) {
1455                 return $ni;
1456             }
1457         }
1458
1459         if (is_null($recipients)) {
1460             $recipients = $this->getReplies();
1461         }
1462
1463         $ni = array();
1464
1465         // Give plugins a chance to add folks in at start...
1466         if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1467
1468             $users = $this->getSubscribedUsers();
1469             foreach ($users as $id) {
1470                 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1471             }
1472
1473             if (is_null($groups)) {
1474                 $groups = $this->getGroups();
1475             }
1476             foreach ($groups as $group) {
1477                 $users = $group->getUserMembers();
1478                 foreach ($users as $id) {
1479                     if (!array_key_exists($id, $ni)) {
1480                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1481                     }
1482                 }
1483             }
1484
1485             $ptAtts = $this->getAttentionsFromProfileTags();
1486             foreach ($ptAtts as $key=>$val) {
1487                 if (!array_key_exists($key, $ni)) {
1488                     $ni[$key] = $val;
1489                 }
1490             }
1491
1492             foreach ($recipients as $recipient) {
1493                 if (!array_key_exists($recipient, $ni)) {
1494                     $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1495                 }
1496             }
1497
1498             // Exclude any deleted, non-local, or blocking recipients.
1499             $profile = $this->getProfile();
1500             $originalProfile = null;
1501             if ($this->isRepeat()) {
1502                 // Check blocks against the original notice's poster as well.
1503                 $original = Notice::getKV('id', $this->repeat_of);
1504                 if ($original instanceof Notice) {
1505                     $originalProfile = $original->getProfile();
1506                 }
1507             }
1508
1509             foreach ($ni as $id => $source) {
1510                 try {
1511                     $user = User::getKV('id', $id);
1512                     if (!$user instanceof User ||
1513                         $user->hasBlocked($profile) ||
1514                         ($originalProfile && $user->hasBlocked($originalProfile))) {
1515                         unset($ni[$id]);
1516                     }
1517                 } catch (UserNoProfileException $e) {
1518                     // User doesn't have a profile; invalid; skip them.
1519                     unset($ni[$id]);
1520                 }
1521             }
1522
1523             // Give plugins a chance to filter out...
1524             Event::handle('EndNoticeWhoGets', array($this, &$ni));
1525         }
1526
1527         if (!empty($c)) {
1528             // XXX: pack this data better
1529             $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1530         }
1531
1532         return $ni;
1533     }
1534
1535     function getSubscribedUsers()
1536     {
1537         $user = new User();
1538
1539         if(common_config('db','quote_identifiers'))
1540           $user_table = '"user"';
1541         else $user_table = 'user';
1542
1543         $qry =
1544           'SELECT id ' .
1545           'FROM '. $user_table .' JOIN subscription '.
1546           'ON '. $user_table .'.id = subscription.subscriber ' .
1547           'WHERE subscription.subscribed = %d ';
1548
1549         $user->query(sprintf($qry, $this->profile_id));
1550
1551         $ids = array();
1552
1553         while ($user->fetch()) {
1554             $ids[] = $user->id;
1555         }
1556
1557         $user->free();
1558
1559         return $ids;
1560     }
1561
1562     function getProfileTags()
1563     {
1564         $ptags   = array();
1565         try {
1566             $profile = $this->getProfile();
1567             $list    = $profile->getOtherTags($profile);
1568
1569             while($list->fetch()) {
1570                 $ptags[] = clone($list);
1571             }
1572         } catch (Exception $e) {
1573             common_log(LOG_ERR, "Error during Notice->getProfileTags() for id=={$this->getID()}: {$e->getMessage()}");
1574         }
1575
1576         return $ptags;
1577     }
1578
1579     public function getAttentionsFromProfileTags()
1580     {
1581         $ni = array();
1582         $ptags = $this->getProfileTags();
1583         foreach ($ptags as $ptag) {
1584             $users = $ptag->getUserSubscribers();
1585             foreach ($users as $id) {
1586                 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1587             }
1588         }
1589         return $ni;
1590     }
1591
1592     /**
1593      * Record this notice to the given group inboxes for delivery.
1594      * Overrides the regular parsing of !group markup.
1595      *
1596      * @param string $group_ids
1597      * @fixme might prefer URIs as identifiers, as for replies?
1598      *        best with generalizations on user_group to support
1599      *        remote groups better.
1600      */
1601     function saveKnownGroups(array $group_ids)
1602     {
1603         $groups = array();
1604         foreach (array_unique($group_ids) as $id) {
1605             $group = User_group::getKV('id', $id);
1606             if ($group instanceof User_group) {
1607                 common_log(LOG_DEBUG, "Local delivery to group id $id, $group->nickname");
1608                 $result = $this->addToGroupInbox($group);
1609                 if (!$result) {
1610                     common_log_db_error($gi, 'INSERT', __FILE__);
1611                 }
1612
1613                 if (common_config('group', 'addtag')) {
1614                     // we automatically add a tag for every group name, too
1615                     common_debug('Adding hashtag matching group nickname: '._ve($group->getNickname()));
1616                     $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->getNickname()),
1617                                                      'notice_id' => $this->getID()));
1618
1619                     if (is_null($tag)) {
1620                         $this->saveTag($group->getNickname());
1621                     }
1622                 }
1623
1624                 $groups[] = clone($group);
1625             } else {
1626                 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1627             }
1628         }
1629
1630         return $groups;
1631     }
1632
1633     function addToGroupInbox(User_group $group)
1634     {
1635         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1636                                          'notice_id' => $this->id));
1637
1638         if (!$gi instanceof Group_inbox) {
1639
1640             $gi = new Group_inbox();
1641
1642             $gi->group_id  = $group->id;
1643             $gi->notice_id = $this->id;
1644             $gi->created   = $this->created;
1645
1646             $result = $gi->insert();
1647
1648             if (!$result) {
1649                 common_log_db_error($gi, 'INSERT', __FILE__);
1650                 // TRANS: Server exception thrown when an update for a group inbox fails.
1651                 throw new ServerException(_('Problem saving group inbox.'));
1652             }
1653
1654             self::blow('user_group:notice_ids:%d', $gi->group_id);
1655         }
1656
1657         return true;
1658     }
1659
1660     function saveAttentions(array $uris)
1661     {
1662         foreach ($uris as $uri=>$type) {
1663             try {
1664                 $target = Profile::fromUri($uri);
1665             } catch (UnknownUriException $e) {
1666                 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1667                 continue;
1668             }
1669
1670             try {
1671                 $this->saveAttention($target);
1672             } catch (AlreadyFulfilledException $e) {
1673                 common_debug('Attention already exists: '.var_export($e->getMessage(),true));
1674             } catch (Exception $e) {
1675                 common_log(LOG_ERR, "Could not save notice id=={$this->getID()} attention for profile id=={$target->getID()}: {$e->getMessage()}");
1676             }
1677         }
1678     }
1679
1680     /**
1681      * Saves an attention for a profile (user or group) which means
1682      * it shows up in their home feed and such.
1683      */
1684     function saveAttention(Profile $target, $reason=null)
1685     {
1686         if ($target->isGroup()) {
1687             // FIXME: Make sure we check (for both local and remote) users are in the groups they send to!
1688
1689             // legacy notification method, will still be in use for quite a while I think
1690             $this->addToGroupInbox($target->getGroup());
1691         } else {
1692             if ($target->hasBlocked($this->getProfile())) {
1693                 common_log(LOG_INFO, "Not saving reply to profile {$target->id} ($uri) from sender {$sender->id} because of a block.");
1694                 return false;
1695             }
1696         }
1697
1698         if ($target->isLocal()) {
1699             // legacy notification method, will still be in use for quite a while I think
1700             $this->saveReply($target->getID());
1701         }
1702
1703         $att = Attention::saveNew($this, $target, $reason);
1704         return true;
1705     }
1706
1707     /**
1708      * Save reply records indicating that this notice needs to be
1709      * delivered to the local users with the given URIs.
1710      *
1711      * Since this is expected to be used when saving foreign-sourced
1712      * messages, we won't deliver to any remote targets as that's the
1713      * source service's responsibility.
1714      *
1715      * Mail notifications etc will be handled later.
1716      *
1717      * @param array  $uris   Array of unique identifier URIs for recipients
1718      */
1719     function saveKnownReplies(array $uris)
1720     {
1721         if (empty($uris)) {
1722             return;
1723         }
1724
1725         $sender = $this->getProfile();
1726
1727         foreach (array_unique($uris) as $uri) {
1728             try {
1729                 $profile = Profile::fromUri($uri);
1730             } catch (UnknownUriException $e) {
1731                 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1732                 continue;
1733             }
1734
1735             if ($profile->hasBlocked($sender)) {
1736                 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1737                 continue;
1738             }
1739
1740             $this->saveReply($profile->getID());
1741             self::blow('reply:stream:%d', $profile->getID());
1742         }
1743     }
1744
1745     /**
1746      * Pull @-replies from this message's content in StatusNet markup format
1747      * and save reply records indicating that this message needs to be
1748      * delivered to those users.
1749      *
1750      * Mail notifications to local profiles will be sent later.
1751      *
1752      * @return array of integer profile IDs
1753      */
1754
1755     function saveReplies()
1756     {
1757         $sender = $this->getProfile();
1758
1759         $replied = array();
1760
1761         // If it's a reply, save for the replied-to author
1762         try {
1763             $parent = $this->getParent();
1764             $parentauthor = $parent->getProfile();
1765             $this->saveReply($parentauthor->getID());
1766             $replied[$parentauthor->getID()] = 1;
1767             self::blow('reply:stream:%d', $parentauthor->getID());
1768         } catch (NoParentNoticeException $e) {
1769             // Not a reply, since it has no parent!
1770             $parent = null;
1771         } catch (NoResultException $e) {
1772             // Parent notice was probably deleted
1773             $parent = null;
1774         }
1775
1776         // @todo ideally this parser information would only
1777         // be calculated once.
1778
1779         $mentions = common_find_mentions($this->content, $sender, $parent);
1780
1781         foreach ($mentions as $mention) {
1782
1783             foreach ($mention['mentioned'] as $mentioned) {
1784
1785                 // skip if they're already covered
1786                 if (array_key_exists($mentioned->id, $replied)) {
1787                     continue;
1788                 }
1789
1790                 // Don't save replies from blocked profile to local user
1791                 if ($mentioned->hasBlocked($sender)) {
1792                     continue;
1793                 }
1794
1795                 $this->saveReply($mentioned->id);
1796                 $replied[$mentioned->id] = 1;
1797                 self::blow('reply:stream:%d', $mentioned->id);
1798             }
1799         }
1800
1801         $recipientIds = array_keys($replied);
1802
1803         return $recipientIds;
1804     }
1805
1806     function saveReply($profileId)
1807     {
1808         $reply = new Reply();
1809
1810         $reply->notice_id  = $this->id;
1811         $reply->profile_id = $profileId;
1812         $reply->modified   = $this->created;
1813
1814         $reply->insert();
1815
1816         return $reply;
1817     }
1818
1819     protected $_attentionids = array();
1820
1821     /**
1822      * Pull the complete list of known activity context attentions for this notice.
1823      *
1824      * @return array of integer profile ids (also group profiles)
1825      */
1826     function getAttentionProfileIDs()
1827     {
1828         if (!isset($this->_attentionids[$this->getID()])) {
1829             $atts = Attention::multiGet('notice_id', array($this->getID()));
1830             // (array)null means empty array
1831             $this->_attentionids[$this->getID()] = (array)$atts->fetchAll('profile_id');
1832         }
1833         return $this->_attentionids[$this->getID()];
1834     }
1835
1836     protected $_replies = array();
1837
1838     /**
1839      * Pull the complete list of @-mentioned profile IDs for this notice.
1840      *
1841      * @return array of integer profile ids
1842      */
1843     function getReplies()
1844     {
1845         if (!isset($this->_replies[$this->getID()])) {
1846             $mentions = Reply::multiGet('notice_id', array($this->getID()));
1847             $this->_replies[$this->getID()] = $mentions->fetchAll('profile_id');
1848         }
1849         return $this->_replies[$this->getID()];
1850     }
1851
1852     function _setReplies($replies)
1853     {
1854         $this->_replies[$this->getID()] = $replies;
1855     }
1856
1857     /**
1858      * Pull the complete list of @-reply targets for this notice.
1859      *
1860      * @return array of Profiles
1861      */
1862     function getAttentionProfiles()
1863     {
1864         $ids = array_unique(array_merge($this->getReplies(), $this->getGroupProfileIDs(), $this->getAttentionProfileIDs()));
1865
1866         $profiles = Profile::multiGet('id', (array)$ids);
1867
1868         return $profiles->fetchAll();
1869     }
1870
1871     /**
1872      * Send e-mail notifications to local @-reply targets.
1873      *
1874      * Replies must already have been saved; this is expected to be run
1875      * from the distrib queue handler.
1876      */
1877     function sendReplyNotifications()
1878     {
1879         // Don't send reply notifications for repeats
1880         if ($this->isRepeat()) {
1881             return array();
1882         }
1883
1884         $recipientIds = $this->getReplies();
1885         if (Event::handle('StartNotifyMentioned', array($this, &$recipientIds))) {
1886             require_once INSTALLDIR.'/lib/mail.php';
1887
1888             foreach ($recipientIds as $recipientId) {
1889                 try {
1890                     $user = User::getByID($recipientId);
1891                     mail_notify_attn($user->getProfile(), $this);
1892                 } catch (NoResultException $e) {
1893                     // No such user
1894                 }
1895             }
1896             Event::handle('EndNotifyMentioned', array($this, $recipientIds));
1897         }
1898     }
1899
1900     /**
1901      * Pull list of Profile IDs of groups this notice addresses.
1902      *
1903      * @return array of Group _profile_ IDs
1904      */
1905
1906     function getGroupProfileIDs()
1907     {
1908         $ids = array();
1909
1910                 foreach ($this->getGroups() as $group) {
1911                     $ids[] = $group->profile_id;
1912                 }
1913
1914         return $ids;
1915     }
1916
1917     /**
1918      * Pull list of groups this notice needs to be delivered to,
1919      * as previously recorded by saveKnownGroups().
1920      *
1921      * @return array of Group objects
1922      */
1923
1924     protected $_groups = array();
1925
1926     function getGroups()
1927     {
1928         // Don't save groups for repeats
1929
1930         if (!empty($this->repeat_of)) {
1931             return array();
1932         }
1933
1934         if (isset($this->_groups[$this->id])) {
1935             return $this->_groups[$this->id];
1936         }
1937
1938         $gis = Group_inbox::listGet('notice_id', array($this->id));
1939
1940         $ids = array();
1941
1942                 foreach ($gis[$this->id] as $gi) {
1943                     $ids[] = $gi->group_id;
1944                 }
1945
1946                 $groups = User_group::multiGet('id', $ids);
1947                 $this->_groups[$this->id] = $groups->fetchAll();
1948                 return $this->_groups[$this->id];
1949     }
1950
1951     function _setGroups($groups)
1952     {
1953         $this->_groups[$this->id] = $groups;
1954     }
1955
1956     /**
1957      * Convert a notice into an activity for export.
1958      *
1959      * @param Profile $scoped   The currently logged in/scoped profile
1960      *
1961      * @return Activity activity object representing this Notice.
1962      */
1963
1964     function asActivity(Profile $scoped=null)
1965     {
1966         $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1967
1968         if ($act instanceof Activity) {
1969             return $act;
1970         }
1971         $act = new Activity();
1972
1973         if (Event::handle('StartNoticeAsActivity', array($this, $act, $scoped))) {
1974
1975             $act->id      = $this->uri;
1976             $act->time    = strtotime($this->created);
1977             try {
1978                 $act->link    = $this->getUrl();
1979             } catch (InvalidUrlException $e) {
1980                 // The notice is probably a share or similar, which don't
1981                 // have a representational URL of their own.
1982             }
1983             $act->content = common_xml_safe_str($this->getRendered());
1984
1985             $profile = $this->getProfile();
1986
1987             $act->actor            = $profile->asActivityObject();
1988             $act->actor->extra[]   = $profile->profileInfo($scoped);
1989
1990             $act->verb = $this->verb;
1991
1992             if (!$this->repeat_of) {
1993                 $act->objects[] = $this->asActivityObject();
1994             }
1995
1996             // XXX: should this be handled by default processing for object entry?
1997
1998             // Categories
1999
2000             $tags = $this->getTags();
2001
2002             foreach ($tags as $tag) {
2003                 $cat       = new AtomCategory();
2004                 $cat->term = $tag;
2005
2006                 $act->categories[] = $cat;
2007             }
2008
2009             // Enclosures
2010             // XXX: use Atom Media and/or File activity objects instead
2011
2012             $attachments = $this->attachments();
2013
2014             foreach ($attachments as $attachment) {
2015                 // Include local attachments in Activity
2016                 if (!empty($attachment->filename)) {
2017                     $act->enclosures[] = $attachment->getEnclosure();
2018                 }
2019             }
2020
2021             $ctx = new ActivityContext();
2022
2023             try {
2024                 $reply = $this->getParent();
2025                 $ctx->replyToID  = $reply->getUri();
2026                 $ctx->replyToUrl = $reply->getUrl(true);    // true for fallback to local URL, less messy
2027             } catch (NoParentNoticeException $e) {
2028                 // This is not a reply to something
2029             } catch (NoResultException $e) {
2030                 // Parent notice was probably deleted
2031             }
2032
2033             try {
2034                 $ctx->location = Notice_location::locFromStored($this);
2035             } catch (ServerException $e) {
2036                 $ctx->location = null;
2037             }
2038
2039             $conv = null;
2040
2041             if (!empty($this->conversation)) {
2042                 $conv = Conversation::getKV('id', $this->conversation);
2043                 if ($conv instanceof Conversation) {
2044                     $ctx->conversation = $conv->uri;
2045                     $ctx->conversation_url = $conv->url;
2046                 }
2047             }
2048
2049             // This covers the legacy getReplies and getGroups too which get their data
2050             // from entries stored via Notice::saveNew (which we want to move away from)...
2051             foreach ($this->getAttentionProfiles() as $target) {
2052                 // User and group profiles which get the attention of this notice
2053                 $ctx->attention[$target->getUri()] = $target->getObjectType();
2054             }
2055
2056             switch ($this->scope) {
2057             case Notice::PUBLIC_SCOPE:
2058                 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
2059                 break;
2060             case Notice::FOLLOWER_SCOPE:
2061                 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
2062                 $ctx->attention[$surl] = ActivityObject::COLLECTION;
2063                 break;
2064             }
2065
2066             $act->context = $ctx;
2067
2068             $source = $this->getSource();
2069
2070             if ($source instanceof Notice_source) {
2071                 $act->generator = ActivityObject::fromNoticeSource($source);
2072             }
2073
2074             // Source
2075
2076             $atom_feed = $profile->getAtomFeed();
2077
2078             if (!empty($atom_feed)) {
2079
2080                 $act->source = new ActivitySource();
2081
2082                 // XXX: we should store the actual feed ID
2083
2084                 $act->source->id = $atom_feed;
2085
2086                 // XXX: we should store the actual feed title
2087
2088                 $act->source->title = $profile->getBestName();
2089
2090                 $act->source->links['alternate'] = $profile->profileurl;
2091                 $act->source->links['self']      = $atom_feed;
2092
2093                 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
2094
2095                 $notice = $profile->getCurrentNotice();
2096
2097                 if ($notice instanceof Notice) {
2098                     $act->source->updated = self::utcDate($notice->created);
2099                 }
2100
2101                 $user = User::getKV('id', $profile->id);
2102
2103                 if ($user instanceof User) {
2104                     $act->source->links['license'] = common_config('license', 'url');
2105                 }
2106             }
2107
2108             try {
2109                 $act->selfLink = $this->getSelfLink();
2110             } catch (InvalidUrlException $e) {
2111                 $act->selfLink = null;
2112             }
2113             if ($this->isLocal()) {
2114                 $act->editLink = $act->selfLink;
2115             }
2116
2117             Event::handle('EndNoticeAsActivity', array($this, $act, $scoped));
2118         }
2119
2120         self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
2121
2122         return $act;
2123     }
2124
2125     // This has gotten way too long. Needs to be sliced up into functional bits
2126     // or ideally exported to a utility class.
2127
2128     function asAtomEntry($namespace=false,
2129                          $source=false,
2130                          $author=true,
2131                          Profile $scoped=null)
2132     {
2133         $act = $this->asActivity($scoped);
2134         $act->extra[] = $this->noticeInfo($scoped);
2135         return $act->asString($namespace, $author, $source);
2136     }
2137
2138     /**
2139      * Extra notice info for atom entries
2140      *
2141      * Clients use some extra notice info in the atom stream.
2142      * This gives it to them.
2143      *
2144      * @param Profile $scoped   The currently logged in/scoped profile
2145      *
2146      * @return array representation of <statusnet:notice_info> element
2147      */
2148
2149     function noticeInfo(Profile $scoped=null)
2150     {
2151         // local notice ID (useful to clients for ordering)
2152
2153         $noticeInfoAttr = array('local_id' => $this->id);
2154
2155         // notice source
2156
2157         $ns = $this->getSource();
2158
2159         if ($ns instanceof Notice_source) {
2160             $noticeInfoAttr['source'] =  $ns->code;
2161             if (!empty($ns->url)) {
2162                 $noticeInfoAttr['source_link'] = $ns->url;
2163                 if (!empty($ns->name)) {
2164                     $noticeInfoAttr['source'] = $ns->name;
2165                 }
2166             }
2167         }
2168
2169         // favorite and repeated
2170
2171         if ($scoped instanceof Profile) {
2172             $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
2173         }
2174
2175         if (!empty($this->repeat_of)) {
2176             $noticeInfoAttr['repeat_of'] = $this->repeat_of;
2177         }
2178
2179         Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
2180
2181         return array('statusnet:notice_info', $noticeInfoAttr, null);
2182     }
2183
2184     /**
2185      * Returns an XML string fragment with a reference to a notice as an
2186      * Activity Streams noun object with the given element type.
2187      *
2188      * Assumes that 'activity' namespace has been previously defined.
2189      *
2190      * @param string $element one of 'subject', 'object', 'target'
2191      * @return string
2192      */
2193
2194     function asActivityNoun($element)
2195     {
2196         $noun = $this->asActivityObject();
2197         return $noun->asString('activity:' . $element);
2198     }
2199
2200     public function asActivityObject()
2201     {
2202         $object = new ActivityObject();
2203
2204         if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
2205             $object->type    = $this->object_type ?: ActivityObject::NOTE;
2206             $object->id      = $this->getUri();
2207             //FIXME: = $object->title ?: sprintf(... because we might get a title from StartActivityObjectFromNotice
2208             $object->title   = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
2209             $object->content = $this->getRendered();
2210             $object->link    = $this->getUrl();
2211             try {
2212                 $object->selfLink = $this->getSelfLink();
2213             } catch (InvalidUrlException $e) {
2214                 $object->selfLink = null;
2215             }
2216
2217             $object->extra[] = array('status_net', array('notice_id' => $this->id));
2218
2219             Event::handle('EndActivityObjectFromNotice', array($this, &$object));
2220         }
2221
2222         if (!$object instanceof ActivityObject) {
2223             common_log(LOG_ERR, 'Notice asActivityObject created something else for uri=='._ve($this->getUri()).': '._ve($object));
2224             throw new ServerException('Notice asActivityObject created something else.');
2225         }
2226
2227         return $object;
2228     }
2229
2230     /**
2231      * Determine which notice, if any, a new notice is in reply to.
2232      *
2233      * For conversation tracking, we try to see where this notice fits
2234      * in the tree. Beware that this may very well give false positives
2235      * and add replies to wrong threads (if there have been newer posts
2236      * by the same user as we're replying to).
2237      *
2238      * @param Profile $sender     Author profile
2239      * @param string  $content    Final notice content
2240      *
2241      * @return integer ID of replied-to notice, or null for not a reply.
2242      */
2243
2244     static function getInlineReplyTo(Profile $sender, $content)
2245     {
2246         // Is there an initial @ or T?
2247         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
2248                 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
2249             $nickname = common_canonical_nickname($match[1]);
2250         } else {
2251             return null;
2252         }
2253
2254         // Figure out who that is.
2255         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
2256
2257         if ($recipient instanceof Profile) {
2258             // Get their last notice
2259             $last = $recipient->getCurrentNotice();
2260             if ($last instanceof Notice) {
2261                 return $last;
2262             }
2263             // Maybe in the future we want to handle something else below
2264             // so don't return getCurrentNotice() immediately.
2265         }
2266
2267         return null;
2268     }
2269
2270     static function maxContent()
2271     {
2272         $contentlimit = common_config('notice', 'contentlimit');
2273         // null => use global limit (distinct from 0!)
2274         if (is_null($contentlimit)) {
2275             $contentlimit = common_config('site', 'textlimit');
2276         }
2277         return $contentlimit;
2278     }
2279
2280     static function contentTooLong($content)
2281     {
2282         $contentlimit = self::maxContent();
2283         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
2284     }
2285
2286     /**
2287      * Convenience function for posting a repeat of an existing message.
2288      *
2289      * @param Profile $repeater Profile which is doing the repeat
2290      * @param string $source: posting source key, eg 'web', 'api', etc
2291      * @return Notice
2292      *
2293      * @throws Exception on failure or permission problems
2294      */
2295     function repeat(Profile $repeater, $source)
2296     {
2297         $author = $this->getProfile();
2298
2299         // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
2300         // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
2301         $content = sprintf(_('RT @%1$s %2$s'),
2302                            $author->getNickname(),
2303                            $this->content);
2304
2305         $maxlen = self::maxContent();
2306         if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
2307             // Web interface and current Twitter API clients will
2308             // pull the original notice's text, but some older
2309             // clients and RSS/Atom feeds will see this trimmed text.
2310             //
2311             // Unfortunately this is likely to lose tags or URLs
2312             // at the end of long notices.
2313             $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
2314         }
2315
2316
2317         // Scope is same as this one's
2318         return self::saveNew($repeater->id,
2319                              $content,
2320                              $source,
2321                              array('repeat_of' => $this->id,
2322                                    'scope' => $this->scope));
2323     }
2324
2325     // These are supposed to be in chron order!
2326
2327     function repeatStream($limit=100)
2328     {
2329         $cache = Cache::instance();
2330
2331         if (empty($cache)) {
2332             $ids = $this->_repeatStreamDirect($limit);
2333         } else {
2334             $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
2335             if ($idstr !== false) {
2336                 if (empty($idstr)) {
2337                         $ids = array();
2338                 } else {
2339                         $ids = explode(',', $idstr);
2340                 }
2341             } else {
2342                 $ids = $this->_repeatStreamDirect(100);
2343                 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
2344             }
2345             if ($limit < 100) {
2346                 // We do a max of 100, so slice down to limit
2347                 $ids = array_slice($ids, 0, $limit);
2348             }
2349         }
2350
2351         return NoticeStream::getStreamByIds($ids);
2352     }
2353
2354     function _repeatStreamDirect($limit)
2355     {
2356         $notice = new Notice();
2357
2358         $notice->selectAdd(); // clears it
2359         $notice->selectAdd('id');
2360
2361         $notice->repeat_of = $this->id;
2362
2363         $notice->orderBy('created, id'); // NB: asc!
2364
2365         if (!is_null($limit)) {
2366             $notice->limit(0, $limit);
2367         }
2368
2369         return $notice->fetchAll('id');
2370     }
2371
2372     static function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
2373     {
2374         $options = array();
2375
2376         if (!empty($location_id) && !empty($location_ns)) {
2377             $options['location_id'] = $location_id;
2378             $options['location_ns'] = $location_ns;
2379
2380             $location = Location::fromId($location_id, $location_ns);
2381
2382             if ($location instanceof Location) {
2383                 $options['lat'] = $location->lat;
2384                 $options['lon'] = $location->lon;
2385             }
2386
2387         } else if (!empty($lat) && !empty($lon)) {
2388             $options['lat'] = $lat;
2389             $options['lon'] = $lon;
2390
2391             $location = Location::fromLatLon($lat, $lon);
2392
2393             if ($location instanceof Location) {
2394                 $options['location_id'] = $location->location_id;
2395                 $options['location_ns'] = $location->location_ns;
2396             }
2397         } else if (!empty($profile)) {
2398             if (isset($profile->lat) && isset($profile->lon)) {
2399                 $options['lat'] = $profile->lat;
2400                 $options['lon'] = $profile->lon;
2401             }
2402
2403             if (isset($profile->location_id) && isset($profile->location_ns)) {
2404                 $options['location_id'] = $profile->location_id;
2405                 $options['location_ns'] = $profile->location_ns;
2406             }
2407         }
2408
2409         return $options;
2410     }
2411
2412     function clearAttentions()
2413     {
2414         $att = new Attention();
2415         $att->notice_id = $this->getID();
2416
2417         if ($att->find()) {
2418             while ($att->fetch()) {
2419                 // Can't do delete() on the object directly since it won't remove all of it
2420                 $other = clone($att);
2421                 $other->delete();
2422             }
2423         }
2424     }
2425
2426     function clearReplies()
2427     {
2428         $replyNotice = new Notice();
2429         $replyNotice->reply_to = $this->id;
2430
2431         //Null any notices that are replies to this notice
2432
2433         if ($replyNotice->find()) {
2434             while ($replyNotice->fetch()) {
2435                 $orig = clone($replyNotice);
2436                 $replyNotice->reply_to = null;
2437                 $replyNotice->update($orig);
2438             }
2439         }
2440
2441         // Reply records
2442
2443         $reply = new Reply();
2444         $reply->notice_id = $this->id;
2445
2446         if ($reply->find()) {
2447             while($reply->fetch()) {
2448                 self::blow('reply:stream:%d', $reply->profile_id);
2449                 $reply->delete();
2450             }
2451         }
2452
2453         $reply->free();
2454     }
2455
2456     function clearLocation()
2457     {
2458         $loc = new Notice_location();
2459         $loc->notice_id = $this->id;
2460
2461         if ($loc->find()) {
2462             $loc->delete();
2463         }
2464     }
2465
2466     function clearFiles()
2467     {
2468         $f2p = new File_to_post();
2469
2470         $f2p->post_id = $this->id;
2471
2472         if ($f2p->find()) {
2473             while ($f2p->fetch()) {
2474                 $f2p->delete();
2475             }
2476         }
2477         // FIXME: decide whether to delete File objects
2478         // ...and related (actual) files
2479     }
2480
2481     function clearRepeats()
2482     {
2483         $repeatNotice = new Notice();
2484         $repeatNotice->repeat_of = $this->id;
2485
2486         //Null any notices that are repeats of this notice
2487
2488         if ($repeatNotice->find()) {
2489             while ($repeatNotice->fetch()) {
2490                 $orig = clone($repeatNotice);
2491                 $repeatNotice->repeat_of = null;
2492                 $repeatNotice->update($orig);
2493             }
2494         }
2495     }
2496
2497     function clearTags()
2498     {
2499         $tag = new Notice_tag();
2500         $tag->notice_id = $this->id;
2501
2502         if ($tag->find()) {
2503             while ($tag->fetch()) {
2504                 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2505                 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2506                 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2507                 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2508                 $tag->delete();
2509             }
2510         }
2511
2512         $tag->free();
2513     }
2514
2515     function clearGroupInboxes()
2516     {
2517         $gi = new Group_inbox();
2518
2519         $gi->notice_id = $this->id;
2520
2521         if ($gi->find()) {
2522             while ($gi->fetch()) {
2523                 self::blow('user_group:notice_ids:%d', $gi->group_id);
2524                 $gi->delete();
2525             }
2526         }
2527
2528         $gi->free();
2529     }
2530
2531     function distribute()
2532     {
2533         // We always insert for the author so they don't
2534         // have to wait
2535         Event::handle('StartNoticeDistribute', array($this));
2536
2537         // If there's a failure, we want to _force_
2538         // distribution at this point.
2539         try {
2540             $json = json_encode((object)array('id' => $this->getID(),
2541                                               'type' => 'Notice',
2542                                               ));
2543             $qm = QueueManager::get();
2544             $qm->enqueue($json, 'distrib');
2545         } catch (Exception $e) {
2546             // If the exception isn't transient, this
2547             // may throw more exceptions as DQH does
2548             // its own enqueueing. So, we ignore them!
2549             try {
2550                 $handler = new DistribQueueHandler();
2551                 $handler->handle($this);
2552             } catch (Exception $e) {
2553                 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2554             }
2555             // Re-throw so somebody smarter can handle it.
2556             throw $e;
2557         }
2558     }
2559
2560     function insert()
2561     {
2562         $result = parent::insert();
2563
2564         if ($result === false) {
2565             common_log_db_error($this, 'INSERT', __FILE__);
2566             // TRANS: Server exception thrown when a stored object entry cannot be saved.
2567             throw new ServerException('Could not save Notice');
2568         }
2569
2570         // Profile::hasRepeated() abuses pkeyGet(), so we
2571         // have to clear manually
2572         if (!empty($this->repeat_of)) {
2573             $c = self::memcache();
2574             if (!empty($c)) {
2575                 $ck = self::multicacheKey('Notice',
2576                                           array('profile_id' => $this->profile_id,
2577                                                 'repeat_of' => $this->repeat_of));
2578                 $c->delete($ck);
2579             }
2580         }
2581
2582         // Update possibly ID-dependent columns: URI, conversation
2583         // (now that INSERT has added the notice's local id)
2584         $orig = clone($this);
2585         $changed = false;
2586
2587         // We can only get here if it's a local notice, since remote notices
2588         // should've bailed out earlier due to lacking a URI.
2589         if (empty($this->uri)) {
2590             $this->uri = sprintf('%s%s=%d:%s=%s',
2591                                 TagURI::mint(),
2592                                 'noticeId', $this->id,
2593                                 'objectType', $this->getObjectType(true));
2594             $changed = true;
2595         }
2596
2597         if ($changed && $this->update($orig) === false) {
2598             common_log_db_error($notice, 'UPDATE', __FILE__);
2599             // TRANS: Server exception thrown when a notice cannot be updated.
2600             throw new ServerException(_('Problem saving notice.'));
2601         }
2602
2603         $this->blowOnInsert();
2604
2605         return $result;
2606     }
2607
2608     /**
2609      * Get the source of the notice
2610      *
2611      * @return Notice_source $ns A notice source object. 'code' is the only attribute
2612      *                           guaranteed to be populated.
2613      */
2614     function getSource()
2615     {
2616         if (empty($this->source)) {
2617             return false;
2618         }
2619
2620         $ns = new Notice_source();
2621         switch ($this->source) {
2622         case 'web':
2623         case 'xmpp':
2624         case 'mail':
2625         case 'omb':
2626         case 'system':
2627         case 'api':
2628             $ns->code = $this->source;
2629             break;
2630         default:
2631             $ns = Notice_source::getKV($this->source);
2632             if (!$ns) {
2633                 $ns = new Notice_source();
2634                 $ns->code = $this->source;
2635                 $app = Oauth_application::getKV('name', $this->source);
2636                 if ($app) {
2637                     $ns->name = $app->name;
2638                     $ns->url  = $app->source_url;
2639                 }
2640             }
2641             break;
2642         }
2643
2644         return $ns;
2645     }
2646
2647     /**
2648      * Determine whether the notice was locally created
2649      *
2650      * @return boolean locality
2651      */
2652
2653     public function isLocal()
2654     {
2655         $is_local = intval($this->is_local);
2656         return ($is_local === self::LOCAL_PUBLIC || $is_local === self::LOCAL_NONPUBLIC);
2657     }
2658
2659     public function getScope()
2660     {
2661         return intval($this->scope);
2662     }
2663
2664     public function isRepeat()
2665     {
2666         return !empty($this->repeat_of);
2667     }
2668
2669     public function isRepeated()
2670     {
2671         $n = new Notice();
2672         $n->repeat_of = $this->getID();
2673         return $n->find() && $n->N > 0;
2674     }
2675
2676     /**
2677      * Get the list of hash tags saved with this notice.
2678      *
2679      * @return array of strings
2680      */
2681     public function getTags()
2682     {
2683         $tags = array();
2684
2685         $keypart = sprintf('notice:tags:%d', $this->id);
2686
2687         $tagstr = self::cacheGet($keypart);
2688
2689         if ($tagstr !== false) {
2690             $tags = explode(',', $tagstr);
2691         } else {
2692             $tag = new Notice_tag();
2693             $tag->notice_id = $this->id;
2694             if ($tag->find()) {
2695                 while ($tag->fetch()) {
2696                     $tags[] = $tag->tag;
2697                 }
2698             }
2699             self::cacheSet($keypart, implode(',', $tags));
2700         }
2701
2702         return $tags;
2703     }
2704
2705     static private function utcDate($dt)
2706     {
2707         $dateStr = date('d F Y H:i:s', strtotime($dt));
2708         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2709         return $d->format(DATE_W3C);
2710     }
2711
2712     /**
2713      * Look up the creation timestamp for a given notice ID, even
2714      * if it's been deleted.
2715      *
2716      * @param int $id
2717      * @return mixed string recorded creation timestamp, or false if can't be found
2718      */
2719     public static function getAsTimestamp($id)
2720     {
2721         if (empty($id)) {
2722             throw new EmptyPkeyValueException('Notice', 'id');
2723         }
2724
2725         $timestamp = null;
2726         if (Event::handle('GetNoticeSqlTimestamp', array($id, &$timestamp))) {
2727             // getByID throws exception if $id isn't found
2728             $notice = Notice::getByID($id);
2729             $timestamp = $notice->created;
2730         }
2731
2732         if (empty($timestamp)) {
2733             throw new ServerException('No timestamp found for Notice with id=='._ve($id));
2734         }
2735         return $timestamp;
2736     }
2737
2738     /**
2739      * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2740      * parameter, matching notices posted after the given one (exclusive).
2741      *
2742      * If the referenced notice can't be found, will return false.
2743      *
2744      * @param int $id
2745      * @param string $idField
2746      * @param string $createdField
2747      * @return mixed string or false if no match
2748      */
2749     public static function whereSinceId($id, $idField='id', $createdField='created')
2750     {
2751         try {
2752             $since = Notice::getAsTimestamp($id);
2753         } catch (Exception $e) {
2754             return false;
2755         }
2756         return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2757     }
2758
2759     /**
2760      * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2761      * parameter, matching notices posted after the given one (exclusive), and
2762      * if necessary add it to the data object's query.
2763      *
2764      * @param DB_DataObject $obj
2765      * @param int $id
2766      * @param string $idField
2767      * @param string $createdField
2768      * @return mixed string or false if no match
2769      */
2770     public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2771     {
2772         $since = self::whereSinceId($id, $idField, $createdField);
2773         if ($since) {
2774             $obj->whereAdd($since);
2775         }
2776     }
2777
2778     /**
2779      * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2780      * parameter, matching notices posted before the given one (inclusive).
2781      *
2782      * If the referenced notice can't be found, will return false.
2783      *
2784      * @param int $id
2785      * @param string $idField
2786      * @param string $createdField
2787      * @return mixed string or false if no match
2788      */
2789     public static function whereMaxId($id, $idField='id', $createdField='created')
2790     {
2791         try {
2792             $max = Notice::getAsTimestamp($id);
2793         } catch (Exception $e) {
2794             return false;
2795         }
2796         return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2797     }
2798
2799     /**
2800      * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2801      * parameter, matching notices posted before the given one (inclusive), and
2802      * if necessary add it to the data object's query.
2803      *
2804      * @param DB_DataObject $obj
2805      * @param int $id
2806      * @param string $idField
2807      * @param string $createdField
2808      * @return mixed string or false if no match
2809      */
2810     public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2811     {
2812         $max = self::whereMaxId($id, $idField, $createdField);
2813         if ($max) {
2814             $obj->whereAdd($max);
2815         }
2816     }
2817
2818     public function isPublic()
2819     {
2820         $is_local = intval($this->is_local);
2821         return !($is_local === Notice::LOCAL_NONPUBLIC || $is_local === Notice::GATEWAY);
2822     }
2823
2824     /**
2825      * Check that the given profile is allowed to read, respond to, or otherwise
2826      * act on this notice.
2827      *
2828      * The $scope member is a bitmask of scopes, representing a logical AND of the
2829      * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2830      * "only visible to people who are mentioned in the notice AND are users on this site."
2831      * Users on the site who are not mentioned in the notice will not be able to see the
2832      * notice.
2833      *
2834      * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2835      *
2836      * @return boolean whether the profile is in the notice's scope
2837      */
2838     function inScope($profile)
2839     {
2840         if (is_null($profile)) {
2841             $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2842         } else {
2843             $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2844         }
2845
2846         $result = self::cacheGet($keypart);
2847
2848         if ($result === false) {
2849             $bResult = false;
2850             if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2851                 $bResult = $this->_inScope($profile);
2852                 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2853             }
2854             $result = ($bResult) ? 1 : 0;
2855             self::cacheSet($keypart, $result, 0, 300);
2856         }
2857
2858         return ($result == 1) ? true : false;
2859     }
2860
2861     protected function _inScope($profile)
2862     {
2863         $scope = is_null($this->scope) ? self::defaultScope() : $this->getScope();
2864
2865         if ($scope === 0 && !$this->getProfile()->isPrivateStream()) { // Not scoping, so it is public.
2866             return !$this->isHiddenSpam($profile);
2867         }
2868
2869         // If there's scope, anon cannot be in scope
2870         if (empty($profile)) {
2871             return false;
2872         }
2873
2874         // Author is always in scope
2875         if ($this->profile_id == $profile->id) {
2876             return true;
2877         }
2878
2879         // Only for users on this site
2880         if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2881             return false;
2882         }
2883
2884         // Only for users mentioned in the notice
2885         if ($scope & Notice::ADDRESSEE_SCOPE) {
2886
2887             $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2888                                          'profile_id' => $profile->id));
2889
2890             if (!$reply instanceof Reply) {
2891                 return false;
2892             }
2893         }
2894
2895         // Only for members of the given group
2896         if ($scope & Notice::GROUP_SCOPE) {
2897
2898             // XXX: just query for the single membership
2899
2900             $groups = $this->getGroups();
2901
2902             $foundOne = false;
2903
2904             foreach ($groups as $group) {
2905                 if ($profile->isMember($group)) {
2906                     $foundOne = true;
2907                     break;
2908                 }
2909             }
2910
2911             if (!$foundOne) {
2912                 return false;
2913             }
2914         }
2915
2916         if ($scope & Notice::FOLLOWER_SCOPE || $this->getProfile()->isPrivateStream()) {
2917
2918             if (!Subscription::exists($profile, $this->getProfile())) {
2919                 return false;
2920             }
2921         }
2922
2923         return !$this->isHiddenSpam($profile);
2924     }
2925
2926     function isHiddenSpam($profile) {
2927
2928         // Hide posts by silenced users from everyone but moderators.
2929
2930         if (common_config('notice', 'hidespam')) {
2931
2932             try {
2933                 $author = $this->getProfile();
2934             } catch(Exception $e) {
2935                 // If we can't get an author, keep it hidden.
2936                 // XXX: technically not spam, but, whatever.
2937                 return true;
2938             }
2939
2940             if ($author->hasRole(Profile_role::SILENCED)) {
2941                 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2942                     return true;
2943                 }
2944             }
2945         }
2946
2947         return false;
2948     }
2949
2950     public function hasParent()
2951     {
2952         try {
2953             $this->getParent();
2954         } catch (NoParentNoticeException $e) {
2955             return false;
2956         }
2957         return true;
2958     }
2959
2960     public function getParent()
2961     {
2962         $reply_to_id = null;
2963
2964         if (empty($this->reply_to)) {
2965             throw new NoParentNoticeException($this);
2966         }
2967
2968         // The reply_to ID in the table Notice could exist with a number
2969         // however, the replied to notice might not exist in the database.
2970         // Thus we need to catch the exception and throw the NoParentNoticeException else
2971         // the timeline will not display correctly.
2972         try {
2973             $reply_to_id = self::getByID($this->reply_to);
2974         } catch(Exception $e){
2975             throw new NoParentNoticeException($this);
2976         }
2977
2978         return $reply_to_id;
2979     }
2980
2981     /**
2982      * Magic function called at serialize() time.
2983      *
2984      * We use this to drop a couple process-specific references
2985      * from DB_DataObject which can cause trouble in future
2986      * processes.
2987      *
2988      * @return array of variable names to include in serialization.
2989      */
2990
2991     function __sleep()
2992     {
2993         $vars = parent::__sleep();
2994         $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2995         return array_diff($vars, $skip);
2996     }
2997
2998     static function defaultScope()
2999     {
3000         $scope = common_config('notice', 'defaultscope');
3001         if (is_null($scope)) {
3002                 if (common_config('site', 'private')) {
3003                         $scope = 1;
3004                 } else {
3005                         $scope = 0;
3006                 }
3007         }
3008         return $scope;
3009     }
3010
3011         static function fillProfiles($notices)
3012         {
3013                 $map = self::getProfiles($notices);
3014                 foreach ($notices as $entry=>$notice) {
3015             try {
3016                         if (array_key_exists($notice->profile_id, $map)) {
3017                                 $notice->_setProfile($map[$notice->profile_id]);
3018                         }
3019             } catch (NoProfileException $e) {
3020                 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
3021                 unset($notices[$entry]);
3022             }
3023                 }
3024
3025                 return array_values($map);
3026         }
3027
3028         static function getProfiles(&$notices)
3029         {
3030                 $ids = array();
3031                 foreach ($notices as $notice) {
3032                         $ids[] = $notice->profile_id;
3033                 }
3034                 $ids = array_unique($ids);
3035                 return Profile::pivotGet('id', $ids);
3036         }
3037
3038         static function fillGroups(&$notices)
3039         {
3040         $ids = self::_idsOf($notices);
3041         $gis = Group_inbox::listGet('notice_id', $ids);
3042         $gids = array();
3043
3044                 foreach ($gis as $id => $gi) {
3045                     foreach ($gi as $g)
3046                     {
3047                         $gids[] = $g->group_id;
3048                     }
3049                 }
3050
3051                 $gids = array_unique($gids);
3052                 $group = User_group::pivotGet('id', $gids);
3053                 foreach ($notices as $notice)
3054                 {
3055                         $grps = array();
3056                         $gi = $gis[$notice->id];
3057                         foreach ($gi as $g) {
3058                             $grps[] = $group[$g->group_id];
3059                         }
3060                     $notice->_setGroups($grps);
3061                 }
3062         }
3063
3064     static function _idsOf(array &$notices)
3065     {
3066                 $ids = array();
3067                 foreach ($notices as $notice) {
3068                         $ids[$notice->id] = true;
3069                 }
3070                 return array_keys($ids);
3071     }
3072
3073     static function fillAttachments(&$notices)
3074     {
3075         $ids = self::_idsOf($notices);
3076         $f2pMap = File_to_post::listGet('post_id', $ids);
3077                 $fileIds = array();
3078                 foreach ($f2pMap as $noticeId => $f2ps) {
3079             foreach ($f2ps as $f2p) {
3080                 $fileIds[] = $f2p->file_id;
3081             }
3082         }
3083
3084         $fileIds = array_unique($fileIds);
3085                 $fileMap = File::pivotGet('id', $fileIds);
3086                 foreach ($notices as $notice)
3087                 {
3088                         $files = array();
3089                         $f2ps = $f2pMap[$notice->id];
3090                         foreach ($f2ps as $f2p) {
3091                 if (!isset($fileMap[$f2p->file_id])) {
3092                     // We have probably deleted value from fileMap since
3093                     // it as a NULL entry (see the following elseif).
3094                     continue;
3095                 } elseif (is_null($fileMap[$f2p->file_id])) {
3096                     // If the file id lookup returned a NULL value, it doesn't
3097                     // exist in our file table! So this is a remnant file_to_post
3098                     // entry that is no longer valid and should be removed.
3099                     common_debug('ATTACHMENT deleting f2p for post_id='.$f2p->post_id.' file_id='.$f2p->file_id);
3100                     $f2p->delete();
3101                     unset($fileMap[$f2p->file_id]);
3102                     continue;
3103                 }
3104                             $files[] = $fileMap[$f2p->file_id];
3105                         }
3106                     $notice->_setAttachments($files);
3107                 }
3108     }
3109
3110     static function fillReplies(&$notices)
3111     {
3112         $ids = self::_idsOf($notices);
3113         $replyMap = Reply::listGet('notice_id', $ids);
3114         foreach ($notices as $notice) {
3115             $replies = $replyMap[$notice->id];
3116             $ids = array();
3117             foreach ($replies as $reply) {
3118                 $ids[] = $reply->profile_id;
3119             }
3120             $notice->_setReplies($ids);
3121         }
3122     }
3123
3124     static public function beforeSchemaUpdate()
3125     {
3126         $table = strtolower(get_called_class());
3127         $schema = Schema::get();
3128         $schemadef = $schema->getTableDef($table);
3129
3130         // 2015-09-04 We move Notice location data to Notice_location
3131         // First we see if we have to do this at all
3132         if (isset($schemadef['fields']['lat'])
3133                 && isset($schemadef['fields']['lon'])
3134                 && isset($schemadef['fields']['location_id'])
3135                 && isset($schemadef['fields']['location_ns'])) {
3136             // Then we make sure the Notice_location table is created!
3137             $schema->ensureTable('notice_location', Notice_location::schemaDef());
3138
3139             // Then we continue on our road to migration!
3140             echo "\nFound old $table table, moving location data to 'notice_location' table... (this will probably take a LONG time, but can be aborted and continued)";
3141
3142             $notice = new Notice();
3143             $notice->query(sprintf('SELECT id, lat, lon, location_id, location_ns FROM %1$s ' .
3144                                  'WHERE lat IS NOT NULL ' .
3145                                     'OR lon IS NOT NULL ' .
3146                                     'OR location_id IS NOT NULL ' .
3147                                     'OR location_ns IS NOT NULL',
3148                                  $schema->quoteIdentifier($table)));
3149             print "\nFound {$notice->N} notices with location data, inserting";
3150             while ($notice->fetch()) {
3151                 $notloc = Notice_location::getKV('notice_id', $notice->id);
3152                 if ($notloc instanceof Notice_location) {
3153                     print "-";
3154                     continue;
3155                 }
3156                 $notloc = new Notice_location();
3157                 $notloc->notice_id = $notice->id;
3158                 $notloc->lat= $notice->lat;
3159                 $notloc->lon= $notice->lon;
3160                 $notloc->location_id= $notice->location_id;
3161                 $notloc->location_ns= $notice->location_ns;
3162                 $notloc->insert();
3163                 print ".";
3164             }
3165             print "\n";
3166         }
3167
3168         /**
3169          *  Make sure constraints are met before upgrading, if foreign keys
3170          *  are not already in use.
3171          *  2016-03-31
3172          */
3173         if (!isset($schemadef['foreign keys'])) {
3174             $newschemadef = self::schemaDef();
3175             printfnq("\nConstraint checking Notice table...\n");
3176             /**
3177              *  Improve typing and make sure no NULL values in any id-related columns are 0
3178              *  2016-03-31
3179              */
3180             foreach (['reply_to', 'repeat_of'] as $field) {
3181                 $notice = new Notice(); // reset the object
3182                 $notice->query(sprintf('UPDATE %1$s SET %2$s=NULL WHERE %2$s=0', $notice->escapedTableName(), $field));
3183                 // Now we're sure that no Notice entries have repeat_of=0, only an id > 0 or NULL
3184                 unset($notice);
3185             }
3186
3187             /**
3188              *  This Will find foreign keys which do not fulfill the constraints and fix
3189              *  where appropriate, such as delete when "repeat_of" ID not found in notice.id
3190              *  or set to NULL for "reply_to" in the same case.
3191              *  2016-03-31
3192              *
3193              *  XXX: How does this work if we would use multicolumn foreign keys?
3194              */
3195             foreach (['reply_to' => 'reset', 'repeat_of' => 'delete', 'profile_id' => 'delete'] as $field=>$action) {
3196                 $notice = new Notice();
3197
3198                 $fkeyname = $notice->tableName().'_'.$field.'_fkey';
3199                 assert(isset($newschemadef['foreign keys'][$fkeyname]));
3200                 assert($newschemadef['foreign keys'][$fkeyname]);
3201
3202                 $foreign_key = $newschemadef['foreign keys'][$fkeyname];
3203                 $fkeytable = $foreign_key[0];
3204                 assert(isset($foreign_key[1][$field]));
3205                 $fkeycol   = $foreign_key[1][$field];
3206
3207                 printfnq("* {$fkeyname} ({$field} => {$fkeytable}.{$fkeycol})\n");
3208
3209                 // NOTE: Above we set all repeat_of to NULL if they were 0, so this really gets them all.
3210                 $notice->whereAdd(sprintf('%1$s NOT IN (SELECT %2$s FROM %3$s)', $field, $fkeycol, $fkeytable));
3211                 if ($notice->find()) {
3212                     printfnq("\tFound {$notice->N} notices with {$field} NOT IN notice.id, {$action}ing...");
3213                     switch ($action) {
3214                     case 'delete':  // since it's a directly dependant notice for an unknown ID we don't want it in our DB
3215                         while ($notice->fetch()) {
3216                             $notice->delete();
3217                         }
3218                         break;
3219                     case 'reset':   // just set it to NULL to be compatible with our constraints, if it was related to an unknown ID
3220                         $ids = [];
3221                         foreach ($notice->fetchAll('id') as $id) {
3222                             settype($id, 'int');
3223                             $ids[] = $id;
3224                         }
3225                         unset($notice);
3226                         $notice = new Notice();
3227                         $notice->query(sprintf('UPDATE %1$s SET %2$s=NULL WHERE id IN (%3$s)',
3228                                             $notice->escapedTableName(),
3229                                             $field,
3230                                             implode(',', $ids)));
3231                         break;
3232                     default:
3233                         throw new ServerException('The programmer sucks, invalid action name when fixing table.');
3234                     }
3235                     printfnq("DONE.\n");
3236                 }
3237                 unset($notice);
3238             }
3239         }
3240     }
3241 }