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