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