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