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