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