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