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