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