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