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