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