]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/User_group.php
Introduced common_location_shared() to check if location sharing is always,
[quix0rs-gnu-social.git] / classes / User_group.php
1 <?php
2 /**
3  * Table Definition for user_group
4  */
5
6 class User_group extends Managed_DataObject
7 {
8     const JOIN_POLICY_OPEN = 0;
9     const JOIN_POLICY_MODERATE = 1;
10     const CACHE_WINDOW = 201;
11
12     ###START_AUTOCODE
13     /* the code below is auto generated do not remove the above tag */
14
15     public $__table = 'user_group';                      // table name
16     public $id;                              // int(4)  primary_key not_null
17     public $profile_id;                      // int(4)  primary_key not_null
18     public $nickname;                        // varchar(64)
19     public $fullname;                        // varchar(191)   not 255 because utf8mb4 takes more space
20     public $homepage;                        // varchar(191)   not 255 because utf8mb4 takes more space
21     public $description;                     // text
22     public $location;                        // varchar(191)   not 255 because utf8mb4 takes more space
23     public $original_logo;                   // varchar(191)   not 255 because utf8mb4 takes more space
24     public $homepage_logo;                   // varchar(191)   not 255 because utf8mb4 takes more space
25     public $stream_logo;                     // varchar(191)   not 255 because utf8mb4 takes more space
26     public $mini_logo;                       // varchar(191)   not 255 because utf8mb4 takes more space
27     public $created;                         // datetime   not_null default_0000-00-00%2000%3A00%3A00
28     public $modified;                        // timestamp   not_null default_CURRENT_TIMESTAMP
29     public $uri;                             // varchar(191)  unique_key   not 255 because utf8mb4 takes more space
30     public $mainpage;                        // varchar(191)   not 255 because utf8mb4 takes more space
31     public $join_policy;                     // tinyint
32     public $force_scope;                     // tinyint
33
34     /* the code above is auto generated do not remove the tag below */
35     ###END_AUTOCODE
36
37     public function getObjectType()
38     {
39         return ActivityObject::GROUP;
40     }
41
42
43     public static function schemaDef()
44     {
45         return array(
46             'fields' => array(
47                 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
48                 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'foreign key to profile table'),
49
50                 'nickname' => array('type' => 'varchar', 'length' => 64, 'description' => 'nickname for addressing'),
51                 'fullname' => array('type' => 'varchar', 'length' => 191, 'description' => 'display name'),
52                 'homepage' => array('type' => 'varchar', 'length' => 191, 'description' => 'URL, cached so we dont regenerate'),
53                 'description' => array('type' => 'text', 'description' => 'group description'),
54                 'location' => array('type' => 'varchar', 'length' => 191, 'description' => 'related physical location, if any'),
55
56                 'original_logo' => array('type' => 'varchar', 'length' => 191, 'description' => 'original size logo'),
57                 'homepage_logo' => array('type' => 'varchar', 'length' => 191, 'description' => 'homepage (profile) size logo'),
58                 'stream_logo' => array('type' => 'varchar', 'length' => 191, 'description' => 'stream-sized logo'),
59                 'mini_logo' => array('type' => 'varchar', 'length' => 191, 'description' => 'mini logo'),
60
61                 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
62                 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
63
64                 'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universal identifier'),
65                 'mainpage' => array('type' => 'varchar', 'length' => 191, 'description' => 'page for group info to link to'),
66                 'join_policy' => array('type' => 'int', 'size' => 'tiny', 'description' => '0=open; 1=requires admin approval'),      
67                 'force_scope' => array('type' => 'int', 'size' => 'tiny', 'description' => '0=never,1=sometimes,-1=always'),
68             ),
69             'primary key' => array('id'),
70             'unique keys' => array(
71                 'user_group_uri_key' => array('uri'),
72 // when it's safe and everyone's run upgrade.php                'user_profile_id_key' => array('profile_id'),
73             ),
74             'foreign keys' => array(
75                 'user_group_id_fkey' => array('profile', array('profile_id' => 'id')),
76             ),
77             'indexes' => array(
78                 'user_group_nickname_idx' => array('nickname'),
79                 'user_group_profile_id_idx' => array('profile_id'), //make this unique in future
80             ),
81         );
82     }
83
84     protected $_profile = array();
85
86     /**
87      * @return Profile
88      *
89      * @throws GroupNoProfileException if user has no profile
90      */
91     public function getProfile()
92     {
93         if (!isset($this->_profile[$this->profile_id])) {
94             $profile = Profile::getKV('id', $this->profile_id);
95
96             if (!$profile instanceof Profile) {
97
98                 $profile = new Profile();
99                 $profile->nickname   = $this->nickname;
100                 $profile->fullname   = $this->fullname;
101                 $profile->profileurl = $this->mainpage;
102                 $profile->homepage   = $this->homepage;
103                 $profile->bio        = $this->description;
104                 $profile->location   = $this->location;
105                 $profile->created    = common_sql_now();
106                 $this->profile_id = $profile->insert();
107
108                 //throw new GroupNoProfileException($this);
109             }
110
111             $this->_profile[$this->profile_id] = $profile;
112         }
113         return $this->_profile[$this->profile_id];
114     }
115
116     public function getNickname()
117     {
118         return $this->getProfile()->getNickname();
119     }
120
121     public static function defaultLogo($size)
122     {
123         static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
124                                   AVATAR_STREAM_SIZE => 'stream',
125                                   AVATAR_MINI_SIZE => 'mini');
126         return Theme::path('default-avatar-'.$sizenames[$size].'.png');
127     }
128
129     function homeUrl()
130     {
131         return $this->getProfile()->getUrl();
132     }
133
134     function getUri()
135     {
136         $uri = null;
137         if (Event::handle('StartUserGroupGetUri', array($this, &$uri))) {
138             if (!empty($this->uri)) {
139                 $uri = $this->uri;
140             } elseif ($this->isLocal()) {
141                 $uri = common_local_url('groupbyid',
142                                         array('id' => $this->id));
143             }
144         }
145         Event::handle('EndUserGroupGetUri', array($this, &$uri));
146         return $uri;
147     }
148
149     function permalink()
150     {
151         $url = null;
152         if (Event::handle('StartUserGroupPermalink', array($this, &$url))) {
153             if ($this->isLocal()) {
154                 $url = common_local_url('groupbyid',
155                                         array('id' => $this->id));
156             }
157         }
158         Event::handle('EndUserGroupPermalink', array($this, &$url));
159         return $url;
160     }
161
162     function getNotices($offset, $limit, $since_id=null, $max_id=null)
163     {
164         $stream = new GroupNoticeStream($this);
165
166         return $stream->getNotices($offset, $limit, $since_id, $max_id);
167     }
168
169     function getMembers($offset=0, $limit=null) {
170         $ids = null;
171         if (is_null($limit) || $offset + $limit > User_group::CACHE_WINDOW) {
172             $ids = $this->getMemberIDs($offset,
173                                        $limit);
174         } else {
175             $key = sprintf('group:member_ids:%d', $this->id);
176             $window = self::cacheGet($key);
177             if ($window === false) {
178                 $window = $this->getMemberIDs(0,
179                                               User_group::CACHE_WINDOW);
180                 self::cacheSet($key, $window);
181             }
182
183             $ids = array_slice($window,
184                                $offset,
185                                $limit);
186         }
187
188         return Profile::multiGet('id', $ids);
189     }
190
191     function getMemberIDs($offset=0, $limit=null)
192     {
193         $gm = new Group_member();
194
195         $gm->selectAdd();
196         $gm->selectAdd('profile_id');
197
198         $gm->group_id = $this->id;
199
200         $gm->orderBy('created DESC');
201
202         if (!is_null($limit)) {
203             $gm->limit($offset, $limit);
204         }
205
206         $ids = array();
207
208         if ($gm->find()) {
209             while ($gm->fetch()) {
210                 $ids[] = $gm->profile_id;
211             }
212         }
213
214         return $ids;
215     }
216
217     /**
218      * Get pending members, who have not yet been approved.
219      *
220      * @param int $offset
221      * @param int $limit
222      * @return Profile
223      */
224     function getRequests($offset=0, $limit=null)
225     {
226         $rq = new Group_join_queue();
227         $rq->group_id = $this->id;
228
229         $members = new Profile();
230
231         $members->joinAdd(['id', $rq, 'profile_id']);
232
233         if ($limit != null) {
234             $members->limit($offset, $limit);
235         }
236
237         $members->find();
238
239         return $members;
240     }
241
242     public function getAdminCount()
243     {
244         $block = new Group_member();
245         $block->group_id = $this->id;
246         $block->is_admin = 1;
247
248         return $block->count();
249     }
250
251     public function getMemberCount()
252     {
253         $key = sprintf("group:member_count:%d", $this->id);
254
255         $cnt = self::cacheGet($key);
256
257         if (is_integer($cnt)) {
258             return (int) $cnt;
259         }
260
261         $mem = new Group_member();
262         $mem->group_id = $this->id;
263
264         // XXX: why 'distinct'?
265
266         $cnt = (int) $mem->count('distinct profile_id');
267
268         self::cacheSet($key, $cnt);
269
270         return $cnt;
271     }
272
273     function getBlockedCount()
274     {
275         // XXX: WORM cache this
276
277         $block = new Group_block();
278         $block->group_id = $this->id;
279
280         return $block->count();
281     }
282
283     function getQueueCount()
284     {
285         // XXX: WORM cache this
286
287         $queue = new Group_join_queue();
288         $queue->group_id = $this->id;
289
290         return $queue->count();
291     }
292
293     function getAdmins($offset=null, $limit=null)   // offset is null because DataObject wants it, 0 would mean no results
294     {
295         $admins = new Profile();
296         $admins->joinAdd(array('id', 'group_member:profile_id'));
297         $admins->whereAdd(sprintf('group_member.group_id = %u AND group_member.is_admin = 1', $this->id));
298         $admins->orderBy('group_member.modified ASC');
299         $admins->limit($offset, $limit);
300         $admins->find();
301
302         return $admins;
303     }
304
305     function getBlocked($offset=null, $limit=null)   // offset is null because DataObject wants it, 0 would mean no results
306     {
307         $blocked = new Profile();
308         $blocked->joinAdd(array('id', 'group_block:blocked'));
309         $blocked->whereAdd(sprintf('group_block.group_id = %u', $this->id));
310         $blocked->orderBy('group_block.modified DESC');
311         $blocked->limit($offset, $limit);
312         $blocked->find();
313
314         return $blocked;
315     }
316
317     function setOriginal($filename)
318     {
319         // This should be handled by the Profile->setOriginal function so user and group avatars are handled the same
320         $imagefile = new ImageFile(null, Avatar::path($filename));
321
322         $sizes = array('homepage_logo' => AVATAR_PROFILE_SIZE,
323                        'stream_logo' => AVATAR_STREAM_SIZE,
324                        'mini_logo' => AVATAR_MINI_SIZE);
325
326         $orig = clone($this);
327         $this->original_logo = Avatar::url($filename);
328         foreach ($sizes as $name=>$size) {
329             $filename = Avatar::filename($this->profile_id, image_type_to_extension($imagefile->preferredType()),
330                                          $size, common_timestamp());
331             $imagefile->resizeTo(Avatar::path($filename), array('width'=>$size, 'height'=>$size));
332             $this->$name = Avatar::url($filename);
333         }
334         common_debug(common_log_objstring($this));
335         return $this->update($orig);
336     }
337
338     function getBestName()
339     {
340         return ($this->fullname) ? $this->fullname : $this->nickname;
341     }
342
343     /**
344      * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
345      * if no fullname is provided.
346      *
347      * @return string
348      */
349     function getFancyName()
350     {
351         if ($this->fullname) {
352             // TRANS: Full name of a profile or group followed by nickname in parens
353             return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
354         } else {
355             return $this->nickname;
356         }
357     }
358
359     function getAliases()
360     {
361         $aliases = array();
362
363         // XXX: cache this
364
365         $alias = new Group_alias();
366
367         $alias->group_id = $this->id;
368
369         if ($alias->find()) {
370             while ($alias->fetch()) {
371                 $aliases[] = $alias->alias;
372             }
373         }
374
375         $alias->free();
376
377         return $aliases;
378     }
379
380     function setAliases($newaliases) {
381
382         $newaliases = array_unique($newaliases);
383
384         $oldaliases = $this->getAliases();
385
386         // Delete stuff that's old that not in new
387
388         $to_delete = array_diff($oldaliases, $newaliases);
389
390         // Insert stuff that's in new and not in old
391
392         $to_insert = array_diff($newaliases, $oldaliases);
393
394         $alias = new Group_alias();
395
396         $alias->group_id = $this->id;
397
398         foreach ($to_delete as $delalias) {
399             $alias->alias = $delalias;
400             $result = $alias->delete();
401             if (!$result) {
402                 common_log_db_error($alias, 'DELETE', __FILE__);
403                 return false;
404             }
405         }
406
407         foreach ($to_insert as $insalias) {
408             if ($insalias === $this->nickname) {
409                 continue;
410             }
411             $alias->alias = Nickname::normalize($insalias, true);
412             $result = $alias->insert();
413             if (!$result) {
414                 common_log_db_error($alias, 'INSERT', __FILE__);
415                 return false;
416             }
417         }
418
419         return true;
420     }
421
422     static function getForNickname($nickname, Profile $profile=null)
423     {
424         $nickname = Nickname::normalize($nickname);
425
426         // Are there any matching remote groups this profile's in?
427         if ($profile instanceof Profile) {
428             $group = $profile->getGroups(0, null);
429             while ($group instanceof User_group && $group->fetch()) {
430                 if ($group->nickname == $nickname) {
431                     // @fixme is this the best way?
432                     return clone($group);
433                 }
434             }
435         }
436
437         // If not, check local groups.
438         $group = Local_group::getKV('nickname', $nickname);
439         if ($group instanceof Local_group) {
440             return User_group::getKV('id', $group->group_id);
441         }
442         $alias = Group_alias::getKV('alias', $nickname);
443         if ($alias instanceof Group_alias) {
444             return User_group::getKV('id', $alias->group_id);
445         }
446         return null;
447     }
448
449     function getUserMembers()
450     {
451         // XXX: cache this
452
453         $user = new User();
454         if(common_config('db','quote_identifiers'))
455             $user_table = '"user"';
456         else $user_table = 'user';
457
458         $qry =
459           'SELECT id ' .
460           'FROM '. $user_table .' JOIN group_member '.
461           'ON '. $user_table .'.id = group_member.profile_id ' .
462           'WHERE group_member.group_id = %d ';
463
464         $user->query(sprintf($qry, $this->id));
465
466         $ids = array();
467
468         while ($user->fetch()) {
469             $ids[] = $user->id;
470         }
471
472         $user->free();
473
474         return $ids;
475     }
476
477     static function maxDescription()
478     {
479         $desclimit = common_config('group', 'desclimit');
480         // null => use global limit (distinct from 0!)
481         if (is_null($desclimit)) {
482             $desclimit = common_config('site', 'textlimit');
483         }
484         return $desclimit;
485     }
486
487     static function descriptionTooLong($desc)
488     {
489         $desclimit = self::maxDescription();
490         return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
491     }
492
493     function asAtomEntry($namespace=false, $source=false)
494     {
495         $xs = new XMLStringer(true);
496
497         if ($namespace) {
498             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
499                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
500         } else {
501             $attrs = array();
502         }
503
504         $xs->elementStart('entry', $attrs);
505
506         if ($source) {
507             $xs->elementStart('source');
508             $xs->element('id', null, $this->permalink());
509             $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
510             $xs->element('link', array('href' => $this->permalink()));
511             $xs->element('updated', null, $this->modified);
512             $xs->elementEnd('source');
513         }
514
515         $xs->element('title', null, $this->nickname);
516         $xs->element('summary', null, common_xml_safe_str($this->description));
517
518         $xs->element('link', array('rel' => 'alternate',
519                                    'href' => $this->permalink()));
520
521         $xs->element('id', null, $this->permalink());
522
523         $xs->element('published', null, common_date_w3dtf($this->created));
524         $xs->element('updated', null, common_date_w3dtf($this->modified));
525
526         $xs->element(
527             'content',
528             array('type' => 'html'),
529             common_xml_safe_str($this->description)
530         );
531
532         $xs->elementEnd('entry');
533
534         return $xs->getString();
535     }
536
537     function asAtomAuthor()
538     {
539         $xs = new XMLStringer(true);
540
541         $xs->elementStart('author');
542         $xs->element('name', null, $this->nickname);
543         $xs->element('uri', null, $this->permalink());
544         $xs->elementEnd('author');
545
546         return $xs->getString();
547     }
548
549     /**
550      * Returns an XML string fragment with group information as an
551      * Activity Streams noun object with the given element type.
552      *
553      * Assumes that 'activity', 'georss', and 'poco' namespace has been
554      * previously defined.
555      *
556      * @param string $element one of 'actor', 'subject', 'object', 'target'
557      *
558      * @return string
559      */
560     function asActivityNoun($element)
561     {
562         $noun = ActivityObject::fromGroup($this);
563         return $noun->asString('activity:' . $element);
564     }
565
566     function getAvatar()
567     {
568         return empty($this->homepage_logo)
569             ? User_group::defaultLogo(AVATAR_PROFILE_SIZE)
570             : $this->homepage_logo;
571     }
572
573     static function register($fields) {
574         if (!empty($fields['userid'])) {
575             $profile = Profile::getKV('id', $fields['userid']);
576             if ($profile && !$profile->hasRight(Right::CREATEGROUP)) {
577                 common_log(LOG_WARNING, "Attempted group creation from banned user: " . $profile->nickname);
578
579                 // TRANS: Client exception thrown when a user tries to create a group while banned.
580                 throw new ClientException(_('You are not allowed to create groups on this site.'), 403);
581             }
582         }
583
584         $fields['nickname'] = Nickname::normalize($fields['nickname']);
585
586         // MAGICALLY put fields into current scope
587         // @fixme kill extract(); it makes debugging absurdly hard
588
589                 $defaults = array('nickname' => null,
590                                                   'fullname' => null,
591                                                   'homepage' => null,
592                                                   'description' => null,
593                                                   'location' => null,
594                                                   'uri' => null,
595                                                   'mainpage' => null,
596                                                   'aliases' => array(),
597                                                   'userid' => null);
598                 
599                 $fields = array_merge($defaults, $fields);
600                 
601         extract($fields);
602
603         $group = new User_group();
604
605         if (empty($uri)) {
606             // fill in later...
607             $uri = null;
608         }
609         if (empty($mainpage)) {
610             $mainpage = common_local_url('showgroup', array('nickname' => $nickname));
611         }
612
613         // We must create a new, incrementally assigned profile_id
614         $profile = new Profile();
615         $profile->nickname   = $nickname;
616         $profile->fullname   = $fullname;
617         $profile->profileurl = $mainpage;
618         $profile->homepage   = $homepage;
619         $profile->bio        = $description;
620         $profile->location   = $location;
621         $profile->created    = common_sql_now();
622
623         $group->nickname    = $profile->nickname;
624         $group->fullname    = $profile->fullname;
625         $group->homepage    = $profile->homepage;
626         $group->description = $profile->bio;
627         $group->location    = $profile->location;
628         $group->mainpage    = $profile->profileurl;
629         $group->created     = $profile->created;
630
631         $profile->query('BEGIN');
632         $id = $profile->insert();
633         if ($id === false) {
634             $profile->query('ROLLBACK');
635             throw new ServerException(_('Profile insertion failed'));
636         }
637
638         $group->profile_id = $id;
639         $group->uri        = $uri;
640
641         if (isset($fields['join_policy'])) {
642             $group->join_policy = intval($fields['join_policy']);
643         } else {
644             $group->join_policy = 0;
645         }
646
647         if (isset($fields['force_scope'])) {
648             $group->force_scope = intval($fields['force_scope']);
649         } else {
650             $group->force_scope = 0;
651         }
652
653         if (Event::handle('StartGroupSave', array(&$group))) {
654
655             $result = $group->insert();
656
657             if ($result === false) {
658                 common_log_db_error($group, 'INSERT', __FILE__);
659                 // TRANS: Server exception thrown when creating a group failed.
660                 throw new ServerException(_('Could not create group.'));
661             }
662
663             if (!isset($uri) || empty($uri)) {
664                 $orig = clone($group);
665                 $group->uri = common_local_url('groupbyid', array('id' => $group->id));
666                 $result = $group->update($orig);
667                 if (!$result) {
668                     common_log_db_error($group, 'UPDATE', __FILE__);
669                     // TRANS: Server exception thrown when updating a group URI failed.
670                     throw new ServerException(_('Could not set group URI.'));
671                 }
672             }
673
674             $result = $group->setAliases($aliases);
675
676             if (!$result) {
677                 // TRANS: Server exception thrown when creating group aliases failed.
678                 throw new ServerException(_('Could not create aliases.'));
679             }
680
681             $member = new Group_member();
682
683             $member->group_id   = $group->id;
684             $member->profile_id = $userid;
685             $member->is_admin   = 1;
686             $member->created    = $group->created;
687
688             $result = $member->insert();
689
690             if (!$result) {
691                 common_log_db_error($member, 'INSERT', __FILE__);
692                 // TRANS: Server exception thrown when setting group membership failed.
693                 throw new ServerException(_('Could not set group membership.'));
694             }
695
696             self::blow('profile:groups:%d', $userid);
697             
698             if ($local) {
699                 $local_group = new Local_group();
700
701                 $local_group->group_id = $group->id;
702                 $local_group->nickname = $nickname;
703                 $local_group->created  = common_sql_now();
704
705                 $result = $local_group->insert();
706
707                 if (!$result) {
708                     common_log_db_error($local_group, 'INSERT', __FILE__);
709                     // TRANS: Server exception thrown when saving local group information failed.
710                     throw new ServerException(_('Could not save local group info.'));
711                 }
712             }
713
714             Event::handle('EndGroupSave', array($group));
715         }
716
717         $profile->query('COMMIT');
718
719         return $group;
720     }
721
722     /**
723      * Handle cascading deletion, on the model of notice and profile.
724      *
725      * This should handle freeing up cached entries for the group's
726      * id, nickname, URI, and aliases. There may be other areas that
727      * are not de-cached in the UI, including the sidebar lists on
728      * GroupsAction
729      */
730     function delete($useWhere=false)
731     {
732         if (empty($this->id)) {
733             common_log(LOG_WARNING, "Ambiguous User_group->delete(); skipping related tables.");
734             return parent::delete($useWhere);
735         }
736
737         try {
738             $profile = $this->getProfile();
739             $profile->delete();
740         } catch (GroupNoProfileException $unp) {
741             common_log(LOG_INFO, "Group {$this->nickname} has no profile; continuing deletion.");
742         }
743
744         // Safe to delete in bulk for now
745
746         $related = array('Group_inbox',
747                          'Group_block',
748                          'Group_member',
749                          'Related_group');
750
751         Event::handle('UserGroupDeleteRelated', array($this, &$related));
752
753         foreach ($related as $cls) {
754             $inst = new $cls();
755             $inst->group_id = $this->id;
756
757             if ($inst->find()) {
758                 while ($inst->fetch()) {
759                     $dup = clone($inst);
760                     $dup->delete();
761                 }
762             }
763         }
764
765         // And related groups in the other direction...
766         $inst = new Related_group();
767         $inst->related_group_id = $this->id;
768         $inst->delete();
769
770         // Aliases and the local_group entry need to be cleared explicitly
771         // or we'll miss clearing some cache keys; that can make it hard
772         // to create a new group with one of those names or aliases.
773         $this->setAliases(array());
774
775         // $this->isLocal() but we're using the resulting object
776         $local = Local_group::getKV('group_id', $this->id);
777         if ($local instanceof Local_group) {
778             $local->delete();
779         }
780
781         // blow the cached ids
782         self::blow('user_group:notice_ids:%d', $this->id);
783
784         return parent::delete($useWhere);
785     }
786
787     public function update($dataObject=false)
788     {
789         // Whenever the User_group is updated, find the Local_group
790         // and update its nickname too.
791         if ($this->nickname != $dataObject->nickname) {
792             $local = Local_group::getKV('group_id', $this->id);
793             if ($local instanceof Local_group) {
794                 common_debug("Updating Local_group ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
795                 $local->setNickname($this->nickname);
796             }
797         }
798
799         // Also make sure the Profile table is up to date!
800         $fields = array(/*group field => profile field*/
801                     'nickname'      => 'nickname',
802                     'fullname'      => 'fullname',
803                     'mainpage'      => 'profileurl',
804                     'homepage'      => 'homepage',
805                     'description'   => 'bio',
806                     'location'      => 'location',
807                     'created'       => 'created',
808                     'modified'      => 'modified',
809                     );
810         $profile = $this->getProfile();
811         $origpro = clone($profile);
812         foreach ($fields as $gf=>$pf) {
813             $profile->$pf = $this->$gf;
814         }
815         if ($profile->update($origpro) === false) {
816             throw new ServerException(_('Unable to update profile'));
817         }
818
819         return parent::update($dataObject);
820     }
821
822     function isPrivate()
823     {
824         return ($this->join_policy == self::JOIN_POLICY_MODERATE &&
825                 intval($this->force_scope) === 1);
826     }
827
828     public function isLocal()
829     {
830         $local = Local_group::getKV('group_id', $this->id);
831         return ($local instanceof Local_group);
832     }
833
834     static function groupsFromText($text, Profile $profile)
835     {
836         $groups = array();
837
838         /* extract all !group */
839         $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
840                                 strtolower($text),
841                                 $match);
842
843         if (!$count) {
844             return $groups;
845         }
846
847         foreach (array_unique($match[1]) as $nickname) {
848             $group = self::getForNickname($nickname, $profile);
849             if ($group instanceof User_group && $profile->isMember($group)) {
850                 $groups[] = clone($group);
851             }
852         }
853
854         return $groups;
855     }
856
857     static function idsFromText($text, Profile $profile)
858     {
859         $ids = array();
860         $groups = self::groupsFromText($text, $profile);
861         foreach ($groups as $group) {
862             $ids[$group->id] = true;
863         }
864         return array_keys($ids);
865     }
866 }