]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
Merge remote-tracking branch 'origin/master'
[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_created_id_is_local_idx' => array('created', 'id', 'is_local'),
126                 'notice_profile_id_idx' => array('profile_id', 'created', 'id'),
127                 'notice_repeat_of_created_id_idx' => array('repeat_of', 'created', 'id'),
128                 'notice_conversation_created_id_idx' => array('conversation', 'created', 'id'),
129                 'notice_replyto_idx' => array('reply_to')
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                         $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1012                     }
1013                 }
1014             }
1015
1016             foreach ($recipients as $recipient) {
1017                 if (!array_key_exists($recipient, $ni)) {
1018                     $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1019                 }
1020             }
1021
1022             // Exclude any deleted, non-local, or blocking recipients.
1023             $profile = $this->getProfile();
1024             $originalProfile = null;
1025             if ($this->repeat_of) {
1026                 // Check blocks against the original notice's poster as well.
1027                 $original = Notice::staticGet('id', $this->repeat_of);
1028                 if ($original) {
1029                     $originalProfile = $original->getProfile();
1030                 }
1031             }
1032
1033             foreach ($ni as $id => $source) {
1034                 try {
1035                     $user = User::staticGet('id', $id);
1036                     if (empty($user) ||
1037                         $user->hasBlocked($profile) ||
1038                         ($originalProfile && $user->hasBlocked($originalProfile))) {
1039                         unset($ni[$id]);
1040                     }
1041                 } catch (UserNoProfileException $e) {
1042                     // User doesn't have a profile; invalid; skip them.
1043                     unset($ni[$id]);
1044                 }
1045             }
1046
1047             // Give plugins a chance to filter out...
1048             Event::handle('EndNoticeWhoGets', array($this, &$ni));
1049         }
1050
1051         if (!empty($c)) {
1052             // XXX: pack this data better
1053             $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1054         }
1055
1056         return $ni;
1057     }
1058
1059     /**
1060      * Adds this notice to the inboxes of each local user who should receive
1061      * it, based on author subscriptions, group memberships, and @-replies.
1062      *
1063      * Warning: running a second time currently will make items appear
1064      * multiple times in users' inboxes.
1065      *
1066      * @fixme make more robust against errors
1067      * @fixme break up massive deliveries to smaller background tasks
1068      *
1069      * @param array $groups optional list of Group objects;
1070      *              if left empty, will be loaded from group_inbox records
1071      * @param array $recipient optional list of reply profile ids
1072      *              if left empty, will be loaded from reply records
1073      */
1074     function addToInboxes($groups=null, $recipients=null)
1075     {
1076         $ni = $this->whoGets($groups, $recipients);
1077
1078         $ids = array_keys($ni);
1079
1080         // We remove the author (if they're a local user),
1081         // since we'll have already done this in distribute()
1082
1083         $i = array_search($this->profile_id, $ids);
1084
1085         if ($i !== false) {
1086             unset($ids[$i]);
1087         }
1088
1089         // Bulk insert
1090
1091         Inbox::bulkInsert($this->id, $ids);
1092
1093         return;
1094     }
1095
1096     function getSubscribedUsers()
1097     {
1098         $user = new User();
1099
1100         if(common_config('db','quote_identifiers'))
1101           $user_table = '"user"';
1102         else $user_table = 'user';
1103
1104         $qry =
1105           'SELECT id ' .
1106           'FROM '. $user_table .' JOIN subscription '.
1107           'ON '. $user_table .'.id = subscription.subscriber ' .
1108           'WHERE subscription.subscribed = %d ';
1109
1110         $user->query(sprintf($qry, $this->profile_id));
1111
1112         $ids = array();
1113
1114         while ($user->fetch()) {
1115             $ids[] = $user->id;
1116         }
1117
1118         $user->free();
1119
1120         return $ids;
1121     }
1122
1123     function getProfileTags()
1124     {
1125         $profile = $this->getProfile();
1126         $list    = $profile->getOtherTags($profile);
1127         $ptags   = array();
1128
1129         while($list->fetch()) {
1130             $ptags[] = clone($list);
1131         }
1132
1133         return $ptags;
1134     }
1135
1136     /**
1137      * Record this notice to the given group inboxes for delivery.
1138      * Overrides the regular parsing of !group markup.
1139      *
1140      * @param string $group_ids
1141      * @fixme might prefer URIs as identifiers, as for replies?
1142      *        best with generalizations on user_group to support
1143      *        remote groups better.
1144      */
1145     function saveKnownGroups($group_ids)
1146     {
1147         if (!is_array($group_ids)) {
1148             // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1149             throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1150         }
1151
1152         $groups = array();
1153         foreach (array_unique($group_ids) as $id) {
1154             $group = User_group::staticGet('id', $id);
1155             if ($group) {
1156                 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1157                 $result = $this->addToGroupInbox($group);
1158                 if (!$result) {
1159                     common_log_db_error($gi, 'INSERT', __FILE__);
1160                 }
1161
1162                 if (common_config('group', 'addtag')) {
1163                     // we automatically add a tag for every group name, too
1164
1165                     $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1166                                                      'notice_id' => $this->id));
1167
1168                     if (is_null($tag)) {
1169                         $this->saveTag($group->nickname);
1170                     }
1171                 }
1172
1173                 $groups[] = clone($group);
1174             } else {
1175                 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1176             }
1177         }
1178
1179         return $groups;
1180     }
1181
1182     /**
1183      * Parse !group delivery and record targets into group_inbox.
1184      * @return array of Group objects
1185      */
1186     function saveGroups()
1187     {
1188         // Don't save groups for repeats
1189
1190         if (!empty($this->repeat_of)) {
1191             return array();
1192         }
1193
1194         $profile = $this->getProfile();
1195
1196         $groups = self::groupsFromText($this->content, $profile);
1197
1198         /* Add them to the database */
1199
1200         foreach ($groups as $group) {
1201             /* XXX: remote groups. */
1202
1203             if (empty($group)) {
1204                 continue;
1205             }
1206
1207
1208             if ($profile->isMember($group)) {
1209
1210                 $result = $this->addToGroupInbox($group);
1211
1212                 if (!$result) {
1213                     common_log_db_error($gi, 'INSERT', __FILE__);
1214                 }
1215
1216                 $groups[] = clone($group);
1217             }
1218         }
1219
1220         return $groups;
1221     }
1222
1223     function addToGroupInbox($group)
1224     {
1225         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1226                                          'notice_id' => $this->id));
1227
1228         if (empty($gi)) {
1229
1230             $gi = new Group_inbox();
1231
1232             $gi->group_id  = $group->id;
1233             $gi->notice_id = $this->id;
1234             $gi->created   = $this->created;
1235
1236             $result = $gi->insert();
1237
1238             if (!$result) {
1239                 common_log_db_error($gi, 'INSERT', __FILE__);
1240                 // TRANS: Server exception thrown when an update for a group inbox fails.
1241                 throw new ServerException(_('Problem saving group inbox.'));
1242             }
1243
1244             self::blow('user_group:notice_ids:%d', $gi->group_id);
1245         }
1246
1247         return true;
1248     }
1249
1250     /**
1251      * Save reply records indicating that this notice needs to be
1252      * delivered to the local users with the given URIs.
1253      *
1254      * Since this is expected to be used when saving foreign-sourced
1255      * messages, we won't deliver to any remote targets as that's the
1256      * source service's responsibility.
1257      *
1258      * Mail notifications etc will be handled later.
1259      *
1260      * @param array of unique identifier URIs for recipients
1261      */
1262     function saveKnownReplies($uris)
1263     {
1264         if (empty($uris)) {
1265             return;
1266         }
1267
1268         $sender = Profile::staticGet($this->profile_id);
1269
1270         foreach (array_unique($uris) as $uri) {
1271
1272             $profile = Profile::fromURI($uri);
1273
1274             if (empty($profile)) {
1275                 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1276                 continue;
1277             }
1278
1279             if ($profile->hasBlocked($sender)) {
1280                 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1281                 continue;
1282             }
1283
1284             $this->saveReply($profile->id);
1285             self::blow('reply:stream:%d', $profile->id);
1286         }
1287
1288         return;
1289     }
1290
1291     /**
1292      * Pull @-replies from this message's content in StatusNet markup format
1293      * and save reply records indicating that this message needs to be
1294      * delivered to those users.
1295      *
1296      * Mail notifications to local profiles will be sent later.
1297      *
1298      * @return array of integer profile IDs
1299      */
1300
1301     function saveReplies()
1302     {
1303         // Don't save reply data for repeats
1304
1305         if (!empty($this->repeat_of)) {
1306             return array();
1307         }
1308
1309         $sender = Profile::staticGet($this->profile_id);
1310
1311         $replied = array();
1312
1313         // If it's a reply, save for the replied-to author
1314
1315         if (!empty($this->reply_to)) {
1316             $original = $this->getOriginal();
1317             if (!empty($original)) { // that'd be weird
1318                 $author = $original->getProfile();
1319                 if (!empty($author)) {
1320                     $this->saveReply($author->id);
1321                     $replied[$author->id] = 1;
1322                     self::blow('reply:stream:%d', $author->id);
1323                 }
1324             }
1325         }
1326
1327         // @todo ideally this parser information would only
1328         // be calculated once.
1329
1330         $mentions = common_find_mentions($this->content, $this);
1331
1332         // store replied only for first @ (what user/notice what the reply directed,
1333         // we assume first @ is it)
1334
1335         foreach ($mentions as $mention) {
1336
1337             foreach ($mention['mentioned'] as $mentioned) {
1338
1339                 // skip if they're already covered
1340
1341                 if (!empty($replied[$mentioned->id])) {
1342                     continue;
1343                 }
1344
1345                 // Don't save replies from blocked profile to local user
1346
1347                 $mentioned_user = User::staticGet('id', $mentioned->id);
1348                 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1349                     continue;
1350                 }
1351
1352                 $this->saveReply($mentioned->id);
1353                 $replied[$mentioned->id] = 1;
1354                 self::blow('reply:stream:%d', $mentioned->id);
1355             }
1356         }
1357
1358         $recipientIds = array_keys($replied);
1359
1360         return $recipientIds;
1361     }
1362
1363     function saveReply($profileId)
1364     {
1365         $reply = new Reply();
1366
1367         $reply->notice_id  = $this->id;
1368         $reply->profile_id = $profileId;
1369         $reply->modified   = $this->created;
1370
1371         $reply->insert();
1372
1373         return $reply;
1374     }
1375
1376     protected $_replies = -1;
1377
1378     /**
1379      * Pull the complete list of @-reply targets for this notice.
1380      *
1381      * @return array of integer profile ids
1382      */
1383     function getReplies()
1384     {
1385         if ($this->_replies != -1) {
1386             return $this->_replies;
1387         }
1388
1389         $replyMap = Memcached_DataObject::listGet('Reply', 'notice_id', array($this->id));
1390
1391         $ids = array();
1392
1393         foreach ($replyMap[$this->id] as $reply) {
1394             $ids[] = $reply->profile_id;
1395         }
1396
1397         $this->_replies = $ids;
1398
1399         return $ids;
1400     }
1401
1402     function _setReplies($replies)
1403     {
1404         $this->_replies = $replies;
1405     }
1406
1407     /**
1408      * Pull the complete list of @-reply targets for this notice.
1409      *
1410      * @return array of Profiles
1411      */
1412     function getReplyProfiles()
1413     {
1414         $ids = $this->getReplies();
1415         
1416         $profiles = Profile::multiGet('id', $ids);
1417         
1418         return $profiles->fetchAll();
1419     }
1420
1421     /**
1422      * Send e-mail notifications to local @-reply targets.
1423      *
1424      * Replies must already have been saved; this is expected to be run
1425      * from the distrib queue handler.
1426      */
1427     function sendReplyNotifications()
1428     {
1429         // Don't send reply notifications for repeats
1430
1431         if (!empty($this->repeat_of)) {
1432             return array();
1433         }
1434
1435         $recipientIds = $this->getReplies();
1436
1437         foreach ($recipientIds as $recipientId) {
1438             $user = User::staticGet('id', $recipientId);
1439             if (!empty($user)) {
1440                 mail_notify_attn($user, $this);
1441             }
1442         }
1443     }
1444
1445     /**
1446      * Pull list of groups this notice needs to be delivered to,
1447      * as previously recorded by saveGroups() or saveKnownGroups().
1448      *
1449      * @return array of Group objects
1450      */
1451     
1452     protected $_groups = -1;
1453     
1454     function getGroups()
1455     {
1456         // Don't save groups for repeats
1457
1458         if (!empty($this->repeat_of)) {
1459             return array();
1460         }
1461         
1462         if ($this->_groups != -1)
1463         {
1464             return $this->_groups;
1465         }
1466         
1467         $gis = Memcached_DataObject::listGet('Group_inbox', 'notice_id', array($this->id));
1468
1469         $ids = array();
1470
1471                 foreach ($gis[$this->id] as $gi)
1472                 {
1473                     $ids[] = $gi->group_id;
1474                 }
1475                 
1476                 $groups = User_group::multiGet('id', $ids);
1477                 
1478                 $this->_groups = $groups->fetchAll();
1479                 
1480                 return $this->_groups;
1481     }
1482     
1483     function _setGroups($groups)
1484     {
1485         $this->_groups = $groups;
1486     }
1487
1488     /**
1489      * Convert a notice into an activity for export.
1490      *
1491      * @param User $cur Current user
1492      *
1493      * @return Activity activity object representing this Notice.
1494      */
1495
1496     function asActivity($cur=null)
1497     {
1498         $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1499
1500         if (!empty($act)) {
1501             return $act;
1502         }
1503         $act = new Activity();
1504
1505         if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1506
1507             $act->id      = $this->uri;
1508             $act->time    = strtotime($this->created);
1509             $act->link    = $this->bestUrl();
1510             $act->content = common_xml_safe_str($this->rendered);
1511
1512             $profile = $this->getProfile();
1513
1514             $act->actor            = ActivityObject::fromProfile($profile);
1515             $act->actor->extra[]   = $profile->profileInfo($cur);
1516
1517             $act->verb = $this->verb;
1518
1519             if ($this->repeat_of) {
1520                 $repeated = Notice::staticGet('id', $this->repeat_of);
1521                 if (!empty($repeated)) {
1522                     $act->objects[] = $repeated->asActivity($cur);
1523                 }
1524             } else {
1525                 $act->objects[] = ActivityObject::fromNotice($this);
1526             }
1527
1528             // XXX: should this be handled by default processing for object entry?
1529
1530             // Categories
1531
1532             $tags = $this->getTags();
1533
1534             foreach ($tags as $tag) {
1535                 $cat       = new AtomCategory();
1536                 $cat->term = $tag;
1537
1538                 $act->categories[] = $cat;
1539             }
1540
1541             // Enclosures
1542             // XXX: use Atom Media and/or File activity objects instead
1543
1544             $attachments = $this->attachments();
1545
1546             foreach ($attachments as $attachment) {
1547                 // Save local attachments
1548                 if (!empty($attachment->filename)) {
1549                     $act->attachments[] = ActivityObject::fromFile($attachment);
1550                 }
1551             }
1552
1553             $ctx = new ActivityContext();
1554
1555             if (!empty($this->reply_to)) {
1556                 $reply = Notice::staticGet('id', $this->reply_to);
1557                 if (!empty($reply)) {
1558                     $ctx->replyToID  = $reply->uri;
1559                     $ctx->replyToUrl = $reply->bestUrl();
1560                 }
1561             }
1562
1563             $ctx->location = $this->getLocation();
1564
1565             $conv = null;
1566
1567             if (!empty($this->conversation)) {
1568                 $conv = Conversation::staticGet('id', $this->conversation);
1569                 if (!empty($conv)) {
1570                     $ctx->conversation = $conv->uri;
1571                 }
1572             }
1573
1574             $reply_ids = $this->getReplies();
1575
1576             foreach ($reply_ids as $id) {
1577                 $rprofile = Profile::staticGet('id', $id);
1578                 if (!empty($rprofile)) {
1579                     $ctx->attention[] = $rprofile->getUri();
1580                     $ctx->attentionType[$rprofile->getUri()] = ActivityObject::PERSON;
1581                 }
1582             }
1583
1584             $groups = $this->getGroups();
1585
1586             foreach ($groups as $group) {
1587                 $ctx->attention[] = $group->getUri();
1588                 $ctx->attentionType[$group->getUri()] = ActivityObject::GROUP;
1589             }
1590
1591             switch ($this->scope) {
1592             case Notice::PUBLIC_SCOPE:
1593                 $ctx->attention[] = "http://activityschema.org/collection/public";
1594                 $ctx->attentionType["http://activityschema.org/collection/public"] = ActivityObject::COLLECTION;
1595                 break;
1596             case Notice::FOLLOWER_SCOPE:
1597                 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1598                 $ctx->attention[] = $surl;
1599                 $ctx->attentionType[$surl] = ActivityObject::COLLECTION;
1600                 break;
1601             }
1602
1603             // XXX: deprecated; use ActivityVerb::SHARE instead
1604
1605             $repeat = null;
1606
1607             if (!empty($this->repeat_of)) {
1608                 $repeat = Notice::staticGet('id', $this->repeat_of);
1609                 if (!empty($repeat)) {
1610                     $ctx->forwardID  = $repeat->uri;
1611                     $ctx->forwardUrl = $repeat->bestUrl();
1612                 }
1613             }
1614
1615             $act->context = $ctx;
1616
1617             $source = $this->getSource();
1618
1619             if ($source) {
1620                 $act->generator = ActivityObject::fromNoticeSource($source);
1621             }
1622
1623             // Source
1624
1625             $atom_feed = $profile->getAtomFeed();
1626
1627             if (!empty($atom_feed)) {
1628
1629                 $act->source = new ActivitySource();
1630
1631                 // XXX: we should store the actual feed ID
1632
1633                 $act->source->id = $atom_feed;
1634
1635                 // XXX: we should store the actual feed title
1636
1637                 $act->source->title = $profile->getBestName();
1638
1639                 $act->source->links['alternate'] = $profile->profileurl;
1640                 $act->source->links['self']      = $atom_feed;
1641
1642                 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1643
1644                 $notice = $profile->getCurrentNotice();
1645
1646                 if (!empty($notice)) {
1647                     $act->source->updated = self::utcDate($notice->created);
1648                 }
1649
1650                 $user = User::staticGet('id', $profile->id);
1651
1652                 if (!empty($user)) {
1653                     $act->source->links['license'] = common_config('license', 'url');
1654                 }
1655             }
1656
1657             if ($this->isLocal()) {
1658                 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1659                                                                            'format' => 'atom'));
1660                 $act->editLink = $act->selfLink;
1661             }
1662
1663             Event::handle('EndNoticeAsActivity', array($this, &$act));
1664         }
1665
1666         self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1667
1668         return $act;
1669     }
1670
1671     // This has gotten way too long. Needs to be sliced up into functional bits
1672     // or ideally exported to a utility class.
1673
1674     function asAtomEntry($namespace=false,
1675                          $source=false,
1676                          $author=true,
1677                          $cur=null)
1678     {
1679         $act = $this->asActivity($cur);
1680         $act->extra[] = $this->noticeInfo($cur);
1681         return $act->asString($namespace, $author, $source);
1682     }
1683
1684     /**
1685      * Extra notice info for atom entries
1686      *
1687      * Clients use some extra notice info in the atom stream.
1688      * This gives it to them.
1689      *
1690      * @param User $cur Current user
1691      *
1692      * @return array representation of <statusnet:notice_info> element
1693      */
1694
1695     function noticeInfo($cur)
1696     {
1697         // local notice ID (useful to clients for ordering)
1698
1699         $noticeInfoAttr = array('local_id' => $this->id);
1700
1701         // notice source
1702
1703         $ns = $this->getSource();
1704
1705         if (!empty($ns)) {
1706             $noticeInfoAttr['source'] =  $ns->code;
1707             if (!empty($ns->url)) {
1708                 $noticeInfoAttr['source_link'] = $ns->url;
1709                 if (!empty($ns->name)) {
1710                     $noticeInfoAttr['source'] =  '<a href="'
1711                         . htmlspecialchars($ns->url)
1712                         . '" rel="nofollow">'
1713                         . htmlspecialchars($ns->name)
1714                         . '</a>';
1715                 }
1716             }
1717         }
1718
1719         // favorite and repeated
1720
1721         if (!empty($cur)) {
1722             $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1723             $cp = $cur->getProfile();
1724             $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this->id)) ? "true" : "false";
1725         }
1726
1727         if (!empty($this->repeat_of)) {
1728             $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1729         }
1730
1731         return array('statusnet:notice_info', $noticeInfoAttr, null);
1732     }
1733
1734     /**
1735      * Returns an XML string fragment with a reference to a notice as an
1736      * Activity Streams noun object with the given element type.
1737      *
1738      * Assumes that 'activity' namespace has been previously defined.
1739      *
1740      * @param string $element one of 'subject', 'object', 'target'
1741      * @return string
1742      */
1743
1744     function asActivityNoun($element)
1745     {
1746         $noun = ActivityObject::fromNotice($this);
1747         return $noun->asString('activity:' . $element);
1748     }
1749
1750     function bestUrl()
1751     {
1752         if (!empty($this->url)) {
1753             return $this->url;
1754         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1755             return $this->uri;
1756         } else {
1757             return common_local_url('shownotice',
1758                                     array('notice' => $this->id));
1759         }
1760     }
1761
1762
1763     /**
1764      * Determine which notice, if any, a new notice is in reply to.
1765      *
1766      * For conversation tracking, we try to see where this notice fits
1767      * in the tree. Rough algorithm is:
1768      *
1769      * if (reply_to is set and valid) {
1770      *     return reply_to;
1771      * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1772      *     return ID of last notice by initial @name in content;
1773      * }
1774      *
1775      * Note that all @nickname instances will still be used to save "reply" records,
1776      * so the notice shows up in the mentioned users' "replies" tab.
1777      *
1778      * @param integer $reply_to   ID passed in by Web or API
1779      * @param integer $profile_id ID of author
1780      * @param string  $source     Source tag, like 'web' or 'gwibber'
1781      * @param string  $content    Final notice content
1782      *
1783      * @return integer ID of replied-to notice, or null for not a reply.
1784      */
1785
1786     static function getReplyTo($reply_to, $profile_id, $source, $content)
1787     {
1788         static $lb = array('xmpp', 'mail', 'sms', 'omb');
1789
1790         // If $reply_to is specified, we check that it exists, and then
1791         // return it if it does
1792
1793         if (!empty($reply_to)) {
1794             $reply_notice = Notice::staticGet('id', $reply_to);
1795             if (!empty($reply_notice)) {
1796                 return $reply_notice;
1797             }
1798         }
1799
1800         // If it's not a "low bandwidth" source (one where you can't set
1801         // a reply_to argument), we return. This is mostly web and API
1802         // clients.
1803
1804         if (!in_array($source, $lb)) {
1805             return null;
1806         }
1807
1808         // Is there an initial @ or T?
1809
1810         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1811             preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1812             $nickname = common_canonical_nickname($match[1]);
1813         } else {
1814             return null;
1815         }
1816
1817         // Figure out who that is.
1818
1819         $sender = Profile::staticGet('id', $profile_id);
1820         if (empty($sender)) {
1821             return null;
1822         }
1823
1824         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1825
1826         if (empty($recipient)) {
1827             return null;
1828         }
1829
1830         // Get their last notice
1831
1832         $last = $recipient->getCurrentNotice();
1833
1834         if (!empty($last)) {
1835             return $last;
1836         }
1837
1838         return null;
1839     }
1840
1841     static function maxContent()
1842     {
1843         $contentlimit = common_config('notice', 'contentlimit');
1844         // null => use global limit (distinct from 0!)
1845         if (is_null($contentlimit)) {
1846             $contentlimit = common_config('site', 'textlimit');
1847         }
1848         return $contentlimit;
1849     }
1850
1851     static function contentTooLong($content)
1852     {
1853         $contentlimit = self::maxContent();
1854         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1855     }
1856
1857     function getLocation()
1858     {
1859         $location = null;
1860
1861         if (!empty($this->location_id) && !empty($this->location_ns)) {
1862             $location = Location::fromId($this->location_id, $this->location_ns);
1863         }
1864
1865         if (is_null($location)) { // no ID, or Location::fromId() failed
1866             if (!empty($this->lat) && !empty($this->lon)) {
1867                 $location = Location::fromLatLon($this->lat, $this->lon);
1868             }
1869         }
1870
1871         return $location;
1872     }
1873
1874     /**
1875      * Convenience function for posting a repeat of an existing message.
1876      *
1877      * @param int $repeater_id: profile ID of user doing the repeat
1878      * @param string $source: posting source key, eg 'web', 'api', etc
1879      * @return Notice
1880      *
1881      * @throws Exception on failure or permission problems
1882      */
1883     function repeat($repeater_id, $source)
1884     {
1885         $author = Profile::staticGet('id', $this->profile_id);
1886
1887         // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1888         // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1889         $content = sprintf(_('RT @%1$s %2$s'),
1890                            $author->nickname,
1891                            $this->content);
1892
1893         $maxlen = common_config('site', 'textlimit');
1894         if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1895             // Web interface and current Twitter API clients will
1896             // pull the original notice's text, but some older
1897             // clients and RSS/Atom feeds will see this trimmed text.
1898             //
1899             // Unfortunately this is likely to lose tags or URLs
1900             // at the end of long notices.
1901             $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1902         }
1903
1904         // Scope is same as this one's
1905
1906         return self::saveNew($repeater_id,
1907                              $content,
1908                              $source,
1909                              array('repeat_of' => $this->id,
1910                                    'scope' => $this->scope));
1911     }
1912
1913     // These are supposed to be in chron order!
1914
1915     function repeatStream($limit=100)
1916     {
1917         $cache = Cache::instance();
1918
1919         if (empty($cache)) {
1920             $ids = $this->_repeatStreamDirect($limit);
1921         } else {
1922             $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1923             if ($idstr !== false) {
1924                 if (empty($idstr)) {
1925                         $ids = array();
1926                 } else {
1927                         $ids = explode(',', $idstr);
1928                 }
1929             } else {
1930                 $ids = $this->_repeatStreamDirect(100);
1931                 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1932             }
1933             if ($limit < 100) {
1934                 // We do a max of 100, so slice down to limit
1935                 $ids = array_slice($ids, 0, $limit);
1936             }
1937         }
1938
1939         return NoticeStream::getStreamByIds($ids);
1940     }
1941
1942     function _repeatStreamDirect($limit)
1943     {
1944         $notice = new Notice();
1945
1946         $notice->selectAdd(); // clears it
1947         $notice->selectAdd('id');
1948
1949         $notice->repeat_of = $this->id;
1950
1951         $notice->orderBy('created, id'); // NB: asc!
1952
1953         if (!is_null($limit)) {
1954             $notice->limit(0, $limit);
1955         }
1956
1957         return $notice->fetchAll('id');
1958     }
1959
1960     function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1961     {
1962         $options = array();
1963
1964         if (!empty($location_id) && !empty($location_ns)) {
1965             $options['location_id'] = $location_id;
1966             $options['location_ns'] = $location_ns;
1967
1968             $location = Location::fromId($location_id, $location_ns);
1969
1970             if (!empty($location)) {
1971                 $options['lat'] = $location->lat;
1972                 $options['lon'] = $location->lon;
1973             }
1974
1975         } else if (!empty($lat) && !empty($lon)) {
1976             $options['lat'] = $lat;
1977             $options['lon'] = $lon;
1978
1979             $location = Location::fromLatLon($lat, $lon);
1980
1981             if (!empty($location)) {
1982                 $options['location_id'] = $location->location_id;
1983                 $options['location_ns'] = $location->location_ns;
1984             }
1985         } else if (!empty($profile)) {
1986             if (isset($profile->lat) && isset($profile->lon)) {
1987                 $options['lat'] = $profile->lat;
1988                 $options['lon'] = $profile->lon;
1989             }
1990
1991             if (isset($profile->location_id) && isset($profile->location_ns)) {
1992                 $options['location_id'] = $profile->location_id;
1993                 $options['location_ns'] = $profile->location_ns;
1994             }
1995         }
1996
1997         return $options;
1998     }
1999
2000     function clearReplies()
2001     {
2002         $replyNotice = new Notice();
2003         $replyNotice->reply_to = $this->id;
2004
2005         //Null any notices that are replies to this notice
2006
2007         if ($replyNotice->find()) {
2008             while ($replyNotice->fetch()) {
2009                 $orig = clone($replyNotice);
2010                 $replyNotice->reply_to = null;
2011                 $replyNotice->update($orig);
2012             }
2013         }
2014
2015         // Reply records
2016
2017         $reply = new Reply();
2018         $reply->notice_id = $this->id;
2019
2020         if ($reply->find()) {
2021             while($reply->fetch()) {
2022                 self::blow('reply:stream:%d', $reply->profile_id);
2023                 $reply->delete();
2024             }
2025         }
2026
2027         $reply->free();
2028     }
2029
2030     function clearFiles()
2031     {
2032         $f2p = new File_to_post();
2033
2034         $f2p->post_id = $this->id;
2035
2036         if ($f2p->find()) {
2037             while ($f2p->fetch()) {
2038                 $f2p->delete();
2039             }
2040         }
2041         // FIXME: decide whether to delete File objects
2042         // ...and related (actual) files
2043     }
2044
2045     function clearRepeats()
2046     {
2047         $repeatNotice = new Notice();
2048         $repeatNotice->repeat_of = $this->id;
2049
2050         //Null any notices that are repeats of this notice
2051
2052         if ($repeatNotice->find()) {
2053             while ($repeatNotice->fetch()) {
2054                 $orig = clone($repeatNotice);
2055                 $repeatNotice->repeat_of = null;
2056                 $repeatNotice->update($orig);
2057             }
2058         }
2059     }
2060
2061     function clearFaves()
2062     {
2063         $fave = new Fave();
2064         $fave->notice_id = $this->id;
2065
2066         if ($fave->find()) {
2067             while ($fave->fetch()) {
2068                 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2069                 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2070                 self::blow('fave:ids_by_user:%d', $fave->user_id);
2071                 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2072                 $fave->delete();
2073             }
2074         }
2075
2076         $fave->free();
2077     }
2078
2079     function clearTags()
2080     {
2081         $tag = new Notice_tag();
2082         $tag->notice_id = $this->id;
2083
2084         if ($tag->find()) {
2085             while ($tag->fetch()) {
2086                 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2087                 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2088                 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2089                 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2090                 $tag->delete();
2091             }
2092         }
2093
2094         $tag->free();
2095     }
2096
2097     function clearGroupInboxes()
2098     {
2099         $gi = new Group_inbox();
2100
2101         $gi->notice_id = $this->id;
2102
2103         if ($gi->find()) {
2104             while ($gi->fetch()) {
2105                 self::blow('user_group:notice_ids:%d', $gi->group_id);
2106                 $gi->delete();
2107             }
2108         }
2109
2110         $gi->free();
2111     }
2112
2113     function distribute()
2114     {
2115         // We always insert for the author so they don't
2116         // have to wait
2117         Event::handle('StartNoticeDistribute', array($this));
2118
2119         $user = User::staticGet('id', $this->profile_id);
2120         if (!empty($user)) {
2121             Inbox::insertNotice($user->id, $this->id);
2122         }
2123
2124         if (common_config('queue', 'inboxes')) {
2125             // If there's a failure, we want to _force_
2126             // distribution at this point.
2127             try {
2128                 $qm = QueueManager::get();
2129                 $qm->enqueue($this, 'distrib');
2130             } catch (Exception $e) {
2131                 // If the exception isn't transient, this
2132                 // may throw more exceptions as DQH does
2133                 // its own enqueueing. So, we ignore them!
2134                 try {
2135                     $handler = new DistribQueueHandler();
2136                     $handler->handle($this);
2137                 } catch (Exception $e) {
2138                     common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2139                 }
2140                 // Re-throw so somebody smarter can handle it.
2141                 throw $e;
2142             }
2143         } else {
2144             $handler = new DistribQueueHandler();
2145             $handler->handle($this);
2146         }
2147     }
2148
2149     function insert()
2150     {
2151         $result = parent::insert();
2152
2153         if ($result) {
2154             // Profile::hasRepeated() abuses pkeyGet(), so we
2155             // have to clear manually
2156             if (!empty($this->repeat_of)) {
2157                 $c = self::memcache();
2158                 if (!empty($c)) {
2159                     $ck = self::multicacheKey('Notice',
2160                                               array('profile_id' => $this->profile_id,
2161                                                     'repeat_of' => $this->repeat_of));
2162                     $c->delete($ck);
2163                 }
2164             }
2165         }
2166
2167         return $result;
2168     }
2169
2170     /**
2171      * Get the source of the notice
2172      *
2173      * @return Notice_source $ns A notice source object. 'code' is the only attribute
2174      *                           guaranteed to be populated.
2175      */
2176     function getSource()
2177     {
2178         $ns = new Notice_source();
2179         if (!empty($this->source)) {
2180             switch ($this->source) {
2181             case 'web':
2182             case 'xmpp':
2183             case 'mail':
2184             case 'omb':
2185             case 'system':
2186             case 'api':
2187                 $ns->code = $this->source;
2188                 break;
2189             default:
2190                 $ns = Notice_source::staticGet($this->source);
2191                 if (!$ns) {
2192                     $ns = new Notice_source();
2193                     $ns->code = $this->source;
2194                     $app = Oauth_application::staticGet('name', $this->source);
2195                     if ($app) {
2196                         $ns->name = $app->name;
2197                         $ns->url  = $app->source_url;
2198                     }
2199                 }
2200                 break;
2201             }
2202         }
2203         return $ns;
2204     }
2205
2206     /**
2207      * Determine whether the notice was locally created
2208      *
2209      * @return boolean locality
2210      */
2211
2212     public function isLocal()
2213     {
2214         return ($this->is_local == Notice::LOCAL_PUBLIC ||
2215                 $this->is_local == Notice::LOCAL_NONPUBLIC);
2216     }
2217
2218     /**
2219      * Get the list of hash tags saved with this notice.
2220      *
2221      * @return array of strings
2222      */
2223     public function getTags()
2224     {
2225         $tags = array();
2226
2227         $keypart = sprintf('notice:tags:%d', $this->id);
2228
2229         $tagstr = self::cacheGet($keypart);
2230
2231         if ($tagstr !== false) {
2232             $tags = explode(',', $tagstr);
2233         } else {
2234             $tag = new Notice_tag();
2235             $tag->notice_id = $this->id;
2236             if ($tag->find()) {
2237                 while ($tag->fetch()) {
2238                     $tags[] = $tag->tag;
2239                 }
2240             }
2241             self::cacheSet($keypart, implode(',', $tags));
2242         }
2243
2244         return $tags;
2245     }
2246
2247     static private function utcDate($dt)
2248     {
2249         $dateStr = date('d F Y H:i:s', strtotime($dt));
2250         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2251         return $d->format(DATE_W3C);
2252     }
2253
2254     /**
2255      * Look up the creation timestamp for a given notice ID, even
2256      * if it's been deleted.
2257      *
2258      * @param int $id
2259      * @return mixed string recorded creation timestamp, or false if can't be found
2260      */
2261     public static function getAsTimestamp($id)
2262     {
2263         if (!$id) {
2264             return false;
2265         }
2266
2267         $notice = Notice::staticGet('id', $id);
2268         if ($notice) {
2269             return $notice->created;
2270         }
2271
2272         $deleted = Deleted_notice::staticGet('id', $id);
2273         if ($deleted) {
2274             return $deleted->created;
2275         }
2276
2277         return false;
2278     }
2279
2280     /**
2281      * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2282      * parameter, matching notices posted after the given one (exclusive).
2283      *
2284      * If the referenced notice can't be found, will return false.
2285      *
2286      * @param int $id
2287      * @param string $idField
2288      * @param string $createdField
2289      * @return mixed string or false if no match
2290      */
2291     public static function whereSinceId($id, $idField='id', $createdField='created')
2292     {
2293         $since = Notice::getAsTimestamp($id);
2294         if ($since) {
2295             return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2296         }
2297         return false;
2298     }
2299
2300     /**
2301      * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2302      * parameter, matching notices posted after the given one (exclusive), and
2303      * if necessary add it to the data object's query.
2304      *
2305      * @param DB_DataObject $obj
2306      * @param int $id
2307      * @param string $idField
2308      * @param string $createdField
2309      * @return mixed string or false if no match
2310      */
2311     public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2312     {
2313         $since = self::whereSinceId($id, $idField, $createdField);
2314         if ($since) {
2315             $obj->whereAdd($since);
2316         }
2317     }
2318
2319     /**
2320      * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2321      * parameter, matching notices posted before the given one (inclusive).
2322      *
2323      * If the referenced notice can't be found, will return false.
2324      *
2325      * @param int $id
2326      * @param string $idField
2327      * @param string $createdField
2328      * @return mixed string or false if no match
2329      */
2330     public static function whereMaxId($id, $idField='id', $createdField='created')
2331     {
2332         $max = Notice::getAsTimestamp($id);
2333         if ($max) {
2334             return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2335         }
2336         return false;
2337     }
2338
2339     /**
2340      * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2341      * parameter, matching notices posted before the given one (inclusive), and
2342      * if necessary add it to the data object's query.
2343      *
2344      * @param DB_DataObject $obj
2345      * @param int $id
2346      * @param string $idField
2347      * @param string $createdField
2348      * @return mixed string or false if no match
2349      */
2350     public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2351     {
2352         $max = self::whereMaxId($id, $idField, $createdField);
2353         if ($max) {
2354             $obj->whereAdd($max);
2355         }
2356     }
2357
2358     function isPublic()
2359     {
2360         if (common_config('public', 'localonly')) {
2361             return ($this->is_local == Notice::LOCAL_PUBLIC);
2362         } else {
2363             return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2364                     ($this->is_local != Notice::GATEWAY));
2365         }
2366     }
2367
2368     /**
2369      * Check that the given profile is allowed to read, respond to, or otherwise
2370      * act on this notice.
2371      *
2372      * The $scope member is a bitmask of scopes, representing a logical AND of the
2373      * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2374      * "only visible to people who are mentioned in the notice AND are users on this site."
2375      * Users on the site who are not mentioned in the notice will not be able to see the
2376      * notice.
2377      *
2378      * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2379      *
2380      * @return boolean whether the profile is in the notice's scope
2381      */
2382     function inScope($profile)
2383     {
2384         if (is_null($profile)) {
2385             $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2386         } else {
2387             $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2388         }
2389
2390         $result = self::cacheGet($keypart);
2391
2392         if ($result === false) {
2393             $bResult = false;
2394             if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2395                 $bResult = $this->_inScope($profile);
2396                 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2397             }
2398             $result = ($bResult) ? 1 : 0;
2399             self::cacheSet($keypart, $result, 0, 300);
2400         }
2401
2402         return ($result == 1) ? true : false;
2403     }
2404
2405     protected function _inScope($profile)
2406     {
2407         if (!is_null($this->scope)) {
2408             $scope = $this->scope;
2409         } else {
2410             $scope = self::defaultScope();
2411         }
2412
2413         // If there's no scope, anyone (even anon) is in scope.
2414
2415         if ($scope == 0) { // Not private
2416
2417             return !$this->isHiddenSpam($profile);
2418
2419         } else { // Private, somehow
2420
2421             // If there's scope, anon cannot be in scope
2422
2423             if (empty($profile)) {
2424                 return false;
2425             }
2426
2427             // Author is always in scope
2428
2429             if ($this->profile_id == $profile->id) {
2430                 return true;
2431             }
2432
2433             // Only for users on this site
2434
2435             if ($scope & Notice::SITE_SCOPE) {
2436                 $user = $profile->getUser();
2437                 if (empty($user)) {
2438                     return false;
2439                 }
2440             }
2441
2442             // Only for users mentioned in the notice
2443
2444             if ($scope & Notice::ADDRESSEE_SCOPE) {
2445
2446                 $repl = Reply::pkeyGet(array('notice_id' => $this->id,
2447                                              'profile_id' => $profile->id));
2448                                                                                  
2449                 if (empty($repl)) {
2450                     return false;
2451                 }
2452             }
2453
2454             // Only for members of the given group
2455
2456             if ($scope & Notice::GROUP_SCOPE) {
2457
2458                 // XXX: just query for the single membership
2459
2460                 $groups = $this->getGroups();
2461
2462                 $foundOne = false;
2463
2464                 foreach ($groups as $group) {
2465                     if ($profile->isMember($group)) {
2466                         $foundOne = true;
2467                         break;
2468                     }
2469                 }
2470
2471                 if (!$foundOne) {
2472                     return false;
2473                 }
2474             }
2475
2476             // Only for followers of the author
2477
2478             $author = null;
2479
2480             if ($scope & Notice::FOLLOWER_SCOPE) {
2481
2482                 try {
2483                     $author = $this->getProfile();
2484                 } catch (Exception $e) {
2485                     return false;
2486                 }
2487         
2488                 if (!Subscription::exists($profile, $author)) {
2489                     return false;
2490                 }
2491             }
2492
2493             return !$this->isHiddenSpam($profile);
2494         }
2495     }
2496
2497     function isHiddenSpam($profile) {
2498         
2499         // Hide posts by silenced users from everyone but moderators.
2500
2501         if (common_config('notice', 'hidespam')) {
2502
2503             try {
2504                 $author = $this->getProfile();
2505             } catch(Exception $e) {
2506                 // If we can't get an author, keep it hidden.
2507                 // XXX: technically not spam, but, whatever.
2508                 return true;
2509             }
2510
2511             if ($author->hasRole(Profile_role::SILENCED)) {
2512                 if (empty($profile) || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2513                     return true;
2514                 }
2515             }
2516         }
2517
2518         return false;
2519     }
2520
2521     static function groupsFromText($text, $profile)
2522     {
2523         $groups = array();
2524
2525         /* extract all !group */
2526         $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
2527                                 strtolower($text),
2528                                 $match);
2529
2530         if (!$count) {
2531             return $groups;
2532         }
2533
2534         foreach (array_unique($match[1]) as $nickname) {
2535             $group = User_group::getForNickname($nickname, $profile);
2536             if (!empty($group) && $profile->isMember($group)) {
2537                 $groups[] = $group->id;
2538             }
2539         }
2540
2541         return $groups;
2542     }
2543
2544     protected $_original = -1;
2545
2546     function getOriginal()
2547     {
2548         if (is_int($this->_original) && $this->_original == -1) {
2549             if (empty($this->reply_to)) {
2550                 $this->_original = null;
2551             } else {
2552                 $this->_original = Notice::staticGet('id', $this->reply_to);
2553             }
2554         }
2555         return $this->_original;
2556     }
2557
2558     /**
2559      * Magic function called at serialize() time.
2560      *
2561      * We use this to drop a couple process-specific references
2562      * from DB_DataObject which can cause trouble in future
2563      * processes.
2564      *
2565      * @return array of variable names to include in serialization.
2566      */
2567
2568     function __sleep()
2569     {
2570         $vars = parent::__sleep();
2571         $skip = array('_original', '_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2572         return array_diff($vars, $skip);
2573     }
2574     
2575     static function defaultScope()
2576     {
2577         $scope = common_config('notice', 'defaultscope');
2578         if (is_null($scope)) {
2579                 if (common_config('site', 'private')) {
2580                         $scope = 1;
2581                 } else {
2582                         $scope = 0;
2583                 }
2584         }
2585         return $scope;
2586     }
2587
2588         static function fillProfiles($notices)
2589         {
2590                 $map = self::getProfiles($notices);
2591                 
2592                 foreach ($notices as $notice) {
2593                         if (array_key_exists($notice->profile_id, $map)) {
2594                                 $notice->_setProfile($map[$notice->profile_id]);    
2595                         }
2596                 }
2597                 
2598                 return array_values($map);
2599         }
2600         
2601         static function getProfiles(&$notices)
2602         {
2603                 $ids = array();
2604                 foreach ($notices as $notice) {
2605                         $ids[] = $notice->profile_id;
2606                 }
2607                 
2608                 $ids = array_unique($ids);
2609                 
2610                 return Memcached_DataObject::pivotGet('Profile', 'id', $ids); 
2611         }
2612         
2613         static function fillGroups(&$notices)
2614         {
2615         $ids = self::_idsOf($notices);
2616                 
2617                 $gis = Memcached_DataObject::listGet('Group_inbox', 'notice_id', $ids);
2618                 
2619         $gids = array();
2620
2621                 foreach ($gis as $id => $gi)
2622                 {
2623                     foreach ($gi as $g)
2624                     {
2625                         $gids[] = $g->group_id;
2626                     }
2627                 }
2628                 
2629                 $gids = array_unique($gids);
2630                 
2631                 $group = Memcached_DataObject::pivotGet('User_group', 'id', $gids);
2632                 
2633                 foreach ($notices as $notice)
2634                 {
2635                         $grps = array();
2636                         $gi = $gis[$notice->id];
2637                         foreach ($gi as $g) {
2638                             $grps[] = $group[$g->group_id];
2639                         }
2640                     $notice->_setGroups($grps);
2641                 }
2642         }
2643
2644     static function _idsOf(&$notices)
2645     {
2646                 $ids = array();
2647                 foreach ($notices as $notice) {
2648                         $ids[] = $notice->id;
2649                 }
2650                 $ids = array_unique($ids);
2651         return $ids;
2652     }
2653
2654     static function fillAttachments(&$notices)
2655     {
2656         $ids = self::_idsOf($notices);
2657
2658                 $f2pMap = Memcached_DataObject::listGet('File_to_post', 'post_id', $ids);
2659                 
2660                 $fileIds = array();
2661                 
2662                 foreach ($f2pMap as $noticeId => $f2ps) {
2663             foreach ($f2ps as $f2p) {
2664                 $fileIds[] = $f2p->file_id;    
2665             }
2666         }
2667
2668         $fileIds = array_unique($fileIds);
2669
2670                 $fileMap = Memcached_DataObject::pivotGet('File', 'id', $fileIds);
2671
2672                 foreach ($notices as $notice)
2673                 {
2674                         $files = array();
2675                         $f2ps = $f2pMap[$notice->id];
2676                         foreach ($f2ps as $f2p) {
2677                             $files[] = $fileMap[$f2p->file_id];
2678                         }
2679                     $notice->_setAttachments($files);
2680                 }
2681     }
2682
2683     protected $_faves;
2684
2685     /**
2686      * All faves of this notice
2687      *
2688      * @return array Array of Fave objects
2689      */
2690
2691     function getFaves()
2692     {
2693         if (isset($this->_faves) && is_array($this->_faves)) {
2694             return $this->_faves;
2695         }
2696         $faveMap = Memcached_DataObject::listGet('Fave', 'notice_id', array($this->id));
2697         $this->_faves = $faveMap[$this->id];
2698         return $this->_faves;
2699     }
2700
2701     function _setFaves($faves)
2702     {
2703         $this->_faves = $faves;
2704     }
2705
2706     static function fillFaves(&$notices)
2707     {
2708         $ids = self::_idsOf($notices);
2709         $faveMap = Memcached_DataObject::listGet('Fave', 'notice_id', $ids);
2710         $cnt = 0;
2711         $faved = array();
2712         foreach ($faveMap as $id => $faves) {
2713             $cnt += count($faves);
2714             if (count($faves) > 0) {
2715                 $faved[] = $id;
2716             }
2717         }
2718         foreach ($notices as $notice) {
2719                 $faves = $faveMap[$notice->id];
2720             $notice->_setFaves($faves);
2721         }
2722     }
2723
2724     static function fillReplies(&$notices)
2725     {
2726         $ids = self::_idsOf($notices);
2727         $replyMap = Memcached_DataObject::listGet('Reply', 'notice_id', $ids);
2728         foreach ($notices as $notice) {
2729             $replies = $replyMap[$notice->id];
2730             $ids = array();
2731             foreach ($replies as $reply) {
2732                 $ids[] = $reply->profile_id;
2733             }
2734             $notice->_setReplies($ids);
2735         }
2736     }
2737
2738     protected $_repeats;
2739
2740     function getRepeats()
2741     {
2742         if (isset($this->_repeats) && is_array($this->_repeats)) {
2743             return $this->_repeats;
2744         }
2745         $repeatMap = Memcached_DataObject::listGet('Notice', 'repeat_of', array($this->id));
2746         $this->_repeats = $repeatMap[$this->id];
2747         return $this->_repeats;
2748     }
2749
2750     function _setRepeats($repeats)
2751     {
2752         $this->_repeats = $repeats;
2753     }
2754
2755     static function fillRepeats(&$notices)
2756     {
2757         $ids = self::_idsOf($notices);
2758         $repeatMap = Memcached_DataObject::listGet('Notice', 'repeat_of', $ids);
2759         foreach ($notices as $notice) {
2760                 $repeats = $repeatMap[$notice->id];
2761             $notice->_setRepeats($repeats);
2762         }
2763     }
2764 }