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