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 // FIXME: Get the Profile::current() some other way, to avoid
157 // possible confusion between current session and queue process.
158 $stream = new GroupNoticeStream($this, Profile::current());
160 return $stream->getNotices($offset, $limit, $since_id, $max_id);
163 function getMembers($offset=0, $limit=null) {
165 if (is_null($limit) || $offset + $limit > User_group::CACHE_WINDOW) {
166 $ids = $this->getMemberIDs($offset,
169 $key = sprintf('group:member_ids:%d', $this->id);
170 $window = self::cacheGet($key);
171 if ($window === false) {
172 $window = $this->getMemberIDs(0,
173 User_group::CACHE_WINDOW);
174 self::cacheSet($key, $window);
177 $ids = array_slice($window,
182 return Profile::multiGet('id', $ids);
185 function getMemberIDs($offset=0, $limit=null)
187 $gm = new Group_member();
190 $gm->selectAdd('profile_id');
192 $gm->group_id = $this->id;
194 $gm->orderBy('created DESC');
196 if (!is_null($limit)) {
197 $gm->limit($offset, $limit);
203 while ($gm->fetch()) {
204 $ids[] = $gm->profile_id;
212 * Get pending members, who have not yet been approved.
218 function getRequests($offset=0, $limit=null)
220 $rq = new Group_join_queue();
221 $rq->group_id = $this->id;
223 $members = new Profile();
225 $members->joinAdd(['id', $rq, 'profile_id']);
227 if ($limit != null) {
228 $members->limit($offset, $limit);
236 public function getAdminCount()
238 $block = new Group_member();
239 $block->group_id = $this->id;
240 $block->is_admin = 1;
242 return $block->count();
245 public function getMemberCount()
247 $key = sprintf("group:member_count:%d", $this->id);
249 $cnt = self::cacheGet($key);
251 if (is_integer($cnt)) {
255 $mem = new Group_member();
256 $mem->group_id = $this->id;
258 // XXX: why 'distinct'?
260 $cnt = (int) $mem->count('distinct profile_id');
262 self::cacheSet($key, $cnt);
267 function getBlockedCount()
269 // XXX: WORM cache this
271 $block = new Group_block();
272 $block->group_id = $this->id;
274 return $block->count();
277 function getQueueCount()
279 // XXX: WORM cache this
281 $queue = new Group_join_queue();
282 $queue->group_id = $this->id;
284 return $queue->count();
287 function getAdmins($offset=null, $limit=null) // offset is null because DataObject wants it, 0 would mean no results
289 $admins = new Profile();
290 $admins->joinAdd(array('id', 'group_member:profile_id'));
291 $admins->whereAdd(sprintf('group_member.group_id = %u AND group_member.is_admin = 1', $this->id));
292 $admins->orderBy('group_member.modified ASC');
293 $admins->limit($offset, $limit);
299 function getBlocked($offset=null, $limit=null) // offset is null because DataObject wants it, 0 would mean no results
301 $blocked = new Profile();
302 $blocked->joinAdd(array('id', 'group_block:blocked'));
303 $blocked->whereAdd(sprintf('group_block.group_id = %u', $this->id));
304 $blocked->orderBy('group_block.modified DESC');
305 $blocked->limit($offset, $limit);
311 function setOriginal($filename)
313 // This should be handled by the Profile->setOriginal function so user and group avatars are handled the same
314 $imagefile = new ImageFile(null, Avatar::path($filename));
316 $sizes = array('homepage_logo' => AVATAR_PROFILE_SIZE,
317 'stream_logo' => AVATAR_STREAM_SIZE,
318 'mini_logo' => AVATAR_MINI_SIZE);
320 $orig = clone($this);
321 $this->original_logo = Avatar::url($filename);
322 foreach ($sizes as $name=>$size) {
323 $filename = Avatar::filename($this->profile_id, image_type_to_extension($imagefile->preferredType()),
324 $size, common_timestamp());
325 $imagefile->resizeTo(Avatar::path($filename), array('width'=>$size, 'height'=>$size));
326 $this->$name = Avatar::url($filename);
328 common_debug(common_log_objstring($this));
329 return $this->update($orig);
332 function getBestName()
334 return ($this->fullname) ? $this->fullname : $this->nickname;
338 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
339 * if no fullname is provided.
343 function getFancyName()
345 if ($this->fullname) {
346 // TRANS: Full name of a profile or group followed by nickname in parens
347 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
349 return $this->nickname;
353 function getAliases()
359 $alias = new Group_alias();
361 $alias->group_id = $this->id;
363 if ($alias->find()) {
364 while ($alias->fetch()) {
365 $aliases[] = $alias->alias;
374 function setAliases($newaliases) {
376 $newaliases = array_unique($newaliases);
378 $oldaliases = $this->getAliases();
380 // Delete stuff that's old that not in new
382 $to_delete = array_diff($oldaliases, $newaliases);
384 // Insert stuff that's in new and not in old
386 $to_insert = array_diff($newaliases, $oldaliases);
388 $alias = new Group_alias();
390 $alias->group_id = $this->id;
392 foreach ($to_delete as $delalias) {
393 $alias->alias = $delalias;
394 $result = $alias->delete();
396 common_log_db_error($alias, 'DELETE', __FILE__);
401 foreach ($to_insert as $insalias) {
402 if ($insalias === $this->nickname) {
405 $alias->alias = Nickname::normalize($insalias, true);
406 $result = $alias->insert();
408 common_log_db_error($alias, 'INSERT', __FILE__);
416 static function getForNickname($nickname, Profile $profile=null)
418 $nickname = Nickname::normalize($nickname);
420 // Are there any matching remote groups this profile's in?
421 if ($profile instanceof Profile) {
422 $group = $profile->getGroups(0, null);
423 while ($group instanceof User_group && $group->fetch()) {
424 if ($group->nickname == $nickname) {
425 // @fixme is this the best way?
426 return clone($group);
431 // If not, check local groups.
432 $group = Local_group::getKV('nickname', $nickname);
433 if ($group instanceof Local_group) {
434 return User_group::getKV('id', $group->group_id);
436 $alias = Group_alias::getKV('alias', $nickname);
437 if ($alias instanceof Group_alias) {
438 return User_group::getKV('id', $alias->group_id);
443 function getUserMembers()
448 if(common_config('db','quote_identifiers'))
449 $user_table = '"user"';
450 else $user_table = 'user';
454 'FROM '. $user_table .' JOIN group_member '.
455 'ON '. $user_table .'.id = group_member.profile_id ' .
456 'WHERE group_member.group_id = %d ';
458 $user->query(sprintf($qry, $this->id));
462 while ($user->fetch()) {
471 static function maxDescription()
473 $desclimit = common_config('group', 'desclimit');
474 // null => use global limit (distinct from 0!)
475 if (is_null($desclimit)) {
476 $desclimit = common_config('site', 'textlimit');
481 static function descriptionTooLong($desc)
483 $desclimit = self::maxDescription();
484 return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
487 function asAtomEntry($namespace=false, $source=false)
489 $xs = new XMLStringer(true);
492 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
493 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
498 $xs->elementStart('entry', $attrs);
501 $xs->elementStart('source');
502 $xs->element('id', null, $this->permalink());
503 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
504 $xs->element('link', array('href' => $this->permalink()));
505 $xs->element('updated', null, $this->modified);
506 $xs->elementEnd('source');
509 $xs->element('title', null, $this->nickname);
510 $xs->element('summary', null, common_xml_safe_str($this->description));
512 $xs->element('link', array('rel' => 'alternate',
513 'href' => $this->permalink()));
515 $xs->element('id', null, $this->permalink());
517 $xs->element('published', null, common_date_w3dtf($this->created));
518 $xs->element('updated', null, common_date_w3dtf($this->modified));
522 array('type' => 'html'),
523 common_xml_safe_str($this->description)
526 $xs->elementEnd('entry');
528 return $xs->getString();
531 function asAtomAuthor()
533 $xs = new XMLStringer(true);
535 $xs->elementStart('author');
536 $xs->element('name', null, $this->nickname);
537 $xs->element('uri', null, $this->permalink());
538 $xs->elementEnd('author');
540 return $xs->getString();
544 * Returns an XML string fragment with group information as an
545 * Activity Streams noun object with the given element type.
547 * Assumes that 'activity', 'georss', and 'poco' namespace has been
548 * previously defined.
550 * @param string $element one of 'actor', 'subject', 'object', 'target'
554 function asActivityNoun($element)
556 $noun = ActivityObject::fromGroup($this);
557 return $noun->asString('activity:' . $element);
562 return empty($this->homepage_logo)
563 ? User_group::defaultLogo(AVATAR_PROFILE_SIZE)
564 : $this->homepage_logo;
567 static function register($fields) {
568 if (!empty($fields['userid'])) {
569 $profile = Profile::getKV('id', $fields['userid']);
570 if ($profile && !$profile->hasRight(Right::CREATEGROUP)) {
571 common_log(LOG_WARNING, "Attempted group creation from banned user: " . $profile->nickname);
573 // TRANS: Client exception thrown when a user tries to create a group while banned.
574 throw new ClientException(_('You are not allowed to create groups on this site.'), 403);
578 $fields['nickname'] = Nickname::normalize($fields['nickname']);
580 // MAGICALLY put fields into current scope
581 // @fixme kill extract(); it makes debugging absurdly hard
583 $defaults = array('nickname' => null,
586 'description' => null,
590 'aliases' => array(),
593 $fields = array_merge($defaults, $fields);
597 $group = new User_group();
603 if (empty($mainpage)) {
604 $mainpage = common_local_url('showgroup', array('nickname' => $nickname));
607 // We must create a new, incrementally assigned profile_id
608 $profile = new Profile();
609 $profile->nickname = $nickname;
610 $profile->fullname = $fullname;
611 $profile->profileurl = $mainpage;
612 $profile->homepage = $homepage;
613 $profile->bio = $description;
614 $profile->location = $location;
615 $profile->created = common_sql_now();
617 $group->nickname = $profile->nickname;
618 $group->fullname = $profile->fullname;
619 $group->homepage = $profile->homepage;
620 $group->description = $profile->bio;
621 $group->location = $profile->location;
622 $group->mainpage = $profile->profileurl;
623 $group->created = $profile->created;
625 $profile->query('BEGIN');
626 $id = $profile->insert();
628 $profile->query('ROLLBACK');
629 throw new ServerException(_('Profile insertion failed'));
632 $group->profile_id = $id;
635 if (isset($fields['join_policy'])) {
636 $group->join_policy = intval($fields['join_policy']);
638 $group->join_policy = 0;
641 if (isset($fields['force_scope'])) {
642 $group->force_scope = intval($fields['force_scope']);
644 $group->force_scope = 0;
647 if (Event::handle('StartGroupSave', array(&$group))) {
649 $result = $group->insert();
651 if ($result === false) {
652 common_log_db_error($group, 'INSERT', __FILE__);
653 // TRANS: Server exception thrown when creating a group failed.
654 throw new ServerException(_('Could not create group.'));
657 if (!isset($uri) || empty($uri)) {
658 $orig = clone($group);
659 $group->uri = common_local_url('groupbyid', array('id' => $group->id));
660 $result = $group->update($orig);
662 common_log_db_error($group, 'UPDATE', __FILE__);
663 // TRANS: Server exception thrown when updating a group URI failed.
664 throw new ServerException(_('Could not set group URI.'));
668 $result = $group->setAliases($aliases);
671 // TRANS: Server exception thrown when creating group aliases failed.
672 throw new ServerException(_('Could not create aliases.'));
675 $member = new Group_member();
677 $member->group_id = $group->id;
678 $member->profile_id = $userid;
679 $member->is_admin = 1;
680 $member->created = $group->created;
682 $result = $member->insert();
685 common_log_db_error($member, 'INSERT', __FILE__);
686 // TRANS: Server exception thrown when setting group membership failed.
687 throw new ServerException(_('Could not set group membership.'));
690 self::blow('profile:groups:%d', $userid);
693 $local_group = new Local_group();
695 $local_group->group_id = $group->id;
696 $local_group->nickname = $nickname;
697 $local_group->created = common_sql_now();
699 $result = $local_group->insert();
702 common_log_db_error($local_group, 'INSERT', __FILE__);
703 // TRANS: Server exception thrown when saving local group information failed.
704 throw new ServerException(_('Could not save local group info.'));
708 Event::handle('EndGroupSave', array($group));
711 $profile->query('COMMIT');
717 * Handle cascading deletion, on the model of notice and profile.
719 * This should handle freeing up cached entries for the group's
720 * id, nickname, URI, and aliases. There may be other areas that
721 * are not de-cached in the UI, including the sidebar lists on
724 function delete($useWhere=false)
726 if (empty($this->id)) {
727 common_log(LOG_WARNING, "Ambiguous User_group->delete(); skipping related tables.");
728 return parent::delete($useWhere);
732 $profile = $this->getProfile();
734 } catch (GroupNoProfileException $unp) {
735 common_log(LOG_INFO, "Group {$this->nickname} has no profile; continuing deletion.");
738 // Safe to delete in bulk for now
740 $related = array('Group_inbox',
745 Event::handle('UserGroupDeleteRelated', array($this, &$related));
747 foreach ($related as $cls) {
749 $inst->group_id = $this->id;
752 while ($inst->fetch()) {
759 // And related groups in the other direction...
760 $inst = new Related_group();
761 $inst->related_group_id = $this->id;
764 // Aliases and the local_group entry need to be cleared explicitly
765 // or we'll miss clearing some cache keys; that can make it hard
766 // to create a new group with one of those names or aliases.
767 $this->setAliases(array());
769 // $this->isLocal() but we're using the resulting object
770 $local = Local_group::getKV('group_id', $this->id);
771 if ($local instanceof Local_group) {
775 // blow the cached ids
776 self::blow('user_group:notice_ids:%d', $this->id);
778 return parent::delete($useWhere);
781 public function update($dataObject=false)
783 // Whenever the User_group is updated, find the Local_group
784 // and update its nickname too.
785 if ($this->nickname != $dataObject->nickname) {
786 $local = Local_group::getKV('group_id', $this->id);
787 if ($local instanceof Local_group) {
788 common_debug("Updating Local_group ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
789 $local->setNickname($this->nickname);
793 // Also make sure the Profile table is up to date!
794 $fields = array(/*group field => profile field*/
795 'nickname' => 'nickname',
796 'fullname' => 'fullname',
797 'mainpage' => 'profileurl',
798 'homepage' => 'homepage',
799 'description' => 'bio',
800 'location' => 'location',
801 'created' => 'created',
802 'modified' => 'modified',
804 $profile = $this->getProfile();
805 $origpro = clone($profile);
806 foreach ($fields as $gf=>$pf) {
807 $profile->$pf = $this->$gf;
809 if ($profile->update($origpro) === false) {
810 throw new ServerException(_('Unable to update profile'));
813 return parent::update($dataObject);
818 return ($this->join_policy == self::JOIN_POLICY_MODERATE &&
819 intval($this->force_scope) === 1);
822 public function isLocal()
824 $local = Local_group::getKV('group_id', $this->id);
825 return ($local instanceof Local_group);
828 static function groupsFromText($text, Profile $profile)
832 /* extract all !group */
833 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
841 foreach (array_unique($match[1]) as $nickname) {
842 $group = self::getForNickname($nickname, $profile);
843 if ($group instanceof User_group && $profile->isMember($group)) {
844 $groups[] = clone($group);
851 static function idsFromText($text, Profile $profile)
854 $groups = self::groupsFromText($text, $profile);
855 foreach ($groups as $group) {
856 $ids[$group->id] = true;
858 return array_keys($ids);