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