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