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