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