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