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