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