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