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