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