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');
119 if (Event::handle('StartUserGroupHomeUrl', array($this, &$url))) {
120 // normally stored in mainpage, but older ones may be null
121 if (!empty($this->mainpage)) {
122 $url = $this->mainpage;
123 } elseif ($this->isLocal()) {
124 $url = common_local_url('showgroup',
125 array('nickname' => $this->nickname));
128 Event::handle('EndUserGroupHomeUrl', array($this, &$url));
135 if (Event::handle('StartUserGroupGetUri', array($this, &$uri))) {
136 if (!empty($this->uri)) {
138 } elseif ($this->isLocal()) {
139 $uri = common_local_url('groupbyid',
140 array('id' => $this->id));
143 Event::handle('EndUserGroupGetUri', array($this, &$uri));
150 if (Event::handle('StartUserGroupPermalink', array($this, &$url))) {
151 if ($this->isLocal()) {
152 $url = common_local_url('groupbyid',
153 array('id' => $this->id));
156 Event::handle('EndUserGroupPermalink', array($this, &$url));
160 function getNotices($offset, $limit, $since_id=null, $max_id=null)
162 $stream = new GroupNoticeStream($this);
164 return $stream->getNotices($offset, $limit, $since_id, $max_id);
167 function getMembers($offset=0, $limit=null) {
169 if (is_null($limit) || $offset + $limit > User_group::CACHE_WINDOW) {
170 $ids = $this->getMemberIDs($offset,
173 $key = sprintf('group:member_ids:%d', $this->id);
174 $window = self::cacheGet($key);
175 if ($window === false) {
176 $window = $this->getMemberIDs(0,
177 User_group::CACHE_WINDOW);
178 self::cacheSet($key, $window);
181 $ids = array_slice($window,
186 return Profile::multiGet('id', $ids);
189 function getMemberIDs($offset=0, $limit=null)
191 $gm = new Group_member();
194 $gm->selectAdd('profile_id');
196 $gm->group_id = $this->id;
198 $gm->orderBy('created DESC');
200 if (!is_null($limit)) {
201 $gm->limit($offset, $limit);
207 while ($gm->fetch()) {
208 $ids[] = $gm->profile_id;
216 * Get pending members, who have not yet been approved.
222 function getRequests($offset=0, $limit=null)
224 $rq = new Group_join_queue();
225 $rq->group_id = $this->id;
227 $members = new Profile();
229 $members->joinAdd(['id', $rq, 'profile_id']);
231 if ($limit != null) {
232 $members->limit($offset, $limit);
240 public function getAdminCount()
242 $block = new Group_member();
243 $block->group_id = $this->id;
244 $block->is_admin = 1;
246 return $block->count();
249 public function getMemberCount()
251 $key = sprintf("group:member_count:%d", $this->id);
253 $cnt = self::cacheGet($key);
255 if (is_integer($cnt)) {
259 $mem = new Group_member();
260 $mem->group_id = $this->id;
262 // XXX: why 'distinct'?
264 $cnt = (int) $mem->count('distinct profile_id');
266 self::cacheSet($key, $cnt);
271 function getBlockedCount()
273 // XXX: WORM cache this
275 $block = new Group_block();
276 $block->group_id = $this->id;
278 return $block->count();
281 function getQueueCount()
283 // XXX: WORM cache this
285 $queue = new Group_join_queue();
286 $queue->group_id = $this->id;
288 return $queue->count();
291 function getAdmins($offset=null, $limit=null) // offset is null because DataObject wants it, 0 would mean no results
293 $admins = new Profile();
294 $admins->joinAdd(array('id', 'group_member:profile_id'));
295 $admins->whereAdd(sprintf('group_member.group_id = %u AND group_member.is_admin = 1', $this->id));
296 $admins->orderBy('group_member.modified ASC');
297 $admins->limit($offset, $limit);
303 function getBlocked($offset=null, $limit=null) // offset is null because DataObject wants it, 0 would mean no results
305 $blocked = new Profile();
306 $blocked->joinAdd(array('id', 'group_block:blocked'));
307 $blocked->whereAdd(sprintf('group_block.group_id = %u', $this->id));
308 $blocked->orderBy('group_block.modified DESC');
309 $blocked->limit($offset, $limit);
315 function setOriginal($filename)
317 // This should be handled by the Profile->setOriginal function so user and group avatars are handled the same
318 $imagefile = new ImageFile(null, Avatar::path($filename));
320 $sizes = array('homepage_logo' => AVATAR_PROFILE_SIZE,
321 'stream_logo' => AVATAR_STREAM_SIZE,
322 'mini_logo' => AVATAR_MINI_SIZE);
324 $orig = clone($this);
325 $this->original_logo = Avatar::url($filename);
326 foreach ($sizes as $name=>$size) {
327 $filename = Avatar::filename($this->profile_id, image_type_to_extension($imagefile->preferredType()),
328 $size, common_timestamp());
329 $imagefile->resizeTo(Avatar::path($filename), array('width'=>$size, 'height'=>$size));
330 $this->$name = Avatar::url($filename);
332 common_debug(common_log_objstring($this));
333 return $this->update($orig);
336 function getBestName()
338 return ($this->fullname) ? $this->fullname : $this->nickname;
342 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
343 * if no fullname is provided.
347 function getFancyName()
349 if ($this->fullname) {
350 // TRANS: Full name of a profile or group followed by nickname in parens
351 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
353 return $this->nickname;
357 function getAliases()
363 $alias = new Group_alias();
365 $alias->group_id = $this->id;
367 if ($alias->find()) {
368 while ($alias->fetch()) {
369 $aliases[] = $alias->alias;
378 function setAliases($newaliases) {
380 $newaliases = array_unique($newaliases);
382 $oldaliases = $this->getAliases();
384 // Delete stuff that's old that not in new
386 $to_delete = array_diff($oldaliases, $newaliases);
388 // Insert stuff that's in new and not in old
390 $to_insert = array_diff($newaliases, $oldaliases);
392 $alias = new Group_alias();
394 $alias->group_id = $this->id;
396 foreach ($to_delete as $delalias) {
397 $alias->alias = $delalias;
398 $result = $alias->delete();
400 common_log_db_error($alias, 'DELETE', __FILE__);
405 foreach ($to_insert as $insalias) {
406 if ($insalias === $this->nickname) {
409 $alias->alias = Nickname::normalize($insalias, true);
410 $result = $alias->insert();
412 common_log_db_error($alias, 'INSERT', __FILE__);
420 static function getForNickname($nickname, Profile $profile=null)
422 $nickname = Nickname::normalize($nickname);
424 // Are there any matching remote groups this profile's in?
425 if ($profile instanceof Profile) {
426 $group = $profile->getGroups(0, null);
427 while ($group instanceof User_group && $group->fetch()) {
428 if ($group->nickname == $nickname) {
429 // @fixme is this the best way?
430 return clone($group);
435 // If not, check local groups.
436 $group = Local_group::getKV('nickname', $nickname);
437 if ($group instanceof Local_group) {
438 return User_group::getKV('id', $group->group_id);
440 $alias = Group_alias::getKV('alias', $nickname);
441 if ($alias instanceof Group_alias) {
442 return User_group::getKV('id', $alias->group_id);
447 function getUserMembers()
452 if(common_config('db','quote_identifiers'))
453 $user_table = '"user"';
454 else $user_table = 'user';
458 'FROM '. $user_table .' JOIN group_member '.
459 'ON '. $user_table .'.id = group_member.profile_id ' .
460 'WHERE group_member.group_id = %d ';
462 $user->query(sprintf($qry, $this->id));
466 while ($user->fetch()) {
475 static function maxDescription()
477 $desclimit = common_config('group', 'desclimit');
478 // null => use global limit (distinct from 0!)
479 if (is_null($desclimit)) {
480 $desclimit = common_config('site', 'textlimit');
485 static function descriptionTooLong($desc)
487 $desclimit = self::maxDescription();
488 return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
491 function asAtomEntry($namespace=false, $source=false)
493 $xs = new XMLStringer(true);
496 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
497 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
502 $xs->elementStart('entry', $attrs);
505 $xs->elementStart('source');
506 $xs->element('id', null, $this->permalink());
507 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
508 $xs->element('link', array('href' => $this->permalink()));
509 $xs->element('updated', null, $this->modified);
510 $xs->elementEnd('source');
513 $xs->element('title', null, $this->nickname);
514 $xs->element('summary', null, common_xml_safe_str($this->description));
516 $xs->element('link', array('rel' => 'alternate',
517 'href' => $this->permalink()));
519 $xs->element('id', null, $this->permalink());
521 $xs->element('published', null, common_date_w3dtf($this->created));
522 $xs->element('updated', null, common_date_w3dtf($this->modified));
526 array('type' => 'html'),
527 common_xml_safe_str($this->description)
530 $xs->elementEnd('entry');
532 return $xs->getString();
535 function asAtomAuthor()
537 $xs = new XMLStringer(true);
539 $xs->elementStart('author');
540 $xs->element('name', null, $this->nickname);
541 $xs->element('uri', null, $this->permalink());
542 $xs->elementEnd('author');
544 return $xs->getString();
548 * Returns an XML string fragment with group information as an
549 * Activity Streams noun object with the given element type.
551 * Assumes that 'activity', 'georss', and 'poco' namespace has been
552 * previously defined.
554 * @param string $element one of 'actor', 'subject', 'object', 'target'
558 function asActivityNoun($element)
560 $noun = ActivityObject::fromGroup($this);
561 return $noun->asString('activity:' . $element);
566 return empty($this->homepage_logo)
567 ? User_group::defaultLogo(AVATAR_PROFILE_SIZE)
568 : $this->homepage_logo;
571 static function register($fields) {
572 if (!empty($fields['userid'])) {
573 $profile = Profile::getKV('id', $fields['userid']);
574 if ($profile && !$profile->hasRight(Right::CREATEGROUP)) {
575 common_log(LOG_WARNING, "Attempted group creation from banned user: " . $profile->nickname);
577 // TRANS: Client exception thrown when a user tries to create a group while banned.
578 throw new ClientException(_('You are not allowed to create groups on this site.'), 403);
582 $fields['nickname'] = Nickname::normalize($fields['nickname']);
584 // MAGICALLY put fields into current scope
585 // @fixme kill extract(); it makes debugging absurdly hard
587 $defaults = array('nickname' => null,
590 'description' => null,
594 'aliases' => array(),
597 $fields = array_merge($defaults, $fields);
601 $group = new User_group();
607 if (empty($mainpage)) {
608 $mainpage = common_local_url('showgroup', array('nickname' => $nickname));
611 // We must create a new, incrementally assigned profile_id
612 $profile = new Profile();
613 $profile->nickname = $nickname;
614 $profile->fullname = $fullname;
615 $profile->profileurl = $mainpage;
616 $profile->homepage = $homepage;
617 $profile->bio = $description;
618 $profile->location = $location;
619 $profile->created = common_sql_now();
621 $group->nickname = $profile->nickname;
622 $group->fullname = $profile->fullname;
623 $group->homepage = $profile->homepage;
624 $group->description = $profile->bio;
625 $group->location = $profile->location;
626 $group->mainpage = $profile->profileurl;
627 $group->created = $profile->created;
629 $profile->query('BEGIN');
630 $id = $profile->insert();
632 $profile->query('ROLLBACK');
633 throw new ServerException(_('Profile insertion failed'));
636 $group->profile_id = $id;
639 if (isset($fields['join_policy'])) {
640 $group->join_policy = intval($fields['join_policy']);
642 $group->join_policy = 0;
645 if (isset($fields['force_scope'])) {
646 $group->force_scope = intval($fields['force_scope']);
648 $group->force_scope = 0;
651 if (Event::handle('StartGroupSave', array(&$group))) {
653 $result = $group->insert();
655 if ($result === false) {
656 common_log_db_error($group, 'INSERT', __FILE__);
657 // TRANS: Server exception thrown when creating a group failed.
658 throw new ServerException(_('Could not create group.'));
661 if (!isset($uri) || empty($uri)) {
662 $orig = clone($group);
663 $group->uri = common_local_url('groupbyid', array('id' => $group->id));
664 $result = $group->update($orig);
666 common_log_db_error($group, 'UPDATE', __FILE__);
667 // TRANS: Server exception thrown when updating a group URI failed.
668 throw new ServerException(_('Could not set group URI.'));
672 $result = $group->setAliases($aliases);
675 // TRANS: Server exception thrown when creating group aliases failed.
676 throw new ServerException(_('Could not create aliases.'));
679 $member = new Group_member();
681 $member->group_id = $group->id;
682 $member->profile_id = $userid;
683 $member->is_admin = 1;
684 $member->created = $group->created;
686 $result = $member->insert();
689 common_log_db_error($member, 'INSERT', __FILE__);
690 // TRANS: Server exception thrown when setting group membership failed.
691 throw new ServerException(_('Could not set group membership.'));
694 self::blow('profile:groups:%d', $userid);
697 $local_group = new Local_group();
699 $local_group->group_id = $group->id;
700 $local_group->nickname = $nickname;
701 $local_group->created = common_sql_now();
703 $result = $local_group->insert();
706 common_log_db_error($local_group, 'INSERT', __FILE__);
707 // TRANS: Server exception thrown when saving local group information failed.
708 throw new ServerException(_('Could not save local group info.'));
712 Event::handle('EndGroupSave', array($group));
715 $profile->query('COMMIT');
721 * Handle cascading deletion, on the model of notice and profile.
723 * This should handle freeing up cached entries for the group's
724 * id, nickname, URI, and aliases. There may be other areas that
725 * are not de-cached in the UI, including the sidebar lists on
728 function delete($useWhere=false)
730 if (empty($this->id)) {
731 common_log(LOG_WARNING, "Ambiguous User_group->delete(); skipping related tables.");
732 return parent::delete($useWhere);
736 $profile = $this->getProfile();
738 } catch (GroupNoProfileException $unp) {
739 common_log(LOG_INFO, "Group {$this->nickname} has no profile; continuing deletion.");
742 // Safe to delete in bulk for now
744 $related = array('Group_inbox',
749 Event::handle('UserGroupDeleteRelated', array($this, &$related));
751 foreach ($related as $cls) {
753 $inst->group_id = $this->id;
756 while ($inst->fetch()) {
763 // And related groups in the other direction...
764 $inst = new Related_group();
765 $inst->related_group_id = $this->id;
768 // Aliases and the local_group entry need to be cleared explicitly
769 // or we'll miss clearing some cache keys; that can make it hard
770 // to create a new group with one of those names or aliases.
771 $this->setAliases(array());
773 // $this->isLocal() but we're using the resulting object
774 $local = Local_group::getKV('group_id', $this->id);
775 if ($local instanceof Local_group) {
779 // blow the cached ids
780 self::blow('user_group:notice_ids:%d', $this->id);
782 return parent::delete($useWhere);
785 public function update($dataObject=false)
787 // Whenever the User_group is updated, find the Local_group
788 // and update its nickname too.
789 if ($this->nickname != $dataObject->nickname) {
790 $local = Local_group::getKV('group_id', $this->id);
791 if ($local instanceof Local_group) {
792 common_debug("Updating Local_group ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
793 $local->setNickname($this->nickname);
797 // Also make sure the Profile table is up to date!
798 $fields = array(/*group field => profile field*/
799 'nickname' => 'nickname',
800 'fullname' => 'fullname',
801 'mainpage' => 'profileurl',
802 'homepage' => 'homepage',
803 'description' => 'bio',
804 'location' => 'location',
805 'created' => 'created',
806 'modified' => 'modified',
808 $profile = $this->getProfile();
809 $origpro = clone($profile);
810 foreach ($fields as $gf=>$pf) {
811 $profile->$pf = $this->$gf;
813 if ($profile->update($origpro) === false) {
814 throw new ServerException(_('Unable to update profile'));
817 return parent::update($dataObject);
822 return ($this->join_policy == self::JOIN_POLICY_MODERATE &&
823 intval($this->force_scope) === 1);
826 public function isLocal()
828 $local = Local_group::getKV('group_id', $this->id);
829 return ($local instanceof Local_group);
832 static function groupsFromText($text, Profile $profile)
836 /* extract all !group */
837 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
845 foreach (array_unique($match[1]) as $nickname) {
846 $group = self::getForNickname($nickname, $profile);
847 if ($group instanceof User_group && $profile->isMember($group)) {
848 $groups[] = clone($group);
855 static function idsFromText($text, Profile $profile)
858 $groups = self::groupsFromText($text, $profile);
859 foreach ($groups as $group) {
860 $ids[$group->id] = true;
862 return array_keys($ids);