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