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