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