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