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