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