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