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