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