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);
94 if (!$profile instanceof Profile) {
95 throw new GroupNoProfileException($this);
97 $this->_profile[$this->profile_id] = $profile;
99 return $this->_profile[$this->profile_id];
102 public function getNickname()
104 return $this->getProfile()->getNickname();
107 public static function defaultLogo($size)
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');
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));
127 Event::handle('EndUserGroupHomeUrl', array($this, &$url));
134 if (Event::handle('StartUserGroupGetUri', array($this, &$uri))) {
135 if (!empty($this->uri)) {
137 } elseif ($this->isLocal()) {
138 $uri = common_local_url('groupbyid',
139 array('id' => $this->id));
142 Event::handle('EndUserGroupGetUri', array($this, &$uri));
149 if (Event::handle('StartUserGroupPermalink', array($this, &$url))) {
150 if ($this->isLocal()) {
151 $url = common_local_url('groupbyid',
152 array('id' => $this->id));
155 Event::handle('EndUserGroupPermalink', array($this, &$url));
159 function getNotices($offset, $limit, $since_id=null, $max_id=null)
161 $stream = new GroupNoticeStream($this);
163 return $stream->getNotices($offset, $limit, $since_id, $max_id);
166 function getMembers($offset=0, $limit=null) {
168 if (is_null($limit) || $offset + $limit > User_group::CACHE_WINDOW) {
169 $ids = $this->getMemberIDs($offset,
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);
180 $ids = array_slice($window,
185 return Profile::multiGet('id', $ids);
188 function getMemberIDs($offset=0, $limit=null)
190 $gm = new Group_member();
193 $gm->selectAdd('profile_id');
195 $gm->group_id = $this->id;
197 $gm->orderBy('created DESC');
199 if (!is_null($limit)) {
200 $gm->limit($offset, $limit);
206 while ($gm->fetch()) {
207 $ids[] = $gm->profile_id;
215 * Get pending members, who have not yet been approved.
221 function getRequests($offset=0, $limit=null)
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 ';
230 if ($limit != null) {
231 if (common_config('db','type') == 'pgsql') {
232 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
234 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
238 $members = new Profile();
240 $members->query(sprintf($qry, $this->id));
244 public function getAdminCount()
246 $block = new Group_member();
247 $block->group_id = $this->id;
248 $block->is_admin = 1;
250 return $block->count();
253 public function getMemberCount()
255 $key = sprintf("group:member_count:%d", $this->id);
257 $cnt = self::cacheGet($key);
259 if (is_integer($cnt)) {
263 $mem = new Group_member();
264 $mem->group_id = $this->id;
266 // XXX: why 'distinct'?
268 $cnt = (int) $mem->count('distinct profile_id');
270 self::cacheSet($key, $cnt);
275 function getBlockedCount()
277 // XXX: WORM cache this
279 $block = new Group_block();
280 $block->group_id = $this->id;
282 return $block->count();
285 function getQueueCount()
287 // XXX: WORM cache this
289 $queue = new Group_join_queue();
290 $queue->group_id = $this->id;
292 return $queue->count();
295 function getAdmins($offset=null, $limit=null) // offset is null because DataObject wants it, 0 would mean no results
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);
307 function getBlocked($offset=null, $limit=null) // offset is null because DataObject wants it, 0 would mean no results
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);
319 function setOriginal($filename)
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));
324 $sizes = array('homepage_logo' => AVATAR_PROFILE_SIZE,
325 'stream_logo' => AVATAR_STREAM_SIZE,
326 'mini_logo' => AVATAR_MINI_SIZE);
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);
336 common_debug(common_log_objstring($this));
337 return $this->update($orig);
340 function getBestName()
342 return ($this->fullname) ? $this->fullname : $this->nickname;
346 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
347 * if no fullname is provided.
351 function getFancyName()
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);
357 return $this->nickname;
361 function getAliases()
367 $alias = new Group_alias();
369 $alias->group_id = $this->id;
371 if ($alias->find()) {
372 while ($alias->fetch()) {
373 $aliases[] = $alias->alias;
382 function setAliases($newaliases) {
384 $newaliases = array_unique($newaliases);
386 $oldaliases = $this->getAliases();
388 // Delete stuff that's old that not in new
390 $to_delete = array_diff($oldaliases, $newaliases);
392 // Insert stuff that's in new and not in old
394 $to_insert = array_diff($newaliases, $oldaliases);
396 $alias = new Group_alias();
398 $alias->group_id = $this->id;
400 foreach ($to_delete as $delalias) {
401 $alias->alias = $delalias;
402 $result = $alias->delete();
404 common_log_db_error($alias, 'DELETE', __FILE__);
409 foreach ($to_insert as $insalias) {
410 if ($insalias === $this->nickname) {
413 $alias->alias = Nickname::normalize($insalias, true);
414 $result = $alias->insert();
416 common_log_db_error($alias, 'INSERT', __FILE__);
424 static function getForNickname($nickname, Profile $profile=null)
426 $nickname = Nickname::normalize($nickname);
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);
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);
444 $alias = Group_alias::getKV('alias', $nickname);
445 if ($alias instanceof Group_alias) {
446 return User_group::getKV('id', $alias->group_id);
451 function getUserMembers()
456 if(common_config('db','quote_identifiers'))
457 $user_table = '"user"';
458 else $user_table = 'user';
462 'FROM '. $user_table .' JOIN group_member '.
463 'ON '. $user_table .'.id = group_member.profile_id ' .
464 'WHERE group_member.group_id = %d ';
466 $user->query(sprintf($qry, $this->id));
470 while ($user->fetch()) {
479 static function maxDescription()
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');
489 static function descriptionTooLong($desc)
491 $desclimit = self::maxDescription();
492 return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
495 function asAtomEntry($namespace=false, $source=false)
497 $xs = new XMLStringer(true);
500 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
501 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
506 $xs->elementStart('entry', $attrs);
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');
517 $xs->element('title', null, $this->nickname);
518 $xs->element('summary', null, common_xml_safe_str($this->description));
520 $xs->element('link', array('rel' => 'alternate',
521 'href' => $this->permalink()));
523 $xs->element('id', null, $this->permalink());
525 $xs->element('published', null, common_date_w3dtf($this->created));
526 $xs->element('updated', null, common_date_w3dtf($this->modified));
530 array('type' => 'html'),
531 common_xml_safe_str($this->description)
534 $xs->elementEnd('entry');
536 return $xs->getString();
539 function asAtomAuthor()
541 $xs = new XMLStringer(true);
543 $xs->elementStart('author');
544 $xs->element('name', null, $this->nickname);
545 $xs->element('uri', null, $this->permalink());
546 $xs->elementEnd('author');
548 return $xs->getString();
552 * Returns an XML string fragment with group information as an
553 * Activity Streams noun object with the given element type.
555 * Assumes that 'activity', 'georss', and 'poco' namespace has been
556 * previously defined.
558 * @param string $element one of 'actor', 'subject', 'object', 'target'
562 function asActivityNoun($element)
564 $noun = ActivityObject::fromGroup($this);
565 return $noun->asString('activity:' . $element);
570 return empty($this->homepage_logo)
571 ? User_group::defaultLogo(AVATAR_PROFILE_SIZE)
572 : $this->homepage_logo;
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);
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);
586 $fields['nickname'] = Nickname::normalize($fields['nickname']);
588 // MAGICALLY put fields into current scope
589 // @fixme kill extract(); it makes debugging absurdly hard
591 $defaults = array('nickname' => null,
594 'description' => null,
598 'aliases' => array(),
601 $fields = array_merge($defaults, $fields);
605 $group = new User_group();
611 if (empty($mainpage)) {
612 $mainpage = common_local_url('showgroup', array('nickname' => $nickname));
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();
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;
633 $profile->query('BEGIN');
634 $id = $profile->insert();
636 $profile->query('ROLLBACK');
637 throw new ServerException(_('Profile insertion failed'));
640 $group->profile_id = $id;
643 if (isset($fields['join_policy'])) {
644 $group->join_policy = intval($fields['join_policy']);
646 $group->join_policy = 0;
649 if (isset($fields['force_scope'])) {
650 $group->force_scope = intval($fields['force_scope']);
652 $group->force_scope = 0;
655 if (Event::handle('StartGroupSave', array(&$group))) {
657 $result = $group->insert();
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.'));
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);
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.'));
676 $result = $group->setAliases($aliases);
679 // TRANS: Server exception thrown when creating group aliases failed.
680 throw new ServerException(_('Could not create aliases.'));
683 $member = new Group_member();
685 $member->group_id = $group->id;
686 $member->profile_id = $userid;
687 $member->is_admin = 1;
688 $member->created = $group->created;
690 $result = $member->insert();
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.'));
698 self::blow('profile:groups:%d', $userid);
701 $local_group = new Local_group();
703 $local_group->group_id = $group->id;
704 $local_group->nickname = $nickname;
705 $local_group->created = common_sql_now();
707 $result = $local_group->insert();
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.'));
716 Event::handle('EndGroupSave', array($group));
719 $profile->query('COMMIT');
725 * Handle cascading deletion, on the model of notice and profile.
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
732 function delete($useWhere=false)
734 if (empty($this->id)) {
735 common_log(LOG_WARNING, "Ambiguous User_group->delete(); skipping related tables.");
736 return parent::delete($useWhere);
740 $profile = $this->getProfile();
742 } catch (GroupNoProfileException $unp) {
743 common_log(LOG_INFO, "Group {$this->nickname} has no profile; continuing deletion.");
746 // Safe to delete in bulk for now
748 $related = array('Group_inbox',
753 Event::handle('UserGroupDeleteRelated', array($this, &$related));
755 foreach ($related as $cls) {
757 $inst->group_id = $this->id;
760 while ($inst->fetch()) {
767 // And related groups in the other direction...
768 $inst = new Related_group();
769 $inst->related_group_id = $this->id;
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());
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) {
783 // blow the cached ids
784 self::blow('user_group:notice_ids:%d', $this->id);
786 return parent::delete($useWhere);
789 public function update($dataObject=false)
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);
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',
812 $profile = $this->getProfile();
813 $origpro = clone($profile);
814 foreach ($fields as $gf=>$pf) {
815 $profile->$pf = $this->$gf;
817 if ($profile->update($origpro) === false) {
818 throw new ServerException(_('Unable to update profile'));
821 return parent::update($dataObject);
826 return ($this->join_policy == self::JOIN_POLICY_MODERATE &&
827 intval($this->force_scope) === 1);
830 public function isLocal()
832 $local = Local_group::getKV('group_id', $this->id);
833 return ($local instanceof Local_group);
836 static function groupsFromText($text, Profile $profile)
840 /* extract all !group */
841 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
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);
859 static function idsFromText($text, Profile $profile)
862 $groups = self::groupsFromText($text, $profile);
863 foreach ($groups as $group) {
864 $ids[$group->id] = true;
866 return array_keys($ids);