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