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