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