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