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);
95 if (!$profile instanceof Profile) {
97 $profile = new Profile();
98 $profile->nickname = $this->nickname;
99 $profile->fullname = $this->fullname;
100 $profile->profileurl = $this->mainpage;
101 $profile->homepage = $this->homepage;
102 $profile->bio = $this->description;
103 $profile->location = $this->location;
104 $profile->created = common_sql_now();
105 $this->profile_id = $profile->insert();
107 //throw new GroupNoProfileException($this);
110 $this->_profile[$this->profile_id] = $profile;
112 return $this->_profile[$this->profile_id];
115 public function getNickname()
117 return $this->getProfile()->getNickname();
120 public static function defaultLogo($size)
122 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
123 AVATAR_STREAM_SIZE => 'stream',
124 AVATAR_MINI_SIZE => 'mini');
125 return Theme::path('default-avatar-'.$sizenames[$size].'.png');
131 if (Event::handle('StartUserGroupHomeUrl', array($this, &$url))) {
132 // normally stored in mainpage, but older ones may be null
133 if (!empty($this->mainpage)) {
134 $url = $this->mainpage;
135 } elseif ($this->isLocal()) {
136 $url = common_local_url('showgroup',
137 array('nickname' => $this->nickname));
140 Event::handle('EndUserGroupHomeUrl', array($this, &$url));
147 if (Event::handle('StartUserGroupGetUri', array($this, &$uri))) {
148 if (!empty($this->uri)) {
150 } elseif ($this->isLocal()) {
151 $uri = common_local_url('groupbyid',
152 array('id' => $this->id));
155 Event::handle('EndUserGroupGetUri', array($this, &$uri));
162 if (Event::handle('StartUserGroupPermalink', array($this, &$url))) {
163 if ($this->isLocal()) {
164 $url = common_local_url('groupbyid',
165 array('id' => $this->id));
168 Event::handle('EndUserGroupPermalink', array($this, &$url));
172 function getNotices($offset, $limit, $since_id=null, $max_id=null)
174 $stream = new GroupNoticeStream($this);
176 return $stream->getNotices($offset, $limit, $since_id, $max_id);
179 function getMembers($offset=0, $limit=null) {
181 if (is_null($limit) || $offset + $limit > User_group::CACHE_WINDOW) {
182 $ids = $this->getMemberIDs($offset,
185 $key = sprintf('group:member_ids:%d', $this->id);
186 $window = self::cacheGet($key);
187 if ($window === false) {
188 $window = $this->getMemberIDs(0,
189 User_group::CACHE_WINDOW);
190 self::cacheSet($key, $window);
193 $ids = array_slice($window,
198 return Profile::multiGet('id', $ids);
201 function getMemberIDs($offset=0, $limit=null)
203 $gm = new Group_member();
206 $gm->selectAdd('profile_id');
208 $gm->group_id = $this->id;
210 $gm->orderBy('created DESC');
212 if (!is_null($limit)) {
213 $gm->limit($offset, $limit);
219 while ($gm->fetch()) {
220 $ids[] = $gm->profile_id;
228 * Get pending members, who have not yet been approved.
234 function getRequests($offset=0, $limit=null)
237 'SELECT profile.* ' .
238 'FROM profile JOIN group_join_queue '.
239 'ON profile.id = group_join_queue.profile_id ' .
240 'WHERE group_join_queue.group_id = %d ' .
241 'ORDER BY group_join_queue.created DESC ';
243 if ($limit != null) {
244 if (common_config('db','type') == 'pgsql') {
245 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
247 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
251 $members = new Profile();
253 $members->query(sprintf($qry, $this->id));
257 public function getAdminCount()
259 $block = new Group_member();
260 $block->group_id = $this->id;
261 $block->is_admin = 1;
263 return $block->count();
266 public function getMemberCount()
268 $key = sprintf("group:member_count:%d", $this->id);
270 $cnt = self::cacheGet($key);
272 if (is_integer($cnt)) {
276 $mem = new Group_member();
277 $mem->group_id = $this->id;
279 // XXX: why 'distinct'?
281 $cnt = (int) $mem->count('distinct profile_id');
283 self::cacheSet($key, $cnt);
288 function getBlockedCount()
290 // XXX: WORM cache this
292 $block = new Group_block();
293 $block->group_id = $this->id;
295 return $block->count();
298 function getQueueCount()
300 // XXX: WORM cache this
302 $queue = new Group_join_queue();
303 $queue->group_id = $this->id;
305 return $queue->count();
308 function getAdmins($offset=null, $limit=null) // offset is null because DataObject wants it, 0 would mean no results
310 $admins = new Profile();
311 $admins->joinAdd(array('id', 'group_member:profile_id'));
312 $admins->whereAdd(sprintf('group_member.group_id = %u AND group_member.is_admin = 1', $this->id));
313 $admins->orderBy('group_member.modified ASC');
314 $admins->limit($offset, $limit);
320 function getBlocked($offset=null, $limit=null) // offset is null because DataObject wants it, 0 would mean no results
322 $blocked = new Profile();
323 $blocked->joinAdd(array('id', 'group_block:blocked'));
324 $blocked->whereAdd(sprintf('group_block.group_id = %u', $this->id));
325 $blocked->orderBy('group_block.modified DESC');
326 $blocked->limit($offset, $limit);
332 function setOriginal($filename)
334 // This should be handled by the Profile->setOriginal function so user and group avatars are handled the same
335 $imagefile = new ImageFile(null, Avatar::path($filename));
337 $sizes = array('homepage_logo' => AVATAR_PROFILE_SIZE,
338 'stream_logo' => AVATAR_STREAM_SIZE,
339 'mini_logo' => AVATAR_MINI_SIZE);
341 $orig = clone($this);
342 $this->original_logo = Avatar::url($filename);
343 foreach ($sizes as $name=>$size) {
344 $filename = Avatar::filename($this->profile_id, image_type_to_extension($imagefile->preferredType()),
345 $size, common_timestamp());
346 $imagefile->resizeTo(Avatar::path($filename), array('width'=>$size, 'height'=>$size));
347 $this->$name = Avatar::url($filename);
349 common_debug(common_log_objstring($this));
350 return $this->update($orig);
353 function getBestName()
355 return ($this->fullname) ? $this->fullname : $this->nickname;
359 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
360 * if no fullname is provided.
364 function getFancyName()
366 if ($this->fullname) {
367 // TRANS: Full name of a profile or group followed by nickname in parens
368 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
370 return $this->nickname;
374 function getAliases()
380 $alias = new Group_alias();
382 $alias->group_id = $this->id;
384 if ($alias->find()) {
385 while ($alias->fetch()) {
386 $aliases[] = $alias->alias;
395 function setAliases($newaliases) {
397 $newaliases = array_unique($newaliases);
399 $oldaliases = $this->getAliases();
401 // Delete stuff that's old that not in new
403 $to_delete = array_diff($oldaliases, $newaliases);
405 // Insert stuff that's in new and not in old
407 $to_insert = array_diff($newaliases, $oldaliases);
409 $alias = new Group_alias();
411 $alias->group_id = $this->id;
413 foreach ($to_delete as $delalias) {
414 $alias->alias = $delalias;
415 $result = $alias->delete();
417 common_log_db_error($alias, 'DELETE', __FILE__);
422 foreach ($to_insert as $insalias) {
423 if ($insalias === $this->nickname) {
426 $alias->alias = Nickname::normalize($insalias, true);
427 $result = $alias->insert();
429 common_log_db_error($alias, 'INSERT', __FILE__);
437 static function getForNickname($nickname, Profile $profile=null)
439 $nickname = Nickname::normalize($nickname);
441 // Are there any matching remote groups this profile's in?
442 if ($profile instanceof Profile) {
443 $group = $profile->getGroups(0, null);
444 while ($group instanceof User_group && $group->fetch()) {
445 if ($group->nickname == $nickname) {
446 // @fixme is this the best way?
447 return clone($group);
452 // If not, check local groups.
453 $group = Local_group::getKV('nickname', $nickname);
454 if ($group instanceof Local_group) {
455 return User_group::getKV('id', $group->group_id);
457 $alias = Group_alias::getKV('alias', $nickname);
458 if ($alias instanceof Group_alias) {
459 return User_group::getKV('id', $alias->group_id);
464 function getUserMembers()
469 if(common_config('db','quote_identifiers'))
470 $user_table = '"user"';
471 else $user_table = 'user';
475 'FROM '. $user_table .' JOIN group_member '.
476 'ON '. $user_table .'.id = group_member.profile_id ' .
477 'WHERE group_member.group_id = %d ';
479 $user->query(sprintf($qry, $this->id));
483 while ($user->fetch()) {
492 static function maxDescription()
494 $desclimit = common_config('group', 'desclimit');
495 // null => use global limit (distinct from 0!)
496 if (is_null($desclimit)) {
497 $desclimit = common_config('site', 'textlimit');
502 static function descriptionTooLong($desc)
504 $desclimit = self::maxDescription();
505 return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
508 function asAtomEntry($namespace=false, $source=false)
510 $xs = new XMLStringer(true);
513 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
514 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
519 $xs->elementStart('entry', $attrs);
522 $xs->elementStart('source');
523 $xs->element('id', null, $this->permalink());
524 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
525 $xs->element('link', array('href' => $this->permalink()));
526 $xs->element('updated', null, $this->modified);
527 $xs->elementEnd('source');
530 $xs->element('title', null, $this->nickname);
531 $xs->element('summary', null, common_xml_safe_str($this->description));
533 $xs->element('link', array('rel' => 'alternate',
534 'href' => $this->permalink()));
536 $xs->element('id', null, $this->permalink());
538 $xs->element('published', null, common_date_w3dtf($this->created));
539 $xs->element('updated', null, common_date_w3dtf($this->modified));
543 array('type' => 'html'),
544 common_xml_safe_str($this->description)
547 $xs->elementEnd('entry');
549 return $xs->getString();
552 function asAtomAuthor()
554 $xs = new XMLStringer(true);
556 $xs->elementStart('author');
557 $xs->element('name', null, $this->nickname);
558 $xs->element('uri', null, $this->permalink());
559 $xs->elementEnd('author');
561 return $xs->getString();
565 * Returns an XML string fragment with group information as an
566 * Activity Streams noun object with the given element type.
568 * Assumes that 'activity', 'georss', and 'poco' namespace has been
569 * previously defined.
571 * @param string $element one of 'actor', 'subject', 'object', 'target'
575 function asActivityNoun($element)
577 $noun = ActivityObject::fromGroup($this);
578 return $noun->asString('activity:' . $element);
583 return empty($this->homepage_logo)
584 ? User_group::defaultLogo(AVATAR_PROFILE_SIZE)
585 : $this->homepage_logo;
588 static function register($fields) {
589 if (!empty($fields['userid'])) {
590 $profile = Profile::getKV('id', $fields['userid']);
591 if ($profile && !$profile->hasRight(Right::CREATEGROUP)) {
592 common_log(LOG_WARNING, "Attempted group creation from banned user: " . $profile->nickname);
594 // TRANS: Client exception thrown when a user tries to create a group while banned.
595 throw new ClientException(_('You are not allowed to create groups on this site.'), 403);
599 $fields['nickname'] = Nickname::normalize($fields['nickname']);
601 // MAGICALLY put fields into current scope
602 // @fixme kill extract(); it makes debugging absurdly hard
604 $defaults = array('nickname' => null,
607 'description' => null,
611 'aliases' => array(),
614 $fields = array_merge($defaults, $fields);
618 $group = new User_group();
624 if (empty($mainpage)) {
625 $mainpage = common_local_url('showgroup', array('nickname' => $nickname));
628 // We must create a new, incrementally assigned profile_id
629 $profile = new Profile();
630 $profile->nickname = $nickname;
631 $profile->fullname = $fullname;
632 $profile->profileurl = $mainpage;
633 $profile->homepage = $homepage;
634 $profile->bio = $description;
635 $profile->location = $location;
636 $profile->created = common_sql_now();
638 $group->nickname = $profile->nickname;
639 $group->fullname = $profile->fullname;
640 $group->homepage = $profile->homepage;
641 $group->description = $profile->bio;
642 $group->location = $profile->location;
643 $group->mainpage = $profile->profileurl;
644 $group->created = $profile->created;
646 $profile->query('BEGIN');
647 $id = $profile->insert();
649 $profile->query('ROLLBACK');
650 throw new ServerException(_('Profile insertion failed'));
653 $group->profile_id = $id;
656 if (isset($fields['join_policy'])) {
657 $group->join_policy = intval($fields['join_policy']);
659 $group->join_policy = 0;
662 if (isset($fields['force_scope'])) {
663 $group->force_scope = intval($fields['force_scope']);
665 $group->force_scope = 0;
668 if (Event::handle('StartGroupSave', array(&$group))) {
670 $result = $group->insert();
672 if ($result === false) {
673 common_log_db_error($group, 'INSERT', __FILE__);
674 // TRANS: Server exception thrown when creating a group failed.
675 throw new ServerException(_('Could not create group.'));
678 if (!isset($uri) || empty($uri)) {
679 $orig = clone($group);
680 $group->uri = common_local_url('groupbyid', array('id' => $group->id));
681 $result = $group->update($orig);
683 common_log_db_error($group, 'UPDATE', __FILE__);
684 // TRANS: Server exception thrown when updating a group URI failed.
685 throw new ServerException(_('Could not set group URI.'));
689 $result = $group->setAliases($aliases);
692 // TRANS: Server exception thrown when creating group aliases failed.
693 throw new ServerException(_('Could not create aliases.'));
696 $member = new Group_member();
698 $member->group_id = $group->id;
699 $member->profile_id = $userid;
700 $member->is_admin = 1;
701 $member->created = $group->created;
703 $result = $member->insert();
706 common_log_db_error($member, 'INSERT', __FILE__);
707 // TRANS: Server exception thrown when setting group membership failed.
708 throw new ServerException(_('Could not set group membership.'));
711 self::blow('profile:groups:%d', $userid);
714 $local_group = new Local_group();
716 $local_group->group_id = $group->id;
717 $local_group->nickname = $nickname;
718 $local_group->created = common_sql_now();
720 $result = $local_group->insert();
723 common_log_db_error($local_group, 'INSERT', __FILE__);
724 // TRANS: Server exception thrown when saving local group information failed.
725 throw new ServerException(_('Could not save local group info.'));
729 Event::handle('EndGroupSave', array($group));
732 $profile->query('COMMIT');
738 * Handle cascading deletion, on the model of notice and profile.
740 * This should handle freeing up cached entries for the group's
741 * id, nickname, URI, and aliases. There may be other areas that
742 * are not de-cached in the UI, including the sidebar lists on
745 function delete($useWhere=false)
747 if (empty($this->id)) {
748 common_log(LOG_WARNING, "Ambiguous User_group->delete(); skipping related tables.");
749 return parent::delete($useWhere);
753 $profile = $this->getProfile();
755 } catch (GroupNoProfileException $unp) {
756 common_log(LOG_INFO, "Group {$this->nickname} has no profile; continuing deletion.");
759 // Safe to delete in bulk for now
761 $related = array('Group_inbox',
766 Event::handle('UserGroupDeleteRelated', array($this, &$related));
768 foreach ($related as $cls) {
770 $inst->group_id = $this->id;
773 while ($inst->fetch()) {
780 // And related groups in the other direction...
781 $inst = new Related_group();
782 $inst->related_group_id = $this->id;
785 // Aliases and the local_group entry need to be cleared explicitly
786 // or we'll miss clearing some cache keys; that can make it hard
787 // to create a new group with one of those names or aliases.
788 $this->setAliases(array());
790 // $this->isLocal() but we're using the resulting object
791 $local = Local_group::getKV('group_id', $this->id);
792 if ($local instanceof Local_group) {
796 // blow the cached ids
797 self::blow('user_group:notice_ids:%d', $this->id);
799 return parent::delete($useWhere);
802 public function update($dataObject=false)
804 // Whenever the User_group is updated, find the Local_group
805 // and update its nickname too.
806 if ($this->nickname != $dataObject->nickname) {
807 $local = Local_group::getKV('group_id', $this->id);
808 if ($local instanceof Local_group) {
809 common_debug("Updating Local_group ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
810 $local->setNickname($this->nickname);
814 // Also make sure the Profile table is up to date!
815 $fields = array(/*group field => profile field*/
816 'nickname' => 'nickname',
817 'fullname' => 'fullname',
818 'mainpage' => 'profileurl',
819 'homepage' => 'homepage',
820 'description' => 'bio',
821 'location' => 'location',
822 'created' => 'created',
823 'modified' => 'modified',
825 $profile = $this->getProfile();
826 $origpro = clone($profile);
827 foreach ($fields as $gf=>$pf) {
828 $profile->$pf = $this->$gf;
830 if ($profile->update($origpro) === false) {
831 throw new ServerException(_('Unable to update profile'));
834 return parent::update($dataObject);
839 return ($this->join_policy == self::JOIN_POLICY_MODERATE &&
840 intval($this->force_scope) === 1);
843 public function isLocal()
845 $local = Local_group::getKV('group_id', $this->id);
846 return ($local instanceof Local_group);
849 static function groupsFromText($text, Profile $profile)
853 /* extract all !group */
854 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
862 foreach (array_unique($match[1]) as $nickname) {
863 $group = self::getForNickname($nickname, $profile);
864 if ($group instanceof User_group && $profile->isMember($group)) {
865 $groups[] = clone($group);
872 static function idsFromText($text, Profile $profile)
875 $groups = self::groupsFromText($text, $profile);
876 foreach ($groups as $group) {
877 $ids[$group->id] = true;
879 return array_keys($ids);