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