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