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