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