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