]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
Start/End NoticeAsActivity modifications
[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     public function getContent()
273     {
274         return $this->content;
275     }
276
277     /*
278      * Get the original representation URL of this notice.
279      */
280     public function getUrl()
281     {
282         // The risk is we start having empty urls and non-http uris...
283         // and we can't really handle any other protocol right now.
284         switch (true) {
285         case common_valid_http_url($this->url): // should we allow non-http/https URLs?
286             return $this->url;
287         case $this->isLocal():
288             // let's generate a valid link to our locally available notice on demand
289             return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
290         case common_valid_http_url($this->uri):
291             return $this->uri;
292         default:
293             common_debug('No URL available for notice: id='.$this->id);
294             throw new InvalidUrlException($this->url);
295         }
296     }
297
298     public function get_object_type($canonical=false) {
299         return $canonical
300                 ? ActivityObject::canonicalType($this->object_type)
301                 : $this->object_type;
302     }
303
304     public static function getByUri($uri)
305     {
306         $notice = new Notice();
307         $notice->uri = $uri;
308         if (!$notice->find(true)) {
309             throw new NoResultException($notice);
310         }
311         return $notice;
312     }
313
314     /**
315      * Extract #hashtags from this notice's content and save them to the database.
316      */
317     function saveTags()
318     {
319         /* extract all #hastags */
320         $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
321         if (!$count) {
322             return true;
323         }
324
325         /* Add them to the database */
326         return $this->saveKnownTags($match[1]);
327     }
328
329     /**
330      * Record the given set of hash tags in the db for this notice.
331      * Given tag strings will be normalized and checked for dupes.
332      */
333     function saveKnownTags($hashtags)
334     {
335         //turn each into their canonical tag
336         //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
337         for($i=0; $i<count($hashtags); $i++) {
338             /* elide characters we don't want in the tag */
339             $hashtags[$i] = common_canonical_tag($hashtags[$i]);
340         }
341
342         foreach(array_unique($hashtags) as $hashtag) {
343             $this->saveTag($hashtag);
344             self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
345         }
346         return true;
347     }
348
349     /**
350      * Record a single hash tag as associated with this notice.
351      * Tag format and uniqueness must be validated by caller.
352      */
353     function saveTag($hashtag)
354     {
355         $tag = new Notice_tag();
356         $tag->notice_id = $this->id;
357         $tag->tag = $hashtag;
358         $tag->created = $this->created;
359         $id = $tag->insert();
360
361         if (!$id) {
362             // TRANS: Server exception. %s are the error details.
363             throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
364                                               $last_error->message));
365             return;
366         }
367
368         // if it's saved, blow its cache
369         $tag->blowCache(false);
370     }
371
372     /**
373      * Save a new notice and push it out to subscribers' inboxes.
374      * Poster's permissions are checked before sending.
375      *
376      * @param int $profile_id Profile ID of the poster
377      * @param string $content source message text; links may be shortened
378      *                        per current user's preference
379      * @param string $source source key ('web', 'api', etc)
380      * @param array $options Associative array of optional properties:
381      *              string 'created' timestamp of notice; defaults to now
382      *              int 'is_local' source/gateway ID, one of:
383      *                  Notice::LOCAL_PUBLIC    - Local, ok to appear in public timeline
384      *                  Notice::REMOTE          - Sent from a remote service;
385      *                                            hide from public timeline but show in
386      *                                            local "and friends" timelines
387      *                  Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
388      *                  Notice::GATEWAY         - From another non-OStatus service;
389      *                                            will not appear in public views
390      *              float 'lat' decimal latitude for geolocation
391      *              float 'lon' decimal longitude for geolocation
392      *              int 'location_id' geoname identifier
393      *              int 'location_ns' geoname namespace to interpret location_id
394      *              int 'reply_to'; notice ID this is a reply to
395      *              int 'repeat_of'; notice ID this is a repeat of
396      *              string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
397      *              string 'url' permalink to notice; defaults to local notice URL
398      *              string 'rendered' rendered HTML version of content
399      *              array 'replies' list of profile URIs for reply delivery in
400      *                              place of extracting @-replies from content.
401      *              array 'groups' list of group IDs to deliver to, in place of
402      *                              extracting ! tags from content
403      *              array 'tags' list of hashtag strings to save with the notice
404      *                           in place of extracting # tags from content
405      *              array 'urls' list of attached/referred URLs to save with the
406      *                           notice in place of extracting links from content
407      *              boolean 'distribute' whether to distribute the notice, default true
408      *              string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
409      *              string 'verb' URL of the associated verb (default ActivityVerb::POST)
410      *              int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
411      *
412      * @fixme tag override
413      *
414      * @return Notice
415      * @throws ClientException
416      */
417     static function saveNew($profile_id, $content, $source, array $options=null) {
418         $defaults = array('uri' => null,
419                           'url' => null,
420                           'reply_to' => null,
421                           'repeat_of' => null,
422                           'scope' => null,
423                           'distribute' => true,
424                           'object_type' => null,
425                           'verb' => null);
426
427         if (!empty($options) && is_array($options)) {
428             $options = array_merge($defaults, $options);
429             extract($options);
430         } else {
431             extract($defaults);
432         }
433
434         if (!isset($is_local)) {
435             $is_local = Notice::LOCAL_PUBLIC;
436         }
437
438         $profile = Profile::getKV('id', $profile_id);
439         if (!$profile instanceof Profile) {
440             // TRANS: Client exception thrown when trying to save a notice for an unknown user.
441             throw new ClientException(_('Problem saving notice. Unknown user.'));
442         }
443
444         $user = User::getKV('id', $profile_id);
445         if ($user instanceof User) {
446             // Use the local user's shortening preferences, if applicable.
447             $final = $user->shortenLinks($content);
448         } else {
449             $final = common_shorten_links($content);
450         }
451
452         if (Notice::contentTooLong($final)) {
453             // TRANS: Client exception thrown if a notice contains too many characters.
454             throw new ClientException(_('Problem saving notice. Too long.'));
455         }
456
457         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
458             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
459             // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
460             throw new ClientException(_('Too many notices too fast; take a breather '.
461                                         'and post again in a few minutes.'));
462         }
463
464         if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
465             common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
466             // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
467             throw new ClientException(_('Too many duplicate messages too quickly;'.
468                                         ' take a breather and post again in a few minutes.'));
469         }
470
471         if (!$profile->hasRight(Right::NEWNOTICE)) {
472             common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
473
474             // TRANS: Client exception thrown when a user tries to post while being banned.
475             throw new ClientException(_('You are banned from posting notices on this site.'), 403);
476         }
477
478         $notice = new Notice();
479         $notice->profile_id = $profile_id;
480
481         $autosource = common_config('public', 'autosource');
482
483         // Sandboxed are non-false, but not 1, either
484
485         if (!$profile->hasRight(Right::PUBLICNOTICE) ||
486             ($source && $autosource && in_array($source, $autosource))) {
487             $notice->is_local = Notice::LOCAL_NONPUBLIC;
488         } else {
489             $notice->is_local = $is_local;
490         }
491
492         if (!empty($created)) {
493             $notice->created = $created;
494         } else {
495             $notice->created = common_sql_now();
496         }
497
498         if (!$notice->isLocal()) {
499             // Only do these checks for non-local notices. Local notices will generate these values later.
500             if (!common_valid_http_url($url)) {
501                 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
502             }
503             if (empty($uri)) {
504                 throw new ServerException('No URI for remote notice. Cannot accept that.');
505             }
506         }
507
508         $notice->content = $final;
509
510         $notice->source = $source;
511         $notice->uri = $uri;
512         $notice->url = $url;
513
514         // Get the groups here so we can figure out replies and such
515         if (!isset($groups)) {
516             $groups = User_group::idsFromText($notice->content, $profile);
517         }
518
519         $reply = null;
520
521         // Handle repeat case
522
523         if (isset($repeat_of)) {
524
525             // Check for a private one
526
527             $repeat = Notice::getKV('id', $repeat_of);
528
529             if (!($repeat instanceof Notice)) {
530                 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
531                 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
532             }
533
534             if ($profile->id == $repeat->profile_id) {
535                 // TRANS: Client error displayed when trying to repeat an own notice.
536                 throw new ClientException(_('You cannot repeat your own notice.'));
537             }
538
539             if ($repeat->scope != Notice::SITE_SCOPE &&
540                 $repeat->scope != Notice::PUBLIC_SCOPE) {
541                 // TRANS: Client error displayed when trying to repeat a non-public notice.
542                 throw new ClientException(_('Cannot repeat a private notice.'), 403);
543             }
544
545             if (!$repeat->inScope($profile)) {
546                 // The generic checks above should cover this, but let's be sure!
547                 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
548                 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
549             }
550
551             if ($profile->hasRepeated($repeat)) {
552                 // TRANS: Client error displayed when trying to repeat an already repeated notice.
553                 throw new ClientException(_('You already repeated that notice.'));
554             }
555
556             $notice->repeat_of = $repeat->id;
557             $notice->conversation = $repeat->conversation;
558         } else {
559             $reply = null;
560
561             // If $reply_to is specified, we check that it exists, and then
562             // return it if it does
563             if (!empty($reply_to)) {
564                 $reply = Notice::getKV('id', $reply_to);
565             } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
566                 // If the source lacks capability of sending the "reply_to"
567                 // metadata, let's try to find an inline replyto-reference.
568                 $reply = self::getInlineReplyTo($profile, $final);
569             }
570
571             if ($reply instanceof Notice) {
572                 if (!$reply->inScope($profile)) {
573                     // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
574                     // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
575                     throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
576                                                       $profile->nickname, $reply->id), 403);
577                 }
578
579                 // If it's a repeat, the reply_to should be to the original
580                 if ($reply->isRepeat()) {
581                     $notice->reply_to = $reply->repeat_of;
582                 } else {
583                     $notice->reply_to = $reply->id;
584                 }
585                 // But the conversation ought to be the same :)
586                 $notice->conversation = $reply->conversation;
587
588                 // If the original is private to a group, and notice has
589                 // no group specified, make it to the same group(s)
590
591                 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
592                     $groups = array();
593                     $replyGroups = $reply->getGroups();
594                     foreach ($replyGroups as $group) {
595                         if ($profile->isMember($group)) {
596                             $groups[] = $group->id;
597                         }
598                     }
599                 }
600
601                 // Scope set below
602             }
603         }
604
605         if (!empty($lat) && !empty($lon)) {
606             $notice->lat = $lat;
607             $notice->lon = $lon;
608         }
609
610         if (!empty($location_ns) && !empty($location_id)) {
611             $notice->location_id = $location_id;
612             $notice->location_ns = $location_ns;
613         }
614
615         if (!empty($rendered)) {
616             $notice->rendered = $rendered;
617         } else {
618             $notice->rendered = common_render_content($final, $notice);
619         }
620
621         if (empty($verb)) {
622             if ($notice->isRepeat()) {
623                 $notice->verb        = ActivityVerb::SHARE;
624                 $notice->object_type = ActivityObject::ACTIVITY;
625             } else {
626                 $notice->verb        = ActivityVerb::POST;
627             }
628         } else {
629             $notice->verb = $verb;
630         }
631
632         if (empty($object_type)) {
633             $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
634         } else {
635             $notice->object_type = $object_type;
636         }
637
638         if (is_null($scope) && $reply instanceof Notice) {
639             $notice->scope = $reply->scope;
640         } else {
641             $notice->scope = $scope;
642         }
643
644         $notice->scope = self::figureOutScope($profile, $groups, $notice->scope);
645
646         if (Event::handle('StartNoticeSave', array(&$notice))) {
647
648             // XXX: some of these functions write to the DB
649
650             try {
651                 $notice->insert();  // throws exception on failure
652             } catch (Exception $e) {
653                 // Let's test if we managed initial insert, which would imply
654                 // failing on some update-part (check 'insert()'). Delete if
655                 // something had been stored to the database.
656                 if (!empty($notice->id)) {
657                     $notice->delete();
658                 }
659             }
660         }
661
662         // Clear the cache for subscribed users, so they'll update at next request
663         // XXX: someone clever could prepend instead of clearing the cache
664
665         // Save per-notice metadata...
666
667         if (isset($replies)) {
668             $notice->saveKnownReplies($replies);
669         } else {
670             $notice->saveReplies();
671         }
672
673         if (isset($tags)) {
674             $notice->saveKnownTags($tags);
675         } else {
676             $notice->saveTags();
677         }
678
679         // Note: groups may save tags, so must be run after tags are saved
680         // to avoid errors on duplicates.
681         // Note: groups should always be set.
682
683         $notice->saveKnownGroups($groups);
684
685         if (isset($urls)) {
686             $notice->saveKnownUrls($urls);
687         } else {
688             $notice->saveUrls();
689         }
690
691         if ($distribute) {
692             // Prepare inbox delivery, may be queued to background.
693             $notice->distribute();
694         }
695
696         return $notice;
697     }
698
699     static function saveActivity(Activity $act, Profile $actor, array $options=array())
700     {
701         // First check if we're going to let this Activity through from the specific actor
702         if (!$actor->hasRight(Right::NEWNOTICE)) {
703             common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $actor->getNickname());
704
705             // TRANS: Client exception thrown when a user tries to post while being banned.
706             throw new ClientException(_m('You are banned from posting notices on this site.'), 403);
707         }
708         if (common_config('throttle', 'enabled') && !self::checkEditThrottle($actor->id)) {
709             common_log(LOG_WARNING, 'Excessive posting by profile #' . $actor->id . '; throttled.');
710             // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
711             throw new ClientException(_m('Too many notices too fast; take a breather '.
712                                         'and post again in a few minutes.'));
713         }
714
715         // Get ActivityObject properties
716         if (!empty($act->id)) {
717             // implied object
718             $options['uri'] = $act->id;
719             $options['url'] = $act->link;
720         } else {
721             $actobj = count($act->objects)==1 ? $act->objects[0] : null;
722             if (!is_null($actobj) && !empty($actobj->id)) {
723                 $options['uri'] = $actobj->id;
724                 if ($actobj->link) {
725                     $options['url'] = $actobj->link;
726                 } elseif (preg_match('!^https?://!', $actobj->id)) {
727                     $options['url'] = $actobj->id;
728                 }
729             }
730         }
731
732         $defaults = array(
733                           'groups'   => array(),
734                           'is_local' => self::LOCAL_PUBLIC,
735                           'mentions' => array(),
736                           'reply_to' => null,
737                           'repeat_of' => null,
738                           'scope' => null,
739                           'source' => 'unknown',
740                           'tags' => array(),
741                           'uri' => null,
742                           'url' => null,
743                           'urls' => array(),
744                           'distribute' => true);
745
746         // options will have default values when nothing has been supplied
747         $options = array_merge($defaults, $options); 
748         foreach (array_keys($defaults) as $key) {
749             // Only convert the keynames we specify ourselves from 'defaults' array into variables
750             $$key = $options[$key];
751         }
752         extract($options, EXTR_SKIP);
753
754         $stored = new Notice();
755         if (!empty($uri)) {
756             $stored->uri = $uri;
757             if ($stored->find()) {
758                 common_debug('cannot create duplicate Notice URI: '.$stored->uri);
759                 throw new Exception('Notice URI already exists');
760             }
761         }
762
763         $stored->profile_id = $actor->id;
764         $stored->source = $source;
765         $stored->uri = $uri;
766         $stored->url = $url;
767         $stored->verb = $act->verb;
768
769         // Use the local user's shortening preferences, if applicable.
770         $stored->rendered = $actor->isLocal()
771                                 ? $actor->shortenLinks($act->content)
772                                 : $act->content;
773         $stored->content = common_strip_html($stored->rendered);
774
775         $autosource = common_config('public', 'autosource');
776
777         // Sandboxed are non-false, but not 1, either
778         if (!$actor->hasRight(Right::PUBLICNOTICE) ||
779             ($source && $autosource && in_array($source, $autosource))) {
780             $stored->is_local = Notice::LOCAL_NONPUBLIC;
781         }
782
783         // Maybe a missing act-time should be fatal if the actor is not local?
784         if (!empty($act->time)) {
785             $stored->created = common_sql_date($act->time);
786         } else {
787             $stored->created = common_sql_now();
788         }
789
790         $reply = null;
791         if ($act->context instanceof ActivityContext && !empty($act->context->replyToID)) {
792             $reply = self::getKV('uri', $act->context->replyToID);
793         }
794         if (!$reply instanceof Notice && $act->target instanceof ActivityObject) {
795             $reply = self::getKV('uri', $act->target->id);
796         }
797
798         if ($reply instanceof Notice) {
799             if (!$reply->inScope($actor)) {
800                 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
801                 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
802                 throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $actor->getNickname(), $reply->id), 403);
803             }
804
805             $stored->reply_to     = $reply->id;
806             $stored->conversation = $reply->conversation;
807
808             // If the original is private to a group, and notice has no group specified,
809             // make it to the same group(s)
810             if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
811                 $groups = array();
812                 $replyGroups = $reply->getGroups();
813                 foreach ($replyGroups as $group) {
814                     if ($actor->isMember($group)) {
815                         $groups[] = $group->id;
816                     }
817                 }
818             }
819
820             if (is_null($scope)) {
821                 $scope = $reply->scope;
822             }
823         }
824
825         if ($act->context instanceof ActivityContext) {
826             $location = $act->context->location;
827             if ($location) {
828                 $stored->lat = $location->lat;
829                 $stored->lon = $location->lon;
830                 if ($location->location_id) {
831                     $stored->location_ns = $location->location_ns;
832                     $stored->location_id = $location->location_id;
833                 }
834             }
835         } else {
836             $act->context = new ActivityContext();
837         }
838
839         $stored->scope = self::figureOutScope($actor, $groups, $scope);
840
841         foreach ($act->categories as $cat) {
842             if ($cat->term) {
843                 $term = common_canonical_tag($cat->term);
844                 if (!empty($term)) {
845                     $tags[] = $term;
846                 }
847             }
848         }
849
850         foreach ($act->enclosures as $href) {
851             // @todo FIXME: Save these locally or....?
852             $urls[] = $href;
853         }
854
855         if (Event::handle('StartNoticeSave', array(&$stored))) {
856             // XXX: some of these functions write to the DB
857
858             try {
859                 $stored->insert();    // throws exception on error
860
861                 $object = null;
862                 Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
863                 if (empty($object)) {
864                     throw new ServerException('No object from StoreActivityObject '.$stored->uri . ': '.$act->asString());
865                 }
866                 $orig = clone($stored);
867                 $stored->object_type = ActivityUtils::resolveUri($object->getObjectType(), true);
868                 $stored->update($orig);
869             } catch (Exception $e) {
870                 if (empty($stored->id)) {
871                     common_debug('Failed to save stored object entry in database ('.$e->getMessage().')');
872                 } else {
873                     common_debug('Failed to store activity object in database ('.$e->getMessage().'), deleting notice id '.$stored->id);
874                     $stored->delete();
875                 }
876                 throw $e;
877             }
878         }
879         if (!$stored instanceof Notice) {
880             throw new ServerException('StartNoticeSave did not give back a Notice');
881         }
882
883         // Save per-notice metadata...
884         $mentions = array();
885         $groups   = array();
886
887         // This event lets plugins filter out non-local recipients (attentions we don't care about)
888         // Used primarily for OStatus (and if we don't federate, all attentions would be local anyway)
889         Event::handle('GetLocalAttentions', array($actor, $act->context->attention, &$mentions, &$groups));
890
891         if (!empty($mentions)) {
892             $stored->saveKnownReplies($mentions);
893         } else {
894             $stored->saveReplies();
895         }
896
897         if (!empty($tags)) {
898             $stored->saveKnownTags($tags);
899         } else {
900             $stored->saveTags();
901         }
902
903         // Note: groups may save tags, so must be run after tags are saved
904         // to avoid errors on duplicates.
905         // Note: groups should always be set.
906
907         $stored->saveKnownGroups($groups);
908
909         if (!empty($urls)) {
910             $stored->saveKnownUrls($urls);
911         } else {
912             $stored->saveUrls();
913         }
914
915         if ($distribute) {
916             // Prepare inbox delivery, may be queued to background.
917             $stored->distribute();
918         }
919         
920         return $stored;
921     }
922
923     static public function figureOutScope(Profile $actor, array $groups, $scope=null) {
924         if (is_null($scope)) {
925             $scope = self::defaultScope();
926         }
927
928         // For private streams
929         try {
930             $user = $actor->getUser();
931             // FIXME: We can't do bit comparison with == (Legacy StatusNet thing. Let's keep it for now.)
932             if ($user->private_stream && ($scope == Notice::PUBLIC_SCOPE || $scope == Notice::SITE_SCOPE)) {
933                 $scope |= Notice::FOLLOWER_SCOPE;
934             }
935         } catch (NoSuchUserException $e) {
936             // TODO: Not a local user, so we don't know about scope preferences... yet!
937         }
938
939         // Force the scope for private groups
940         foreach ($groups as $group_id) {
941             $group = User_group::staticGet('id', $group_id);
942             if ($group instanceof User_group) {
943                 if ($group->force_scope) {
944                     $scope |= Notice::GROUP_SCOPE;
945                     break;
946                 }
947             }
948         }
949
950         return $scope;
951     }
952
953     function blowOnInsert($conversation = false)
954     {
955         $this->blowStream('profile:notice_ids:%d', $this->profile_id);
956
957         if ($this->isPublic()) {
958             $this->blowStream('public');
959         }
960
961         self::blow('notice:list-ids:conversation:%s', $this->conversation);
962         self::blow('conversation:notice_count:%d', $this->conversation);
963
964         if ($this->isRepeat()) {
965             // XXX: we should probably only use one of these
966             $this->blowStream('notice:repeats:%d', $this->repeat_of);
967             self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
968         }
969
970         $original = Notice::getKV('id', $this->repeat_of);
971
972         if ($original instanceof Notice) {
973             $originalUser = User::getKV('id', $original->profile_id);
974             if ($originalUser instanceof User) {
975                 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
976             }
977         }
978
979         $profile = Profile::getKV($this->profile_id);
980
981         if ($profile instanceof Profile) {
982             $profile->blowNoticeCount();
983         }
984
985         $ptags = $this->getProfileTags();
986         foreach ($ptags as $ptag) {
987             $ptag->blowNoticeStreamCache();
988         }
989     }
990
991     /**
992      * Clear cache entries related to this notice at delete time.
993      * Necessary to avoid breaking paging on public, profile timelines.
994      */
995     function blowOnDelete()
996     {
997         $this->blowOnInsert();
998
999         self::blow('profile:notice_ids:%d;last', $this->profile_id);
1000
1001         if ($this->isPublic()) {
1002             self::blow('public;last');
1003         }
1004
1005         self::blow('fave:by_notice', $this->id);
1006
1007         if ($this->conversation) {
1008             // In case we're the first, will need to calc a new root.
1009             self::blow('notice:conversation_root:%d', $this->conversation);
1010         }
1011
1012         $ptags = $this->getProfileTags();
1013         foreach ($ptags as $ptag) {
1014             $ptag->blowNoticeStreamCache(true);
1015         }
1016     }
1017
1018     function blowStream()
1019     {
1020         $c = self::memcache();
1021
1022         if (empty($c)) {
1023             return false;
1024         }
1025
1026         $args = func_get_args();
1027
1028         $format = array_shift($args);
1029
1030         $keyPart = vsprintf($format, $args);
1031
1032         $cacheKey = Cache::key($keyPart);
1033         
1034         $c->delete($cacheKey);
1035
1036         // delete the "last" stream, too, if this notice is
1037         // older than the top of that stream
1038
1039         $lastKey = $cacheKey.';last';
1040
1041         $lastStr = $c->get($lastKey);
1042
1043         if ($lastStr !== false) {
1044             $window     = explode(',', $lastStr);
1045             $lastID     = $window[0];
1046             $lastNotice = Notice::getKV('id', $lastID);
1047             if (!$lastNotice instanceof Notice // just weird
1048                 || strtotime($lastNotice->created) >= strtotime($this->created)) {
1049                 $c->delete($lastKey);
1050             }
1051         }
1052     }
1053
1054     /** save all urls in the notice to the db
1055      *
1056      * follow redirects and save all available file information
1057      * (mimetype, date, size, oembed, etc.)
1058      *
1059      * @return void
1060      */
1061     function saveUrls() {
1062         if (common_config('attachments', 'process_links')) {
1063             common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
1064         }
1065     }
1066
1067     /**
1068      * Save the given URLs as related links/attachments to the db
1069      *
1070      * follow redirects and save all available file information
1071      * (mimetype, date, size, oembed, etc.)
1072      *
1073      * @return void
1074      */
1075     function saveKnownUrls($urls)
1076     {
1077         if (common_config('attachments', 'process_links')) {
1078             // @fixme validation?
1079             foreach (array_unique($urls) as $url) {
1080                 try {
1081                     File::processNew($url, $this->id);
1082                 } catch (ServerException $e) {
1083                     // Could not save URL. Log it?
1084                 }
1085             }
1086         }
1087     }
1088
1089     /**
1090      * @private callback
1091      */
1092     function saveUrl($url, $notice_id) {
1093         try {
1094             File::processNew($url, $notice_id);
1095         } catch (ServerException $e) {
1096             // Could not save URL. Log it?
1097         }
1098     }
1099
1100     static function checkDupes($profile_id, $content) {
1101         $profile = Profile::getKV($profile_id);
1102         if (!$profile instanceof Profile) {
1103             return false;
1104         }
1105         $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
1106         if (!empty($notice)) {
1107             $last = 0;
1108             while ($notice->fetch()) {
1109                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
1110                     return true;
1111                 } else if ($notice->content == $content) {
1112                     return false;
1113                 }
1114             }
1115         }
1116         // If we get here, oldest item in cache window is not
1117         // old enough for dupe limit; do direct check against DB
1118         $notice = new Notice();
1119         $notice->profile_id = $profile_id;
1120         $notice->content = $content;
1121         $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
1122         $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
1123
1124         $cnt = $notice->count();
1125         return ($cnt == 0);
1126     }
1127
1128     static function checkEditThrottle($profile_id) {
1129         $profile = Profile::getKV($profile_id);
1130         if (!$profile instanceof Profile) {
1131             return false;
1132         }
1133         // Get the Nth notice
1134         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
1135         if ($notice && $notice->fetch()) {
1136             // If the Nth notice was posted less than timespan seconds ago
1137             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
1138                 // Then we throttle
1139                 return false;
1140             }
1141         }
1142         // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
1143         return true;
1144     }
1145
1146         protected $_attachments = array();
1147         
1148     function attachments() {
1149                 if (isset($this->_attachments[$this->id])) {
1150             return $this->_attachments[$this->id];
1151         }
1152                 
1153         $f2ps = File_to_post::listGet('post_id', array($this->id));
1154                 
1155                 $ids = array();
1156                 
1157                 foreach ($f2ps[$this->id] as $f2p) {
1158             $ids[] = $f2p->file_id;    
1159         }
1160                 
1161                 $files = File::multiGet('id', $ids);
1162
1163                 $this->_attachments[$this->id] = $files->fetchAll();
1164                 
1165         return $this->_attachments[$this->id];
1166     }
1167
1168         function _setAttachments($attachments)
1169         {
1170             $this->_attachments[$this->id] = $attachments;
1171         }
1172
1173     function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
1174     {
1175         $stream = new PublicNoticeStream();
1176         return $stream->getNotices($offset, $limit, $since_id, $max_id);
1177     }
1178
1179
1180     function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
1181     {
1182         $stream = new ConversationNoticeStream($id);
1183
1184         return $stream->getNotices($offset, $limit, $since_id, $max_id);
1185     }
1186
1187     /**
1188      * Is this notice part of an active conversation?
1189      *
1190      * @return boolean true if other messages exist in the same
1191      *                 conversation, false if this is the only one
1192      */
1193     function hasConversation()
1194     {
1195         if (!empty($this->conversation)) {
1196             $conversation = Notice::conversationStream(
1197                 $this->conversation,
1198                 1,
1199                 1
1200             );
1201
1202             if ($conversation->N > 0) {
1203                 return true;
1204             }
1205         }
1206         return false;
1207     }
1208
1209     /**
1210      * Grab the earliest notice from this conversation.
1211      *
1212      * @return Notice or null
1213      */
1214     function conversationRoot($profile=-1)
1215     {
1216         // XXX: can this happen?
1217
1218         if (empty($this->conversation)) {
1219             return null;
1220         }
1221
1222         // Get the current profile if not specified
1223
1224         if (is_int($profile) && $profile == -1) {
1225             $profile = Profile::current();
1226         }
1227
1228         // If this notice is out of scope, no root for you!
1229
1230         if (!$this->inScope($profile)) {
1231             return null;
1232         }
1233
1234         // If this isn't a reply to anything, then it's its own
1235         // root.
1236
1237         if (empty($this->reply_to)) {
1238             return $this;
1239         }
1240         
1241         if (is_null($profile)) {
1242             $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1243         } else {
1244             $keypart = sprintf('notice:conversation_root:%d:%d',
1245                                $this->id,
1246                                $profile->id);
1247         }
1248             
1249         $root = self::cacheGet($keypart);
1250
1251         if ($root !== false && $root->inScope($profile)) {
1252             return $root;
1253         }
1254
1255         $last = $this;
1256         while (true) {
1257             try {
1258                 $parent = $last->getParent();
1259                 if ($parent->inScope($profile)) {
1260                     $last = $parent;
1261                     continue;
1262                 }
1263             } catch (Exception $e) {
1264                 // Latest notice has no parent
1265             }
1266             // No parent, or parent out of scope
1267             $root = $last;
1268             break;
1269         }
1270
1271         self::cacheSet($keypart, $root);
1272
1273         return $root;
1274     }
1275
1276     /**
1277      * Pull up a full list of local recipients who will be getting
1278      * this notice in their inbox. Results will be cached, so don't
1279      * change the input data wily-nilly!
1280      *
1281      * @param array $groups optional list of Group objects;
1282      *              if left empty, will be loaded from group_inbox records
1283      * @param array $recipient optional list of reply profile ids
1284      *              if left empty, will be loaded from reply records
1285      * @return array associating recipient user IDs with an inbox source constant
1286      */
1287     function whoGets(array $groups=null, array $recipients=null)
1288     {
1289         $c = self::memcache();
1290
1291         if (!empty($c)) {
1292             $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1293             if ($ni !== false) {
1294                 return $ni;
1295             }
1296         }
1297
1298         if (is_null($recipients)) {
1299             $recipients = $this->getReplies();
1300         }
1301
1302         $ni = array();
1303
1304         // Give plugins a chance to add folks in at start...
1305         if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1306
1307             $users = $this->getSubscribedUsers();
1308             foreach ($users as $id) {
1309                 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1310             }
1311
1312             if (is_null($groups)) {
1313                 $groups = $this->getGroups();
1314             }
1315             foreach ($groups as $group) {
1316                 $users = $group->getUserMembers();
1317                 foreach ($users as $id) {
1318                     if (!array_key_exists($id, $ni)) {
1319                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1320                     }
1321                 }
1322             }
1323
1324             $ptAtts = $this->getAttentionsFromProfileTags();
1325             foreach ($ptAtts as $key=>$val) {
1326                 if (!array_key_exists($key, $ni)) {
1327                     $ni[$key] = $val;
1328                 }
1329             }
1330
1331             foreach ($recipients as $recipient) {
1332                 if (!array_key_exists($recipient, $ni)) {
1333                     $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1334                 }
1335             }
1336
1337             // Exclude any deleted, non-local, or blocking recipients.
1338             $profile = $this->getProfile();
1339             $originalProfile = null;
1340             if ($this->isRepeat()) {
1341                 // Check blocks against the original notice's poster as well.
1342                 $original = Notice::getKV('id', $this->repeat_of);
1343                 if ($original instanceof Notice) {
1344                     $originalProfile = $original->getProfile();
1345                 }
1346             }
1347
1348             foreach ($ni as $id => $source) {
1349                 try {
1350                     $user = User::getKV('id', $id);
1351                     if (!$user instanceof User ||
1352                         $user->hasBlocked($profile) ||
1353                         ($originalProfile && $user->hasBlocked($originalProfile))) {
1354                         unset($ni[$id]);
1355                     }
1356                 } catch (UserNoProfileException $e) {
1357                     // User doesn't have a profile; invalid; skip them.
1358                     unset($ni[$id]);
1359                 }
1360             }
1361
1362             // Give plugins a chance to filter out...
1363             Event::handle('EndNoticeWhoGets', array($this, &$ni));
1364         }
1365
1366         if (!empty($c)) {
1367             // XXX: pack this data better
1368             $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1369         }
1370
1371         return $ni;
1372     }
1373
1374     function getSubscribedUsers()
1375     {
1376         $user = new User();
1377
1378         if(common_config('db','quote_identifiers'))
1379           $user_table = '"user"';
1380         else $user_table = 'user';
1381
1382         $qry =
1383           'SELECT id ' .
1384           'FROM '. $user_table .' JOIN subscription '.
1385           'ON '. $user_table .'.id = subscription.subscriber ' .
1386           'WHERE subscription.subscribed = %d ';
1387
1388         $user->query(sprintf($qry, $this->profile_id));
1389
1390         $ids = array();
1391
1392         while ($user->fetch()) {
1393             $ids[] = $user->id;
1394         }
1395
1396         $user->free();
1397
1398         return $ids;
1399     }
1400
1401     function getProfileTags()
1402     {
1403         $profile = $this->getProfile();
1404         $list    = $profile->getOtherTags($profile);
1405         $ptags   = array();
1406
1407         while($list->fetch()) {
1408             $ptags[] = clone($list);
1409         }
1410
1411         return $ptags;
1412     }
1413
1414     public function getAttentionsFromProfileTags()
1415     {
1416         $ni = array();
1417         $ptags = $this->getProfileTags();
1418         foreach ($ptags as $ptag) {
1419             $users = $ptag->getUserSubscribers();
1420             foreach ($users as $id) {
1421                 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1422             }
1423         }
1424         return $ni;
1425     }
1426
1427     /**
1428      * Record this notice to the given group inboxes for delivery.
1429      * Overrides the regular parsing of !group markup.
1430      *
1431      * @param string $group_ids
1432      * @fixme might prefer URIs as identifiers, as for replies?
1433      *        best with generalizations on user_group to support
1434      *        remote groups better.
1435      */
1436     function saveKnownGroups($group_ids)
1437     {
1438         if (!is_array($group_ids)) {
1439             // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1440             throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1441         }
1442
1443         $groups = array();
1444         foreach (array_unique($group_ids) as $id) {
1445             $group = User_group::getKV('id', $id);
1446             if ($group instanceof User_group) {
1447                 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1448                 $result = $this->addToGroupInbox($group);
1449                 if (!$result) {
1450                     common_log_db_error($gi, 'INSERT', __FILE__);
1451                 }
1452
1453                 if (common_config('group', 'addtag')) {
1454                     // we automatically add a tag for every group name, too
1455
1456                     $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1457                                                      'notice_id' => $this->id));
1458
1459                     if (is_null($tag)) {
1460                         $this->saveTag($group->nickname);
1461                     }
1462                 }
1463
1464                 $groups[] = clone($group);
1465             } else {
1466                 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1467             }
1468         }
1469
1470         return $groups;
1471     }
1472
1473     function addToGroupInbox(User_group $group)
1474     {
1475         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1476                                          'notice_id' => $this->id));
1477
1478         if (!$gi instanceof Group_inbox) {
1479
1480             $gi = new Group_inbox();
1481
1482             $gi->group_id  = $group->id;
1483             $gi->notice_id = $this->id;
1484             $gi->created   = $this->created;
1485
1486             $result = $gi->insert();
1487
1488             if (!$result) {
1489                 common_log_db_error($gi, 'INSERT', __FILE__);
1490                 // TRANS: Server exception thrown when an update for a group inbox fails.
1491                 throw new ServerException(_('Problem saving group inbox.'));
1492             }
1493
1494             self::blow('user_group:notice_ids:%d', $gi->group_id);
1495         }
1496
1497         return true;
1498     }
1499
1500     /**
1501      * Save reply records indicating that this notice needs to be
1502      * delivered to the local users with the given URIs.
1503      *
1504      * Since this is expected to be used when saving foreign-sourced
1505      * messages, we won't deliver to any remote targets as that's the
1506      * source service's responsibility.
1507      *
1508      * Mail notifications etc will be handled later.
1509      *
1510      * @param array  $uris   Array of unique identifier URIs for recipients
1511      */
1512     function saveKnownReplies(array $uris)
1513     {
1514         if (empty($uris)) {
1515             return;
1516         }
1517
1518         $sender = Profile::getKV($this->profile_id);
1519
1520         foreach (array_unique($uris) as $uri) {
1521             try {
1522                 $profile = Profile::fromUri($uri);
1523             } catch (UnknownUriException $e) {
1524                 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1525                 continue;
1526             }
1527
1528             if ($profile->hasBlocked($sender)) {
1529                 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1530                 continue;
1531             }
1532
1533             $this->saveReply($profile->id);
1534             self::blow('reply:stream:%d', $profile->id);
1535         }
1536
1537         return;
1538     }
1539
1540     /**
1541      * Pull @-replies from this message's content in StatusNet markup format
1542      * and save reply records indicating that this message needs to be
1543      * delivered to those users.
1544      *
1545      * Mail notifications to local profiles will be sent later.
1546      *
1547      * @return array of integer profile IDs
1548      */
1549
1550     function saveReplies()
1551     {
1552         // Don't save reply data for repeats
1553
1554         if ($this->isRepeat()) {
1555             return array();
1556         }
1557
1558         $sender = $this->getProfile();
1559
1560         $replied = array();
1561
1562         // If it's a reply, save for the replied-to author
1563         try {
1564             $parent = $this->getParent();
1565             $parentauthor = $parent->getProfile();
1566             $this->saveReply($parentauthor->id);
1567             $replied[$parentauthor->id] = 1;
1568             self::blow('reply:stream:%d', $parentauthor->id);
1569         } catch (Exception $e) {
1570             // Not a reply, since it has no parent!
1571         }
1572
1573         // @todo ideally this parser information would only
1574         // be calculated once.
1575
1576         $mentions = common_find_mentions($this->content, $this);
1577
1578         // store replied only for first @ (what user/notice what the reply directed,
1579         // we assume first @ is it)
1580
1581         foreach ($mentions as $mention) {
1582
1583             foreach ($mention['mentioned'] as $mentioned) {
1584
1585                 // skip if they're already covered
1586
1587                 if (!empty($replied[$mentioned->id])) {
1588                     continue;
1589                 }
1590
1591                 // Don't save replies from blocked profile to local user
1592
1593                 $mentioned_user = User::getKV('id', $mentioned->id);
1594                 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1595                     continue;
1596                 }
1597
1598                 $this->saveReply($mentioned->id);
1599                 $replied[$mentioned->id] = 1;
1600                 self::blow('reply:stream:%d', $mentioned->id);
1601             }
1602         }
1603
1604         $recipientIds = array_keys($replied);
1605
1606         return $recipientIds;
1607     }
1608
1609     function saveReply($profileId)
1610     {
1611         $reply = new Reply();
1612
1613         $reply->notice_id  = $this->id;
1614         $reply->profile_id = $profileId;
1615         $reply->modified   = $this->created;
1616
1617         $reply->insert();
1618
1619         return $reply;
1620     }
1621
1622     protected $_replies = array();
1623
1624     /**
1625      * Pull the complete list of @-reply targets for this notice.
1626      *
1627      * @return array of integer profile ids
1628      */
1629     function getReplies()
1630     {
1631         if (isset($this->_replies[$this->id])) {
1632             return $this->_replies[$this->id];
1633         }
1634
1635         $replyMap = Reply::listGet('notice_id', array($this->id));
1636
1637         $ids = array();
1638
1639         foreach ($replyMap[$this->id] as $reply) {
1640             $ids[] = $reply->profile_id;
1641         }
1642
1643         $this->_replies[$this->id] = $ids;
1644
1645         return $ids;
1646     }
1647
1648     function _setReplies($replies)
1649     {
1650         $this->_replies[$this->id] = $replies;
1651     }
1652
1653     /**
1654      * Pull the complete list of @-reply targets for this notice.
1655      *
1656      * @return array of Profiles
1657      */
1658     function getReplyProfiles()
1659     {
1660         $ids = $this->getReplies();
1661         
1662         $profiles = Profile::multiGet('id', $ids);
1663         
1664         return $profiles->fetchAll();
1665     }
1666
1667     /**
1668      * Send e-mail notifications to local @-reply targets.
1669      *
1670      * Replies must already have been saved; this is expected to be run
1671      * from the distrib queue handler.
1672      */
1673     function sendReplyNotifications()
1674     {
1675         // Don't send reply notifications for repeats
1676
1677         if ($this->isRepeat()) {
1678             return array();
1679         }
1680
1681         $recipientIds = $this->getReplies();
1682         if (Event::handle('StartNotifyMentioned', array($this, &$recipientIds))) {
1683             require_once INSTALLDIR.'/lib/mail.php';
1684
1685             foreach ($recipientIds as $recipientId) {
1686                 $user = User::getKV('id', $recipientId);
1687                 if ($user instanceof User) {
1688                     mail_notify_attn($user, $this);
1689                 }
1690             }
1691             Event::handle('EndNotifyMentioned', array($this, $recipientIds));
1692         }
1693     }
1694
1695     /**
1696      * Pull list of groups this notice needs to be delivered to,
1697      * as previously recorded by saveKnownGroups().
1698      *
1699      * @return array of Group objects
1700      */
1701     
1702     protected $_groups = array();
1703     
1704     function getGroups()
1705     {
1706         // Don't save groups for repeats
1707
1708         if (!empty($this->repeat_of)) {
1709             return array();
1710         }
1711         
1712         if (isset($this->_groups[$this->id])) {
1713             return $this->_groups[$this->id];
1714         }
1715         
1716         $gis = Group_inbox::listGet('notice_id', array($this->id));
1717
1718         $ids = array();
1719
1720                 foreach ($gis[$this->id] as $gi)
1721                 {
1722                     $ids[] = $gi->group_id;
1723                 }
1724                 
1725                 $groups = User_group::multiGet('id', $ids);
1726                 
1727                 $this->_groups[$this->id] = $groups->fetchAll();
1728                 
1729                 return $this->_groups[$this->id];
1730     }
1731     
1732     function _setGroups($groups)
1733     {
1734         $this->_groups[$this->id] = $groups;
1735     }
1736
1737     /**
1738      * Convert a notice into an activity for export.
1739      *
1740      * @param Profile $scoped   The currently logged in/scoped profile
1741      *
1742      * @return Activity activity object representing this Notice.
1743      */
1744
1745     function asActivity(Profile $scoped=null)
1746     {
1747         $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1748
1749         if ($act instanceof Activity) {
1750             return $act;
1751         }
1752         $act = new Activity();
1753
1754         if (Event::handle('StartNoticeAsActivity', array($this, $act, $scoped))) {
1755
1756             $act->id      = $this->uri;
1757             $act->time    = strtotime($this->created);
1758             try {
1759                 $act->link    = $this->getUrl();
1760             } catch (InvalidUrlException $e) {
1761                 // The notice is probably a share or similar, which don't
1762                 // have a representational URL of their own.
1763             }
1764             $act->content = common_xml_safe_str($this->rendered);
1765
1766             $profile = $this->getProfile();
1767
1768             $act->actor            = $profile->asActivityObject();
1769             $act->actor->extra[]   = $profile->profileInfo($scoped);
1770
1771             $act->verb = $this->verb;
1772
1773             if ($this->repeat_of) {
1774                 $repeated = Notice::getKV('id', $this->repeat_of);
1775                 if ($repeated instanceof Notice) {
1776                     $act->objects[] = $repeated->asActivity($scoped);
1777                 }
1778             } else {
1779                 $act->objects[] = $this->asActivityObject();
1780             }
1781
1782             // XXX: should this be handled by default processing for object entry?
1783
1784             // Categories
1785
1786             $tags = $this->getTags();
1787
1788             foreach ($tags as $tag) {
1789                 $cat       = new AtomCategory();
1790                 $cat->term = $tag;
1791
1792                 $act->categories[] = $cat;
1793             }
1794
1795             // Enclosures
1796             // XXX: use Atom Media and/or File activity objects instead
1797
1798             $attachments = $this->attachments();
1799
1800             foreach ($attachments as $attachment) {
1801                 // Save local attachments
1802                 if (!empty($attachment->filename)) {
1803                     $act->attachments[] = ActivityObject::fromFile($attachment);
1804                 }
1805             }
1806
1807             $ctx = new ActivityContext();
1808
1809             try {
1810                 $reply = $this->getParent();
1811                 $ctx->replyToID  = $reply->getUri();
1812                 $ctx->replyToUrl = $reply->getUrl();
1813             } catch (Exception $e) {
1814                 // This is not a reply to something
1815             }
1816
1817             $ctx->location = $this->getLocation();
1818
1819             $conv = null;
1820
1821             if (!empty($this->conversation)) {
1822                 $conv = Conversation::getKV('id', $this->conversation);
1823                 if ($conv instanceof Conversation) {
1824                     $ctx->conversation = $conv->uri;
1825                 }
1826             }
1827
1828             $reply_ids = $this->getReplies();
1829
1830             foreach ($reply_ids as $id) {
1831                 $rprofile = Profile::getKV('id', $id);
1832                 if ($rprofile instanceof Profile) {
1833                     $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1834                 }
1835             }
1836
1837             $groups = $this->getGroups();
1838
1839             foreach ($groups as $group) {
1840                 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1841             }
1842
1843             switch ($this->scope) {
1844             case Notice::PUBLIC_SCOPE:
1845                 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1846                 break;
1847             case Notice::FOLLOWER_SCOPE:
1848                 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1849                 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1850                 break;
1851             }
1852
1853             $act->context = $ctx;
1854
1855             $source = $this->getSource();
1856
1857             if ($source instanceof Notice_source) {
1858                 $act->generator = ActivityObject::fromNoticeSource($source);
1859             }
1860
1861             // Source
1862
1863             $atom_feed = $profile->getAtomFeed();
1864
1865             if (!empty($atom_feed)) {
1866
1867                 $act->source = new ActivitySource();
1868
1869                 // XXX: we should store the actual feed ID
1870
1871                 $act->source->id = $atom_feed;
1872
1873                 // XXX: we should store the actual feed title
1874
1875                 $act->source->title = $profile->getBestName();
1876
1877                 $act->source->links['alternate'] = $profile->profileurl;
1878                 $act->source->links['self']      = $atom_feed;
1879
1880                 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1881
1882                 $notice = $profile->getCurrentNotice();
1883
1884                 if ($notice instanceof Notice) {
1885                     $act->source->updated = self::utcDate($notice->created);
1886                 }
1887
1888                 $user = User::getKV('id', $profile->id);
1889
1890                 if ($user instanceof User) {
1891                     $act->source->links['license'] = common_config('license', 'url');
1892                 }
1893             }
1894
1895             if ($this->isLocal()) {
1896                 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1897                                                                            'format' => 'atom'));
1898                 $act->editLink = $act->selfLink;
1899             }
1900
1901             Event::handle('EndNoticeAsActivity', array($this, $act, $scoped));
1902         }
1903
1904         self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1905
1906         return $act;
1907     }
1908
1909     // This has gotten way too long. Needs to be sliced up into functional bits
1910     // or ideally exported to a utility class.
1911
1912     function asAtomEntry($namespace=false,
1913                          $source=false,
1914                          $author=true,
1915                          Profile $scoped=null)
1916     {
1917         $act = $this->asActivity($scoped);
1918         $act->extra[] = $this->noticeInfo($scoped);
1919         return $act->asString($namespace, $author, $source);
1920     }
1921
1922     /**
1923      * Extra notice info for atom entries
1924      *
1925      * Clients use some extra notice info in the atom stream.
1926      * This gives it to them.
1927      *
1928      * @param Profile $scoped   The currently logged in/scoped profile
1929      *
1930      * @return array representation of <statusnet:notice_info> element
1931      */
1932
1933     function noticeInfo(Profile $scoped=null)
1934     {
1935         // local notice ID (useful to clients for ordering)
1936
1937         $noticeInfoAttr = array('local_id' => $this->id);
1938
1939         // notice source
1940
1941         $ns = $this->getSource();
1942
1943         if ($ns instanceof Notice_source) {
1944             $noticeInfoAttr['source'] =  $ns->code;
1945             if (!empty($ns->url)) {
1946                 $noticeInfoAttr['source_link'] = $ns->url;
1947                 if (!empty($ns->name)) {
1948                     $noticeInfoAttr['source'] =  '<a href="'
1949                         . htmlspecialchars($ns->url)
1950                         . '" rel="nofollow">'
1951                         . htmlspecialchars($ns->name)
1952                         . '</a>';
1953                 }
1954             }
1955         }
1956
1957         // favorite and repeated
1958
1959         if ($scoped instanceof Profile) {
1960             $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
1961         }
1962
1963         if (!empty($this->repeat_of)) {
1964             $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1965         }
1966
1967         Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
1968
1969         return array('statusnet:notice_info', $noticeInfoAttr, null);
1970     }
1971
1972     /**
1973      * Returns an XML string fragment with a reference to a notice as an
1974      * Activity Streams noun object with the given element type.
1975      *
1976      * Assumes that 'activity' namespace has been previously defined.
1977      *
1978      * @param string $element one of 'subject', 'object', 'target'
1979      * @return string
1980      */
1981
1982     function asActivityNoun($element)
1983     {
1984         $noun = $this->asActivityObject();
1985         return $noun->asString('activity:' . $element);
1986     }
1987
1988     public function asActivityObject()
1989     {
1990         $object = new ActivityObject();
1991
1992         if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
1993             $object->type    = $this->object_type ?: ActivityObject::NOTE;
1994             $object->id      = $this->getUri();
1995             $object->title   = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
1996             $object->content = $this->rendered;
1997             $object->link    = $this->getUrl();
1998
1999             $object->extra[] = array('status_net', array('notice_id' => $this->id));
2000
2001             Event::handle('EndActivityObjectFromNotice', array($this, &$object));
2002         }
2003
2004         return $object;
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             common_log_db_error($this, 'INSERT', __FILE__);
2335             // TRANS: Server exception thrown when a stored object entry cannot be saved.
2336             throw new ServerException('Could not save Notice');
2337         }
2338
2339         // Profile::hasRepeated() abuses pkeyGet(), so we
2340         // have to clear manually
2341         if (!empty($this->repeat_of)) {
2342             $c = self::memcache();
2343             if (!empty($c)) {
2344                 $ck = self::multicacheKey('Notice',
2345                                           array('profile_id' => $this->profile_id,
2346                                                 'repeat_of' => $this->repeat_of));
2347                 $c->delete($ck);
2348             }
2349         }
2350
2351         // Update possibly ID-dependent columns: URI, conversation
2352         // (now that INSERT has added the notice's local id)
2353         $orig = clone($this);
2354         $changed = false;
2355
2356         // We can only get here if it's a local notice, since remote notices
2357         // should've bailed out earlier due to lacking a URI.
2358         if (empty($this->uri)) {
2359             $this->uri = sprintf('%s%s=%d:%s=%s',
2360                                 TagURI::mint(),
2361                                 'noticeId', $this->id,
2362                                 'objectType', $this->get_object_type(true));
2363             $changed = true;
2364         }
2365
2366         // If it's not part of a conversation, it's
2367         // the beginning of a new conversation.
2368         if (empty($this->conversation)) {
2369             $conv = Conversation::create($this);
2370             $this->conversation = $conv->id;
2371             $changed = true;
2372         }
2373
2374         if ($changed && $this->update($orig) === false) {
2375             common_log_db_error($notice, 'UPDATE', __FILE__);
2376             // TRANS: Server exception thrown when a notice cannot be updated.
2377             throw new ServerException(_('Problem saving notice.'));
2378         }
2379
2380         $this->blowOnInsert();
2381
2382         return $result;
2383     }
2384
2385     /**
2386      * Get the source of the notice
2387      *
2388      * @return Notice_source $ns A notice source object. 'code' is the only attribute
2389      *                           guaranteed to be populated.
2390      */
2391     function getSource()
2392     {
2393         $ns = new Notice_source();
2394         if (!empty($this->source)) {
2395             switch ($this->source) {
2396             case 'web':
2397             case 'xmpp':
2398             case 'mail':
2399             case 'omb':
2400             case 'system':
2401             case 'api':
2402                 $ns->code = $this->source;
2403                 break;
2404             default:
2405                 $ns = Notice_source::getKV($this->source);
2406                 if (!$ns) {
2407                     $ns = new Notice_source();
2408                     $ns->code = $this->source;
2409                     $app = Oauth_application::getKV('name', $this->source);
2410                     if ($app) {
2411                         $ns->name = $app->name;
2412                         $ns->url  = $app->source_url;
2413                     }
2414                 }
2415                 break;
2416             }
2417         }
2418         return $ns;
2419     }
2420
2421     /**
2422      * Determine whether the notice was locally created
2423      *
2424      * @return boolean locality
2425      */
2426
2427     public function isLocal()
2428     {
2429         return ($this->is_local == Notice::LOCAL_PUBLIC ||
2430                 $this->is_local == Notice::LOCAL_NONPUBLIC);
2431     }
2432
2433     public function isRepeat()
2434     {
2435         return !empty($this->repeat_of);
2436     }
2437
2438     /**
2439      * Get the list of hash tags saved with this notice.
2440      *
2441      * @return array of strings
2442      */
2443     public function getTags()
2444     {
2445         $tags = array();
2446
2447         $keypart = sprintf('notice:tags:%d', $this->id);
2448
2449         $tagstr = self::cacheGet($keypart);
2450
2451         if ($tagstr !== false) {
2452             $tags = explode(',', $tagstr);
2453         } else {
2454             $tag = new Notice_tag();
2455             $tag->notice_id = $this->id;
2456             if ($tag->find()) {
2457                 while ($tag->fetch()) {
2458                     $tags[] = $tag->tag;
2459                 }
2460             }
2461             self::cacheSet($keypart, implode(',', $tags));
2462         }
2463
2464         return $tags;
2465     }
2466
2467     static private function utcDate($dt)
2468     {
2469         $dateStr = date('d F Y H:i:s', strtotime($dt));
2470         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2471         return $d->format(DATE_W3C);
2472     }
2473
2474     /**
2475      * Look up the creation timestamp for a given notice ID, even
2476      * if it's been deleted.
2477      *
2478      * @param int $id
2479      * @return mixed string recorded creation timestamp, or false if can't be found
2480      */
2481     public static function getAsTimestamp($id)
2482     {
2483         if (!$id) {
2484             return false;
2485         }
2486
2487         $notice = Notice::getKV('id', $id);
2488         if ($notice) {
2489             return $notice->created;
2490         }
2491
2492         $deleted = Deleted_notice::getKV('id', $id);
2493         if ($deleted) {
2494             return $deleted->created;
2495         }
2496
2497         return false;
2498     }
2499
2500     /**
2501      * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2502      * parameter, matching notices posted after the given one (exclusive).
2503      *
2504      * If the referenced notice can't be found, will return false.
2505      *
2506      * @param int $id
2507      * @param string $idField
2508      * @param string $createdField
2509      * @return mixed string or false if no match
2510      */
2511     public static function whereSinceId($id, $idField='id', $createdField='created')
2512     {
2513         $since = Notice::getAsTimestamp($id);
2514         if ($since) {
2515             return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2516         }
2517         return false;
2518     }
2519
2520     /**
2521      * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2522      * parameter, matching notices posted after the given one (exclusive), and
2523      * if necessary add it to the data object's query.
2524      *
2525      * @param DB_DataObject $obj
2526      * @param int $id
2527      * @param string $idField
2528      * @param string $createdField
2529      * @return mixed string or false if no match
2530      */
2531     public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2532     {
2533         $since = self::whereSinceId($id, $idField, $createdField);
2534         if ($since) {
2535             $obj->whereAdd($since);
2536         }
2537     }
2538
2539     /**
2540      * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2541      * parameter, matching notices posted before the given one (inclusive).
2542      *
2543      * If the referenced notice can't be found, will return false.
2544      *
2545      * @param int $id
2546      * @param string $idField
2547      * @param string $createdField
2548      * @return mixed string or false if no match
2549      */
2550     public static function whereMaxId($id, $idField='id', $createdField='created')
2551     {
2552         $max = Notice::getAsTimestamp($id);
2553         if ($max) {
2554             return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2555         }
2556         return false;
2557     }
2558
2559     /**
2560      * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2561      * parameter, matching notices posted before the given one (inclusive), and
2562      * if necessary add it to the data object's query.
2563      *
2564      * @param DB_DataObject $obj
2565      * @param int $id
2566      * @param string $idField
2567      * @param string $createdField
2568      * @return mixed string or false if no match
2569      */
2570     public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2571     {
2572         $max = self::whereMaxId($id, $idField, $createdField);
2573         if ($max) {
2574             $obj->whereAdd($max);
2575         }
2576     }
2577
2578     function isPublic()
2579     {
2580         if (common_config('public', 'localonly')) {
2581             return ($this->is_local == Notice::LOCAL_PUBLIC);
2582         } else {
2583             return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2584                     ($this->is_local != Notice::GATEWAY));
2585         }
2586     }
2587
2588     /**
2589      * Check that the given profile is allowed to read, respond to, or otherwise
2590      * act on this notice.
2591      *
2592      * The $scope member is a bitmask of scopes, representing a logical AND of the
2593      * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2594      * "only visible to people who are mentioned in the notice AND are users on this site."
2595      * Users on the site who are not mentioned in the notice will not be able to see the
2596      * notice.
2597      *
2598      * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2599      *
2600      * @return boolean whether the profile is in the notice's scope
2601      */
2602     function inScope($profile)
2603     {
2604         if (is_null($profile)) {
2605             $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2606         } else {
2607             $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2608         }
2609
2610         $result = self::cacheGet($keypart);
2611
2612         if ($result === false) {
2613             $bResult = false;
2614             if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2615                 $bResult = $this->_inScope($profile);
2616                 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2617             }
2618             $result = ($bResult) ? 1 : 0;
2619             self::cacheSet($keypart, $result, 0, 300);
2620         }
2621
2622         return ($result == 1) ? true : false;
2623     }
2624
2625     protected function _inScope($profile)
2626     {
2627         if (!is_null($this->scope)) {
2628             $scope = $this->scope;
2629         } else {
2630             $scope = self::defaultScope();
2631         }
2632
2633         // If there's no scope, anyone (even anon) is in scope.
2634
2635         if ($scope == 0) { // Not private
2636
2637             return !$this->isHiddenSpam($profile);
2638
2639         } else { // Private, somehow
2640
2641             // If there's scope, anon cannot be in scope
2642
2643             if (empty($profile)) {
2644                 return false;
2645             }
2646
2647             // Author is always in scope
2648
2649             if ($this->profile_id == $profile->id) {
2650                 return true;
2651             }
2652
2653             // Only for users on this site
2654
2655             if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2656                 return false;
2657             }
2658
2659             // Only for users mentioned in the notice
2660
2661             if ($scope & Notice::ADDRESSEE_SCOPE) {
2662
2663                 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2664                                              'profile_id' => $profile->id));
2665                                                                                  
2666                 if (!$reply instanceof Reply) {
2667                     return false;
2668                 }
2669             }
2670
2671             // Only for members of the given group
2672
2673             if ($scope & Notice::GROUP_SCOPE) {
2674
2675                 // XXX: just query for the single membership
2676
2677                 $groups = $this->getGroups();
2678
2679                 $foundOne = false;
2680
2681                 foreach ($groups as $group) {
2682                     if ($profile->isMember($group)) {
2683                         $foundOne = true;
2684                         break;
2685                     }
2686                 }
2687
2688                 if (!$foundOne) {
2689                     return false;
2690                 }
2691             }
2692
2693             // Only for followers of the author
2694
2695             $author = null;
2696
2697             if ($scope & Notice::FOLLOWER_SCOPE) {
2698
2699                 try {
2700                     $author = $this->getProfile();
2701                 } catch (Exception $e) {
2702                     return false;
2703                 }
2704         
2705                 if (!Subscription::exists($profile, $author)) {
2706                     return false;
2707                 }
2708             }
2709
2710             return !$this->isHiddenSpam($profile);
2711         }
2712     }
2713
2714     function isHiddenSpam($profile) {
2715         
2716         // Hide posts by silenced users from everyone but moderators.
2717
2718         if (common_config('notice', 'hidespam')) {
2719
2720             try {
2721                 $author = $this->getProfile();
2722             } catch(Exception $e) {
2723                 // If we can't get an author, keep it hidden.
2724                 // XXX: technically not spam, but, whatever.
2725                 return true;
2726             }
2727
2728             if ($author->hasRole(Profile_role::SILENCED)) {
2729                 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2730                     return true;
2731                 }
2732             }
2733         }
2734
2735         return false;
2736     }
2737
2738     public function getParent()
2739     {
2740         $parent = Notice::getKV('id', $this->reply_to);
2741
2742         if (!$parent instanceof Notice) {
2743             throw new ServerException('Notice has no parent');
2744         }
2745
2746         return $parent;
2747     }
2748
2749     /**
2750      * Magic function called at serialize() time.
2751      *
2752      * We use this to drop a couple process-specific references
2753      * from DB_DataObject which can cause trouble in future
2754      * processes.
2755      *
2756      * @return array of variable names to include in serialization.
2757      */
2758
2759     function __sleep()
2760     {
2761         $vars = parent::__sleep();
2762         $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2763         return array_diff($vars, $skip);
2764     }
2765     
2766     static function defaultScope()
2767     {
2768         $scope = common_config('notice', 'defaultscope');
2769         if (is_null($scope)) {
2770                 if (common_config('site', 'private')) {
2771                         $scope = 1;
2772                 } else {
2773                         $scope = 0;
2774                 }
2775         }
2776         return $scope;
2777     }
2778
2779         static function fillProfiles($notices)
2780         {
2781                 $map = self::getProfiles($notices);
2782                 
2783                 foreach ($notices as $entry=>$notice) {
2784             try {
2785                         if (array_key_exists($notice->profile_id, $map)) {
2786                                 $notice->_setProfile($map[$notice->profile_id]);
2787                         }
2788             } catch (NoProfileException $e) {
2789                 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2790                 unset($notices[$entry]);
2791             }
2792                 }
2793                 
2794                 return array_values($map);
2795         }
2796         
2797         static function getProfiles(&$notices)
2798         {
2799                 $ids = array();
2800                 foreach ($notices as $notice) {
2801                         $ids[] = $notice->profile_id;
2802                 }
2803                 
2804                 $ids = array_unique($ids);
2805                 
2806                 return Profile::pivotGet('id', $ids); 
2807         }
2808         
2809         static function fillGroups(&$notices)
2810         {
2811         $ids = self::_idsOf($notices);
2812                 
2813         $gis = Group_inbox::listGet('notice_id', $ids);
2814                 
2815         $gids = array();
2816
2817                 foreach ($gis as $id => $gi)
2818                 {
2819                     foreach ($gi as $g)
2820                     {
2821                         $gids[] = $g->group_id;
2822                     }
2823                 }
2824                 
2825                 $gids = array_unique($gids);
2826                 
2827                 $group = User_group::pivotGet('id', $gids);
2828                 
2829                 foreach ($notices as $notice)
2830                 {
2831                         $grps = array();
2832                         $gi = $gis[$notice->id];
2833                         foreach ($gi as $g) {
2834                             $grps[] = $group[$g->group_id];
2835                         }
2836                     $notice->_setGroups($grps);
2837                 }
2838         }
2839
2840     static function _idsOf(array &$notices)
2841     {
2842                 $ids = array();
2843                 foreach ($notices as $notice) {
2844                         $ids[$notice->id] = true;
2845                 }
2846                 return array_keys($ids);
2847     }
2848
2849     static function fillAttachments(&$notices)
2850     {
2851         $ids = self::_idsOf($notices);
2852
2853         $f2pMap = File_to_post::listGet('post_id', $ids);
2854                 
2855                 $fileIds = array();
2856                 
2857                 foreach ($f2pMap as $noticeId => $f2ps) {
2858             foreach ($f2ps as $f2p) {
2859                 $fileIds[] = $f2p->file_id;    
2860             }
2861         }
2862
2863         $fileIds = array_unique($fileIds);
2864
2865                 $fileMap = File::pivotGet('id', $fileIds);
2866
2867                 foreach ($notices as $notice)
2868                 {
2869                         $files = array();
2870                         $f2ps = $f2pMap[$notice->id];
2871                         foreach ($f2ps as $f2p) {
2872                             $files[] = $fileMap[$f2p->file_id];
2873                         }
2874                     $notice->_setAttachments($files);
2875                 }
2876     }
2877
2878     static function fillReplies(&$notices)
2879     {
2880         $ids = self::_idsOf($notices);
2881         $replyMap = Reply::listGet('notice_id', $ids);
2882         foreach ($notices as $notice) {
2883             $replies = $replyMap[$notice->id];
2884             $ids = array();
2885             foreach ($replies as $reply) {
2886                 $ids[] = $reply->profile_id;
2887             }
2888             $notice->_setReplies($ids);
2889         }
2890     }
2891
2892     protected $_repeats = array();
2893
2894     function getRepeats()
2895     {
2896         if (isset($this->_repeats[$this->id])) {
2897             return $this->_repeats[$this->id];
2898         }
2899         $repeatMap = Notice::listGet('repeat_of', array($this->id));
2900         $this->_repeats[$this->id] = $repeatMap[$this->id];
2901         return $this->_repeats[$this->id];
2902     }
2903
2904     function _setRepeats($repeats)
2905     {
2906         $this->_repeats[$this->id] = $repeats;
2907     }
2908
2909     static function fillRepeats(&$notices)
2910     {
2911         $ids = self::_idsOf($notices);
2912         $repeatMap = Notice::listGet('repeat_of', $ids);
2913         foreach ($notices as $notice) {
2914                 $repeats = $repeatMap[$notice->id];
2915             $notice->_setRepeats($repeats);
2916         }
2917     }
2918 }