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