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