]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
Merge remote-tracking branch 'gitorious/1.0.x' into 1.0.x
[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         // XXX: Before we were blowing the casche only if the notice id
581         // was not the root of the conversation.  What to do now?
582
583         self::blow('notice:conversation_ids:%d', $this->conversation);
584         self::blow('conversation::notice_count:%d', $this->conversation);
585
586         if (!empty($this->repeat_of)) {
587             $this->blowStream('notice:repeats:%d', $this->repeat_of);
588         }
589
590         $original = Notice::staticGet('id', $this->repeat_of);
591
592         if (!empty($original)) {
593             $originalUser = User::staticGet('id', $original->profile_id);
594             if (!empty($originalUser)) {
595                 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
596             }
597         }
598
599         $profile = Profile::staticGet($this->profile_id);
600
601         if (!empty($profile)) {
602             $profile->blowNoticeCount();
603         }
604
605         $ptags = $this->getProfileTags();
606         foreach ($ptags as $ptag) {
607             $ptag->blowNoticeStreamCache();
608         }
609     }
610
611     /**
612      * Clear cache entries related to this notice at delete time.
613      * Necessary to avoid breaking paging on public, profile timelines.
614      */
615     function blowOnDelete()
616     {
617         $this->blowOnInsert();
618
619         self::blow('profile:notice_ids:%d;last', $this->profile_id);
620
621         if ($this->isPublic()) {
622             self::blow('public;last');
623         }
624
625         self::blow('fave:by_notice', $this->id);
626
627         if ($this->conversation) {
628             // In case we're the first, will need to calc a new root.
629             self::blow('notice:conversation_root:%d', $this->conversation);
630         }
631
632         $ptags = $this->getProfileTags();
633         foreach ($ptags as $ptag) {
634             $ptag->blowNoticeStreamCache(true);
635         }
636     }
637
638     function blowStream()
639     {
640         $c = self::memcache();
641
642         if (empty($c)) {
643             return false;
644         }
645
646         $args = func_get_args();
647
648         $format = array_shift($args);
649
650         $keyPart = vsprintf($format, $args);
651
652         $cacheKey = Cache::key($keyPart);
653         
654         $c->delete($cacheKey);
655
656         // delete the "last" stream, too, if this notice is
657         // older than the top of that stream
658
659         $lastKey = $cacheKey.';last';
660
661         $lastStr = $c->get($lastKey);
662
663         if ($lastStr !== false) {
664             $window     = explode(',', $lastStr);
665             $lastID     = $window[0];
666             $lastNotice = Notice::staticGet('id', $lastID);
667             if (empty($lastNotice) // just weird
668                 || strtotime($lastNotice->created) >= strtotime($this->created)) {
669                 $c->delete($lastKey);
670             }
671         }
672     }
673
674     /** save all urls in the notice to the db
675      *
676      * follow redirects and save all available file information
677      * (mimetype, date, size, oembed, etc.)
678      *
679      * @return void
680      */
681     function saveUrls() {
682         if (common_config('attachments', 'process_links')) {
683             common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
684         }
685     }
686
687     /**
688      * Save the given URLs as related links/attachments to the db
689      *
690      * follow redirects and save all available file information
691      * (mimetype, date, size, oembed, etc.)
692      *
693      * @return void
694      */
695     function saveKnownUrls($urls)
696     {
697         if (common_config('attachments', 'process_links')) {
698             // @fixme validation?
699             foreach (array_unique($urls) as $url) {
700                 File::processNew($url, $this->id);
701             }
702         }
703     }
704
705     /**
706      * @private callback
707      */
708     function saveUrl($url, $notice_id) {
709         File::processNew($url, $notice_id);
710     }
711
712     static function checkDupes($profile_id, $content) {
713         $profile = Profile::staticGet($profile_id);
714         if (empty($profile)) {
715             return false;
716         }
717         $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
718         if (!empty($notice)) {
719             $last = 0;
720             while ($notice->fetch()) {
721                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
722                     return true;
723                 } else if ($notice->content == $content) {
724                     return false;
725                 }
726             }
727         }
728         // If we get here, oldest item in cache window is not
729         // old enough for dupe limit; do direct check against DB
730         $notice = new Notice();
731         $notice->profile_id = $profile_id;
732         $notice->content = $content;
733         $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
734         $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
735
736         $cnt = $notice->count();
737         return ($cnt == 0);
738     }
739
740     static function checkEditThrottle($profile_id) {
741         $profile = Profile::staticGet($profile_id);
742         if (empty($profile)) {
743             return false;
744         }
745         // Get the Nth notice
746         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
747         if ($notice && $notice->fetch()) {
748             // If the Nth notice was posted less than timespan seconds ago
749             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
750                 // Then we throttle
751                 return false;
752             }
753         }
754         // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
755         return true;
756     }
757
758         protected $_attachments = -1;
759         
760     function attachments() {
761
762                 if ($this->_attachments != -1)  {
763             return $this->_attachments;
764         }
765                 
766                 $f2ps = Memcached_DataObject::listGet('File_to_post', 'post_id', array($this->id));
767                 
768                 $ids = array();
769                 
770                 foreach ($f2ps[$this->id] as $f2p) {
771             $ids[] = $f2p->file_id;    
772         }
773                 
774                 $files = Memcached_DataObject::multiGet('File', 'id', $ids);
775
776                 $this->_attachments = $files->fetchAll();
777                 
778         return $this->_attachments;
779     }
780
781         function _setAttachments($attachments)
782         {
783             $this->_attachments = $attachments;
784         }
785
786     function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
787     {
788         $stream = new PublicNoticeStream();
789         return $stream->getNotices($offset, $limit, $since_id, $max_id);
790     }
791
792
793     function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
794     {
795         $stream = new ConversationNoticeStream($id);
796
797         return $stream->getNotices($offset, $limit, $since_id, $max_id);
798     }
799
800     /**
801      * Is this notice part of an active conversation?
802      *
803      * @return boolean true if other messages exist in the same
804      *                 conversation, false if this is the only one
805      */
806     function hasConversation()
807     {
808         if (!empty($this->conversation)) {
809             $conversation = Notice::conversationStream(
810                 $this->conversation,
811                 1,
812                 1
813             );
814
815             if ($conversation->N > 0) {
816                 return true;
817             }
818         }
819         return false;
820     }
821
822     /**
823      * Grab the earliest notice from this conversation.
824      *
825      * @return Notice or null
826      */
827     function conversationRoot($profile=-1)
828     {
829         // XXX: can this happen?
830
831         if (empty($this->conversation)) {
832             return null;
833         }
834
835         // Get the current profile if not specified
836
837         if (is_int($profile) && $profile == -1) {
838             $profile = Profile::current();
839         }
840
841         // If this notice is out of scope, no root for you!
842
843         if (!$this->inScope($profile)) {
844             return null;
845         }
846
847         // If this isn't a reply to anything, then it's its own
848         // root.
849
850         if (empty($this->reply_to)) {
851             return $this;
852         }
853         
854         if (is_null($profile)) {
855             $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
856         } else {
857             $keypart = sprintf('notice:conversation_root:%d:%d',
858                                $this->id,
859                                $profile->id);
860         }
861             
862         $root = self::cacheGet($keypart);
863
864         if ($root !== false && $root->inScope($profile)) {
865             return $root;
866         } else {
867             $last = $this;
868
869             do {
870                 $parent = $last->getOriginal();
871                 if (!empty($parent) && $parent->inScope($profile)) {
872                     $last = $parent;
873                     continue;
874                 } else {
875                     $root = $last;
876                     break;
877                 }
878             } while (!empty($parent));
879
880             self::cacheSet($keypart, $root);
881         }
882
883         return $root;
884     }
885
886     /**
887      * Pull up a full list of local recipients who will be getting
888      * this notice in their inbox. Results will be cached, so don't
889      * change the input data wily-nilly!
890      *
891      * @param array $groups optional list of Group objects;
892      *              if left empty, will be loaded from group_inbox records
893      * @param array $recipient optional list of reply profile ids
894      *              if left empty, will be loaded from reply records
895      * @return array associating recipient user IDs with an inbox source constant
896      */
897     function whoGets($groups=null, $recipients=null)
898     {
899         $c = self::memcache();
900
901         if (!empty($c)) {
902             $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
903             if ($ni !== false) {
904                 return $ni;
905             }
906         }
907
908         if (is_null($groups)) {
909             $groups = $this->getGroups();
910         }
911
912         if (is_null($recipients)) {
913             $recipients = $this->getReplies();
914         }
915
916         $users = $this->getSubscribedUsers();
917         $ptags = $this->getProfileTags();
918
919         // FIXME: kind of ignoring 'transitional'...
920         // we'll probably stop supporting inboxless mode
921         // in 0.9.x
922
923         $ni = array();
924
925         // Give plugins a chance to add folks in at start...
926         if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
927
928             foreach ($users as $id) {
929                 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
930             }
931
932             foreach ($groups as $group) {
933                 $users = $group->getUserMembers();
934                 foreach ($users as $id) {
935                     if (!array_key_exists($id, $ni)) {
936                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
937                     }
938                 }
939             }
940
941             foreach ($ptags as $ptag) {
942                 $users = $ptag->getUserSubscribers();
943                 foreach ($users as $id) {
944                     if (!array_key_exists($id, $ni)) {
945                         $user = User::staticGet('id', $id);
946                         if (!$user->hasBlocked($profile)) {
947                             $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
948                         }
949                     }
950                 }
951             }
952
953             foreach ($recipients as $recipient) {
954                 if (!array_key_exists($recipient, $ni)) {
955                     $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
956                 }
957
958                 // Exclude any deleted, non-local, or blocking recipients.
959                 $profile = $this->getProfile();
960                 $originalProfile = null;
961                 if ($this->repeat_of) {
962                     // Check blocks against the original notice's poster as well.
963                     $original = Notice::staticGet('id', $this->repeat_of);
964                     if ($original) {
965                         $originalProfile = $original->getProfile();
966                     }
967                 }
968                 foreach ($ni as $id => $source) {
969                     $user = User::staticGet('id', $id);
970                     if (empty($user) || $user->hasBlocked($profile) ||
971                         ($originalProfile && $user->hasBlocked($originalProfile))) {
972                         unset($ni[$id]);
973                     }
974                 }
975             }
976
977             // Give plugins a chance to filter out...
978             Event::handle('EndNoticeWhoGets', array($this, &$ni));
979         }
980
981         if (!empty($c)) {
982             // XXX: pack this data better
983             $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
984         }
985
986         return $ni;
987     }
988
989     /**
990      * Adds this notice to the inboxes of each local user who should receive
991      * it, based on author subscriptions, group memberships, and @-replies.
992      *
993      * Warning: running a second time currently will make items appear
994      * multiple times in users' inboxes.
995      *
996      * @fixme make more robust against errors
997      * @fixme break up massive deliveries to smaller background tasks
998      *
999      * @param array $groups optional list of Group objects;
1000      *              if left empty, will be loaded from group_inbox records
1001      * @param array $recipient optional list of reply profile ids
1002      *              if left empty, will be loaded from reply records
1003      */
1004     function addToInboxes($groups=null, $recipients=null)
1005     {
1006         $ni = $this->whoGets($groups, $recipients);
1007
1008         $ids = array_keys($ni);
1009
1010         // We remove the author (if they're a local user),
1011         // since we'll have already done this in distribute()
1012
1013         $i = array_search($this->profile_id, $ids);
1014
1015         if ($i !== false) {
1016             unset($ids[$i]);
1017         }
1018
1019         // Bulk insert
1020
1021         Inbox::bulkInsert($this->id, $ids);
1022
1023         return;
1024     }
1025
1026     function getSubscribedUsers()
1027     {
1028         $user = new User();
1029
1030         if(common_config('db','quote_identifiers'))
1031           $user_table = '"user"';
1032         else $user_table = 'user';
1033
1034         $qry =
1035           'SELECT id ' .
1036           'FROM '. $user_table .' JOIN subscription '.
1037           'ON '. $user_table .'.id = subscription.subscriber ' .
1038           'WHERE subscription.subscribed = %d ';
1039
1040         $user->query(sprintf($qry, $this->profile_id));
1041
1042         $ids = array();
1043
1044         while ($user->fetch()) {
1045             $ids[] = $user->id;
1046         }
1047
1048         $user->free();
1049
1050         return $ids;
1051     }
1052
1053     function getProfileTags()
1054     {
1055         $profile = $this->getProfile();
1056         $list    = $profile->getOtherTags($profile);
1057         $ptags   = array();
1058
1059         while($list->fetch()) {
1060             $ptags[] = clone($list);
1061         }
1062
1063         return $ptags;
1064     }
1065
1066     /**
1067      * Record this notice to the given group inboxes for delivery.
1068      * Overrides the regular parsing of !group markup.
1069      *
1070      * @param string $group_ids
1071      * @fixme might prefer URIs as identifiers, as for replies?
1072      *        best with generalizations on user_group to support
1073      *        remote groups better.
1074      */
1075     function saveKnownGroups($group_ids)
1076     {
1077         if (!is_array($group_ids)) {
1078             // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1079             throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1080         }
1081
1082         $groups = array();
1083         foreach (array_unique($group_ids) as $id) {
1084             $group = User_group::staticGet('id', $id);
1085             if ($group) {
1086                 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1087                 $result = $this->addToGroupInbox($group);
1088                 if (!$result) {
1089                     common_log_db_error($gi, 'INSERT', __FILE__);
1090                 }
1091
1092                 if (common_config('group', 'addtag')) {
1093                     // we automatically add a tag for every group name, too
1094
1095                     $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1096                                                      'notice_id' => $this->id));
1097
1098                     if (is_null($tag)) {
1099                         $this->saveTag($group->nickname);
1100                     }
1101                 }
1102
1103                 $groups[] = clone($group);
1104             } else {
1105                 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1106             }
1107         }
1108
1109         return $groups;
1110     }
1111
1112     /**
1113      * Parse !group delivery and record targets into group_inbox.
1114      * @return array of Group objects
1115      */
1116     function saveGroups()
1117     {
1118         // Don't save groups for repeats
1119
1120         if (!empty($this->repeat_of)) {
1121             return array();
1122         }
1123
1124         $profile = $this->getProfile();
1125
1126         $groups = self::groupsFromText($this->content, $profile);
1127
1128         /* Add them to the database */
1129
1130         foreach ($groups as $group) {
1131             /* XXX: remote groups. */
1132
1133             if (empty($group)) {
1134                 continue;
1135             }
1136
1137
1138             if ($profile->isMember($group)) {
1139
1140                 $result = $this->addToGroupInbox($group);
1141
1142                 if (!$result) {
1143                     common_log_db_error($gi, 'INSERT', __FILE__);
1144                 }
1145
1146                 $groups[] = clone($group);
1147             }
1148         }
1149
1150         return $groups;
1151     }
1152
1153     function addToGroupInbox($group)
1154     {
1155         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1156                                          'notice_id' => $this->id));
1157
1158         if (empty($gi)) {
1159
1160             $gi = new Group_inbox();
1161
1162             $gi->group_id  = $group->id;
1163             $gi->notice_id = $this->id;
1164             $gi->created   = $this->created;
1165
1166             $result = $gi->insert();
1167
1168             if (!$result) {
1169                 common_log_db_error($gi, 'INSERT', __FILE__);
1170                 // TRANS: Server exception thrown when an update for a group inbox fails.
1171                 throw new ServerException(_('Problem saving group inbox.'));
1172             }
1173
1174             self::blow('user_group:notice_ids:%d', $gi->group_id);
1175         }
1176
1177         return true;
1178     }
1179
1180     /**
1181      * Save reply records indicating that this notice needs to be
1182      * delivered to the local users with the given URIs.
1183      *
1184      * Since this is expected to be used when saving foreign-sourced
1185      * messages, we won't deliver to any remote targets as that's the
1186      * source service's responsibility.
1187      *
1188      * Mail notifications etc will be handled later.
1189      *
1190      * @param array of unique identifier URIs for recipients
1191      */
1192     function saveKnownReplies($uris)
1193     {
1194         if (empty($uris)) {
1195             return;
1196         }
1197
1198         $sender = Profile::staticGet($this->profile_id);
1199
1200         foreach (array_unique($uris) as $uri) {
1201
1202             $profile = Profile::fromURI($uri);
1203
1204             if (empty($profile)) {
1205                 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1206                 continue;
1207             }
1208
1209             if ($profile->hasBlocked($sender)) {
1210                 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1211                 continue;
1212             }
1213
1214             $this->saveReply($profile->id);
1215             self::blow('reply:stream:%d', $profile->id);
1216         }
1217
1218         return;
1219     }
1220
1221     /**
1222      * Pull @-replies from this message's content in StatusNet markup format
1223      * and save reply records indicating that this message needs to be
1224      * delivered to those users.
1225      *
1226      * Mail notifications to local profiles will be sent later.
1227      *
1228      * @return array of integer profile IDs
1229      */
1230
1231     function saveReplies()
1232     {
1233         // Don't save reply data for repeats
1234
1235         if (!empty($this->repeat_of)) {
1236             return array();
1237         }
1238
1239         $sender = Profile::staticGet($this->profile_id);
1240
1241         $replied = array();
1242
1243         // If it's a reply, save for the replied-to author
1244
1245         if (!empty($this->reply_to)) {
1246             $original = $this->getOriginal();
1247             if (!empty($original)) { // that'd be weird
1248                 $author = $original->getProfile();
1249                 if (!empty($author)) {
1250                     $this->saveReply($author->id);
1251                     $replied[$author->id] = 1;
1252                     self::blow('reply:stream:%d', $author->id);
1253                 }
1254             }
1255         }
1256
1257         // @todo ideally this parser information would only
1258         // be calculated once.
1259
1260         $mentions = common_find_mentions($this->content, $this);
1261
1262         // store replied only for first @ (what user/notice what the reply directed,
1263         // we assume first @ is it)
1264
1265         foreach ($mentions as $mention) {
1266
1267             foreach ($mention['mentioned'] as $mentioned) {
1268
1269                 // skip if they're already covered
1270
1271                 if (!empty($replied[$mentioned->id])) {
1272                     continue;
1273                 }
1274
1275                 // Don't save replies from blocked profile to local user
1276
1277                 $mentioned_user = User::staticGet('id', $mentioned->id);
1278                 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1279                     continue;
1280                 }
1281
1282                 $this->saveReply($mentioned->id);
1283                 $replied[$mentioned->id] = 1;
1284                 self::blow('reply:stream:%d', $mentioned->id);
1285             }
1286         }
1287
1288         $recipientIds = array_keys($replied);
1289
1290         return $recipientIds;
1291     }
1292
1293     function saveReply($profileId)
1294     {
1295         $reply = new Reply();
1296
1297         $reply->notice_id  = $this->id;
1298         $reply->profile_id = $profileId;
1299         $reply->modified   = $this->created;
1300
1301         $reply->insert();
1302
1303         return $reply;
1304     }
1305
1306     protected $_replies = -1;
1307
1308     /**
1309      * Pull the complete list of @-reply targets for this notice.
1310      *
1311      * @return array of integer profile ids
1312      */
1313     function getReplies()
1314     {
1315         if ($this->_replies != -1) {
1316             return $this->_replies;
1317         }
1318
1319         $replyMap = Memcached_DataObject::listGet('Reply', 'notice_id', array($this->id));
1320
1321         $ids = array();
1322
1323         foreach ($replyMap[$this->id] as $reply) {
1324             $ids[] = $reply->profile_id;
1325         }
1326
1327         $this->_replies = $ids;
1328
1329         return $ids;
1330     }
1331
1332     function _setReplies($replies)
1333     {
1334         $this->_replies = $replies;
1335     }
1336
1337     /**
1338      * Pull the complete list of @-reply targets for this notice.
1339      *
1340      * @return array of Profiles
1341      */
1342     function getReplyProfiles()
1343     {
1344         $ids = $this->getReplies();
1345         
1346         $profiles = Profile::multiGet('id', $ids);
1347         
1348         return $profiles->fetchAll();
1349     }
1350
1351     /**
1352      * Send e-mail notifications to local @-reply targets.
1353      *
1354      * Replies must already have been saved; this is expected to be run
1355      * from the distrib queue handler.
1356      */
1357     function sendReplyNotifications()
1358     {
1359         // Don't send reply notifications for repeats
1360
1361         if (!empty($this->repeat_of)) {
1362             return array();
1363         }
1364
1365         $recipientIds = $this->getReplies();
1366
1367         foreach ($recipientIds as $recipientId) {
1368             $user = User::staticGet('id', $recipientId);
1369             if (!empty($user)) {
1370                 mail_notify_attn($user, $this);
1371             }
1372         }
1373     }
1374
1375     /**
1376      * Pull list of groups this notice needs to be delivered to,
1377      * as previously recorded by saveGroups() or saveKnownGroups().
1378      *
1379      * @return array of Group objects
1380      */
1381     
1382     protected $_groups = -1;
1383     
1384     function getGroups()
1385     {
1386         // Don't save groups for repeats
1387
1388         if (!empty($this->repeat_of)) {
1389             return array();
1390         }
1391         
1392         if ($this->_groups != -1)
1393         {
1394             return $this->_groups;
1395         }
1396         
1397         $gis = Memcached_DataObject::listGet('Group_inbox', 'notice_id', array($this->id));
1398
1399         $ids = array();
1400
1401                 foreach ($gis[$this->id] as $gi)
1402                 {
1403                     $ids[] = $gi->group_id;
1404                 }
1405                 
1406                 $groups = User_group::multiGet('id', $ids);
1407                 
1408                 $this->_groups = $groups->fetchAll();
1409                 
1410                 return $this->_groups;
1411     }
1412     
1413     function _setGroups($groups)
1414     {
1415         $this->_groups = $groups;
1416     }
1417
1418     /**
1419      * Convert a notice into an activity for export.
1420      *
1421      * @param User $cur Current user
1422      *
1423      * @return Activity activity object representing this Notice.
1424      */
1425
1426     function asActivity($cur)
1427     {
1428         $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1429
1430         if (!empty($act)) {
1431             return $act;
1432         }
1433         $act = new Activity();
1434
1435         if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1436
1437             $act->id      = $this->uri;
1438             $act->time    = strtotime($this->created);
1439             $act->link    = $this->bestUrl();
1440             $act->content = common_xml_safe_str($this->rendered);
1441             $act->title   = common_xml_safe_str($this->content);
1442
1443             $profile = $this->getProfile();
1444
1445             $act->actor            = ActivityObject::fromProfile($profile);
1446             $act->actor->extra[]   = $profile->profileInfo($cur);
1447
1448             if ($this->repeat_of) {
1449
1450                 $repeated = Notice::staticGet('id', $this->repeat_of);
1451
1452                 $act->verb             = ActivityVerb::SHARE;
1453                 $act->objects[]        = $repeated->asActivity($cur);
1454
1455             } else {
1456
1457                 $act->verb             = ActivityVerb::POST;
1458                 $act->objects[]        = ActivityObject::fromNotice($this);
1459
1460             }
1461
1462             // XXX: should this be handled by default processing for object entry?
1463
1464             // Categories
1465
1466             $tags = $this->getTags();
1467
1468             foreach ($tags as $tag) {
1469                 $cat       = new AtomCategory();
1470                 $cat->term = $tag;
1471
1472                 $act->categories[] = $cat;
1473             }
1474
1475             // Enclosures
1476             // XXX: use Atom Media and/or File activity objects instead
1477
1478             $attachments = $this->attachments();
1479
1480             foreach ($attachments as $attachment) {
1481                 $enclosure = $attachment->getEnclosure();
1482                 if ($enclosure) {
1483                     $act->enclosures[] = $enclosure;
1484                 }
1485             }
1486
1487             $ctx = new ActivityContext();
1488
1489             if (!empty($this->reply_to)) {
1490                 $reply = Notice::staticGet('id', $this->reply_to);
1491                 if (!empty($reply)) {
1492                     $ctx->replyToID  = $reply->uri;
1493                     $ctx->replyToUrl = $reply->bestUrl();
1494                 }
1495             }
1496
1497             $ctx->location = $this->getLocation();
1498
1499             $conv = null;
1500
1501             if (!empty($this->conversation)) {
1502                 $conv = Conversation::staticGet('id', $this->conversation);
1503                 if (!empty($conv)) {
1504                     $ctx->conversation = $conv->uri;
1505                 }
1506             }
1507
1508             $reply_ids = $this->getReplies();
1509
1510             foreach ($reply_ids as $id) {
1511                 $rprofile = Profile::staticGet('id', $id);
1512                 if (!empty($rprofile)) {
1513                     $ctx->attention[] = $rprofile->getUri();
1514                 }
1515             }
1516
1517             $groups = $this->getGroups();
1518
1519             foreach ($groups as $group) {
1520                 $ctx->attention[] = $group->getUri();
1521             }
1522
1523             // XXX: deprecated; use ActivityVerb::SHARE instead
1524
1525             $repeat = null;
1526
1527             if (!empty($this->repeat_of)) {
1528                 $repeat = Notice::staticGet('id', $this->repeat_of);
1529                 $ctx->forwardID  = $repeat->uri;
1530                 $ctx->forwardUrl = $repeat->bestUrl();
1531             }
1532
1533             $act->context = $ctx;
1534
1535             // Source
1536
1537             $atom_feed = $profile->getAtomFeed();
1538
1539             if (!empty($atom_feed)) {
1540
1541                 $act->source = new ActivitySource();
1542
1543                 // XXX: we should store the actual feed ID
1544
1545                 $act->source->id = $atom_feed;
1546
1547                 // XXX: we should store the actual feed title
1548
1549                 $act->source->title = $profile->getBestName();
1550
1551                 $act->source->links['alternate'] = $profile->profileurl;
1552                 $act->source->links['self']      = $atom_feed;
1553
1554                 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1555
1556                 $notice = $profile->getCurrentNotice();
1557
1558                 if (!empty($notice)) {
1559                     $act->source->updated = self::utcDate($notice->created);
1560                 }
1561
1562                 $user = User::staticGet('id', $profile->id);
1563
1564                 if (!empty($user)) {
1565                     $act->source->links['license'] = common_config('license', 'url');
1566                 }
1567             }
1568
1569             if ($this->isLocal()) {
1570                 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1571                                                                            'format' => 'atom'));
1572                 $act->editLink = $act->selfLink;
1573             }
1574
1575             Event::handle('EndNoticeAsActivity', array($this, &$act));
1576         }
1577
1578         self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1579
1580         return $act;
1581     }
1582
1583     // This has gotten way too long. Needs to be sliced up into functional bits
1584     // or ideally exported to a utility class.
1585
1586     function asAtomEntry($namespace=false,
1587                          $source=false,
1588                          $author=true,
1589                          $cur=null)
1590     {
1591         $act = $this->asActivity($cur);
1592         $act->extra[] = $this->noticeInfo($cur);
1593         return $act->asString($namespace, $author, $source);
1594     }
1595
1596     /**
1597      * Extra notice info for atom entries
1598      *
1599      * Clients use some extra notice info in the atom stream.
1600      * This gives it to them.
1601      *
1602      * @param User $cur Current user
1603      *
1604      * @return array representation of <statusnet:notice_info> element
1605      */
1606
1607     function noticeInfo($cur)
1608     {
1609         // local notice ID (useful to clients for ordering)
1610
1611         $noticeInfoAttr = array('local_id' => $this->id);
1612
1613         // notice source
1614
1615         $ns = $this->getSource();
1616
1617         if (!empty($ns)) {
1618             $noticeInfoAttr['source'] =  $ns->code;
1619             if (!empty($ns->url)) {
1620                 $noticeInfoAttr['source_link'] = $ns->url;
1621                 if (!empty($ns->name)) {
1622                     $noticeInfoAttr['source'] =  '<a href="'
1623                         . htmlspecialchars($ns->url)
1624                         . '" rel="nofollow">'
1625                         . htmlspecialchars($ns->name)
1626                         . '</a>';
1627                 }
1628             }
1629         }
1630
1631         // favorite and repeated
1632
1633         if (!empty($cur)) {
1634             $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1635             $cp = $cur->getProfile();
1636             $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this->id)) ? "true" : "false";
1637         }
1638
1639         if (!empty($this->repeat_of)) {
1640             $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1641         }
1642
1643         return array('statusnet:notice_info', $noticeInfoAttr, null);
1644     }
1645
1646     /**
1647      * Returns an XML string fragment with a reference to a notice as an
1648      * Activity Streams noun object with the given element type.
1649      *
1650      * Assumes that 'activity' namespace has been previously defined.
1651      *
1652      * @param string $element one of 'subject', 'object', 'target'
1653      * @return string
1654      */
1655
1656     function asActivityNoun($element)
1657     {
1658         $noun = ActivityObject::fromNotice($this);
1659         return $noun->asString('activity:' . $element);
1660     }
1661
1662     function bestUrl()
1663     {
1664         if (!empty($this->url)) {
1665             return $this->url;
1666         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1667             return $this->uri;
1668         } else {
1669             return common_local_url('shownotice',
1670                                     array('notice' => $this->id));
1671         }
1672     }
1673
1674
1675     /**
1676      * Determine which notice, if any, a new notice is in reply to.
1677      *
1678      * For conversation tracking, we try to see where this notice fits
1679      * in the tree. Rough algorithm is:
1680      *
1681      * if (reply_to is set and valid) {
1682      *     return reply_to;
1683      * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1684      *     return ID of last notice by initial @name in content;
1685      * }
1686      *
1687      * Note that all @nickname instances will still be used to save "reply" records,
1688      * so the notice shows up in the mentioned users' "replies" tab.
1689      *
1690      * @param integer $reply_to   ID passed in by Web or API
1691      * @param integer $profile_id ID of author
1692      * @param string  $source     Source tag, like 'web' or 'gwibber'
1693      * @param string  $content    Final notice content
1694      *
1695      * @return integer ID of replied-to notice, or null for not a reply.
1696      */
1697
1698     static function getReplyTo($reply_to, $profile_id, $source, $content)
1699     {
1700         static $lb = array('xmpp', 'mail', 'sms', 'omb');
1701
1702         // If $reply_to is specified, we check that it exists, and then
1703         // return it if it does
1704
1705         if (!empty($reply_to)) {
1706             $reply_notice = Notice::staticGet('id', $reply_to);
1707             if (!empty($reply_notice)) {
1708                 return $reply_notice;
1709             }
1710         }
1711
1712         // If it's not a "low bandwidth" source (one where you can't set
1713         // a reply_to argument), we return. This is mostly web and API
1714         // clients.
1715
1716         if (!in_array($source, $lb)) {
1717             return null;
1718         }
1719
1720         // Is there an initial @ or T?
1721
1722         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1723             preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1724             $nickname = common_canonical_nickname($match[1]);
1725         } else {
1726             return null;
1727         }
1728
1729         // Figure out who that is.
1730
1731         $sender = Profile::staticGet('id', $profile_id);
1732         if (empty($sender)) {
1733             return null;
1734         }
1735
1736         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1737
1738         if (empty($recipient)) {
1739             return null;
1740         }
1741
1742         // Get their last notice
1743
1744         $last = $recipient->getCurrentNotice();
1745
1746         if (!empty($last)) {
1747             return $last;
1748         }
1749
1750         return null;
1751     }
1752
1753     static function maxContent()
1754     {
1755         $contentlimit = common_config('notice', 'contentlimit');
1756         // null => use global limit (distinct from 0!)
1757         if (is_null($contentlimit)) {
1758             $contentlimit = common_config('site', 'textlimit');
1759         }
1760         return $contentlimit;
1761     }
1762
1763     static function contentTooLong($content)
1764     {
1765         $contentlimit = self::maxContent();
1766         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1767     }
1768
1769     function getLocation()
1770     {
1771         $location = null;
1772
1773         if (!empty($this->location_id) && !empty($this->location_ns)) {
1774             $location = Location::fromId($this->location_id, $this->location_ns);
1775         }
1776
1777         if (is_null($location)) { // no ID, or Location::fromId() failed
1778             if (!empty($this->lat) && !empty($this->lon)) {
1779                 $location = Location::fromLatLon($this->lat, $this->lon);
1780             }
1781         }
1782
1783         return $location;
1784     }
1785
1786     /**
1787      * Convenience function for posting a repeat of an existing message.
1788      *
1789      * @param int $repeater_id: profile ID of user doing the repeat
1790      * @param string $source: posting source key, eg 'web', 'api', etc
1791      * @return Notice
1792      *
1793      * @throws Exception on failure or permission problems
1794      */
1795     function repeat($repeater_id, $source)
1796     {
1797         $author = Profile::staticGet('id', $this->profile_id);
1798
1799         // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1800         // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1801         $content = sprintf(_('RT @%1$s %2$s'),
1802                            $author->nickname,
1803                            $this->content);
1804
1805         $maxlen = common_config('site', 'textlimit');
1806         if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1807             // Web interface and current Twitter API clients will
1808             // pull the original notice's text, but some older
1809             // clients and RSS/Atom feeds will see this trimmed text.
1810             //
1811             // Unfortunately this is likely to lose tags or URLs
1812             // at the end of long notices.
1813             $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1814         }
1815
1816         // Scope is same as this one's
1817
1818         return self::saveNew($repeater_id,
1819                              $content,
1820                              $source,
1821                              array('repeat_of' => $this->id,
1822                                    'scope' => $this->scope));
1823     }
1824
1825     // These are supposed to be in chron order!
1826
1827     function repeatStream($limit=100)
1828     {
1829         $cache = Cache::instance();
1830
1831         if (empty($cache)) {
1832             $ids = $this->_repeatStreamDirect($limit);
1833         } else {
1834             $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1835             if ($idstr !== false) {
1836                 if (empty($idstr)) {
1837                         $ids = array();
1838                 } else {
1839                         $ids = explode(',', $idstr);
1840                 }
1841             } else {
1842                 $ids = $this->_repeatStreamDirect(100);
1843                 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1844             }
1845             if ($limit < 100) {
1846                 // We do a max of 100, so slice down to limit
1847                 $ids = array_slice($ids, 0, $limit);
1848             }
1849         }
1850
1851         return NoticeStream::getStreamByIds($ids);
1852     }
1853
1854     function _repeatStreamDirect($limit)
1855     {
1856         $notice = new Notice();
1857
1858         $notice->selectAdd(); // clears it
1859         $notice->selectAdd('id');
1860
1861         $notice->repeat_of = $this->id;
1862
1863         $notice->orderBy('created, id'); // NB: asc!
1864
1865         if (!is_null($limit)) {
1866             $notice->limit(0, $limit);
1867         }
1868
1869         return $notice->fetchAll('id');
1870     }
1871
1872     function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1873     {
1874         $options = array();
1875
1876         if (!empty($location_id) && !empty($location_ns)) {
1877             $options['location_id'] = $location_id;
1878             $options['location_ns'] = $location_ns;
1879
1880             $location = Location::fromId($location_id, $location_ns);
1881
1882             if (!empty($location)) {
1883                 $options['lat'] = $location->lat;
1884                 $options['lon'] = $location->lon;
1885             }
1886
1887         } else if (!empty($lat) && !empty($lon)) {
1888             $options['lat'] = $lat;
1889             $options['lon'] = $lon;
1890
1891             $location = Location::fromLatLon($lat, $lon);
1892
1893             if (!empty($location)) {
1894                 $options['location_id'] = $location->location_id;
1895                 $options['location_ns'] = $location->location_ns;
1896             }
1897         } else if (!empty($profile)) {
1898             if (isset($profile->lat) && isset($profile->lon)) {
1899                 $options['lat'] = $profile->lat;
1900                 $options['lon'] = $profile->lon;
1901             }
1902
1903             if (isset($profile->location_id) && isset($profile->location_ns)) {
1904                 $options['location_id'] = $profile->location_id;
1905                 $options['location_ns'] = $profile->location_ns;
1906             }
1907         }
1908
1909         return $options;
1910     }
1911
1912     function clearReplies()
1913     {
1914         $replyNotice = new Notice();
1915         $replyNotice->reply_to = $this->id;
1916
1917         //Null any notices that are replies to this notice
1918
1919         if ($replyNotice->find()) {
1920             while ($replyNotice->fetch()) {
1921                 $orig = clone($replyNotice);
1922                 $replyNotice->reply_to = null;
1923                 $replyNotice->update($orig);
1924             }
1925         }
1926
1927         // Reply records
1928
1929         $reply = new Reply();
1930         $reply->notice_id = $this->id;
1931
1932         if ($reply->find()) {
1933             while($reply->fetch()) {
1934                 self::blow('reply:stream:%d', $reply->profile_id);
1935                 $reply->delete();
1936             }
1937         }
1938
1939         $reply->free();
1940     }
1941
1942     function clearFiles()
1943     {
1944         $f2p = new File_to_post();
1945
1946         $f2p->post_id = $this->id;
1947
1948         if ($f2p->find()) {
1949             while ($f2p->fetch()) {
1950                 $f2p->delete();
1951             }
1952         }
1953         // FIXME: decide whether to delete File objects
1954         // ...and related (actual) files
1955     }
1956
1957     function clearRepeats()
1958     {
1959         $repeatNotice = new Notice();
1960         $repeatNotice->repeat_of = $this->id;
1961
1962         //Null any notices that are repeats of this notice
1963
1964         if ($repeatNotice->find()) {
1965             while ($repeatNotice->fetch()) {
1966                 $orig = clone($repeatNotice);
1967                 $repeatNotice->repeat_of = null;
1968                 $repeatNotice->update($orig);
1969             }
1970         }
1971     }
1972
1973     function clearFaves()
1974     {
1975         $fave = new Fave();
1976         $fave->notice_id = $this->id;
1977
1978         if ($fave->find()) {
1979             while ($fave->fetch()) {
1980                 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1981                 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1982                 self::blow('fave:ids_by_user:%d', $fave->user_id);
1983                 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1984                 $fave->delete();
1985             }
1986         }
1987
1988         $fave->free();
1989     }
1990
1991     function clearTags()
1992     {
1993         $tag = new Notice_tag();
1994         $tag->notice_id = $this->id;
1995
1996         if ($tag->find()) {
1997             while ($tag->fetch()) {
1998                 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
1999                 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2000                 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2001                 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2002                 $tag->delete();
2003             }
2004         }
2005
2006         $tag->free();
2007     }
2008
2009     function clearGroupInboxes()
2010     {
2011         $gi = new Group_inbox();
2012
2013         $gi->notice_id = $this->id;
2014
2015         if ($gi->find()) {
2016             while ($gi->fetch()) {
2017                 self::blow('user_group:notice_ids:%d', $gi->group_id);
2018                 $gi->delete();
2019             }
2020         }
2021
2022         $gi->free();
2023     }
2024
2025     function distribute()
2026     {
2027         // We always insert for the author so they don't
2028         // have to wait
2029         Event::handle('StartNoticeDistribute', array($this));
2030
2031         $user = User::staticGet('id', $this->profile_id);
2032         if (!empty($user)) {
2033             Inbox::insertNotice($user->id, $this->id);
2034         }
2035
2036         if (common_config('queue', 'inboxes')) {
2037             // If there's a failure, we want to _force_
2038             // distribution at this point.
2039             try {
2040                 $qm = QueueManager::get();
2041                 $qm->enqueue($this, 'distrib');
2042             } catch (Exception $e) {
2043                 // If the exception isn't transient, this
2044                 // may throw more exceptions as DQH does
2045                 // its own enqueueing. So, we ignore them!
2046                 try {
2047                     $handler = new DistribQueueHandler();
2048                     $handler->handle($this);
2049                 } catch (Exception $e) {
2050                     common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2051                 }
2052                 // Re-throw so somebody smarter can handle it.
2053                 throw $e;
2054             }
2055         } else {
2056             $handler = new DistribQueueHandler();
2057             $handler->handle($this);
2058         }
2059     }
2060
2061     function insert()
2062     {
2063         $result = parent::insert();
2064
2065         if ($result) {
2066             // Profile::hasRepeated() abuses pkeyGet(), so we
2067             // have to clear manually
2068             if (!empty($this->repeat_of)) {
2069                 $c = self::memcache();
2070                 if (!empty($c)) {
2071                     $ck = self::multicacheKey('Notice',
2072                                               array('profile_id' => $this->profile_id,
2073                                                     'repeat_of' => $this->repeat_of));
2074                     $c->delete($ck);
2075                 }
2076             }
2077         }
2078
2079         return $result;
2080     }
2081
2082     /**
2083      * Get the source of the notice
2084      *
2085      * @return Notice_source $ns A notice source object. 'code' is the only attribute
2086      *                           guaranteed to be populated.
2087      */
2088     function getSource()
2089     {
2090         $ns = new Notice_source();
2091         if (!empty($this->source)) {
2092             switch ($this->source) {
2093             case 'web':
2094             case 'xmpp':
2095             case 'mail':
2096             case 'omb':
2097             case 'system':
2098             case 'api':
2099                 $ns->code = $this->source;
2100                 break;
2101             default:
2102                 $ns = Notice_source::staticGet($this->source);
2103                 if (!$ns) {
2104                     $ns = new Notice_source();
2105                     $ns->code = $this->source;
2106                     $app = Oauth_application::staticGet('name', $this->source);
2107                     if ($app) {
2108                         $ns->name = $app->name;
2109                         $ns->url  = $app->source_url;
2110                     }
2111                 }
2112                 break;
2113             }
2114         }
2115         return $ns;
2116     }
2117
2118     /**
2119      * Determine whether the notice was locally created
2120      *
2121      * @return boolean locality
2122      */
2123
2124     public function isLocal()
2125     {
2126         return ($this->is_local == Notice::LOCAL_PUBLIC ||
2127                 $this->is_local == Notice::LOCAL_NONPUBLIC);
2128     }
2129
2130     /**
2131      * Get the list of hash tags saved with this notice.
2132      *
2133      * @return array of strings
2134      */
2135     public function getTags()
2136     {
2137         $tags = array();
2138
2139         $keypart = sprintf('notice:tags:%d', $this->id);
2140
2141         $tagstr = self::cacheGet($keypart);
2142
2143         if ($tagstr !== false) {
2144             $tags = explode(',', $tagstr);
2145         } else {
2146             $tag = new Notice_tag();
2147             $tag->notice_id = $this->id;
2148             if ($tag->find()) {
2149                 while ($tag->fetch()) {
2150                     $tags[] = $tag->tag;
2151                 }
2152             }
2153             self::cacheSet($keypart, implode(',', $tags));
2154         }
2155
2156         return $tags;
2157     }
2158
2159     static private function utcDate($dt)
2160     {
2161         $dateStr = date('d F Y H:i:s', strtotime($dt));
2162         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2163         return $d->format(DATE_W3C);
2164     }
2165
2166     /**
2167      * Look up the creation timestamp for a given notice ID, even
2168      * if it's been deleted.
2169      *
2170      * @param int $id
2171      * @return mixed string recorded creation timestamp, or false if can't be found
2172      */
2173     public static function getAsTimestamp($id)
2174     {
2175         if (!$id) {
2176             return false;
2177         }
2178
2179         $notice = Notice::staticGet('id', $id);
2180         if ($notice) {
2181             return $notice->created;
2182         }
2183
2184         $deleted = Deleted_notice::staticGet('id', $id);
2185         if ($deleted) {
2186             return $deleted->created;
2187         }
2188
2189         return false;
2190     }
2191
2192     /**
2193      * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2194      * parameter, matching notices posted after the given one (exclusive).
2195      *
2196      * If the referenced notice can't be found, will return false.
2197      *
2198      * @param int $id
2199      * @param string $idField
2200      * @param string $createdField
2201      * @return mixed string or false if no match
2202      */
2203     public static function whereSinceId($id, $idField='id', $createdField='created')
2204     {
2205         $since = Notice::getAsTimestamp($id);
2206         if ($since) {
2207             return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2208         }
2209         return false;
2210     }
2211
2212     /**
2213      * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2214      * parameter, matching notices posted after the given one (exclusive), and
2215      * if necessary add it to the data object's query.
2216      *
2217      * @param DB_DataObject $obj
2218      * @param int $id
2219      * @param string $idField
2220      * @param string $createdField
2221      * @return mixed string or false if no match
2222      */
2223     public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2224     {
2225         $since = self::whereSinceId($id, $idField, $createdField);
2226         if ($since) {
2227             $obj->whereAdd($since);
2228         }
2229     }
2230
2231     /**
2232      * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2233      * parameter, matching notices posted before the given one (inclusive).
2234      *
2235      * If the referenced notice can't be found, will return false.
2236      *
2237      * @param int $id
2238      * @param string $idField
2239      * @param string $createdField
2240      * @return mixed string or false if no match
2241      */
2242     public static function whereMaxId($id, $idField='id', $createdField='created')
2243     {
2244         $max = Notice::getAsTimestamp($id);
2245         if ($max) {
2246             return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2247         }
2248         return false;
2249     }
2250
2251     /**
2252      * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2253      * parameter, matching notices posted before the given one (inclusive), and
2254      * if necessary add it to the data object's query.
2255      *
2256      * @param DB_DataObject $obj
2257      * @param int $id
2258      * @param string $idField
2259      * @param string $createdField
2260      * @return mixed string or false if no match
2261      */
2262     public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2263     {
2264         $max = self::whereMaxId($id, $idField, $createdField);
2265         if ($max) {
2266             $obj->whereAdd($max);
2267         }
2268     }
2269
2270     function isPublic()
2271     {
2272         if (common_config('public', 'localonly')) {
2273             return ($this->is_local == Notice::LOCAL_PUBLIC);
2274         } else {
2275             return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2276                     ($this->is_local != Notice::GATEWAY));
2277         }
2278     }
2279
2280     /**
2281      * Check that the given profile is allowed to read, respond to, or otherwise
2282      * act on this notice.
2283      *
2284      * The $scope member is a bitmask of scopes, representing a logical AND of the
2285      * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2286      * "only visible to people who are mentioned in the notice AND are users on this site."
2287      * Users on the site who are not mentioned in the notice will not be able to see the
2288      * notice.
2289      *
2290      * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2291      *
2292      * @return boolean whether the profile is in the notice's scope
2293      */
2294     function inScope($profile)
2295     {
2296         if (is_null($profile)) {
2297             $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2298         } else {
2299             $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2300         }
2301
2302         $result = self::cacheGet($keypart);
2303
2304         if ($result === false) {
2305             $bResult = $this->_inScope($profile);
2306             $result = ($bResult) ? 1 : 0;
2307             self::cacheSet($keypart, $result, 0, 300);
2308         }
2309
2310         return ($result == 1) ? true : false;
2311     }
2312
2313     protected function _inScope($profile)
2314     {
2315         // If there's no scope, anyone (even anon) is in scope.
2316
2317         if ($this->scope == 0) {
2318             return true;
2319         }
2320
2321         // If there's scope, anon cannot be in scope
2322
2323         if (empty($profile)) {
2324             return false;
2325         }
2326
2327         // Author is always in scope
2328
2329         if ($this->profile_id == $profile->id) {
2330             return true;
2331         }
2332
2333         // Only for users on this site
2334
2335         if ($this->scope & Notice::SITE_SCOPE) {
2336             $user = $profile->getUser();
2337             if (empty($user)) {
2338                 return false;
2339             }
2340         }
2341
2342         // Only for users mentioned in the notice
2343
2344         if ($this->scope & Notice::ADDRESSEE_SCOPE) {
2345
2346                         $repl = Reply::pkeyGet(array('notice_id' => $this->id,
2347                                                                                  'profile_id' => $profile->id));
2348                                                                                  
2349             if (empty($repl)) {
2350                 return false;
2351             }
2352         }
2353
2354         // Only for members of the given group
2355
2356         if ($this->scope & Notice::GROUP_SCOPE) {
2357
2358             // XXX: just query for the single membership
2359
2360             $groups = $this->getGroups();
2361
2362             $foundOne = false;
2363
2364             foreach ($groups as $group) {
2365                 if ($profile->isMember($group)) {
2366                     $foundOne = true;
2367                     break;
2368                 }
2369             }
2370
2371             if (!$foundOne) {
2372                 return false;
2373             }
2374         }
2375
2376         // Only for followers of the author
2377
2378         if ($this->scope & Notice::FOLLOWER_SCOPE) {
2379             $author = $this->getProfile();
2380             if (!Subscription::exists($profile, $author)) {
2381                 return false;
2382             }
2383         }
2384
2385         return true;
2386     }
2387
2388     static function groupsFromText($text, $profile)
2389     {
2390         $groups = array();
2391
2392         /* extract all !group */
2393         $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
2394                                 strtolower($text),
2395                                 $match);
2396
2397         if (!$count) {
2398             return $groups;
2399         }
2400
2401         foreach (array_unique($match[1]) as $nickname) {
2402             $group = User_group::getForNickname($nickname, $profile);
2403             if (!empty($group) && $profile->isMember($group)) {
2404                 $groups[] = $group->id;
2405             }
2406         }
2407
2408         return $groups;
2409     }
2410
2411     protected $_original = -1;
2412
2413     function getOriginal()
2414     {
2415         if (is_int($this->_original) && $this->_original == -1) {
2416             if (empty($this->reply_to)) {
2417                 $this->_original = null;
2418             } else {
2419                 $this->_original = Notice::staticGet('id', $this->reply_to);
2420             }
2421         }
2422         return $this->_original;
2423     }
2424
2425     /**
2426      * Magic function called at serialize() time.
2427      *
2428      * We use this to drop a couple process-specific references
2429      * from DB_DataObject which can cause trouble in future
2430      * processes.
2431      *
2432      * @return array of variable names to include in serialization.
2433      */
2434
2435     function __sleep()
2436     {
2437         $vars = parent::__sleep();
2438         $skip = array('_original', '_profile', '_groups', '_attachments', '_faves', '_replies');
2439         return array_diff($vars, $skip);
2440     }
2441     
2442     static function defaultScope()
2443     {
2444         $scope = common_config('notice', 'defaultscope');
2445         if (is_null($scope)) {
2446                 if (common_config('site', 'private')) {
2447                         $scope = 1;
2448                 } else {
2449                         $scope = 0;
2450                 }
2451         }
2452         return $scope;
2453     }
2454
2455         static function fillProfiles($notices)
2456         {
2457                 $map = self::getProfiles($notices);
2458                 
2459                 foreach ($notices as $notice) {
2460                         if (array_key_exists($notice->profile_id, $map)) {
2461                                 $notice->_setProfile($map[$notice->profile_id]);    
2462                         }
2463                 }
2464                 
2465                 return array_values($map);
2466         }
2467         
2468         static function getProfiles(&$notices)
2469         {
2470                 $ids = array();
2471                 foreach ($notices as $notice) {
2472                         $ids[] = $notice->profile_id;
2473                 }
2474                 
2475                 $ids = array_unique($ids);
2476                 
2477                 return Memcached_DataObject::pivotGet('Profile', 'id', $ids); 
2478         }
2479         
2480         static function fillGroups(&$notices)
2481         {
2482         $ids = self::_idsOf($notices);
2483                 
2484                 $gis = Memcached_DataObject::listGet('Group_inbox', 'notice_id', $ids);
2485                 
2486         $gids = array();
2487
2488                 foreach ($gis as $id => $gi)
2489                 {
2490                     foreach ($gi as $g)
2491                     {
2492                         $gids[] = $g->group_id;
2493                     }
2494                 }
2495                 
2496                 $gids = array_unique($gids);
2497                 
2498                 $group = Memcached_DataObject::pivotGet('User_group', 'id', $gids);
2499                 
2500                 foreach ($notices as $notice)
2501                 {
2502                         $grps = array();
2503                         $gi = $gis[$notice->id];
2504                         foreach ($gi as $g) {
2505                             $grps[] = $group[$g->group_id];
2506                         }
2507                     $notice->_setGroups($grps);
2508                 }
2509         }
2510
2511     static function _idsOf(&$notices)
2512     {
2513                 $ids = array();
2514                 foreach ($notices as $notice) {
2515                         $ids[] = $notice->id;
2516                 }
2517                 $ids = array_unique($ids);
2518         return $ids;
2519     }
2520
2521     static function fillAttachments(&$notices)
2522     {
2523         $ids = self::_idsOf($notices);
2524
2525                 $f2pMap = Memcached_DataObject::listGet('File_to_post', 'post_id', $ids);
2526                 
2527                 $fileIds = array();
2528                 
2529                 foreach ($f2pMap as $noticeId => $f2ps) {
2530             foreach ($f2ps as $f2p) {
2531                 $fileIds[] = $f2p->file_id;    
2532             }
2533         }
2534
2535         $fileIds = array_unique($fileIds);
2536
2537                 $fileMap = Memcached_DataObject::pivotGet('File', 'id', $fileIds);
2538
2539                 foreach ($notices as $notice)
2540                 {
2541                         $files = array();
2542                         $f2ps = $f2pMap[$notice->id];
2543                         foreach ($f2ps as $f2p) {
2544                             $files[] = $fileMap[$f2p->file_id];
2545                         }
2546                     $notice->_setAttachments($files);
2547                 }
2548     }
2549
2550     protected $_faves;
2551
2552     /**
2553      * All faves of this notice
2554      *
2555      * @return array Array of Fave objects
2556      */
2557
2558     function getFaves()
2559     {
2560         if (isset($this->_faves) && is_array($this->_faves)) {
2561             return $this->_faves;
2562         }
2563         $faveMap = Memcached_DataObject::listGet('Fave', 'notice_id', array($this->id));
2564         $this->_faves = $faveMap[$this->id];
2565         return $this->_faves;
2566     }
2567
2568     function _setFaves(&$faves)
2569     {
2570         $this->_faves = $faves;
2571     }
2572
2573     static function fillFaves(&$notices)
2574     {
2575         $ids = self::_idsOf($notices);
2576         $faveMap = Memcached_DataObject::listGet('Fave', 'notice_id', $ids);
2577         $cnt = 0;
2578         $faved = array();
2579         foreach ($faveMap as $id => $faves) {
2580             $cnt += count($faves);
2581             if (count($faves) > 0) {
2582                 $faved[] = $id;
2583             }
2584         }
2585         foreach ($notices as $notice) {
2586             $notice->_setFaves($faveMap[$notice->id]);
2587         }
2588     }
2589
2590     static function fillReplies(&$notices)
2591     {
2592         $ids = self::_idsOf($notices);
2593         $replyMap = Memcached_DataObject::listGet('Reply', 'notice_id', $ids);
2594         foreach ($notices as $notice) {
2595             $replies = $replyMap[$notice->id];
2596             $ids = array();
2597             foreach ($replies as $reply) {
2598                 $ids[] = $reply->profile_id;
2599             }
2600             $notice->_setReplies($ids);
2601         }
2602     }
2603 }