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