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