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