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