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