]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
Merge branch '1.0.x' into msn-plugin
[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         // Give plugins a chance to add folks in at start...
816         if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
817
818             foreach ($users as $id) {
819                 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
820             }
821
822             foreach ($groups as $group) {
823                 $users = $group->getUserMembers();
824                 foreach ($users as $id) {
825                     if (!array_key_exists($id, $ni)) {
826                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
827                     }
828                 }
829             }
830
831             foreach ($recipients as $recipient) {
832                 if (!array_key_exists($recipient, $ni)) {
833                     $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
834                 }
835             }
836
837             // Exclude any deleted, non-local, or blocking recipients.
838             $profile = $this->getProfile();
839             $originalProfile = null;
840             if ($this->repeat_of) {
841                 // Check blocks against the original notice's poster as well.
842                 $original = Notice::staticGet('id', $this->repeat_of);
843                 if ($original) {
844                     $originalProfile = $original->getProfile();
845                 }
846             }
847             foreach ($ni as $id => $source) {
848                 $user = User::staticGet('id', $id);
849                 if (empty($user) || $user->hasBlocked($profile) ||
850                     ($originalProfile && $user->hasBlocked($originalProfile))) {
851                     unset($ni[$id]);
852                 }
853             }
854
855             // Give plugins a chance to filter out...
856             Event::handle('EndNoticeWhoGets', array($this, &$ni));
857         }
858
859         if (!empty($c)) {
860             // XXX: pack this data better
861             $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
862         }
863
864         return $ni;
865     }
866
867     /**
868      * Adds this notice to the inboxes of each local user who should receive
869      * it, based on author subscriptions, group memberships, and @-replies.
870      *
871      * Warning: running a second time currently will make items appear
872      * multiple times in users' inboxes.
873      *
874      * @fixme make more robust against errors
875      * @fixme break up massive deliveries to smaller background tasks
876      *
877      * @param array $groups optional list of Group objects;
878      *              if left empty, will be loaded from group_inbox records
879      * @param array $recipient optional list of reply profile ids
880      *              if left empty, will be loaded from reply records
881      */
882     function addToInboxes($groups=null, $recipients=null)
883     {
884         $ni = $this->whoGets($groups, $recipients);
885
886         $ids = array_keys($ni);
887
888         // We remove the author (if they're a local user),
889         // since we'll have already done this in distribute()
890
891         $i = array_search($this->profile_id, $ids);
892
893         if ($i !== false) {
894             unset($ids[$i]);
895         }
896
897         // Bulk insert
898
899         Inbox::bulkInsert($this->id, $ids);
900
901         return;
902     }
903
904     function getSubscribedUsers()
905     {
906         $user = new User();
907
908         if(common_config('db','quote_identifiers'))
909           $user_table = '"user"';
910         else $user_table = 'user';
911
912         $qry =
913           'SELECT id ' .
914           'FROM '. $user_table .' JOIN subscription '.
915           'ON '. $user_table .'.id = subscription.subscriber ' .
916           'WHERE subscription.subscribed = %d ';
917
918         $user->query(sprintf($qry, $this->profile_id));
919
920         $ids = array();
921
922         while ($user->fetch()) {
923             $ids[] = $user->id;
924         }
925
926         $user->free();
927
928         return $ids;
929     }
930
931     /**
932      * Record this notice to the given group inboxes for delivery.
933      * Overrides the regular parsing of !group markup.
934      *
935      * @param string $group_ids
936      * @fixme might prefer URIs as identifiers, as for replies?
937      *        best with generalizations on user_group to support
938      *        remote groups better.
939      */
940     function saveKnownGroups($group_ids)
941     {
942         if (!is_array($group_ids)) {
943             // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
944             throw new ServerException(_('Bad type provided to saveKnownGroups.'));
945         }
946
947         $groups = array();
948         foreach (array_unique($group_ids) as $id) {
949             $group = User_group::staticGet('id', $id);
950             if ($group) {
951                 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
952                 $result = $this->addToGroupInbox($group);
953                 if (!$result) {
954                     common_log_db_error($gi, 'INSERT', __FILE__);
955                 }
956
957                 // @fixme should we save the tags here or not?
958                 $groups[] = clone($group);
959             } else {
960                 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
961             }
962         }
963
964         return $groups;
965     }
966
967     /**
968      * Parse !group delivery and record targets into group_inbox.
969      * @return array of Group objects
970      */
971     function saveGroups()
972     {
973         // Don't save groups for repeats
974
975         if (!empty($this->repeat_of)) {
976             return array();
977         }
978
979         $groups = array();
980
981         /* extract all !group */
982         $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
983                                 strtolower($this->content),
984                                 $match);
985         if (!$count) {
986             return $groups;
987         }
988
989         $profile = $this->getProfile();
990
991         /* Add them to the database */
992
993         foreach (array_unique($match[1]) as $nickname) {
994             /* XXX: remote groups. */
995             $group = User_group::getForNickname($nickname, $profile);
996
997             if (empty($group)) {
998                 continue;
999             }
1000
1001             // we automatically add a tag for every group name, too
1002
1003             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
1004                                              'notice_id' => $this->id));
1005
1006             if (is_null($tag)) {
1007                 $this->saveTag($nickname);
1008             }
1009
1010             if ($profile->isMember($group)) {
1011
1012                 $result = $this->addToGroupInbox($group);
1013
1014                 if (!$result) {
1015                     common_log_db_error($gi, 'INSERT', __FILE__);
1016                 }
1017
1018                 $groups[] = clone($group);
1019             }
1020         }
1021
1022         return $groups;
1023     }
1024
1025     function addToGroupInbox($group)
1026     {
1027         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1028                                          'notice_id' => $this->id));
1029
1030         if (empty($gi)) {
1031
1032             $gi = new Group_inbox();
1033
1034             $gi->group_id  = $group->id;
1035             $gi->notice_id = $this->id;
1036             $gi->created   = $this->created;
1037
1038             $result = $gi->insert();
1039
1040             if (!$result) {
1041                 common_log_db_error($gi, 'INSERT', __FILE__);
1042                 // TRANS: Server exception thrown when an update for a group inbox fails.
1043                 throw new ServerException(_('Problem saving group inbox.'));
1044             }
1045
1046             self::blow('user_group:notice_ids:%d', $gi->group_id);
1047         }
1048
1049         return true;
1050     }
1051
1052     /**
1053      * Save reply records indicating that this notice needs to be
1054      * delivered to the local users with the given URIs.
1055      *
1056      * Since this is expected to be used when saving foreign-sourced
1057      * messages, we won't deliver to any remote targets as that's the
1058      * source service's responsibility.
1059      *
1060      * Mail notifications etc will be handled later.
1061      *
1062      * @param array of unique identifier URIs for recipients
1063      */
1064     function saveKnownReplies($uris)
1065     {
1066         if (empty($uris)) {
1067             return;
1068         }
1069
1070         $sender = Profile::staticGet($this->profile_id);
1071
1072         foreach (array_unique($uris) as $uri) {
1073
1074             $profile = Profile::fromURI($uri);
1075
1076             if (empty($profile)) {
1077                 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1078                 continue;
1079             }
1080
1081             if ($profile->hasBlocked($sender)) {
1082                 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1083                 continue;
1084             }
1085
1086             $reply = new Reply();
1087
1088             $reply->notice_id  = $this->id;
1089             $reply->profile_id = $profile->id;
1090             $reply->modified   = $this->created;
1091
1092             common_log(LOG_INFO, __METHOD__ . ": saving reply: notice $this->id to profile $profile->id");
1093
1094             $id = $reply->insert();
1095         }
1096
1097         return;
1098     }
1099
1100     /**
1101      * Pull @-replies from this message's content in StatusNet markup format
1102      * and save reply records indicating that this message needs to be
1103      * delivered to those users.
1104      *
1105      * Mail notifications to local profiles will be sent later.
1106      *
1107      * @return array of integer profile IDs
1108      */
1109
1110     function saveReplies()
1111     {
1112         // Don't save reply data for repeats
1113
1114         if (!empty($this->repeat_of)) {
1115             return array();
1116         }
1117
1118         $sender = Profile::staticGet($this->profile_id);
1119
1120         // @todo ideally this parser information would only
1121         // be calculated once.
1122
1123         $mentions = common_find_mentions($this->content, $this);
1124
1125         $replied = array();
1126
1127         // store replied only for first @ (what user/notice what the reply directed,
1128         // we assume first @ is it)
1129
1130         foreach ($mentions as $mention) {
1131
1132             foreach ($mention['mentioned'] as $mentioned) {
1133
1134                 // skip if they're already covered
1135
1136                 if (!empty($replied[$mentioned->id])) {
1137                     continue;
1138                 }
1139
1140                 // Don't save replies from blocked profile to local user
1141
1142                 $mentioned_user = User::staticGet('id', $mentioned->id);
1143                 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1144                     continue;
1145                 }
1146
1147                 $reply = new Reply();
1148
1149                 $reply->notice_id  = $this->id;
1150                 $reply->profile_id = $mentioned->id;
1151                 $reply->modified   = $this->created;
1152
1153                 $id = $reply->insert();
1154
1155                 if (!$id) {
1156                     common_log_db_error($reply, 'INSERT', __FILE__);
1157                     // TRANS: Server exception thrown when a reply cannot be saved.
1158                     // TRANS: %1$d is a notice ID, %2$d is the ID of the mentioned user.
1159                     throw new ServerException(sprintf(_('Could not save reply for %1$d, %2$d.'), $this->id, $mentioned->id));
1160                 } else {
1161                     $replied[$mentioned->id] = 1;
1162                     self::blow('reply:stream:%d', $mentioned->id);
1163                 }
1164             }
1165         }
1166
1167         $recipientIds = array_keys($replied);
1168
1169         return $recipientIds;
1170     }
1171
1172     /**
1173      * Pull the complete list of @-reply targets for this notice.
1174      *
1175      * @return array of integer profile ids
1176      */
1177     function getReplies()
1178     {
1179         // XXX: cache me
1180
1181         $ids = array();
1182
1183         $reply = new Reply();
1184         $reply->selectAdd();
1185         $reply->selectAdd('profile_id');
1186         $reply->notice_id = $this->id;
1187
1188         if ($reply->find()) {
1189             while($reply->fetch()) {
1190                 $ids[] = $reply->profile_id;
1191             }
1192         }
1193
1194         $reply->free();
1195
1196         return $ids;
1197     }
1198
1199     /**
1200      * Send e-mail notifications to local @-reply targets.
1201      *
1202      * Replies must already have been saved; this is expected to be run
1203      * from the distrib queue handler.
1204      */
1205     function sendReplyNotifications()
1206     {
1207         // Don't send reply notifications for repeats
1208
1209         if (!empty($this->repeat_of)) {
1210             return array();
1211         }
1212
1213         $recipientIds = $this->getReplies();
1214
1215         foreach ($recipientIds as $recipientId) {
1216             $user = User::staticGet('id', $recipientId);
1217             if (!empty($user)) {
1218                 mail_notify_attn($user, $this);
1219             }
1220         }
1221     }
1222
1223     /**
1224      * Pull list of groups this notice needs to be delivered to,
1225      * as previously recorded by saveGroups() or saveKnownGroups().
1226      *
1227      * @return array of Group objects
1228      */
1229     function getGroups()
1230     {
1231         // Don't save groups for repeats
1232
1233         if (!empty($this->repeat_of)) {
1234             return array();
1235         }
1236
1237         // XXX: cache me
1238
1239         $groups = array();
1240
1241         $gi = new Group_inbox();
1242
1243         $gi->selectAdd();
1244         $gi->selectAdd('group_id');
1245
1246         $gi->notice_id = $this->id;
1247
1248         if ($gi->find()) {
1249             while ($gi->fetch()) {
1250                 $group = User_group::staticGet('id', $gi->group_id);
1251                 if ($group) {
1252                     $groups[] = $group;
1253                 }
1254             }
1255         }
1256
1257         $gi->free();
1258
1259         return $groups;
1260     }
1261
1262     /**
1263      * Convert a notice into an activity for export.
1264      *
1265      * @param User $cur Current user
1266      *
1267      * @return Activity activity object representing this Notice.
1268      */
1269
1270     function asActivity($cur)
1271     {
1272         $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1273
1274         if (!empty($act)) {
1275             return $act;
1276         }
1277         $act = new Activity();
1278
1279         if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1280
1281             $profile = $this->getProfile();
1282
1283             $act->actor            = ActivityObject::fromProfile($profile);
1284             $act->actor->extra[]   = $profile->profileInfo($cur);
1285             $act->verb             = ActivityVerb::POST;
1286             $act->objects[]        = ActivityObject::fromNotice($this);
1287
1288             // XXX: should this be handled by default processing for object entry?
1289
1290             $act->time    = strtotime($this->created);
1291             $act->link    = $this->bestUrl();
1292
1293             $act->content = common_xml_safe_str($this->rendered);
1294             $act->id      = $this->uri;
1295             $act->title   = common_xml_safe_str($this->content);
1296
1297             // Categories
1298
1299             $tags = $this->getTags();
1300
1301             foreach ($tags as $tag) {
1302                 $cat       = new AtomCategory();
1303                 $cat->term = $tag;
1304
1305                 $act->categories[] = $cat;
1306             }
1307
1308             // Enclosures
1309             // XXX: use Atom Media and/or File activity objects instead
1310
1311             $attachments = $this->attachments();
1312
1313             foreach ($attachments as $attachment) {
1314                 $enclosure = $attachment->getEnclosure();
1315                 if ($enclosure) {
1316                     $act->enclosures[] = $enclosure;
1317                 }
1318             }
1319
1320             $ctx = new ActivityContext();
1321
1322             if (!empty($this->reply_to)) {
1323                 $reply = Notice::staticGet('id', $this->reply_to);
1324                 if (!empty($reply)) {
1325                     $ctx->replyToID  = $reply->uri;
1326                     $ctx->replyToUrl = $reply->bestUrl();
1327                 }
1328             }
1329
1330             $ctx->location = $this->getLocation();
1331
1332             $conv = null;
1333
1334             if (!empty($this->conversation)) {
1335                 $conv = Conversation::staticGet('id', $this->conversation);
1336                 if (!empty($conv)) {
1337                     $ctx->conversation = $conv->uri;
1338                 }
1339             }
1340
1341             $reply_ids = $this->getReplies();
1342
1343             foreach ($reply_ids as $id) {
1344                 $profile = Profile::staticGet('id', $id);
1345                 if (!empty($profile)) {
1346                     $ctx->attention[] = $profile->getUri();
1347                 }
1348             }
1349
1350             $groups = $this->getGroups();
1351
1352             foreach ($groups as $group) {
1353                 $ctx->attention[] = $group->getUri();
1354             }
1355
1356             // XXX: deprecated; use ActivityVerb::SHARE instead
1357
1358             $repeat = null;
1359
1360             if (!empty($this->repeat_of)) {
1361                 $repeat = Notice::staticGet('id', $this->repeat_of);
1362                 $ctx->forwardID  = $repeat->uri;
1363                 $ctx->forwardUrl = $repeat->bestUrl();
1364             }
1365
1366             $act->context = $ctx;
1367
1368             // Source
1369
1370             $atom_feed = $profile->getAtomFeed();
1371
1372             if (!empty($atom_feed)) {
1373
1374                 $act->source = new ActivitySource();
1375
1376                 // XXX: we should store the actual feed ID
1377
1378                 $act->source->id = $atom_feed;
1379
1380                 // XXX: we should store the actual feed title
1381
1382                 $act->source->title = $profile->getBestName();
1383
1384                 $act->source->links['alternate'] = $profile->profileurl;
1385                 $act->source->links['self']      = $atom_feed;
1386
1387                 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1388
1389                 $notice = $profile->getCurrentNotice();
1390
1391                 if (!empty($notice)) {
1392                     $act->source->updated = self::utcDate($notice->created);
1393                 }
1394
1395                 $user = User::staticGet('id', $profile->id);
1396
1397                 if (!empty($user)) {
1398                     $act->source->links['license'] = common_config('license', 'url');
1399                 }
1400             }
1401
1402             if ($this->isLocal()) {
1403                 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1404                                                                            'format' => 'atom'));
1405                 $act->editLink = $act->selfLink;
1406             }
1407
1408             Event::handle('EndNoticeAsActivity', array($this, &$act));
1409         }
1410
1411         self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1412
1413         return $act;
1414     }
1415
1416     // This has gotten way too long. Needs to be sliced up into functional bits
1417     // or ideally exported to a utility class.
1418
1419     function asAtomEntry($namespace=false,
1420                          $source=false,
1421                          $author=true,
1422                          $cur=null)
1423     {
1424         $act = $this->asActivity($cur);
1425         $act->extra[] = $this->noticeInfo($cur);
1426         return $act->asString($namespace, $author, $source);
1427     }
1428
1429     /**
1430      * Extra notice info for atom entries
1431      *
1432      * Clients use some extra notice info in the atom stream.
1433      * This gives it to them.
1434      *
1435      * @param User $cur Current user
1436      *
1437      * @return array representation of <statusnet:notice_info> element
1438      */
1439
1440     function noticeInfo($cur)
1441     {
1442         // local notice ID (useful to clients for ordering)
1443
1444         $noticeInfoAttr = array('local_id' => $this->id);
1445
1446         // notice source
1447
1448         $ns = $this->getSource();
1449
1450         if (!empty($ns)) {
1451             $noticeInfoAttr['source'] =  $ns->code;
1452             if (!empty($ns->url)) {
1453                 $noticeInfoAttr['source_link'] = $ns->url;
1454                 if (!empty($ns->name)) {
1455                     $noticeInfoAttr['source'] =  '<a href="'
1456                         . htmlspecialchars($ns->url)
1457                         . '" rel="nofollow">'
1458                         . htmlspecialchars($ns->name)
1459                         . '</a>';
1460                 }
1461             }
1462         }
1463
1464         // favorite and repeated
1465
1466         if (!empty($cur)) {
1467             $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1468             $cp = $cur->getProfile();
1469             $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this->id)) ? "true" : "false";
1470         }
1471
1472         if (!empty($this->repeat_of)) {
1473             $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1474         }
1475
1476         return array('statusnet:notice_info', $noticeInfoAttr, null);
1477     }
1478
1479     /**
1480      * Returns an XML string fragment with a reference to a notice as an
1481      * Activity Streams noun object with the given element type.
1482      *
1483      * Assumes that 'activity' namespace has been previously defined.
1484      *
1485      * @param string $element one of 'subject', 'object', 'target'
1486      * @return string
1487      */
1488
1489     function asActivityNoun($element)
1490     {
1491         $noun = ActivityObject::fromNotice($this);
1492         return $noun->asString('activity:' . $element);
1493     }
1494
1495     function bestUrl()
1496     {
1497         if (!empty($this->url)) {
1498             return $this->url;
1499         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1500             return $this->uri;
1501         } else {
1502             return common_local_url('shownotice',
1503                                     array('notice' => $this->id));
1504         }
1505     }
1506
1507     function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0)
1508     {
1509         $cache = Cache::instance();
1510
1511         if (empty($cache) ||
1512             $since_id != 0 || $max_id != 0 ||
1513             is_null($limit) ||
1514             ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1515             return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1516                                                                       $max_id)));
1517         }
1518
1519         $idkey = Cache::key($cachekey);
1520
1521         $idstr = $cache->get($idkey);
1522
1523         if ($idstr !== false) {
1524             // Cache hit! Woohoo!
1525             $window = explode(',', $idstr);
1526             $ids = array_slice($window, $offset, $limit);
1527             return $ids;
1528         }
1529
1530         $laststr = $cache->get($idkey.';last');
1531
1532         if ($laststr !== false) {
1533             $window = explode(',', $laststr);
1534             $last_id = $window[0];
1535             $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1536                                                                           $last_id, 0, null)));
1537
1538             $new_window = array_merge($new_ids, $window);
1539
1540             $new_windowstr = implode(',', $new_window);
1541
1542             $result = $cache->set($idkey, $new_windowstr);
1543             $result = $cache->set($idkey . ';last', $new_windowstr);
1544
1545             $ids = array_slice($new_window, $offset, $limit);
1546
1547             return $ids;
1548         }
1549
1550         $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1551                                                                      0, 0, null)));
1552
1553         $windowstr = implode(',', $window);
1554
1555         $result = $cache->set($idkey, $windowstr);
1556         $result = $cache->set($idkey . ';last', $windowstr);
1557
1558         $ids = array_slice($window, $offset, $limit);
1559
1560         return $ids;
1561     }
1562
1563     /**
1564      * Determine which notice, if any, a new notice is in reply to.
1565      *
1566      * For conversation tracking, we try to see where this notice fits
1567      * in the tree. Rough algorithm is:
1568      *
1569      * if (reply_to is set and valid) {
1570      *     return reply_to;
1571      * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1572      *     return ID of last notice by initial @name in content;
1573      * }
1574      *
1575      * Note that all @nickname instances will still be used to save "reply" records,
1576      * so the notice shows up in the mentioned users' "replies" tab.
1577      *
1578      * @param integer $reply_to   ID passed in by Web or API
1579      * @param integer $profile_id ID of author
1580      * @param string  $source     Source tag, like 'web' or 'gwibber'
1581      * @param string  $content    Final notice content
1582      *
1583      * @return integer ID of replied-to notice, or null for not a reply.
1584      */
1585
1586     static function getReplyTo($reply_to, $profile_id, $source, $content)
1587     {
1588         static $lb = array('xmpp', 'mail', 'sms', 'omb');
1589
1590         // If $reply_to is specified, we check that it exists, and then
1591         // return it if it does
1592
1593         if (!empty($reply_to)) {
1594             $reply_notice = Notice::staticGet('id', $reply_to);
1595             if (!empty($reply_notice)) {
1596                 return $reply_to;
1597             }
1598         }
1599
1600         // If it's not a "low bandwidth" source (one where you can't set
1601         // a reply_to argument), we return. This is mostly web and API
1602         // clients.
1603
1604         if (!in_array($source, $lb)) {
1605             return null;
1606         }
1607
1608         // Is there an initial @ or T?
1609
1610         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1611             preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1612             $nickname = common_canonical_nickname($match[1]);
1613         } else {
1614             return null;
1615         }
1616
1617         // Figure out who that is.
1618
1619         $sender = Profile::staticGet('id', $profile_id);
1620         if (empty($sender)) {
1621             return null;
1622         }
1623
1624         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1625
1626         if (empty($recipient)) {
1627             return null;
1628         }
1629
1630         // Get their last notice
1631
1632         $last = $recipient->getCurrentNotice();
1633
1634         if (!empty($last)) {
1635             return $last->id;
1636         }
1637     }
1638
1639     static function maxContent()
1640     {
1641         $contentlimit = common_config('notice', 'contentlimit');
1642         // null => use global limit (distinct from 0!)
1643         if (is_null($contentlimit)) {
1644             $contentlimit = common_config('site', 'textlimit');
1645         }
1646         return $contentlimit;
1647     }
1648
1649     static function contentTooLong($content)
1650     {
1651         $contentlimit = self::maxContent();
1652         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1653     }
1654
1655     function getLocation()
1656     {
1657         $location = null;
1658
1659         if (!empty($this->location_id) && !empty($this->location_ns)) {
1660             $location = Location::fromId($this->location_id, $this->location_ns);
1661         }
1662
1663         if (is_null($location)) { // no ID, or Location::fromId() failed
1664             if (!empty($this->lat) && !empty($this->lon)) {
1665                 $location = Location::fromLatLon($this->lat, $this->lon);
1666             }
1667         }
1668
1669         return $location;
1670     }
1671
1672     function repeat($repeater_id, $source)
1673     {
1674         $author = Profile::staticGet('id', $this->profile_id);
1675
1676         // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1677         // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1678         $content = sprintf(_('RT @%1$s %2$s'),
1679                            $author->nickname,
1680                            $this->content);
1681
1682         $maxlen = common_config('site', 'textlimit');
1683         if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1684             // Web interface and current Twitter API clients will
1685             // pull the original notice's text, but some older
1686             // clients and RSS/Atom feeds will see this trimmed text.
1687             //
1688             // Unfortunately this is likely to lose tags or URLs
1689             // at the end of long notices.
1690             $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1691         }
1692
1693         return self::saveNew($repeater_id, $content, $source,
1694                              array('repeat_of' => $this->id));
1695     }
1696
1697     // These are supposed to be in chron order!
1698
1699     function repeatStream($limit=100)
1700     {
1701         $cache = Cache::instance();
1702
1703         if (empty($cache)) {
1704             $ids = $this->_repeatStreamDirect($limit);
1705         } else {
1706             $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1707             if ($idstr !== false) {
1708                 $ids = explode(',', $idstr);
1709             } else {
1710                 $ids = $this->_repeatStreamDirect(100);
1711                 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1712             }
1713             if ($limit < 100) {
1714                 // We do a max of 100, so slice down to limit
1715                 $ids = array_slice($ids, 0, $limit);
1716             }
1717         }
1718
1719         return Notice::getStreamByIds($ids);
1720     }
1721
1722     function _repeatStreamDirect($limit)
1723     {
1724         $notice = new Notice();
1725
1726         $notice->selectAdd(); // clears it
1727         $notice->selectAdd('id');
1728
1729         $notice->repeat_of = $this->id;
1730
1731         $notice->orderBy('created, id'); // NB: asc!
1732
1733         if (!is_null($limit)) {
1734             $notice->limit(0, $limit);
1735         }
1736
1737         $ids = array();
1738
1739         if ($notice->find()) {
1740             while ($notice->fetch()) {
1741                 $ids[] = $notice->id;
1742             }
1743         }
1744
1745         $notice->free();
1746         $notice = NULL;
1747
1748         return $ids;
1749     }
1750
1751     function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1752     {
1753         $options = array();
1754
1755         if (!empty($location_id) && !empty($location_ns)) {
1756             $options['location_id'] = $location_id;
1757             $options['location_ns'] = $location_ns;
1758
1759             $location = Location::fromId($location_id, $location_ns);
1760
1761             if (!empty($location)) {
1762                 $options['lat'] = $location->lat;
1763                 $options['lon'] = $location->lon;
1764             }
1765
1766         } else if (!empty($lat) && !empty($lon)) {
1767             $options['lat'] = $lat;
1768             $options['lon'] = $lon;
1769
1770             $location = Location::fromLatLon($lat, $lon);
1771
1772             if (!empty($location)) {
1773                 $options['location_id'] = $location->location_id;
1774                 $options['location_ns'] = $location->location_ns;
1775             }
1776         } else if (!empty($profile)) {
1777             if (isset($profile->lat) && isset($profile->lon)) {
1778                 $options['lat'] = $profile->lat;
1779                 $options['lon'] = $profile->lon;
1780             }
1781
1782             if (isset($profile->location_id) && isset($profile->location_ns)) {
1783                 $options['location_id'] = $profile->location_id;
1784                 $options['location_ns'] = $profile->location_ns;
1785             }
1786         }
1787
1788         return $options;
1789     }
1790
1791     function clearReplies()
1792     {
1793         $replyNotice = new Notice();
1794         $replyNotice->reply_to = $this->id;
1795
1796         //Null any notices that are replies to this notice
1797
1798         if ($replyNotice->find()) {
1799             while ($replyNotice->fetch()) {
1800                 $orig = clone($replyNotice);
1801                 $replyNotice->reply_to = null;
1802                 $replyNotice->update($orig);
1803             }
1804         }
1805
1806         // Reply records
1807
1808         $reply = new Reply();
1809         $reply->notice_id = $this->id;
1810
1811         if ($reply->find()) {
1812             while($reply->fetch()) {
1813                 self::blow('reply:stream:%d', $reply->profile_id);
1814                 $reply->delete();
1815             }
1816         }
1817
1818         $reply->free();
1819     }
1820
1821     function clearFiles()
1822     {
1823         $f2p = new File_to_post();
1824
1825         $f2p->post_id = $this->id;
1826
1827         if ($f2p->find()) {
1828             while ($f2p->fetch()) {
1829                 $f2p->delete();
1830             }
1831         }
1832         // FIXME: decide whether to delete File objects
1833         // ...and related (actual) files
1834     }
1835
1836     function clearRepeats()
1837     {
1838         $repeatNotice = new Notice();
1839         $repeatNotice->repeat_of = $this->id;
1840
1841         //Null any notices that are repeats of this notice
1842
1843         if ($repeatNotice->find()) {
1844             while ($repeatNotice->fetch()) {
1845                 $orig = clone($repeatNotice);
1846                 $repeatNotice->repeat_of = null;
1847                 $repeatNotice->update($orig);
1848             }
1849         }
1850     }
1851
1852     function clearFaves()
1853     {
1854         $fave = new Fave();
1855         $fave->notice_id = $this->id;
1856
1857         if ($fave->find()) {
1858             while ($fave->fetch()) {
1859                 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1860                 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1861                 self::blow('fave:ids_by_user:%d', $fave->user_id);
1862                 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1863                 $fave->delete();
1864             }
1865         }
1866
1867         $fave->free();
1868     }
1869
1870     function clearTags()
1871     {
1872         $tag = new Notice_tag();
1873         $tag->notice_id = $this->id;
1874
1875         if ($tag->find()) {
1876             while ($tag->fetch()) {
1877                 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
1878                 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
1879                 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
1880                 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
1881                 $tag->delete();
1882             }
1883         }
1884
1885         $tag->free();
1886     }
1887
1888     function clearGroupInboxes()
1889     {
1890         $gi = new Group_inbox();
1891
1892         $gi->notice_id = $this->id;
1893
1894         if ($gi->find()) {
1895             while ($gi->fetch()) {
1896                 self::blow('user_group:notice_ids:%d', $gi->group_id);
1897                 $gi->delete();
1898             }
1899         }
1900
1901         $gi->free();
1902     }
1903
1904     function distribute()
1905     {
1906         // We always insert for the author so they don't
1907         // have to wait
1908         Event::handle('StartNoticeDistribute', array($this));
1909
1910         $user = User::staticGet('id', $this->profile_id);
1911         if (!empty($user)) {
1912             Inbox::insertNotice($user->id, $this->id);
1913         }
1914
1915         if (common_config('queue', 'inboxes')) {
1916             // If there's a failure, we want to _force_
1917             // distribution at this point.
1918             try {
1919                 $qm = QueueManager::get();
1920                 $qm->enqueue($this, 'distrib');
1921             } catch (Exception $e) {
1922                 // If the exception isn't transient, this
1923                 // may throw more exceptions as DQH does
1924                 // its own enqueueing. So, we ignore them!
1925                 try {
1926                     $handler = new DistribQueueHandler();
1927                     $handler->handle($this);
1928                 } catch (Exception $e) {
1929                     common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
1930                 }
1931                 // Re-throw so somebody smarter can handle it.
1932                 throw $e;
1933             }
1934         } else {
1935             $handler = new DistribQueueHandler();
1936             $handler->handle($this);
1937         }
1938     }
1939
1940     function insert()
1941     {
1942         $result = parent::insert();
1943
1944         if ($result) {
1945             // Profile::hasRepeated() abuses pkeyGet(), so we
1946             // have to clear manually
1947             if (!empty($this->repeat_of)) {
1948                 $c = self::memcache();
1949                 if (!empty($c)) {
1950                     $ck = self::multicacheKey('Notice',
1951                                               array('profile_id' => $this->profile_id,
1952                                                     'repeat_of' => $this->repeat_of));
1953                     $c->delete($ck);
1954                 }
1955             }
1956         }
1957
1958         return $result;
1959     }
1960
1961     /**
1962      * Get the source of the notice
1963      *
1964      * @return Notice_source $ns A notice source object. 'code' is the only attribute
1965      *                           guaranteed to be populated.
1966      */
1967     function getSource()
1968     {
1969         $ns = new Notice_source();
1970         if (!empty($this->source)) {
1971             switch ($this->source) {
1972             case 'web':
1973             case 'xmpp':
1974             case 'mail':
1975             case 'omb':
1976             case 'system':
1977             case 'api':
1978                 $ns->code = $this->source;
1979                 break;
1980             default:
1981                 $ns = Notice_source::staticGet($this->source);
1982                 if (!$ns) {
1983                     $ns = new Notice_source();
1984                     $ns->code = $this->source;
1985                     $app = Oauth_application::staticGet('name', $this->source);
1986                     if ($app) {
1987                         $ns->name = $app->name;
1988                         $ns->url  = $app->source_url;
1989                     }
1990                 }
1991                 break;
1992             }
1993         }
1994         return $ns;
1995     }
1996
1997     /**
1998      * Determine whether the notice was locally created
1999      *
2000      * @return boolean locality
2001      */
2002
2003     public function isLocal()
2004     {
2005         return ($this->is_local == Notice::LOCAL_PUBLIC ||
2006                 $this->is_local == Notice::LOCAL_NONPUBLIC);
2007     }
2008
2009     /**
2010      * Get the list of hash tags saved with this notice.
2011      *
2012      * @return array of strings
2013      */
2014     public function getTags()
2015     {
2016         $tags = array();
2017         $tag = new Notice_tag();
2018         $tag->notice_id = $this->id;
2019         if ($tag->find()) {
2020             while ($tag->fetch()) {
2021                 $tags[] = $tag->tag;
2022             }
2023         }
2024         $tag->free();
2025         return $tags;
2026     }
2027
2028     static private function utcDate($dt)
2029     {
2030         $dateStr = date('d F Y H:i:s', strtotime($dt));
2031         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2032         return $d->format(DATE_W3C);
2033     }
2034
2035     /**
2036      * Look up the creation timestamp for a given notice ID, even
2037      * if it's been deleted.
2038      *
2039      * @param int $id
2040      * @return mixed string recorded creation timestamp, or false if can't be found
2041      */
2042     public static function getAsTimestamp($id)
2043     {
2044         if (!$id) {
2045             return false;
2046         }
2047
2048         $notice = Notice::staticGet('id', $id);
2049         if ($notice) {
2050             return $notice->created;
2051         }
2052
2053         $deleted = Deleted_notice::staticGet('id', $id);
2054         if ($deleted) {
2055             return $deleted->created;
2056         }
2057
2058         return false;
2059     }
2060
2061     /**
2062      * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2063      * parameter, matching notices posted after the given one (exclusive).
2064      *
2065      * If the referenced notice can't be found, will return false.
2066      *
2067      * @param int $id
2068      * @param string $idField
2069      * @param string $createdField
2070      * @return mixed string or false if no match
2071      */
2072     public static function whereSinceId($id, $idField='id', $createdField='created')
2073     {
2074         $since = Notice::getAsTimestamp($id);
2075         if ($since) {
2076             return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2077         }
2078         return false;
2079     }
2080
2081     /**
2082      * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2083      * parameter, matching notices posted after the given one (exclusive), and
2084      * if necessary add it to the data object's query.
2085      *
2086      * @param DB_DataObject $obj
2087      * @param int $id
2088      * @param string $idField
2089      * @param string $createdField
2090      * @return mixed string or false if no match
2091      */
2092     public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2093     {
2094         $since = self::whereSinceId($id, $idField, $createdField);
2095         if ($since) {
2096             $obj->whereAdd($since);
2097         }
2098     }
2099
2100     /**
2101      * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2102      * parameter, matching notices posted before the given one (inclusive).
2103      *
2104      * If the referenced notice can't be found, will return false.
2105      *
2106      * @param int $id
2107      * @param string $idField
2108      * @param string $createdField
2109      * @return mixed string or false if no match
2110      */
2111     public static function whereMaxId($id, $idField='id', $createdField='created')
2112     {
2113         $max = Notice::getAsTimestamp($id);
2114         if ($max) {
2115             return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2116         }
2117         return false;
2118     }
2119
2120     /**
2121      * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2122      * parameter, matching notices posted before the given one (inclusive), and
2123      * if necessary add it to the data object's query.
2124      *
2125      * @param DB_DataObject $obj
2126      * @param int $id
2127      * @param string $idField
2128      * @param string $createdField
2129      * @return mixed string or false if no match
2130      */
2131     public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2132     {
2133         $max = self::whereMaxId($id, $idField, $createdField);
2134         if ($max) {
2135             $obj->whereAdd($max);
2136         }
2137     }
2138
2139     function isPublic()
2140     {
2141         if (common_config('public', 'localonly')) {
2142             return ($this->is_local == Notice::LOCAL_PUBLIC);
2143         } else {
2144             return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2145                     ($this->is_local != Notice::GATEWAY));
2146         }
2147     }
2148 }