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