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