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