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