]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
FavorAction now uses Notice::saveActivity
[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 (!empty($reply->repeat_of)) {
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 (!empty($notice->repeat_of)) {
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 /* This interferes with stuff like Favorites from old StatusNet installations (first object in objects is the favored notice)
716         // Get ActivityObject properties
717         $actobj = count($act->objects)==1 ? $act->objects[0] : null;
718         if (!is_null($actobj) && $actobj->id) {
719             $options['uri'] = $actobj->id;
720             if ($actobj->link) {
721                 $options['url'] = $actobj->link;
722             } elseif ($act->link) {
723                 $options['url'] = $act->link;
724             } elseif (preg_match('!^https?://!', $actobj->id)) {
725                 $options['url'] = $actobj->id;
726             }
727         } else {
728             // implied object
729             $options['uri'] = $act->id;
730             $options['url'] = $act->link;
731         }
732 */
733
734         $defaults = array(
735                           'groups'   => array(),
736                           'is_local' => self::LOCAL_PUBLIC,
737                           'mentions' => array(),
738                           'reply_to' => null,
739                           'repeat_of' => null,
740                           'scope' => null,
741                           'source' => 'unknown',
742                           'tags' => array(),
743                           'uri' => null,
744                           'url' => null,
745                           'urls' => array(),
746                           'distribute' => true);
747
748         // options will have default values when nothing has been supplied
749         $options = array_merge($defaults, $options); 
750         foreach (array_keys($defaults) as $key) {
751             // Only convert the keynames we specify ourselves from 'defaults' array into variables
752             $$key = $options[$key];
753         }
754         extract($options, EXTR_SKIP);
755
756         $stored = new Notice();
757         if (!empty($uri)) {
758             $stored->uri = $uri;
759             if ($stored->find()) {
760                 common_debug('cannot create duplicate Notice URI: '.$stored->uri);
761                 throw new Exception('Notice URI already exists');
762             }
763         }
764
765         $stored->profile_id = $actor->id;
766         $stored->source = $source;
767         $stored->uri = $uri;
768         $stored->url = $url;
769         $stored->verb = $act->verb;
770
771         $autosource = common_config('public', 'autosource');
772
773         // Sandboxed are non-false, but not 1, either
774         if (!$actor->hasRight(Right::PUBLICNOTICE) ||
775             ($source && $autosource && in_array($source, $autosource))) {
776             $stored->is_local = Notice::LOCAL_NONPUBLIC;
777         }
778
779         // Maybe a missing act-time should be fatal if the actor is not local?
780         if (!empty($act->time)) {
781             $stored->created = common_sql_date($act->time);
782         } else {
783             $stored->created = common_sql_now();
784         }
785
786         $reply = null;
787         if ($act->context instanceof ActivityContext && !empty($act->context->replyToID)) {
788             $reply = self::getKV('uri', $act->context->replyToID);
789         }
790         if (!$reply instanceof Notice && $act->target instanceof ActivityObject) {
791             $reply = self::getKV('uri', $act->target->id);
792         }
793
794         if ($reply instanceof Notice) {
795             if (!$reply->inScope($actor)) {
796                 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
797                 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
798                 throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $actor->getNickname(), $reply->id), 403);
799             }
800
801             $stored->reply_to     = $reply->id;
802             $stored->conversation = $reply->conversation;
803
804             // If the original is private to a group, and notice has no group specified,
805             // make it to the same group(s)
806             if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
807                 $groups = array();
808                 $replyGroups = $reply->getGroups();
809                 foreach ($replyGroups as $group) {
810                     if ($actor->isMember($group)) {
811                         $groups[] = $group->id;
812                     }
813                 }
814             }
815
816             if (is_null($scope)) {
817                 $scope = $reply->scope;
818             }
819         }
820
821         if ($act->context instanceof ActivityContext) {
822             $location = $act->context->location;
823             if ($location) {
824                 $stored->lat = $location->lat;
825                 $stored->lon = $location->lon;
826                 if ($location->location_id) {
827                     $stored->location_ns = $location->location_ns;
828                     $stored->location_id = $location->location_id;
829                 }
830             }
831         } else {
832             $act->context = new ActivityContext();
833         }
834
835         $stored->scope = self::figureOutScope($actor, $groups, $scope);
836
837         foreach ($act->categories as $cat) {
838             if ($cat->term) {
839                 $term = common_canonical_tag($cat->term);
840                 if (!empty($term)) {
841                     $tags[] = $term;
842                 }
843             }
844         }
845
846         foreach ($act->enclosures as $href) {
847             // @todo FIXME: Save these locally or....?
848             $urls[] = $href;
849         }
850
851         if (Event::handle('StartNoticeSave', array(&$stored))) {
852             // XXX: some of these functions write to the DB
853
854             try {
855                 $stored->insert();    // throws exception on error
856
857                 $object = null;
858                 Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
859                 if (empty($object)) {
860                     throw new ServerException('No object from StoreActivityObject '.$stored->uri . ': '.$act->asString());
861                 }
862                 $orig = clone($stored);
863                 $stored->object_type = ActivityUtils::resolveUri($object->getObjectType(), true);
864                 $stored->update($orig);
865             } catch (Exception $e) {
866                 if (empty($stored->id)) {
867                     common_debug('Failed to save stored object entry in database ('.$e->getMessage().')');
868                 } else {
869                     common_debug('Failed to store activity object in database ('.$e->getMessage().'), deleting notice id '.$stored->id);
870                     $stored->delete();
871                 }
872                 throw $e;
873             }
874         }
875         if (!$stored instanceof Notice) {
876             throw new ServerException('StartNoticeSave did not give back a Notice');
877         }
878
879         // Save per-notice metadata...
880         $mentions = array();
881         $groups   = array();
882
883         // This event lets plugins filter out non-local recipients (attentions we don't care about)
884         // Used primarily for OStatus (and if we don't federate, all attentions would be local anyway)
885         Event::handle('GetLocalAttentions', array($actor, $act->context->attention, &$mentions, &$groups));
886
887         if (!empty($mentions)) {
888             $stored->saveKnownReplies($mentions);
889         } else {
890             $stored->saveReplies();
891         }
892
893         if (!empty($tags)) {
894             $stored->saveKnownTags($tags);
895         } else {
896             $stored->saveTags();
897         }
898
899         // Note: groups may save tags, so must be run after tags are saved
900         // to avoid errors on duplicates.
901         // Note: groups should always be set.
902
903         $stored->saveKnownGroups($groups);
904
905         if (!empty($urls)) {
906             $stored->saveKnownUrls($urls);
907         } else {
908             $stored->saveUrls();
909         }
910
911         if ($distribute) {
912             // Prepare inbox delivery, may be queued to background.
913             $stored->distribute();
914         }
915         
916         return $stored;
917     }
918
919     static public function figureOutScope(Profile $actor, array $groups, $scope=null) {
920         if (is_null($scope)) {
921             $scope = self::defaultScope();
922         }
923
924         // For private streams
925         try {
926             $user = $actor->getUser();
927             // FIXME: We can't do bit comparison with == (Legacy StatusNet thing. Let's keep it for now.)
928             if ($user->private_stream && ($scope == Notice::PUBLIC_SCOPE || $scope == Notice::SITE_SCOPE)) {
929                 $scope |= Notice::FOLLOWER_SCOPE;
930             }
931         } catch (NoSuchUserException $e) {
932             // TODO: Not a local user, so we don't know about scope preferences... yet!
933         }
934
935         // Force the scope for private groups
936         foreach ($groups as $group_id) {
937             $group = User_group::staticGet('id', $group_id);
938             if ($group instanceof User_group) {
939                 if ($group->force_scope) {
940                     $scope |= Notice::GROUP_SCOPE;
941                     break;
942                 }
943             }
944         }
945
946         return $scope;
947     }
948
949     function blowOnInsert($conversation = false)
950     {
951         $this->blowStream('profile:notice_ids:%d', $this->profile_id);
952
953         if ($this->isPublic()) {
954             $this->blowStream('public');
955         }
956
957         self::blow('notice:list-ids:conversation:%s', $this->conversation);
958         self::blow('conversation:notice_count:%d', $this->conversation);
959
960         if (!empty($this->repeat_of)) {
961             // XXX: we should probably only use one of these
962             $this->blowStream('notice:repeats:%d', $this->repeat_of);
963             self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
964         }
965
966         $original = Notice::getKV('id', $this->repeat_of);
967
968         if ($original instanceof Notice) {
969             $originalUser = User::getKV('id', $original->profile_id);
970             if ($originalUser instanceof User) {
971                 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
972             }
973         }
974
975         $profile = Profile::getKV($this->profile_id);
976
977         if ($profile instanceof Profile) {
978             $profile->blowNoticeCount();
979         }
980
981         $ptags = $this->getProfileTags();
982         foreach ($ptags as $ptag) {
983             $ptag->blowNoticeStreamCache();
984         }
985     }
986
987     /**
988      * Clear cache entries related to this notice at delete time.
989      * Necessary to avoid breaking paging on public, profile timelines.
990      */
991     function blowOnDelete()
992     {
993         $this->blowOnInsert();
994
995         self::blow('profile:notice_ids:%d;last', $this->profile_id);
996
997         if ($this->isPublic()) {
998             self::blow('public;last');
999         }
1000
1001         self::blow('fave:by_notice', $this->id);
1002
1003         if ($this->conversation) {
1004             // In case we're the first, will need to calc a new root.
1005             self::blow('notice:conversation_root:%d', $this->conversation);
1006         }
1007
1008         $ptags = $this->getProfileTags();
1009         foreach ($ptags as $ptag) {
1010             $ptag->blowNoticeStreamCache(true);
1011         }
1012     }
1013
1014     function blowStream()
1015     {
1016         $c = self::memcache();
1017
1018         if (empty($c)) {
1019             return false;
1020         }
1021
1022         $args = func_get_args();
1023
1024         $format = array_shift($args);
1025
1026         $keyPart = vsprintf($format, $args);
1027
1028         $cacheKey = Cache::key($keyPart);
1029         
1030         $c->delete($cacheKey);
1031
1032         // delete the "last" stream, too, if this notice is
1033         // older than the top of that stream
1034
1035         $lastKey = $cacheKey.';last';
1036
1037         $lastStr = $c->get($lastKey);
1038
1039         if ($lastStr !== false) {
1040             $window     = explode(',', $lastStr);
1041             $lastID     = $window[0];
1042             $lastNotice = Notice::getKV('id', $lastID);
1043             if (!$lastNotice instanceof Notice // just weird
1044                 || strtotime($lastNotice->created) >= strtotime($this->created)) {
1045                 $c->delete($lastKey);
1046             }
1047         }
1048     }
1049
1050     /** save all urls in the notice to the db
1051      *
1052      * follow redirects and save all available file information
1053      * (mimetype, date, size, oembed, etc.)
1054      *
1055      * @return void
1056      */
1057     function saveUrls() {
1058         if (common_config('attachments', 'process_links')) {
1059             common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
1060         }
1061     }
1062
1063     /**
1064      * Save the given URLs as related links/attachments to the db
1065      *
1066      * follow redirects and save all available file information
1067      * (mimetype, date, size, oembed, etc.)
1068      *
1069      * @return void
1070      */
1071     function saveKnownUrls($urls)
1072     {
1073         if (common_config('attachments', 'process_links')) {
1074             // @fixme validation?
1075             foreach (array_unique($urls) as $url) {
1076                 try {
1077                     File::processNew($url, $this->id);
1078                 } catch (ServerException $e) {
1079                     // Could not save URL. Log it?
1080                 }
1081             }
1082         }
1083     }
1084
1085     /**
1086      * @private callback
1087      */
1088     function saveUrl($url, $notice_id) {
1089         try {
1090             File::processNew($url, $notice_id);
1091         } catch (ServerException $e) {
1092             // Could not save URL. Log it?
1093         }
1094     }
1095
1096     static function checkDupes($profile_id, $content) {
1097         $profile = Profile::getKV($profile_id);
1098         if (!$profile instanceof Profile) {
1099             return false;
1100         }
1101         $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
1102         if (!empty($notice)) {
1103             $last = 0;
1104             while ($notice->fetch()) {
1105                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
1106                     return true;
1107                 } else if ($notice->content == $content) {
1108                     return false;
1109                 }
1110             }
1111         }
1112         // If we get here, oldest item in cache window is not
1113         // old enough for dupe limit; do direct check against DB
1114         $notice = new Notice();
1115         $notice->profile_id = $profile_id;
1116         $notice->content = $content;
1117         $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
1118         $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
1119
1120         $cnt = $notice->count();
1121         return ($cnt == 0);
1122     }
1123
1124     static function checkEditThrottle($profile_id) {
1125         $profile = Profile::getKV($profile_id);
1126         if (!$profile instanceof Profile) {
1127             return false;
1128         }
1129         // Get the Nth notice
1130         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
1131         if ($notice && $notice->fetch()) {
1132             // If the Nth notice was posted less than timespan seconds ago
1133             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
1134                 // Then we throttle
1135                 return false;
1136             }
1137         }
1138         // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
1139         return true;
1140     }
1141
1142         protected $_attachments = array();
1143         
1144     function attachments() {
1145                 if (isset($this->_attachments[$this->id])) {
1146             return $this->_attachments[$this->id];
1147         }
1148                 
1149         $f2ps = File_to_post::listGet('post_id', array($this->id));
1150                 
1151                 $ids = array();
1152                 
1153                 foreach ($f2ps[$this->id] as $f2p) {
1154             $ids[] = $f2p->file_id;    
1155         }
1156                 
1157                 $files = File::multiGet('id', $ids);
1158
1159                 $this->_attachments[$this->id] = $files->fetchAll();
1160                 
1161         return $this->_attachments[$this->id];
1162     }
1163
1164         function _setAttachments($attachments)
1165         {
1166             $this->_attachments[$this->id] = $attachments;
1167         }
1168
1169     function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
1170     {
1171         $stream = new PublicNoticeStream();
1172         return $stream->getNotices($offset, $limit, $since_id, $max_id);
1173     }
1174
1175
1176     function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
1177     {
1178         $stream = new ConversationNoticeStream($id);
1179
1180         return $stream->getNotices($offset, $limit, $since_id, $max_id);
1181     }
1182
1183     /**
1184      * Is this notice part of an active conversation?
1185      *
1186      * @return boolean true if other messages exist in the same
1187      *                 conversation, false if this is the only one
1188      */
1189     function hasConversation()
1190     {
1191         if (!empty($this->conversation)) {
1192             $conversation = Notice::conversationStream(
1193                 $this->conversation,
1194                 1,
1195                 1
1196             );
1197
1198             if ($conversation->N > 0) {
1199                 return true;
1200             }
1201         }
1202         return false;
1203     }
1204
1205     /**
1206      * Grab the earliest notice from this conversation.
1207      *
1208      * @return Notice or null
1209      */
1210     function conversationRoot($profile=-1)
1211     {
1212         // XXX: can this happen?
1213
1214         if (empty($this->conversation)) {
1215             return null;
1216         }
1217
1218         // Get the current profile if not specified
1219
1220         if (is_int($profile) && $profile == -1) {
1221             $profile = Profile::current();
1222         }
1223
1224         // If this notice is out of scope, no root for you!
1225
1226         if (!$this->inScope($profile)) {
1227             return null;
1228         }
1229
1230         // If this isn't a reply to anything, then it's its own
1231         // root.
1232
1233         if (empty($this->reply_to)) {
1234             return $this;
1235         }
1236         
1237         if (is_null($profile)) {
1238             $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1239         } else {
1240             $keypart = sprintf('notice:conversation_root:%d:%d',
1241                                $this->id,
1242                                $profile->id);
1243         }
1244             
1245         $root = self::cacheGet($keypart);
1246
1247         if ($root !== false && $root->inScope($profile)) {
1248             return $root;
1249         }
1250
1251         $last = $this;
1252         while (true) {
1253             try {
1254                 $parent = $last->getParent();
1255                 if ($parent->inScope($profile)) {
1256                     $last = $parent;
1257                     continue;
1258                 }
1259             } catch (Exception $e) {
1260                 // Latest notice has no parent
1261             }
1262             // No parent, or parent out of scope
1263             $root = $last;
1264             break;
1265         }
1266
1267         self::cacheSet($keypart, $root);
1268
1269         return $root;
1270     }
1271
1272     /**
1273      * Pull up a full list of local recipients who will be getting
1274      * this notice in their inbox. Results will be cached, so don't
1275      * change the input data wily-nilly!
1276      *
1277      * @param array $groups optional list of Group objects;
1278      *              if left empty, will be loaded from group_inbox records
1279      * @param array $recipient optional list of reply profile ids
1280      *              if left empty, will be loaded from reply records
1281      * @return array associating recipient user IDs with an inbox source constant
1282      */
1283     function whoGets(array $groups=null, array $recipients=null)
1284     {
1285         $c = self::memcache();
1286
1287         if (!empty($c)) {
1288             $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1289             if ($ni !== false) {
1290                 return $ni;
1291             }
1292         }
1293
1294         if (is_null($recipients)) {
1295             $recipients = $this->getReplies();
1296         }
1297
1298         $ni = array();
1299
1300         // Give plugins a chance to add folks in at start...
1301         if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1302
1303             $users = $this->getSubscribedUsers();
1304             foreach ($users as $id) {
1305                 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1306             }
1307
1308             if (is_null($groups)) {
1309                 $groups = $this->getGroups();
1310             }
1311             foreach ($groups as $group) {
1312                 $users = $group->getUserMembers();
1313                 foreach ($users as $id) {
1314                     if (!array_key_exists($id, $ni)) {
1315                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1316                     }
1317                 }
1318             }
1319
1320             $ptAtts = $this->getAttentionsFromProfileTags();
1321             foreach ($ptAtts as $key=>$val) {
1322                 if (!array_key_exists($key, $ni)) {
1323                     $ni[$key] = $val;
1324                 }
1325             }
1326
1327             foreach ($recipients as $recipient) {
1328                 if (!array_key_exists($recipient, $ni)) {
1329                     $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1330                 }
1331             }
1332
1333             // Exclude any deleted, non-local, or blocking recipients.
1334             $profile = $this->getProfile();
1335             $originalProfile = null;
1336             if ($this->repeat_of) {
1337                 // Check blocks against the original notice's poster as well.
1338                 $original = Notice::getKV('id', $this->repeat_of);
1339                 if ($original instanceof Notice) {
1340                     $originalProfile = $original->getProfile();
1341                 }
1342             }
1343
1344             foreach ($ni as $id => $source) {
1345                 try {
1346                     $user = User::getKV('id', $id);
1347                     if (!$user instanceof User ||
1348                         $user->hasBlocked($profile) ||
1349                         ($originalProfile && $user->hasBlocked($originalProfile))) {
1350                         unset($ni[$id]);
1351                     }
1352                 } catch (UserNoProfileException $e) {
1353                     // User doesn't have a profile; invalid; skip them.
1354                     unset($ni[$id]);
1355                 }
1356             }
1357
1358             // Give plugins a chance to filter out...
1359             Event::handle('EndNoticeWhoGets', array($this, &$ni));
1360         }
1361
1362         if (!empty($c)) {
1363             // XXX: pack this data better
1364             $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1365         }
1366
1367         return $ni;
1368     }
1369
1370     function getSubscribedUsers()
1371     {
1372         $user = new User();
1373
1374         if(common_config('db','quote_identifiers'))
1375           $user_table = '"user"';
1376         else $user_table = 'user';
1377
1378         $qry =
1379           'SELECT id ' .
1380           'FROM '. $user_table .' JOIN subscription '.
1381           'ON '. $user_table .'.id = subscription.subscriber ' .
1382           'WHERE subscription.subscribed = %d ';
1383
1384         $user->query(sprintf($qry, $this->profile_id));
1385
1386         $ids = array();
1387
1388         while ($user->fetch()) {
1389             $ids[] = $user->id;
1390         }
1391
1392         $user->free();
1393
1394         return $ids;
1395     }
1396
1397     function getProfileTags()
1398     {
1399         $profile = $this->getProfile();
1400         $list    = $profile->getOtherTags($profile);
1401         $ptags   = array();
1402
1403         while($list->fetch()) {
1404             $ptags[] = clone($list);
1405         }
1406
1407         return $ptags;
1408     }
1409
1410     public function getAttentionsFromProfileTags()
1411     {
1412         $ni = array();
1413         $ptags = $this->getProfileTags();
1414         foreach ($ptags as $ptag) {
1415             $users = $ptag->getUserSubscribers();
1416             foreach ($users as $id) {
1417                 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1418             }
1419         }
1420         return $ni;
1421     }
1422
1423     /**
1424      * Record this notice to the given group inboxes for delivery.
1425      * Overrides the regular parsing of !group markup.
1426      *
1427      * @param string $group_ids
1428      * @fixme might prefer URIs as identifiers, as for replies?
1429      *        best with generalizations on user_group to support
1430      *        remote groups better.
1431      */
1432     function saveKnownGroups($group_ids)
1433     {
1434         if (!is_array($group_ids)) {
1435             // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1436             throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1437         }
1438
1439         $groups = array();
1440         foreach (array_unique($group_ids) as $id) {
1441             $group = User_group::getKV('id', $id);
1442             if ($group instanceof User_group) {
1443                 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1444                 $result = $this->addToGroupInbox($group);
1445                 if (!$result) {
1446                     common_log_db_error($gi, 'INSERT', __FILE__);
1447                 }
1448
1449                 if (common_config('group', 'addtag')) {
1450                     // we automatically add a tag for every group name, too
1451
1452                     $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1453                                                      'notice_id' => $this->id));
1454
1455                     if (is_null($tag)) {
1456                         $this->saveTag($group->nickname);
1457                     }
1458                 }
1459
1460                 $groups[] = clone($group);
1461             } else {
1462                 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1463             }
1464         }
1465
1466         return $groups;
1467     }
1468
1469     function addToGroupInbox(User_group $group)
1470     {
1471         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1472                                          'notice_id' => $this->id));
1473
1474         if (!$gi instanceof Group_inbox) {
1475
1476             $gi = new Group_inbox();
1477
1478             $gi->group_id  = $group->id;
1479             $gi->notice_id = $this->id;
1480             $gi->created   = $this->created;
1481
1482             $result = $gi->insert();
1483
1484             if (!$result) {
1485                 common_log_db_error($gi, 'INSERT', __FILE__);
1486                 // TRANS: Server exception thrown when an update for a group inbox fails.
1487                 throw new ServerException(_('Problem saving group inbox.'));
1488             }
1489
1490             self::blow('user_group:notice_ids:%d', $gi->group_id);
1491         }
1492
1493         return true;
1494     }
1495
1496     /**
1497      * Save reply records indicating that this notice needs to be
1498      * delivered to the local users with the given URIs.
1499      *
1500      * Since this is expected to be used when saving foreign-sourced
1501      * messages, we won't deliver to any remote targets as that's the
1502      * source service's responsibility.
1503      *
1504      * Mail notifications etc will be handled later.
1505      *
1506      * @param array  $uris   Array of unique identifier URIs for recipients
1507      */
1508     function saveKnownReplies(array $uris)
1509     {
1510         if (empty($uris)) {
1511             return;
1512         }
1513
1514         $sender = Profile::getKV($this->profile_id);
1515
1516         foreach (array_unique($uris) as $uri) {
1517             try {
1518                 $profile = Profile::fromUri($uri);
1519             } catch (UnknownUriException $e) {
1520                 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1521                 continue;
1522             }
1523
1524             if ($profile->hasBlocked($sender)) {
1525                 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1526                 continue;
1527             }
1528
1529             $this->saveReply($profile->id);
1530             self::blow('reply:stream:%d', $profile->id);
1531         }
1532
1533         return;
1534     }
1535
1536     /**
1537      * Pull @-replies from this message's content in StatusNet markup format
1538      * and save reply records indicating that this message needs to be
1539      * delivered to those users.
1540      *
1541      * Mail notifications to local profiles will be sent later.
1542      *
1543      * @return array of integer profile IDs
1544      */
1545
1546     function saveReplies()
1547     {
1548         // Don't save reply data for repeats
1549
1550         if (!empty($this->repeat_of)) {
1551             return array();
1552         }
1553
1554         $sender = $this->getProfile();
1555
1556         $replied = array();
1557
1558         // If it's a reply, save for the replied-to author
1559         try {
1560             $parent = $this->getParent();
1561             $parentauthor = $parent->getProfile();
1562             $this->saveReply($parentauthor->id);
1563             $replied[$parentauthor->id] = 1;
1564             self::blow('reply:stream:%d', $parentauthor->id);
1565         } catch (Exception $e) {
1566             // Not a reply, since it has no parent!
1567         }
1568
1569         // @todo ideally this parser information would only
1570         // be calculated once.
1571
1572         $mentions = common_find_mentions($this->content, $this);
1573
1574         // store replied only for first @ (what user/notice what the reply directed,
1575         // we assume first @ is it)
1576
1577         foreach ($mentions as $mention) {
1578
1579             foreach ($mention['mentioned'] as $mentioned) {
1580
1581                 // skip if they're already covered
1582
1583                 if (!empty($replied[$mentioned->id])) {
1584                     continue;
1585                 }
1586
1587                 // Don't save replies from blocked profile to local user
1588
1589                 $mentioned_user = User::getKV('id', $mentioned->id);
1590                 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1591                     continue;
1592                 }
1593
1594                 $this->saveReply($mentioned->id);
1595                 $replied[$mentioned->id] = 1;
1596                 self::blow('reply:stream:%d', $mentioned->id);
1597             }
1598         }
1599
1600         $recipientIds = array_keys($replied);
1601
1602         return $recipientIds;
1603     }
1604
1605     function saveReply($profileId)
1606     {
1607         $reply = new Reply();
1608
1609         $reply->notice_id  = $this->id;
1610         $reply->profile_id = $profileId;
1611         $reply->modified   = $this->created;
1612
1613         $reply->insert();
1614
1615         return $reply;
1616     }
1617
1618     protected $_replies = array();
1619
1620     /**
1621      * Pull the complete list of @-reply targets for this notice.
1622      *
1623      * @return array of integer profile ids
1624      */
1625     function getReplies()
1626     {
1627         if (isset($this->_replies[$this->id])) {
1628             return $this->_replies[$this->id];
1629         }
1630
1631         $replyMap = Reply::listGet('notice_id', array($this->id));
1632
1633         $ids = array();
1634
1635         foreach ($replyMap[$this->id] as $reply) {
1636             $ids[] = $reply->profile_id;
1637         }
1638
1639         $this->_replies[$this->id] = $ids;
1640
1641         return $ids;
1642     }
1643
1644     function _setReplies($replies)
1645     {
1646         $this->_replies[$this->id] = $replies;
1647     }
1648
1649     /**
1650      * Pull the complete list of @-reply targets for this notice.
1651      *
1652      * @return array of Profiles
1653      */
1654     function getReplyProfiles()
1655     {
1656         $ids = $this->getReplies();
1657         
1658         $profiles = Profile::multiGet('id', $ids);
1659         
1660         return $profiles->fetchAll();
1661     }
1662
1663     /**
1664      * Send e-mail notifications to local @-reply targets.
1665      *
1666      * Replies must already have been saved; this is expected to be run
1667      * from the distrib queue handler.
1668      */
1669     function sendReplyNotifications()
1670     {
1671         // Don't send reply notifications for repeats
1672
1673         if (!empty($this->repeat_of)) {
1674             return array();
1675         }
1676
1677         $recipientIds = $this->getReplies();
1678
1679         foreach ($recipientIds as $recipientId) {
1680             $user = User::getKV('id', $recipientId);
1681             if ($user instanceof User) {
1682                 mail_notify_attn($user, $this);
1683             }
1684         }
1685     }
1686
1687     /**
1688      * Pull list of groups this notice needs to be delivered to,
1689      * as previously recorded by saveKnownGroups().
1690      *
1691      * @return array of Group objects
1692      */
1693     
1694     protected $_groups = array();
1695     
1696     function getGroups()
1697     {
1698         // Don't save groups for repeats
1699
1700         if (!empty($this->repeat_of)) {
1701             return array();
1702         }
1703         
1704         if (isset($this->_groups[$this->id])) {
1705             return $this->_groups[$this->id];
1706         }
1707         
1708         $gis = Group_inbox::listGet('notice_id', array($this->id));
1709
1710         $ids = array();
1711
1712                 foreach ($gis[$this->id] as $gi)
1713                 {
1714                     $ids[] = $gi->group_id;
1715                 }
1716                 
1717                 $groups = User_group::multiGet('id', $ids);
1718                 
1719                 $this->_groups[$this->id] = $groups->fetchAll();
1720                 
1721                 return $this->_groups[$this->id];
1722     }
1723     
1724     function _setGroups($groups)
1725     {
1726         $this->_groups[$this->id] = $groups;
1727     }
1728
1729     /**
1730      * Convert a notice into an activity for export.
1731      *
1732      * @param User $cur Current user
1733      *
1734      * @return Activity activity object representing this Notice.
1735      */
1736
1737     function asActivity($cur=null)
1738     {
1739         $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1740
1741         if ($act instanceof Activity) {
1742             return $act;
1743         }
1744         $act = new Activity();
1745
1746         if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1747
1748             $act->id      = $this->uri;
1749             $act->time    = strtotime($this->created);
1750             try {
1751                 $act->link    = $this->getUrl();
1752             } catch (InvalidUrlException $e) {
1753                 // The notice is probably a share or similar, which don't
1754                 // have a representational URL of their own.
1755             }
1756             $act->content = common_xml_safe_str($this->rendered);
1757
1758             $profile = $this->getProfile();
1759
1760             $act->actor            = $profile->asActivityObject();
1761             $act->actor->extra[]   = $profile->profileInfo($cur);
1762
1763             $act->verb = $this->verb;
1764
1765             if ($this->repeat_of) {
1766                 $repeated = Notice::getKV('id', $this->repeat_of);
1767                 if ($repeated instanceof Notice) {
1768                     $act->objects[] = $repeated->asActivity($cur);
1769                 }
1770             } else {
1771                 $act->objects[] = $this->asActivityObject();
1772             }
1773
1774             // XXX: should this be handled by default processing for object entry?
1775
1776             // Categories
1777
1778             $tags = $this->getTags();
1779
1780             foreach ($tags as $tag) {
1781                 $cat       = new AtomCategory();
1782                 $cat->term = $tag;
1783
1784                 $act->categories[] = $cat;
1785             }
1786
1787             // Enclosures
1788             // XXX: use Atom Media and/or File activity objects instead
1789
1790             $attachments = $this->attachments();
1791
1792             foreach ($attachments as $attachment) {
1793                 // Save local attachments
1794                 if (!empty($attachment->filename)) {
1795                     $act->attachments[] = ActivityObject::fromFile($attachment);
1796                 }
1797             }
1798
1799             $ctx = new ActivityContext();
1800
1801             try {
1802                 $reply = $this->getParent();
1803                 $ctx->replyToID  = $reply->getUri();
1804                 $ctx->replyToUrl = $reply->getUrl();
1805             } catch (Exception $e) {
1806                 // This is not a reply to something
1807             }
1808
1809             $ctx->location = $this->getLocation();
1810
1811             $conv = null;
1812
1813             if (!empty($this->conversation)) {
1814                 $conv = Conversation::getKV('id', $this->conversation);
1815                 if ($conv instanceof Conversation) {
1816                     $ctx->conversation = $conv->uri;
1817                 }
1818             }
1819
1820             $reply_ids = $this->getReplies();
1821
1822             foreach ($reply_ids as $id) {
1823                 $rprofile = Profile::getKV('id', $id);
1824                 if ($rprofile instanceof Profile) {
1825                     $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1826                 }
1827             }
1828
1829             $groups = $this->getGroups();
1830
1831             foreach ($groups as $group) {
1832                 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1833             }
1834
1835             switch ($this->scope) {
1836             case Notice::PUBLIC_SCOPE:
1837                 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1838                 break;
1839             case Notice::FOLLOWER_SCOPE:
1840                 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1841                 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1842                 break;
1843             }
1844
1845             $act->context = $ctx;
1846
1847             $source = $this->getSource();
1848
1849             if ($source instanceof Notice_source) {
1850                 $act->generator = ActivityObject::fromNoticeSource($source);
1851             }
1852
1853             // Source
1854
1855             $atom_feed = $profile->getAtomFeed();
1856
1857             if (!empty($atom_feed)) {
1858
1859                 $act->source = new ActivitySource();
1860
1861                 // XXX: we should store the actual feed ID
1862
1863                 $act->source->id = $atom_feed;
1864
1865                 // XXX: we should store the actual feed title
1866
1867                 $act->source->title = $profile->getBestName();
1868
1869                 $act->source->links['alternate'] = $profile->profileurl;
1870                 $act->source->links['self']      = $atom_feed;
1871
1872                 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1873
1874                 $notice = $profile->getCurrentNotice();
1875
1876                 if ($notice instanceof Notice) {
1877                     $act->source->updated = self::utcDate($notice->created);
1878                 }
1879
1880                 $user = User::getKV('id', $profile->id);
1881
1882                 if ($user instanceof User) {
1883                     $act->source->links['license'] = common_config('license', 'url');
1884                 }
1885             }
1886
1887             if ($this->isLocal()) {
1888                 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1889                                                                            'format' => 'atom'));
1890                 $act->editLink = $act->selfLink;
1891             }
1892
1893             Event::handle('EndNoticeAsActivity', array($this, &$act));
1894         }
1895
1896         self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1897
1898         return $act;
1899     }
1900
1901     // This has gotten way too long. Needs to be sliced up into functional bits
1902     // or ideally exported to a utility class.
1903
1904     function asAtomEntry($namespace=false,
1905                          $source=false,
1906                          $author=true,
1907                          $cur=null)
1908     {
1909         $act = $this->asActivity($cur);
1910         $act->extra[] = $this->noticeInfo($cur);
1911         return $act->asString($namespace, $author, $source);
1912     }
1913
1914     /**
1915      * Extra notice info for atom entries
1916      *
1917      * Clients use some extra notice info in the atom stream.
1918      * This gives it to them.
1919      *
1920      * @param User $cur Current user
1921      *
1922      * @return array representation of <statusnet:notice_info> element
1923      */
1924
1925     function noticeInfo($cur)
1926     {
1927         // local notice ID (useful to clients for ordering)
1928
1929         $noticeInfoAttr = array('local_id' => $this->id);
1930
1931         // notice source
1932
1933         $ns = $this->getSource();
1934
1935         if ($ns instanceof Notice_source) {
1936             $noticeInfoAttr['source'] =  $ns->code;
1937             if (!empty($ns->url)) {
1938                 $noticeInfoAttr['source_link'] = $ns->url;
1939                 if (!empty($ns->name)) {
1940                     $noticeInfoAttr['source'] =  '<a href="'
1941                         . htmlspecialchars($ns->url)
1942                         . '" rel="nofollow">'
1943                         . htmlspecialchars($ns->name)
1944                         . '</a>';
1945                 }
1946             }
1947         }
1948
1949         // favorite and repeated
1950
1951         $scoped = null;
1952         if (!empty($cur)) {
1953             $scoped = $cur->getProfile();
1954             $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
1955         }
1956
1957         if (!empty($this->repeat_of)) {
1958             $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1959         }
1960
1961         Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
1962
1963         return array('statusnet:notice_info', $noticeInfoAttr, null);
1964     }
1965
1966     /**
1967      * Returns an XML string fragment with a reference to a notice as an
1968      * Activity Streams noun object with the given element type.
1969      *
1970      * Assumes that 'activity' namespace has been previously defined.
1971      *
1972      * @param string $element one of 'subject', 'object', 'target'
1973      * @return string
1974      */
1975
1976     function asActivityNoun($element)
1977     {
1978         $noun = $this->asActivityObject();
1979         return $noun->asString('activity:' . $element);
1980     }
1981
1982     public function asActivityObject()
1983     {
1984         $object = new ActivityObject();
1985
1986         if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
1987             $object->type    = $this->object_type ?: ActivityObject::NOTE;
1988             $object->id      = $this->getUri();
1989             $object->title   = sprintf('New %1$s by %2$s', $object->type, $this->getProfile()->getNickname());
1990             $object->content = $this->rendered;
1991             $object->link    = $this->getUrl();
1992
1993             $object->extra[] = array('status_net', array('notice_id' => $this->id));
1994
1995             Event::handle('EndActivityObjectFromNotice', array($this, &$object));
1996         }
1997
1998         return $object;
1999     }
2000
2001     /**
2002      * Determine which notice, if any, a new notice is in reply to.
2003      *
2004      * For conversation tracking, we try to see where this notice fits
2005      * in the tree. Beware that this may very well give false positives
2006      * and add replies to wrong threads (if there have been newer posts
2007      * by the same user as we're replying to).
2008      *
2009      * @param Profile $sender     Author profile
2010      * @param string  $content    Final notice content
2011      *
2012      * @return integer ID of replied-to notice, or null for not a reply.
2013      */
2014
2015     static function getInlineReplyTo(Profile $sender, $content)
2016     {
2017         // Is there an initial @ or T?
2018         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
2019                 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
2020             $nickname = common_canonical_nickname($match[1]);
2021         } else {
2022             return null;
2023         }
2024
2025         // Figure out who that is.
2026         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
2027
2028         if ($recipient instanceof Profile) {
2029             // Get their last notice
2030             $last = $recipient->getCurrentNotice();
2031             if ($last instanceof Notice) {
2032                 return $last;
2033             }
2034             // Maybe in the future we want to handle something else below
2035             // so don't return getCurrentNotice() immediately.
2036         }
2037
2038         return null;
2039     }
2040
2041     static function maxContent()
2042     {
2043         $contentlimit = common_config('notice', 'contentlimit');
2044         // null => use global limit (distinct from 0!)
2045         if (is_null($contentlimit)) {
2046             $contentlimit = common_config('site', 'textlimit');
2047         }
2048         return $contentlimit;
2049     }
2050
2051     static function contentTooLong($content)
2052     {
2053         $contentlimit = self::maxContent();
2054         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
2055     }
2056
2057     function getLocation()
2058     {
2059         $location = null;
2060
2061         if (!empty($this->location_id) && !empty($this->location_ns)) {
2062             $location = Location::fromId($this->location_id, $this->location_ns);
2063         }
2064
2065         if (is_null($location)) { // no ID, or Location::fromId() failed
2066             if (!empty($this->lat) && !empty($this->lon)) {
2067                 $location = Location::fromLatLon($this->lat, $this->lon);
2068             }
2069         }
2070
2071         return $location;
2072     }
2073
2074     /**
2075      * Convenience function for posting a repeat of an existing message.
2076      *
2077      * @param Profile $repeater Profile which is doing the repeat
2078      * @param string $source: posting source key, eg 'web', 'api', etc
2079      * @return Notice
2080      *
2081      * @throws Exception on failure or permission problems
2082      */
2083     function repeat(Profile $repeater, $source)
2084     {
2085         $author = $this->getProfile();
2086
2087         // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
2088         // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
2089         $content = sprintf(_('RT @%1$s %2$s'),
2090                            $author->getNickname(),
2091                            $this->content);
2092
2093         // Scope is same as this one's
2094         return self::saveNew($repeater->id,
2095                              $content,
2096                              $source,
2097                              array('repeat_of' => $this->id,
2098                                    'scope' => $this->scope));
2099     }
2100
2101     // These are supposed to be in chron order!
2102
2103     function repeatStream($limit=100)
2104     {
2105         $cache = Cache::instance();
2106
2107         if (empty($cache)) {
2108             $ids = $this->_repeatStreamDirect($limit);
2109         } else {
2110             $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
2111             if ($idstr !== false) {
2112                 if (empty($idstr)) {
2113                         $ids = array();
2114                 } else {
2115                         $ids = explode(',', $idstr);
2116                 }
2117             } else {
2118                 $ids = $this->_repeatStreamDirect(100);
2119                 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
2120             }
2121             if ($limit < 100) {
2122                 // We do a max of 100, so slice down to limit
2123                 $ids = array_slice($ids, 0, $limit);
2124             }
2125         }
2126
2127         return NoticeStream::getStreamByIds($ids);
2128     }
2129
2130     function _repeatStreamDirect($limit)
2131     {
2132         $notice = new Notice();
2133
2134         $notice->selectAdd(); // clears it
2135         $notice->selectAdd('id');
2136
2137         $notice->repeat_of = $this->id;
2138
2139         $notice->orderBy('created, id'); // NB: asc!
2140
2141         if (!is_null($limit)) {
2142             $notice->limit(0, $limit);
2143         }
2144
2145         return $notice->fetchAll('id');
2146     }
2147
2148     function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
2149     {
2150         $options = array();
2151
2152         if (!empty($location_id) && !empty($location_ns)) {
2153             $options['location_id'] = $location_id;
2154             $options['location_ns'] = $location_ns;
2155
2156             $location = Location::fromId($location_id, $location_ns);
2157
2158             if ($location instanceof Location) {
2159                 $options['lat'] = $location->lat;
2160                 $options['lon'] = $location->lon;
2161             }
2162
2163         } else if (!empty($lat) && !empty($lon)) {
2164             $options['lat'] = $lat;
2165             $options['lon'] = $lon;
2166
2167             $location = Location::fromLatLon($lat, $lon);
2168
2169             if ($location instanceof Location) {
2170                 $options['location_id'] = $location->location_id;
2171                 $options['location_ns'] = $location->location_ns;
2172             }
2173         } else if (!empty($profile)) {
2174             if (isset($profile->lat) && isset($profile->lon)) {
2175                 $options['lat'] = $profile->lat;
2176                 $options['lon'] = $profile->lon;
2177             }
2178
2179             if (isset($profile->location_id) && isset($profile->location_ns)) {
2180                 $options['location_id'] = $profile->location_id;
2181                 $options['location_ns'] = $profile->location_ns;
2182             }
2183         }
2184
2185         return $options;
2186     }
2187
2188     function clearAttentions()
2189     {
2190         $att = new Attention();
2191         $att->notice_id = $this->getID();
2192
2193         if ($att->find()) {
2194             while ($att->fetch()) {
2195                 // Can't do delete() on the object directly since it won't remove all of it
2196                 $other = clone($att);
2197                 $other->delete();
2198             }
2199         }
2200     }
2201
2202     function clearReplies()
2203     {
2204         $replyNotice = new Notice();
2205         $replyNotice->reply_to = $this->id;
2206
2207         //Null any notices that are replies to this notice
2208
2209         if ($replyNotice->find()) {
2210             while ($replyNotice->fetch()) {
2211                 $orig = clone($replyNotice);
2212                 $replyNotice->reply_to = null;
2213                 $replyNotice->update($orig);
2214             }
2215         }
2216
2217         // Reply records
2218
2219         $reply = new Reply();
2220         $reply->notice_id = $this->id;
2221
2222         if ($reply->find()) {
2223             while($reply->fetch()) {
2224                 self::blow('reply:stream:%d', $reply->profile_id);
2225                 $reply->delete();
2226             }
2227         }
2228
2229         $reply->free();
2230     }
2231
2232     function clearFiles()
2233     {
2234         $f2p = new File_to_post();
2235
2236         $f2p->post_id = $this->id;
2237
2238         if ($f2p->find()) {
2239             while ($f2p->fetch()) {
2240                 $f2p->delete();
2241             }
2242         }
2243         // FIXME: decide whether to delete File objects
2244         // ...and related (actual) files
2245     }
2246
2247     function clearRepeats()
2248     {
2249         $repeatNotice = new Notice();
2250         $repeatNotice->repeat_of = $this->id;
2251
2252         //Null any notices that are repeats of this notice
2253
2254         if ($repeatNotice->find()) {
2255             while ($repeatNotice->fetch()) {
2256                 $orig = clone($repeatNotice);
2257                 $repeatNotice->repeat_of = null;
2258                 $repeatNotice->update($orig);
2259             }
2260         }
2261     }
2262
2263     function clearTags()
2264     {
2265         $tag = new Notice_tag();
2266         $tag->notice_id = $this->id;
2267
2268         if ($tag->find()) {
2269             while ($tag->fetch()) {
2270                 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2271                 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2272                 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2273                 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2274                 $tag->delete();
2275             }
2276         }
2277
2278         $tag->free();
2279     }
2280
2281     function clearGroupInboxes()
2282     {
2283         $gi = new Group_inbox();
2284
2285         $gi->notice_id = $this->id;
2286
2287         if ($gi->find()) {
2288             while ($gi->fetch()) {
2289                 self::blow('user_group:notice_ids:%d', $gi->group_id);
2290                 $gi->delete();
2291             }
2292         }
2293
2294         $gi->free();
2295     }
2296
2297     function distribute()
2298     {
2299         // We always insert for the author so they don't
2300         // have to wait
2301         Event::handle('StartNoticeDistribute', array($this));
2302
2303         // If there's a failure, we want to _force_
2304         // distribution at this point.
2305         try {
2306             $qm = QueueManager::get();
2307             $qm->enqueue($this, 'distrib');
2308         } catch (Exception $e) {
2309             // If the exception isn't transient, this
2310             // may throw more exceptions as DQH does
2311             // its own enqueueing. So, we ignore them!
2312             try {
2313                 $handler = new DistribQueueHandler();
2314                 $handler->handle($this);
2315             } catch (Exception $e) {
2316                 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2317             }
2318             // Re-throw so somebody smarter can handle it.
2319             throw $e;
2320         }
2321     }
2322
2323     function insert()
2324     {
2325         $result = parent::insert();
2326
2327         if ($result === false) {
2328             common_log_db_error($this, 'INSERT', __FILE__);
2329             // TRANS: Server exception thrown when a stored object entry cannot be saved.
2330             throw new ServerException('Could not save Notice');
2331         }
2332
2333         // Profile::hasRepeated() abuses pkeyGet(), so we
2334         // have to clear manually
2335         if (!empty($this->repeat_of)) {
2336             $c = self::memcache();
2337             if (!empty($c)) {
2338                 $ck = self::multicacheKey('Notice',
2339                                           array('profile_id' => $this->profile_id,
2340                                                 'repeat_of' => $this->repeat_of));
2341                 $c->delete($ck);
2342             }
2343         }
2344
2345         // Update possibly ID-dependent columns: URI, conversation
2346         // (now that INSERT has added the notice's local id)
2347         $orig = clone($this);
2348         $changed = false;
2349
2350         // We can only get here if it's a local notice, since remote notices
2351         // should've bailed out earlier due to lacking a URI.
2352         if (empty($this->uri)) {
2353             $this->uri = sprintf('%s%s=%d:%s=%s',
2354                                 TagURI::mint(),
2355                                 'noticeId', $this->id,
2356                                 'objectType', $this->get_object_type(true));
2357             $changed = true;
2358         }
2359
2360         // If it's not part of a conversation, it's
2361         // the beginning of a new conversation.
2362         if (empty($this->conversation)) {
2363             $conv = Conversation::create($this);
2364             $this->conversation = $conv->id;
2365             $changed = true;
2366         }
2367
2368         if ($changed && $this->update($orig) === false) {
2369             common_log_db_error($notice, 'UPDATE', __FILE__);
2370             // TRANS: Server exception thrown when a notice cannot be updated.
2371             throw new ServerException(_('Problem saving notice.'));
2372         }
2373
2374         $this->blowOnInsert();
2375
2376         return $result;
2377     }
2378
2379     /**
2380      * Get the source of the notice
2381      *
2382      * @return Notice_source $ns A notice source object. 'code' is the only attribute
2383      *                           guaranteed to be populated.
2384      */
2385     function getSource()
2386     {
2387         $ns = new Notice_source();
2388         if (!empty($this->source)) {
2389             switch ($this->source) {
2390             case 'web':
2391             case 'xmpp':
2392             case 'mail':
2393             case 'omb':
2394             case 'system':
2395             case 'api':
2396                 $ns->code = $this->source;
2397                 break;
2398             default:
2399                 $ns = Notice_source::getKV($this->source);
2400                 if (!$ns) {
2401                     $ns = new Notice_source();
2402                     $ns->code = $this->source;
2403                     $app = Oauth_application::getKV('name', $this->source);
2404                     if ($app) {
2405                         $ns->name = $app->name;
2406                         $ns->url  = $app->source_url;
2407                     }
2408                 }
2409                 break;
2410             }
2411         }
2412         return $ns;
2413     }
2414
2415     /**
2416      * Determine whether the notice was locally created
2417      *
2418      * @return boolean locality
2419      */
2420
2421     public function isLocal()
2422     {
2423         return ($this->is_local == Notice::LOCAL_PUBLIC ||
2424                 $this->is_local == Notice::LOCAL_NONPUBLIC);
2425     }
2426
2427     /**
2428      * Get the list of hash tags saved with this notice.
2429      *
2430      * @return array of strings
2431      */
2432     public function getTags()
2433     {
2434         $tags = array();
2435
2436         $keypart = sprintf('notice:tags:%d', $this->id);
2437
2438         $tagstr = self::cacheGet($keypart);
2439
2440         if ($tagstr !== false) {
2441             $tags = explode(',', $tagstr);
2442         } else {
2443             $tag = new Notice_tag();
2444             $tag->notice_id = $this->id;
2445             if ($tag->find()) {
2446                 while ($tag->fetch()) {
2447                     $tags[] = $tag->tag;
2448                 }
2449             }
2450             self::cacheSet($keypart, implode(',', $tags));
2451         }
2452
2453         return $tags;
2454     }
2455
2456     static private function utcDate($dt)
2457     {
2458         $dateStr = date('d F Y H:i:s', strtotime($dt));
2459         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2460         return $d->format(DATE_W3C);
2461     }
2462
2463     /**
2464      * Look up the creation timestamp for a given notice ID, even
2465      * if it's been deleted.
2466      *
2467      * @param int $id
2468      * @return mixed string recorded creation timestamp, or false if can't be found
2469      */
2470     public static function getAsTimestamp($id)
2471     {
2472         if (!$id) {
2473             return false;
2474         }
2475
2476         $notice = Notice::getKV('id', $id);
2477         if ($notice) {
2478             return $notice->created;
2479         }
2480
2481         $deleted = Deleted_notice::getKV('id', $id);
2482         if ($deleted) {
2483             return $deleted->created;
2484         }
2485
2486         return false;
2487     }
2488
2489     /**
2490      * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2491      * parameter, matching notices posted after the given one (exclusive).
2492      *
2493      * If the referenced notice can't be found, will return false.
2494      *
2495      * @param int $id
2496      * @param string $idField
2497      * @param string $createdField
2498      * @return mixed string or false if no match
2499      */
2500     public static function whereSinceId($id, $idField='id', $createdField='created')
2501     {
2502         $since = Notice::getAsTimestamp($id);
2503         if ($since) {
2504             return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2505         }
2506         return false;
2507     }
2508
2509     /**
2510      * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2511      * parameter, matching notices posted after the given one (exclusive), and
2512      * if necessary add it to the data object's query.
2513      *
2514      * @param DB_DataObject $obj
2515      * @param int $id
2516      * @param string $idField
2517      * @param string $createdField
2518      * @return mixed string or false if no match
2519      */
2520     public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2521     {
2522         $since = self::whereSinceId($id, $idField, $createdField);
2523         if ($since) {
2524             $obj->whereAdd($since);
2525         }
2526     }
2527
2528     /**
2529      * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2530      * parameter, matching notices posted before the given one (inclusive).
2531      *
2532      * If the referenced notice can't be found, will return false.
2533      *
2534      * @param int $id
2535      * @param string $idField
2536      * @param string $createdField
2537      * @return mixed string or false if no match
2538      */
2539     public static function whereMaxId($id, $idField='id', $createdField='created')
2540     {
2541         $max = Notice::getAsTimestamp($id);
2542         if ($max) {
2543             return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2544         }
2545         return false;
2546     }
2547
2548     /**
2549      * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2550      * parameter, matching notices posted before the given one (inclusive), and
2551      * if necessary add it to the data object's query.
2552      *
2553      * @param DB_DataObject $obj
2554      * @param int $id
2555      * @param string $idField
2556      * @param string $createdField
2557      * @return mixed string or false if no match
2558      */
2559     public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2560     {
2561         $max = self::whereMaxId($id, $idField, $createdField);
2562         if ($max) {
2563             $obj->whereAdd($max);
2564         }
2565     }
2566
2567     function isPublic()
2568     {
2569         if (common_config('public', 'localonly')) {
2570             return ($this->is_local == Notice::LOCAL_PUBLIC);
2571         } else {
2572             return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2573                     ($this->is_local != Notice::GATEWAY));
2574         }
2575     }
2576
2577     /**
2578      * Check that the given profile is allowed to read, respond to, or otherwise
2579      * act on this notice.
2580      *
2581      * The $scope member is a bitmask of scopes, representing a logical AND of the
2582      * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2583      * "only visible to people who are mentioned in the notice AND are users on this site."
2584      * Users on the site who are not mentioned in the notice will not be able to see the
2585      * notice.
2586      *
2587      * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2588      *
2589      * @return boolean whether the profile is in the notice's scope
2590      */
2591     function inScope($profile)
2592     {
2593         if (is_null($profile)) {
2594             $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2595         } else {
2596             $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2597         }
2598
2599         $result = self::cacheGet($keypart);
2600
2601         if ($result === false) {
2602             $bResult = false;
2603             if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2604                 $bResult = $this->_inScope($profile);
2605                 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2606             }
2607             $result = ($bResult) ? 1 : 0;
2608             self::cacheSet($keypart, $result, 0, 300);
2609         }
2610
2611         return ($result == 1) ? true : false;
2612     }
2613
2614     protected function _inScope($profile)
2615     {
2616         if (!is_null($this->scope)) {
2617             $scope = $this->scope;
2618         } else {
2619             $scope = self::defaultScope();
2620         }
2621
2622         // If there's no scope, anyone (even anon) is in scope.
2623
2624         if ($scope == 0) { // Not private
2625
2626             return !$this->isHiddenSpam($profile);
2627
2628         } else { // Private, somehow
2629
2630             // If there's scope, anon cannot be in scope
2631
2632             if (empty($profile)) {
2633                 return false;
2634             }
2635
2636             // Author is always in scope
2637
2638             if ($this->profile_id == $profile->id) {
2639                 return true;
2640             }
2641
2642             // Only for users on this site
2643
2644             if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2645                 return false;
2646             }
2647
2648             // Only for users mentioned in the notice
2649
2650             if ($scope & Notice::ADDRESSEE_SCOPE) {
2651
2652                 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2653                                              'profile_id' => $profile->id));
2654                                                                                  
2655                 if (!$reply instanceof Reply) {
2656                     return false;
2657                 }
2658             }
2659
2660             // Only for members of the given group
2661
2662             if ($scope & Notice::GROUP_SCOPE) {
2663
2664                 // XXX: just query for the single membership
2665
2666                 $groups = $this->getGroups();
2667
2668                 $foundOne = false;
2669
2670                 foreach ($groups as $group) {
2671                     if ($profile->isMember($group)) {
2672                         $foundOne = true;
2673                         break;
2674                     }
2675                 }
2676
2677                 if (!$foundOne) {
2678                     return false;
2679                 }
2680             }
2681
2682             // Only for followers of the author
2683
2684             $author = null;
2685
2686             if ($scope & Notice::FOLLOWER_SCOPE) {
2687
2688                 try {
2689                     $author = $this->getProfile();
2690                 } catch (Exception $e) {
2691                     return false;
2692                 }
2693         
2694                 if (!Subscription::exists($profile, $author)) {
2695                     return false;
2696                 }
2697             }
2698
2699             return !$this->isHiddenSpam($profile);
2700         }
2701     }
2702
2703     function isHiddenSpam($profile) {
2704         
2705         // Hide posts by silenced users from everyone but moderators.
2706
2707         if (common_config('notice', 'hidespam')) {
2708
2709             try {
2710                 $author = $this->getProfile();
2711             } catch(Exception $e) {
2712                 // If we can't get an author, keep it hidden.
2713                 // XXX: technically not spam, but, whatever.
2714                 return true;
2715             }
2716
2717             if ($author->hasRole(Profile_role::SILENCED)) {
2718                 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2719                     return true;
2720                 }
2721             }
2722         }
2723
2724         return false;
2725     }
2726
2727     public function getParent()
2728     {
2729         $parent = Notice::getKV('id', $this->reply_to);
2730
2731         if (!$parent instanceof Notice) {
2732             throw new ServerException('Notice has no parent');
2733         }
2734
2735         return $parent;
2736     }
2737
2738     /**
2739      * Magic function called at serialize() time.
2740      *
2741      * We use this to drop a couple process-specific references
2742      * from DB_DataObject which can cause trouble in future
2743      * processes.
2744      *
2745      * @return array of variable names to include in serialization.
2746      */
2747
2748     function __sleep()
2749     {
2750         $vars = parent::__sleep();
2751         $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2752         return array_diff($vars, $skip);
2753     }
2754     
2755     static function defaultScope()
2756     {
2757         $scope = common_config('notice', 'defaultscope');
2758         if (is_null($scope)) {
2759                 if (common_config('site', 'private')) {
2760                         $scope = 1;
2761                 } else {
2762                         $scope = 0;
2763                 }
2764         }
2765         return $scope;
2766     }
2767
2768         static function fillProfiles($notices)
2769         {
2770                 $map = self::getProfiles($notices);
2771                 
2772                 foreach ($notices as $entry=>$notice) {
2773             try {
2774                         if (array_key_exists($notice->profile_id, $map)) {
2775                                 $notice->_setProfile($map[$notice->profile_id]);
2776                         }
2777             } catch (NoProfileException $e) {
2778                 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2779                 unset($notices[$entry]);
2780             }
2781                 }
2782                 
2783                 return array_values($map);
2784         }
2785         
2786         static function getProfiles(&$notices)
2787         {
2788                 $ids = array();
2789                 foreach ($notices as $notice) {
2790                         $ids[] = $notice->profile_id;
2791                 }
2792                 
2793                 $ids = array_unique($ids);
2794                 
2795                 return Profile::pivotGet('id', $ids); 
2796         }
2797         
2798         static function fillGroups(&$notices)
2799         {
2800         $ids = self::_idsOf($notices);
2801                 
2802         $gis = Group_inbox::listGet('notice_id', $ids);
2803                 
2804         $gids = array();
2805
2806                 foreach ($gis as $id => $gi)
2807                 {
2808                     foreach ($gi as $g)
2809                     {
2810                         $gids[] = $g->group_id;
2811                     }
2812                 }
2813                 
2814                 $gids = array_unique($gids);
2815                 
2816                 $group = User_group::pivotGet('id', $gids);
2817                 
2818                 foreach ($notices as $notice)
2819                 {
2820                         $grps = array();
2821                         $gi = $gis[$notice->id];
2822                         foreach ($gi as $g) {
2823                             $grps[] = $group[$g->group_id];
2824                         }
2825                     $notice->_setGroups($grps);
2826                 }
2827         }
2828
2829     static function _idsOf(array &$notices)
2830     {
2831                 $ids = array();
2832                 foreach ($notices as $notice) {
2833                         $ids[$notice->id] = true;
2834                 }
2835                 return array_keys($ids);
2836     }
2837
2838     static function fillAttachments(&$notices)
2839     {
2840         $ids = self::_idsOf($notices);
2841
2842         $f2pMap = File_to_post::listGet('post_id', $ids);
2843                 
2844                 $fileIds = array();
2845                 
2846                 foreach ($f2pMap as $noticeId => $f2ps) {
2847             foreach ($f2ps as $f2p) {
2848                 $fileIds[] = $f2p->file_id;    
2849             }
2850         }
2851
2852         $fileIds = array_unique($fileIds);
2853
2854                 $fileMap = File::pivotGet('id', $fileIds);
2855
2856                 foreach ($notices as $notice)
2857                 {
2858                         $files = array();
2859                         $f2ps = $f2pMap[$notice->id];
2860                         foreach ($f2ps as $f2p) {
2861                             $files[] = $fileMap[$f2p->file_id];
2862                         }
2863                     $notice->_setAttachments($files);
2864                 }
2865     }
2866
2867     static function fillReplies(&$notices)
2868     {
2869         $ids = self::_idsOf($notices);
2870         $replyMap = Reply::listGet('notice_id', $ids);
2871         foreach ($notices as $notice) {
2872             $replies = $replyMap[$notice->id];
2873             $ids = array();
2874             foreach ($replies as $reply) {
2875                 $ids[] = $reply->profile_id;
2876             }
2877             $notice->_setReplies($ids);
2878         }
2879     }
2880
2881     protected $_repeats = array();
2882
2883     function getRepeats()
2884     {
2885         if (isset($this->_repeats[$this->id])) {
2886             return $this->_repeats[$this->id];
2887         }
2888         $repeatMap = Notice::listGet('repeat_of', array($this->id));
2889         $this->_repeats[$this->id] = $repeatMap[$this->id];
2890         return $this->_repeats[$this->id];
2891     }
2892
2893     function _setRepeats($repeats)
2894     {
2895         $this->_repeats[$this->id] = $repeats;
2896     }
2897
2898     static function fillRepeats(&$notices)
2899     {
2900         $ids = self::_idsOf($notices);
2901         $repeatMap = Notice::listGet('repeat_of', $ids);
2902         foreach ($notices as $notice) {
2903                 $repeats = $repeatMap[$notice->id];
2904             $notice->_setRepeats($repeats);
2905         }
2906     }
2907 }