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