3 * Table Definition for user_group
6 class User_group extends Managed_DataObject
8 const JOIN_POLICY_OPEN = 0;
9 const JOIN_POLICY_MODERATE = 1;
10 const CACHE_WINDOW = 201;
13 /* the code below is auto generated do not remove the above tag */
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
33 /* the code above is auto generated do not remove the tag below */
36 public function getObjectType()
38 return ActivityObject::GROUP;
42 public static function schemaDef()
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'),
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'),
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'),
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'),
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'),
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'),
73 'foreign keys' => array(
74 'user_group_id_fkey' => array('profile', array('profile_id' => 'id')),
77 'user_group_nickname_idx' => array('nickname'),
78 'user_group_profile_id_idx' => array('profile_id'), //make this unique in future
83 protected $_profile = array();
88 * @throws GroupNoProfileException if user has no profile
90 public function getProfile()
92 if (!isset($this->_profile[$this->profile_id])) {
93 $profile = Profile::getKV('id', $this->profile_id);
95 if (!$profile instanceof Profile) {
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();
107 //throw new GroupNoProfileException($this);
110 $this->_profile[$this->profile_id] = $profile;
112 return $this->_profile[$this->profile_id];
115 public function getNickname()
117 return $this->getProfile()->getNickname();
120 public static function defaultLogo($size)
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');
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));
140 Event::handle('EndUserGroupHomeUrl', array($this, &$url));
147 if (Event::handle('StartUserGroupGetUri', array($this, &$uri))) {
148 if (!empty($this->uri)) {
150 } elseif ($this->isLocal()) {
151 $uri = common_local_url('groupbyid',
152 array('id' => $this->id));
155 Event::handle('EndUserGroupGetUri', array($this, &$uri));
162 if (Event::handle('StartUserGroupPermalink', array($this, &$url))) {
163 if ($this->isLocal()) {
164 $url = common_local_url('groupbyid',
165 array('id' => $this->id));
168 Event::handle('EndUserGroupPermalink', array($this, &$url));
172 function getNotices($offset, $limit, $since_id=null, $max_id=null)
174 $stream = new GroupNoticeStream($this);
176 return $stream->getNotices($offset, $limit, $since_id, $max_id);
179 function getMembers($offset=0, $limit=null) {
181 if (is_null($limit) || $offset + $limit > User_group::CACHE_WINDOW) {
182 $ids = $this->getMemberIDs($offset,
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);
193 $ids = array_slice($window,
198 return Profile::multiGet('id', $ids);
201 function getMemberIDs($offset=0, $limit=null)
203 $gm = new Group_member();
206 $gm->selectAdd('profile_id');
208 $gm->group_id = $this->id;
210 $gm->orderBy('created DESC');
212 if (!is_null($limit)) {
213 $gm->limit($offset, $limit);
219 while ($gm->fetch()) {
220 $ids[] = $gm->profile_id;
228 * Get pending members, who have not yet been approved.
234 function getRequests($offset=0, $limit=null)
236 $rq = new Group_join_queue();
237 $rq->group_id = $this->id;
239 $members = new Profile();
241 $members->joinAdd(['id', $rq, 'profile_id']);
243 if ($limit != null) {
244 $members->limit($offset, $limit);
252 public function getAdminCount()
254 $block = new Group_member();
255 $block->group_id = $this->id;
256 $block->is_admin = 1;
258 return $block->count();
261 public function getMemberCount()
263 $key = sprintf("group:member_count:%d", $this->id);
265 $cnt = self::cacheGet($key);
267 if (is_integer($cnt)) {
271 $mem = new Group_member();
272 $mem->group_id = $this->id;
274 // XXX: why 'distinct'?
276 $cnt = (int) $mem->count('distinct profile_id');
278 self::cacheSet($key, $cnt);
283 function getBlockedCount()
285 // XXX: WORM cache this
287 $block = new Group_block();
288 $block->group_id = $this->id;
290 return $block->count();
293 function getQueueCount()
295 // XXX: WORM cache this
297 $queue = new Group_join_queue();
298 $queue->group_id = $this->id;
300 return $queue->count();
303 function getAdmins($offset=null, $limit=null) // offset is null because DataObject wants it, 0 would mean no results
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);
315 function getBlocked($offset=null, $limit=null) // offset is null because DataObject wants it, 0 would mean no results
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);
327 function setOriginal($filename)
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));
332 $sizes = array('homepage_logo' => AVATAR_PROFILE_SIZE,
333 'stream_logo' => AVATAR_STREAM_SIZE,
334 'mini_logo' => AVATAR_MINI_SIZE);
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);
344 common_debug(common_log_objstring($this));
345 return $this->update($orig);
348 function getBestName()
350 return ($this->fullname) ? $this->fullname : $this->nickname;
354 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
355 * if no fullname is provided.
359 function getFancyName()
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);
365 return $this->nickname;
369 function getAliases()
375 $alias = new Group_alias();
377 $alias->group_id = $this->id;
379 if ($alias->find()) {
380 while ($alias->fetch()) {
381 $aliases[] = $alias->alias;
390 function setAliases($newaliases) {
392 $newaliases = array_unique($newaliases);
394 $oldaliases = $this->getAliases();
396 // Delete stuff that's old that not in new
398 $to_delete = array_diff($oldaliases, $newaliases);
400 // Insert stuff that's in new and not in old
402 $to_insert = array_diff($newaliases, $oldaliases);
404 $alias = new Group_alias();
406 $alias->group_id = $this->id;
408 foreach ($to_delete as $delalias) {
409 $alias->alias = $delalias;
410 $result = $alias->delete();
412 common_log_db_error($alias, 'DELETE', __FILE__);
417 foreach ($to_insert as $insalias) {
418 if ($insalias === $this->nickname) {
421 $alias->alias = Nickname::normalize($insalias, true);
422 $result = $alias->insert();
424 common_log_db_error($alias, 'INSERT', __FILE__);
432 static function getForNickname($nickname, Profile $profile=null)
434 $nickname = Nickname::normalize($nickname);
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);
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);
452 $alias = Group_alias::getKV('alias', $nickname);
453 if ($alias instanceof Group_alias) {
454 return User_group::getKV('id', $alias->group_id);
459 function getUserMembers()
464 if(common_config('db','quote_identifiers'))
465 $user_table = '"user"';
466 else $user_table = 'user';
470 'FROM '. $user_table .' JOIN group_member '.
471 'ON '. $user_table .'.id = group_member.profile_id ' .
472 'WHERE group_member.group_id = %d ';
474 $user->query(sprintf($qry, $this->id));
478 while ($user->fetch()) {
487 static function maxDescription()
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');
497 static function descriptionTooLong($desc)
499 $desclimit = self::maxDescription();
500 return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
503 function asAtomEntry($namespace=false, $source=false)
505 $xs = new XMLStringer(true);
508 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
509 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
514 $xs->elementStart('entry', $attrs);
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');
525 $xs->element('title', null, $this->nickname);
526 $xs->element('summary', null, common_xml_safe_str($this->description));
528 $xs->element('link', array('rel' => 'alternate',
529 'href' => $this->permalink()));
531 $xs->element('id', null, $this->permalink());
533 $xs->element('published', null, common_date_w3dtf($this->created));
534 $xs->element('updated', null, common_date_w3dtf($this->modified));
538 array('type' => 'html'),
539 common_xml_safe_str($this->description)
542 $xs->elementEnd('entry');
544 return $xs->getString();
547 function asAtomAuthor()
549 $xs = new XMLStringer(true);
551 $xs->elementStart('author');
552 $xs->element('name', null, $this->nickname);
553 $xs->element('uri', null, $this->permalink());
554 $xs->elementEnd('author');
556 return $xs->getString();
560 * Returns an XML string fragment with group information as an
561 * Activity Streams noun object with the given element type.
563 * Assumes that 'activity', 'georss', and 'poco' namespace has been
564 * previously defined.
566 * @param string $element one of 'actor', 'subject', 'object', 'target'
570 function asActivityNoun($element)
572 $noun = ActivityObject::fromGroup($this);
573 return $noun->asString('activity:' . $element);
578 return empty($this->homepage_logo)
579 ? User_group::defaultLogo(AVATAR_PROFILE_SIZE)
580 : $this->homepage_logo;
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);
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);
594 $fields['nickname'] = Nickname::normalize($fields['nickname']);
596 // MAGICALLY put fields into current scope
597 // @fixme kill extract(); it makes debugging absurdly hard
599 $defaults = array('nickname' => null,
602 'description' => null,
606 'aliases' => array(),
609 $fields = array_merge($defaults, $fields);
613 $group = new User_group();
619 if (empty($mainpage)) {
620 $mainpage = common_local_url('showgroup', array('nickname' => $nickname));
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();
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;
641 $profile->query('BEGIN');
642 $id = $profile->insert();
644 $profile->query('ROLLBACK');
645 throw new ServerException(_('Profile insertion failed'));
648 $group->profile_id = $id;
651 if (isset($fields['join_policy'])) {
652 $group->join_policy = intval($fields['join_policy']);
654 $group->join_policy = 0;
657 if (isset($fields['force_scope'])) {
658 $group->force_scope = intval($fields['force_scope']);
660 $group->force_scope = 0;
663 if (Event::handle('StartGroupSave', array(&$group))) {
665 $result = $group->insert();
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.'));
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);
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.'));
684 $result = $group->setAliases($aliases);
687 // TRANS: Server exception thrown when creating group aliases failed.
688 throw new ServerException(_('Could not create aliases.'));
691 $member = new Group_member();
693 $member->group_id = $group->id;
694 $member->profile_id = $userid;
695 $member->is_admin = 1;
696 $member->created = $group->created;
698 $result = $member->insert();
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.'));
706 self::blow('profile:groups:%d', $userid);
709 $local_group = new Local_group();
711 $local_group->group_id = $group->id;
712 $local_group->nickname = $nickname;
713 $local_group->created = common_sql_now();
715 $result = $local_group->insert();
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.'));
724 Event::handle('EndGroupSave', array($group));
727 $profile->query('COMMIT');
733 * Handle cascading deletion, on the model of notice and profile.
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
740 function delete($useWhere=false)
742 if (empty($this->id)) {
743 common_log(LOG_WARNING, "Ambiguous User_group->delete(); skipping related tables.");
744 return parent::delete($useWhere);
748 $profile = $this->getProfile();
750 } catch (GroupNoProfileException $unp) {
751 common_log(LOG_INFO, "Group {$this->nickname} has no profile; continuing deletion.");
754 // Safe to delete in bulk for now
756 $related = array('Group_inbox',
761 Event::handle('UserGroupDeleteRelated', array($this, &$related));
763 foreach ($related as $cls) {
765 $inst->group_id = $this->id;
768 while ($inst->fetch()) {
775 // And related groups in the other direction...
776 $inst = new Related_group();
777 $inst->related_group_id = $this->id;
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());
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) {
791 // blow the cached ids
792 self::blow('user_group:notice_ids:%d', $this->id);
794 return parent::delete($useWhere);
797 public function update($dataObject=false)
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);
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',
820 $profile = $this->getProfile();
821 $origpro = clone($profile);
822 foreach ($fields as $gf=>$pf) {
823 $profile->$pf = $this->$gf;
825 if ($profile->update($origpro) === false) {
826 throw new ServerException(_('Unable to update profile'));
829 return parent::update($dataObject);
834 return ($this->join_policy == self::JOIN_POLICY_MODERATE &&
835 intval($this->force_scope) === 1);
838 public function isLocal()
840 $local = Local_group::getKV('group_id', $this->id);
841 return ($local instanceof Local_group);
844 static function groupsFromText($text, Profile $profile)
848 /* extract all !group */
849 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
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);
867 static function idsFromText($text, Profile $profile)
870 $groups = self::groupsFromText($text, $profile);
871 foreach ($groups as $group) {
872 $ids[$group->id] = true;
874 return array_keys($ids);