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