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 $profile_id; // int(4) primary_key not_null
18 public $nickname; // varchar(64)
19 public $fullname; // varchar(191) not 255 because utf8mb4 takes more space
20 public $homepage; // varchar(191) not 255 because utf8mb4 takes more space
21 public $description; // text
22 public $location; // varchar(191) not 255 because utf8mb4 takes more space
23 public $original_logo; // varchar(191) not 255 because utf8mb4 takes more space
24 public $homepage_logo; // varchar(191) not 255 because utf8mb4 takes more space
25 public $stream_logo; // varchar(191) not 255 because utf8mb4 takes more space
26 public $mini_logo; // varchar(191) not 255 because utf8mb4 takes more space
27 public $created; // datetime not_null default_0000-00-00%2000%3A00%3A00
28 public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
29 public $uri; // varchar(191) unique_key not 255 because utf8mb4 takes more space
30 public $mainpage; // varchar(191) not 255 because utf8mb4 takes more space
31 public $join_policy; // tinyint
32 public $force_scope; // tinyint
34 /* the code above is auto generated do not remove the tag below */
37 public function getObjectType()
39 return ActivityObject::GROUP;
43 public static function schemaDef()
47 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
48 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'foreign key to profile table'),
50 'nickname' => array('type' => 'varchar', 'length' => 64, 'description' => 'nickname for addressing'),
51 'fullname' => array('type' => 'varchar', 'length' => 191, 'description' => 'display name'),
52 'homepage' => array('type' => 'varchar', 'length' => 191, 'description' => 'URL, cached so we dont regenerate'),
53 'description' => array('type' => 'text', 'description' => 'group description'),
54 'location' => array('type' => 'varchar', 'length' => 191, 'description' => 'related physical location, if any'),
56 'original_logo' => array('type' => 'varchar', 'length' => 191, 'description' => 'original size logo'),
57 'homepage_logo' => array('type' => 'varchar', 'length' => 191, 'description' => 'homepage (profile) size logo'),
58 'stream_logo' => array('type' => 'varchar', 'length' => 191, 'description' => 'stream-sized logo'),
59 'mini_logo' => array('type' => 'varchar', 'length' => 191, 'description' => 'mini logo'),
61 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
62 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
64 'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universal identifier'),
65 'mainpage' => array('type' => 'varchar', 'length' => 191, 'description' => 'page for group info to link to'),
66 'join_policy' => array('type' => 'int', 'size' => 'tiny', 'description' => '0=open; 1=requires admin approval'),
67 'force_scope' => array('type' => 'int', 'size' => 'tiny', 'description' => '0=never,1=sometimes,-1=always'),
69 'primary key' => array('id'),
70 'unique keys' => array(
71 'user_group_uri_key' => array('uri'),
72 // when it's safe and everyone's run upgrade.php 'user_profile_id_key' => array('profile_id'),
74 'foreign keys' => array(
75 'user_group_id_fkey' => array('profile', array('profile_id' => 'id')),
78 'user_group_nickname_idx' => array('nickname'),
79 'user_group_profile_id_idx' => array('profile_id'), //make this unique in future
84 protected $_profile = array();
89 * @throws GroupNoProfileException if user has no profile
91 public function getProfile()
93 if (!isset($this->_profile[$this->profile_id])) {
94 $profile = Profile::getKV('id', $this->profile_id);
95 if (!$profile instanceof Profile) {
96 throw new GroupNoProfileException($this);
98 $this->_profile[$this->profile_id] = $profile;
100 return $this->_profile[$this->profile_id];
103 public function getNickname()
105 return $this->getProfile()->getNickname();
108 public function getFullname()
110 return $this->getProfile()->getFullname();
113 public static function defaultLogo($size)
115 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
116 AVATAR_STREAM_SIZE => 'stream',
117 AVATAR_MINI_SIZE => 'mini');
118 return Theme::path('default-avatar-'.$sizenames[$size].'.png');
123 return $this->getProfile()->getUrl();
129 if (Event::handle('StartUserGroupGetUri', array($this, &$uri))) {
130 if (!empty($this->uri)) {
132 } elseif ($this->isLocal()) {
133 $uri = common_local_url('groupbyid',
134 array('id' => $this->id));
137 Event::handle('EndUserGroupGetUri', array($this, &$uri));
144 if (Event::handle('StartUserGroupPermalink', array($this, &$url))) {
145 if ($this->isLocal()) {
146 $url = common_local_url('groupbyid',
147 array('id' => $this->id));
150 Event::handle('EndUserGroupPermalink', array($this, &$url));
154 function getNotices($offset, $limit, $since_id=null, $max_id=null)
156 $stream = new GroupNoticeStream($this);
158 return $stream->getNotices($offset, $limit, $since_id, $max_id);
161 function getMembers($offset=0, $limit=null) {
163 if (is_null($limit) || $offset + $limit > User_group::CACHE_WINDOW) {
164 $ids = $this->getMemberIDs($offset,
167 $key = sprintf('group:member_ids:%d', $this->id);
168 $window = self::cacheGet($key);
169 if ($window === false) {
170 $window = $this->getMemberIDs(0,
171 User_group::CACHE_WINDOW);
172 self::cacheSet($key, $window);
175 $ids = array_slice($window,
180 return Profile::multiGet('id', $ids);
183 function getMemberIDs($offset=0, $limit=null)
185 $gm = new Group_member();
188 $gm->selectAdd('profile_id');
190 $gm->group_id = $this->id;
192 $gm->orderBy('created DESC');
194 if (!is_null($limit)) {
195 $gm->limit($offset, $limit);
201 while ($gm->fetch()) {
202 $ids[] = $gm->profile_id;
210 * Get pending members, who have not yet been approved.
216 function getRequests($offset=0, $limit=null)
218 $rq = new Group_join_queue();
219 $rq->group_id = $this->id;
221 $members = new Profile();
223 $members->joinAdd(['id', $rq, 'profile_id']);
225 if ($limit != null) {
226 $members->limit($offset, $limit);
234 public function getAdminCount()
236 $block = new Group_member();
237 $block->group_id = $this->id;
238 $block->is_admin = 1;
240 return $block->count();
243 public function getMemberCount()
245 $key = sprintf("group:member_count:%d", $this->id);
247 $cnt = self::cacheGet($key);
249 if (is_integer($cnt)) {
253 $mem = new Group_member();
254 $mem->group_id = $this->id;
256 // XXX: why 'distinct'?
258 $cnt = (int) $mem->count('distinct profile_id');
260 self::cacheSet($key, $cnt);
265 function getBlockedCount()
267 // XXX: WORM cache this
269 $block = new Group_block();
270 $block->group_id = $this->id;
272 return $block->count();
275 function getQueueCount()
277 // XXX: WORM cache this
279 $queue = new Group_join_queue();
280 $queue->group_id = $this->id;
282 return $queue->count();
285 function getAdmins($offset=null, $limit=null) // offset is null because DataObject wants it, 0 would mean no results
287 $admins = new Profile();
288 $admins->joinAdd(array('id', 'group_member:profile_id'));
289 $admins->whereAdd(sprintf('group_member.group_id = %u AND group_member.is_admin = 1', $this->id));
290 $admins->orderBy('group_member.modified ASC');
291 $admins->limit($offset, $limit);
297 function getBlocked($offset=null, $limit=null) // offset is null because DataObject wants it, 0 would mean no results
299 $blocked = new Profile();
300 $blocked->joinAdd(array('id', 'group_block:blocked'));
301 $blocked->whereAdd(sprintf('group_block.group_id = %u', $this->id));
302 $blocked->orderBy('group_block.modified DESC');
303 $blocked->limit($offset, $limit);
309 function setOriginal($filename)
311 // This should be handled by the Profile->setOriginal function so user and group avatars are handled the same
312 $imagefile = new ImageFile(null, Avatar::path($filename));
314 $sizes = array('homepage_logo' => AVATAR_PROFILE_SIZE,
315 'stream_logo' => AVATAR_STREAM_SIZE,
316 'mini_logo' => AVATAR_MINI_SIZE);
318 $orig = clone($this);
319 $this->original_logo = Avatar::url($filename);
320 foreach ($sizes as $name=>$size) {
321 $filename = Avatar::filename($this->profile_id, image_type_to_extension($imagefile->preferredType()),
322 $size, common_timestamp());
323 $imagefile->resizeTo(Avatar::path($filename), array('width'=>$size, 'height'=>$size));
324 $this->$name = Avatar::url($filename);
326 common_debug(common_log_objstring($this));
327 return $this->update($orig);
330 function getBestName()
332 return ($this->fullname) ? $this->fullname : $this->nickname;
336 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
337 * if no fullname is provided.
341 function getFancyName()
343 if ($this->fullname) {
344 // TRANS: Full name of a profile or group followed by nickname in parens
345 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
347 return $this->nickname;
351 function getAliases()
357 $alias = new Group_alias();
359 $alias->group_id = $this->id;
361 if ($alias->find()) {
362 while ($alias->fetch()) {
363 $aliases[] = $alias->alias;
372 function setAliases($newaliases) {
374 $newaliases = array_unique($newaliases);
376 $oldaliases = $this->getAliases();
378 // Delete stuff that's old that not in new
380 $to_delete = array_diff($oldaliases, $newaliases);
382 // Insert stuff that's in new and not in old
384 $to_insert = array_diff($newaliases, $oldaliases);
386 $alias = new Group_alias();
388 $alias->group_id = $this->id;
390 foreach ($to_delete as $delalias) {
391 $alias->alias = $delalias;
392 $result = $alias->delete();
394 common_log_db_error($alias, 'DELETE', __FILE__);
399 foreach ($to_insert as $insalias) {
400 if ($insalias === $this->nickname) {
403 $alias->alias = Nickname::normalize($insalias, true);
404 $result = $alias->insert();
406 common_log_db_error($alias, 'INSERT', __FILE__);
414 static function getForNickname($nickname, Profile $profile=null)
416 $nickname = Nickname::normalize($nickname);
418 // Are there any matching remote groups this profile's in?
419 if ($profile instanceof Profile) {
420 $group = $profile->getGroups(0, null);
421 while ($group instanceof User_group && $group->fetch()) {
422 if ($group->nickname == $nickname) {
423 // @fixme is this the best way?
424 return clone($group);
429 // If not, check local groups.
430 $group = Local_group::getKV('nickname', $nickname);
431 if ($group instanceof Local_group) {
432 return User_group::getKV('id', $group->group_id);
434 $alias = Group_alias::getKV('alias', $nickname);
435 if ($alias instanceof Group_alias) {
436 return User_group::getKV('id', $alias->group_id);
441 function getUserMembers()
446 if(common_config('db','quote_identifiers'))
447 $user_table = '"user"';
448 else $user_table = 'user';
452 'FROM '. $user_table .' JOIN group_member '.
453 'ON '. $user_table .'.id = group_member.profile_id ' .
454 'WHERE group_member.group_id = %d ';
456 $user->query(sprintf($qry, $this->id));
460 while ($user->fetch()) {
469 static function maxDescription()
471 $desclimit = common_config('group', 'desclimit');
472 // null => use global limit (distinct from 0!)
473 if (is_null($desclimit)) {
474 $desclimit = common_config('site', 'textlimit');
479 static function descriptionTooLong($desc)
481 $desclimit = self::maxDescription();
482 return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
485 function asAtomEntry($namespace=false, $source=false)
487 $xs = new XMLStringer(true);
490 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
491 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
496 $xs->elementStart('entry', $attrs);
499 $xs->elementStart('source');
500 $xs->element('id', null, $this->permalink());
501 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
502 $xs->element('link', array('href' => $this->permalink()));
503 $xs->element('updated', null, $this->modified);
504 $xs->elementEnd('source');
507 $xs->element('title', null, $this->nickname);
508 $xs->element('summary', null, common_xml_safe_str($this->description));
510 $xs->element('link', array('rel' => 'alternate',
511 'href' => $this->permalink()));
513 $xs->element('id', null, $this->permalink());
515 $xs->element('published', null, common_date_w3dtf($this->created));
516 $xs->element('updated', null, common_date_w3dtf($this->modified));
520 array('type' => 'html'),
521 common_xml_safe_str($this->description)
524 $xs->elementEnd('entry');
526 return $xs->getString();
529 function asAtomAuthor()
531 $xs = new XMLStringer(true);
533 $xs->elementStart('author');
534 $xs->element('name', null, $this->nickname);
535 $xs->element('uri', null, $this->permalink());
536 $xs->elementEnd('author');
538 return $xs->getString();
542 * Returns an XML string fragment with group information as an
543 * Activity Streams noun object with the given element type.
545 * Assumes that 'activity', 'georss', and 'poco' namespace has been
546 * previously defined.
548 * @param string $element one of 'actor', 'subject', 'object', 'target'
552 function asActivityNoun($element)
554 $noun = ActivityObject::fromGroup($this);
555 return $noun->asString('activity:' . $element);
560 return empty($this->homepage_logo)
561 ? User_group::defaultLogo(AVATAR_PROFILE_SIZE)
562 : $this->homepage_logo;
565 static function register($fields) {
566 if (!empty($fields['userid'])) {
567 $profile = Profile::getKV('id', $fields['userid']);
568 if ($profile && !$profile->hasRight(Right::CREATEGROUP)) {
569 common_log(LOG_WARNING, "Attempted group creation from banned user: " . $profile->nickname);
571 // TRANS: Client exception thrown when a user tries to create a group while banned.
572 throw new ClientException(_('You are not allowed to create groups on this site.'), 403);
576 $fields['nickname'] = Nickname::normalize($fields['nickname']);
578 // MAGICALLY put fields into current scope
579 // @fixme kill extract(); it makes debugging absurdly hard
581 $defaults = array('nickname' => null,
584 'description' => null,
588 'aliases' => array(),
591 $fields = array_merge($defaults, $fields);
595 $group = new User_group();
601 if (empty($mainpage)) {
602 $mainpage = common_local_url('showgroup', array('nickname' => $nickname));
605 // We must create a new, incrementally assigned profile_id
606 $profile = new Profile();
607 $profile->nickname = $nickname;
608 $profile->fullname = $fullname;
609 $profile->profileurl = $mainpage;
610 $profile->homepage = $homepage;
611 $profile->bio = $description;
612 $profile->location = $location;
613 $profile->created = common_sql_now();
615 $group->nickname = $profile->nickname;
616 $group->fullname = $profile->fullname;
617 $group->homepage = $profile->homepage;
618 $group->description = $profile->bio;
619 $group->location = $profile->location;
620 $group->mainpage = $profile->profileurl;
621 $group->created = $profile->created;
623 $profile->query('BEGIN');
624 $id = $profile->insert();
626 $profile->query('ROLLBACK');
627 throw new ServerException(_('Profile insertion failed'));
630 $group->profile_id = $id;
633 if (isset($fields['join_policy'])) {
634 $group->join_policy = intval($fields['join_policy']);
636 $group->join_policy = 0;
639 if (isset($fields['force_scope'])) {
640 $group->force_scope = intval($fields['force_scope']);
642 $group->force_scope = 0;
645 if (Event::handle('StartGroupSave', array(&$group))) {
647 $result = $group->insert();
649 if ($result === false) {
650 common_log_db_error($group, 'INSERT', __FILE__);
651 // TRANS: Server exception thrown when creating a group failed.
652 throw new ServerException(_('Could not create group.'));
655 if (!isset($uri) || empty($uri)) {
656 $orig = clone($group);
657 $group->uri = common_local_url('groupbyid', array('id' => $group->id));
658 $result = $group->update($orig);
660 common_log_db_error($group, 'UPDATE', __FILE__);
661 // TRANS: Server exception thrown when updating a group URI failed.
662 throw new ServerException(_('Could not set group URI.'));
666 $result = $group->setAliases($aliases);
669 // TRANS: Server exception thrown when creating group aliases failed.
670 throw new ServerException(_('Could not create aliases.'));
673 $member = new Group_member();
675 $member->group_id = $group->id;
676 $member->profile_id = $userid;
677 $member->is_admin = 1;
678 $member->created = $group->created;
680 $result = $member->insert();
683 common_log_db_error($member, 'INSERT', __FILE__);
684 // TRANS: Server exception thrown when setting group membership failed.
685 throw new ServerException(_('Could not set group membership.'));
688 self::blow('profile:groups:%d', $userid);
691 $local_group = new Local_group();
693 $local_group->group_id = $group->id;
694 $local_group->nickname = $nickname;
695 $local_group->created = common_sql_now();
697 $result = $local_group->insert();
700 common_log_db_error($local_group, 'INSERT', __FILE__);
701 // TRANS: Server exception thrown when saving local group information failed.
702 throw new ServerException(_('Could not save local group info.'));
706 Event::handle('EndGroupSave', array($group));
709 $profile->query('COMMIT');
715 * Handle cascading deletion, on the model of notice and profile.
717 * This should handle freeing up cached entries for the group's
718 * id, nickname, URI, and aliases. There may be other areas that
719 * are not de-cached in the UI, including the sidebar lists on
722 function delete($useWhere=false)
724 if (empty($this->id)) {
725 common_log(LOG_WARNING, "Ambiguous User_group->delete(); skipping related tables.");
726 return parent::delete($useWhere);
730 $profile = $this->getProfile();
732 } catch (GroupNoProfileException $unp) {
733 common_log(LOG_INFO, "Group {$this->nickname} has no profile; continuing deletion.");
736 // Safe to delete in bulk for now
738 $related = array('Group_inbox',
743 Event::handle('UserGroupDeleteRelated', array($this, &$related));
745 foreach ($related as $cls) {
747 $inst->group_id = $this->id;
750 while ($inst->fetch()) {
757 // And related groups in the other direction...
758 $inst = new Related_group();
759 $inst->related_group_id = $this->id;
762 // Aliases and the local_group entry need to be cleared explicitly
763 // or we'll miss clearing some cache keys; that can make it hard
764 // to create a new group with one of those names or aliases.
765 $this->setAliases(array());
767 // $this->isLocal() but we're using the resulting object
768 $local = Local_group::getKV('group_id', $this->id);
769 if ($local instanceof Local_group) {
773 // blow the cached ids
774 self::blow('user_group:notice_ids:%d', $this->id);
776 return parent::delete($useWhere);
779 public function update($dataObject=false)
781 // Whenever the User_group is updated, find the Local_group
782 // and update its nickname too.
783 if ($this->nickname != $dataObject->nickname) {
784 $local = Local_group::getKV('group_id', $this->id);
785 if ($local instanceof Local_group) {
786 common_debug("Updating Local_group ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
787 $local->setNickname($this->nickname);
791 // Also make sure the Profile table is up to date!
792 $fields = array(/*group field => profile field*/
793 'nickname' => 'nickname',
794 'fullname' => 'fullname',
795 'mainpage' => 'profileurl',
796 'homepage' => 'homepage',
797 'description' => 'bio',
798 'location' => 'location',
799 'created' => 'created',
800 'modified' => 'modified',
802 $profile = $this->getProfile();
803 $origpro = clone($profile);
804 foreach ($fields as $gf=>$pf) {
805 $profile->$pf = $this->$gf;
807 if ($profile->update($origpro) === false) {
808 throw new ServerException(_('Unable to update profile'));
811 return parent::update($dataObject);
816 return ($this->join_policy == self::JOIN_POLICY_MODERATE &&
817 intval($this->force_scope) === 1);
820 public function isLocal()
822 $local = Local_group::getKV('group_id', $this->id);
823 return ($local instanceof Local_group);
826 static function groupsFromText($text, Profile $profile)
830 /* extract all !group */
831 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
839 foreach (array_unique($match[1]) as $nickname) {
840 $group = self::getForNickname($nickname, $profile);
841 if ($group instanceof User_group && $profile->isMember($group)) {
842 $groups[] = clone($group);
849 static function idsFromText($text, Profile $profile)
852 $groups = self::groupsFromText($text, $profile);
853 foreach ($groups as $group) {
854 $ids[$group->id] = true;
856 return array_keys($ids);