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