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