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