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