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