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