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