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