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