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