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