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 static function defaultLogo($size)
110 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
111 AVATAR_STREAM_SIZE => 'stream',
112 AVATAR_MINI_SIZE => 'mini');
113 return Theme::path('default-avatar-'.$sizenames[$size].'.png');
118 return $this->getProfile()->getUrl();
124 if (Event::handle('StartUserGroupGetUri', array($this, &$uri))) {
125 if (!empty($this->uri)) {
127 } elseif ($this->isLocal()) {
128 $uri = common_local_url('groupbyid',
129 array('id' => $this->id));
132 Event::handle('EndUserGroupGetUri', array($this, &$uri));
139 if (Event::handle('StartUserGroupPermalink', array($this, &$url))) {
140 if ($this->isLocal()) {
141 $url = common_local_url('groupbyid',
142 array('id' => $this->id));
145 Event::handle('EndUserGroupPermalink', array($this, &$url));
149 function getNotices($offset, $limit, $since_id=null, $max_id=null)
151 $stream = new GroupNoticeStream($this);
153 return $stream->getNotices($offset, $limit, $since_id, $max_id);
156 function getMembers($offset=0, $limit=null) {
158 if (is_null($limit) || $offset + $limit > User_group::CACHE_WINDOW) {
159 $ids = $this->getMemberIDs($offset,
162 $key = sprintf('group:member_ids:%d', $this->id);
163 $window = self::cacheGet($key);
164 if ($window === false) {
165 $window = $this->getMemberIDs(0,
166 User_group::CACHE_WINDOW);
167 self::cacheSet($key, $window);
170 $ids = array_slice($window,
175 return Profile::multiGet('id', $ids);
178 function getMemberIDs($offset=0, $limit=null)
180 $gm = new Group_member();
183 $gm->selectAdd('profile_id');
185 $gm->group_id = $this->id;
187 $gm->orderBy('created DESC');
189 if (!is_null($limit)) {
190 $gm->limit($offset, $limit);
196 while ($gm->fetch()) {
197 $ids[] = $gm->profile_id;
205 * Get pending members, who have not yet been approved.
211 function getRequests($offset=0, $limit=null)
213 $rq = new Group_join_queue();
214 $rq->group_id = $this->id;
216 $members = new Profile();
218 $members->joinAdd(['id', $rq, 'profile_id']);
220 if ($limit != null) {
221 $members->limit($offset, $limit);
229 public function getAdminCount()
231 $block = new Group_member();
232 $block->group_id = $this->id;
233 $block->is_admin = 1;
235 return $block->count();
238 public function getMemberCount()
240 $key = sprintf("group:member_count:%d", $this->id);
242 $cnt = self::cacheGet($key);
244 if (is_integer($cnt)) {
248 $mem = new Group_member();
249 $mem->group_id = $this->id;
251 // XXX: why 'distinct'?
253 $cnt = (int) $mem->count('distinct profile_id');
255 self::cacheSet($key, $cnt);
260 function getBlockedCount()
262 // XXX: WORM cache this
264 $block = new Group_block();
265 $block->group_id = $this->id;
267 return $block->count();
270 function getQueueCount()
272 // XXX: WORM cache this
274 $queue = new Group_join_queue();
275 $queue->group_id = $this->id;
277 return $queue->count();
280 function getAdmins($offset=null, $limit=null) // offset is null because DataObject wants it, 0 would mean no results
282 $admins = new Profile();
283 $admins->joinAdd(array('id', 'group_member:profile_id'));
284 $admins->whereAdd(sprintf('group_member.group_id = %u AND group_member.is_admin = 1', $this->id));
285 $admins->orderBy('group_member.modified ASC');
286 $admins->limit($offset, $limit);
292 function getBlocked($offset=null, $limit=null) // offset is null because DataObject wants it, 0 would mean no results
294 $blocked = new Profile();
295 $blocked->joinAdd(array('id', 'group_block:blocked'));
296 $blocked->whereAdd(sprintf('group_block.group_id = %u', $this->id));
297 $blocked->orderBy('group_block.modified DESC');
298 $blocked->limit($offset, $limit);
304 function setOriginal($filename)
306 // This should be handled by the Profile->setOriginal function so user and group avatars are handled the same
307 $imagefile = new ImageFile(null, Avatar::path($filename));
309 $sizes = array('homepage_logo' => AVATAR_PROFILE_SIZE,
310 'stream_logo' => AVATAR_STREAM_SIZE,
311 'mini_logo' => AVATAR_MINI_SIZE);
313 $orig = clone($this);
314 $this->original_logo = Avatar::url($filename);
315 foreach ($sizes as $name=>$size) {
316 $filename = Avatar::filename($this->profile_id, image_type_to_extension($imagefile->preferredType()),
317 $size, common_timestamp());
318 $imagefile->resizeTo(Avatar::path($filename), array('width'=>$size, 'height'=>$size));
319 $this->$name = Avatar::url($filename);
321 common_debug(common_log_objstring($this));
322 return $this->update($orig);
325 function getBestName()
327 return ($this->fullname) ? $this->fullname : $this->nickname;
331 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
332 * if no fullname is provided.
336 function getFancyName()
338 if ($this->fullname) {
339 // TRANS: Full name of a profile or group followed by nickname in parens
340 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
342 return $this->nickname;
346 function getAliases()
352 $alias = new Group_alias();
354 $alias->group_id = $this->id;
356 if ($alias->find()) {
357 while ($alias->fetch()) {
358 $aliases[] = $alias->alias;
367 function setAliases($newaliases) {
369 $newaliases = array_unique($newaliases);
371 $oldaliases = $this->getAliases();
373 // Delete stuff that's old that not in new
375 $to_delete = array_diff($oldaliases, $newaliases);
377 // Insert stuff that's in new and not in old
379 $to_insert = array_diff($newaliases, $oldaliases);
381 $alias = new Group_alias();
383 $alias->group_id = $this->id;
385 foreach ($to_delete as $delalias) {
386 $alias->alias = $delalias;
387 $result = $alias->delete();
389 common_log_db_error($alias, 'DELETE', __FILE__);
394 foreach ($to_insert as $insalias) {
395 if ($insalias === $this->nickname) {
398 $alias->alias = Nickname::normalize($insalias, true);
399 $result = $alias->insert();
401 common_log_db_error($alias, 'INSERT', __FILE__);
409 static function getForNickname($nickname, Profile $profile=null)
411 $nickname = Nickname::normalize($nickname);
413 // Are there any matching remote groups this profile's in?
414 if ($profile instanceof Profile) {
415 $group = $profile->getGroups(0, null);
416 while ($group instanceof User_group && $group->fetch()) {
417 if ($group->nickname == $nickname) {
418 // @fixme is this the best way?
419 return clone($group);
424 // If not, check local groups.
425 $group = Local_group::getKV('nickname', $nickname);
426 if ($group instanceof Local_group) {
427 return User_group::getKV('id', $group->group_id);
429 $alias = Group_alias::getKV('alias', $nickname);
430 if ($alias instanceof Group_alias) {
431 return User_group::getKV('id', $alias->group_id);
436 function getUserMembers()
441 if(common_config('db','quote_identifiers'))
442 $user_table = '"user"';
443 else $user_table = 'user';
447 'FROM '. $user_table .' JOIN group_member '.
448 'ON '. $user_table .'.id = group_member.profile_id ' .
449 'WHERE group_member.group_id = %d ';
451 $user->query(sprintf($qry, $this->id));
455 while ($user->fetch()) {
464 static function maxDescription()
466 $desclimit = common_config('group', 'desclimit');
467 // null => use global limit (distinct from 0!)
468 if (is_null($desclimit)) {
469 $desclimit = common_config('site', 'textlimit');
474 static function descriptionTooLong($desc)
476 $desclimit = self::maxDescription();
477 return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
480 function asAtomEntry($namespace=false, $source=false)
482 $xs = new XMLStringer(true);
485 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
486 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
491 $xs->elementStart('entry', $attrs);
494 $xs->elementStart('source');
495 $xs->element('id', null, $this->permalink());
496 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
497 $xs->element('link', array('href' => $this->permalink()));
498 $xs->element('updated', null, $this->modified);
499 $xs->elementEnd('source');
502 $xs->element('title', null, $this->nickname);
503 $xs->element('summary', null, common_xml_safe_str($this->description));
505 $xs->element('link', array('rel' => 'alternate',
506 'href' => $this->permalink()));
508 $xs->element('id', null, $this->permalink());
510 $xs->element('published', null, common_date_w3dtf($this->created));
511 $xs->element('updated', null, common_date_w3dtf($this->modified));
515 array('type' => 'html'),
516 common_xml_safe_str($this->description)
519 $xs->elementEnd('entry');
521 return $xs->getString();
524 function asAtomAuthor()
526 $xs = new XMLStringer(true);
528 $xs->elementStart('author');
529 $xs->element('name', null, $this->nickname);
530 $xs->element('uri', null, $this->permalink());
531 $xs->elementEnd('author');
533 return $xs->getString();
537 * Returns an XML string fragment with group information as an
538 * Activity Streams noun object with the given element type.
540 * Assumes that 'activity', 'georss', and 'poco' namespace has been
541 * previously defined.
543 * @param string $element one of 'actor', 'subject', 'object', 'target'
547 function asActivityNoun($element)
549 $noun = ActivityObject::fromGroup($this);
550 return $noun->asString('activity:' . $element);
555 return empty($this->homepage_logo)
556 ? User_group::defaultLogo(AVATAR_PROFILE_SIZE)
557 : $this->homepage_logo;
560 static function register($fields) {
561 if (!empty($fields['userid'])) {
562 $profile = Profile::getKV('id', $fields['userid']);
563 if ($profile && !$profile->hasRight(Right::CREATEGROUP)) {
564 common_log(LOG_WARNING, "Attempted group creation from banned user: " . $profile->nickname);
566 // TRANS: Client exception thrown when a user tries to create a group while banned.
567 throw new ClientException(_('You are not allowed to create groups on this site.'), 403);
571 $fields['nickname'] = Nickname::normalize($fields['nickname']);
573 // MAGICALLY put fields into current scope
574 // @fixme kill extract(); it makes debugging absurdly hard
576 $defaults = array('nickname' => null,
579 'description' => null,
583 'aliases' => array(),
586 $fields = array_merge($defaults, $fields);
590 $group = new User_group();
596 if (empty($mainpage)) {
597 $mainpage = common_local_url('showgroup', array('nickname' => $nickname));
600 // We must create a new, incrementally assigned profile_id
601 $profile = new Profile();
602 $profile->nickname = $nickname;
603 $profile->fullname = $fullname;
604 $profile->profileurl = $mainpage;
605 $profile->homepage = $homepage;
606 $profile->bio = $description;
607 $profile->location = $location;
608 $profile->created = common_sql_now();
610 $group->nickname = $profile->nickname;
611 $group->fullname = $profile->fullname;
612 $group->homepage = $profile->homepage;
613 $group->description = $profile->bio;
614 $group->location = $profile->location;
615 $group->mainpage = $profile->profileurl;
616 $group->created = $profile->created;
618 $profile->query('BEGIN');
619 $id = $profile->insert();
621 $profile->query('ROLLBACK');
622 throw new ServerException(_('Profile insertion failed'));
625 $group->profile_id = $id;
628 if (isset($fields['join_policy'])) {
629 $group->join_policy = intval($fields['join_policy']);
631 $group->join_policy = 0;
634 if (isset($fields['force_scope'])) {
635 $group->force_scope = intval($fields['force_scope']);
637 $group->force_scope = 0;
640 if (Event::handle('StartGroupSave', array(&$group))) {
642 $result = $group->insert();
644 if ($result === false) {
645 common_log_db_error($group, 'INSERT', __FILE__);
646 // TRANS: Server exception thrown when creating a group failed.
647 throw new ServerException(_('Could not create group.'));
650 if (!isset($uri) || empty($uri)) {
651 $orig = clone($group);
652 $group->uri = common_local_url('groupbyid', array('id' => $group->id));
653 $result = $group->update($orig);
655 common_log_db_error($group, 'UPDATE', __FILE__);
656 // TRANS: Server exception thrown when updating a group URI failed.
657 throw new ServerException(_('Could not set group URI.'));
661 $result = $group->setAliases($aliases);
664 // TRANS: Server exception thrown when creating group aliases failed.
665 throw new ServerException(_('Could not create aliases.'));
668 $member = new Group_member();
670 $member->group_id = $group->id;
671 $member->profile_id = $userid;
672 $member->is_admin = 1;
673 $member->created = $group->created;
675 $result = $member->insert();
678 common_log_db_error($member, 'INSERT', __FILE__);
679 // TRANS: Server exception thrown when setting group membership failed.
680 throw new ServerException(_('Could not set group membership.'));
683 self::blow('profile:groups:%d', $userid);
686 $local_group = new Local_group();
688 $local_group->group_id = $group->id;
689 $local_group->nickname = $nickname;
690 $local_group->created = common_sql_now();
692 $result = $local_group->insert();
695 common_log_db_error($local_group, 'INSERT', __FILE__);
696 // TRANS: Server exception thrown when saving local group information failed.
697 throw new ServerException(_('Could not save local group info.'));
701 Event::handle('EndGroupSave', array($group));
704 $profile->query('COMMIT');
710 * Handle cascading deletion, on the model of notice and profile.
712 * This should handle freeing up cached entries for the group's
713 * id, nickname, URI, and aliases. There may be other areas that
714 * are not de-cached in the UI, including the sidebar lists on
717 function delete($useWhere=false)
719 if (empty($this->id)) {
720 common_log(LOG_WARNING, "Ambiguous User_group->delete(); skipping related tables.");
721 return parent::delete($useWhere);
725 $profile = $this->getProfile();
727 } catch (GroupNoProfileException $unp) {
728 common_log(LOG_INFO, "Group {$this->nickname} has no profile; continuing deletion.");
731 // Safe to delete in bulk for now
733 $related = array('Group_inbox',
738 Event::handle('UserGroupDeleteRelated', array($this, &$related));
740 foreach ($related as $cls) {
742 $inst->group_id = $this->id;
745 while ($inst->fetch()) {
752 // And related groups in the other direction...
753 $inst = new Related_group();
754 $inst->related_group_id = $this->id;
757 // Aliases and the local_group entry need to be cleared explicitly
758 // or we'll miss clearing some cache keys; that can make it hard
759 // to create a new group with one of those names or aliases.
760 $this->setAliases(array());
762 // $this->isLocal() but we're using the resulting object
763 $local = Local_group::getKV('group_id', $this->id);
764 if ($local instanceof Local_group) {
768 // blow the cached ids
769 self::blow('user_group:notice_ids:%d', $this->id);
771 return parent::delete($useWhere);
774 public function update($dataObject=false)
776 // Whenever the User_group is updated, find the Local_group
777 // and update its nickname too.
778 if ($this->nickname != $dataObject->nickname) {
779 $local = Local_group::getKV('group_id', $this->id);
780 if ($local instanceof Local_group) {
781 common_debug("Updating Local_group ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
782 $local->setNickname($this->nickname);
786 // Also make sure the Profile table is up to date!
787 $fields = array(/*group field => profile field*/
788 'nickname' => 'nickname',
789 'fullname' => 'fullname',
790 'mainpage' => 'profileurl',
791 'homepage' => 'homepage',
792 'description' => 'bio',
793 'location' => 'location',
794 'created' => 'created',
795 'modified' => 'modified',
797 $profile = $this->getProfile();
798 $origpro = clone($profile);
799 foreach ($fields as $gf=>$pf) {
800 $profile->$pf = $this->$gf;
802 if ($profile->update($origpro) === false) {
803 throw new ServerException(_('Unable to update profile'));
806 return parent::update($dataObject);
811 return ($this->join_policy == self::JOIN_POLICY_MODERATE &&
812 intval($this->force_scope) === 1);
815 public function isLocal()
817 $local = Local_group::getKV('group_id', $this->id);
818 return ($local instanceof Local_group);
821 static function groupsFromText($text, Profile $profile)
825 /* extract all !group */
826 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
834 foreach (array_unique($match[1]) as $nickname) {
835 $group = self::getForNickname($nickname, $profile);
836 if ($group instanceof User_group && $profile->isMember($group)) {
837 $groups[] = clone($group);
844 static function idsFromText($text, Profile $profile)
847 $groups = self::groupsFromText($text, $profile);
848 foreach ($groups as $group) {
849 $ids[$group->id] = true;
851 return array_keys($ids);