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