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