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 static function schemaDef()
40 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
41 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'foreign key to profile table'),
43 'nickname' => array('type' => 'varchar', 'length' => 64, 'description' => 'nickname for addressing'),
44 'fullname' => array('type' => 'varchar', 'length' => 191, 'description' => 'display name'),
45 'homepage' => array('type' => 'varchar', 'length' => 191, 'description' => 'URL, cached so we dont regenerate'),
46 'description' => array('type' => 'text', 'description' => 'group description'),
47 'location' => array('type' => 'varchar', 'length' => 191, 'description' => 'related physical location, if any'),
49 'original_logo' => array('type' => 'varchar', 'length' => 191, 'description' => 'original size logo'),
50 'homepage_logo' => array('type' => 'varchar', 'length' => 191, 'description' => 'homepage (profile) size logo'),
51 'stream_logo' => array('type' => 'varchar', 'length' => 191, 'description' => 'stream-sized logo'),
52 'mini_logo' => array('type' => 'varchar', 'length' => 191, 'description' => 'mini logo'),
54 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
55 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
57 'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universal identifier'),
58 'mainpage' => array('type' => 'varchar', 'length' => 191, 'description' => 'page for group info to link to'),
59 'join_policy' => array('type' => 'int', 'size' => 'tiny', 'description' => '0=open; 1=requires admin approval'),
60 'force_scope' => array('type' => 'int', 'size' => 'tiny', 'description' => '0=never,1=sometimes,-1=always'),
62 'primary key' => array('id'),
63 'unique keys' => array(
64 'user_group_uri_key' => array('uri'),
65 // when it's safe and everyone's run upgrade.php 'user_profile_id_key' => array('profile_id'),
67 'foreign keys' => array(
68 'user_group_id_fkey' => array('profile', array('profile_id' => 'id')),
71 'user_group_nickname_idx' => array('nickname'),
72 'user_group_profile_id_idx' => array('profile_id'), //make this unique in future
77 protected $_profile = array();
82 * @throws GroupNoProfileException if user has no profile
84 public function getProfile()
86 if (!isset($this->_profile[$this->profile_id])) {
87 $profile = Profile::getKV('id', $this->profile_id);
89 if (!$profile instanceof Profile) {
91 $profile = new Profile();
92 $profile->nickname = $this->nickname;
93 $profile->fullname = $this->fullname;
94 $profile->profileurl = $this->mainpage;
95 $profile->homepage = $this->homepage;
96 $profile->bio = $this->description;
97 $profile->location = $this->location;
98 $profile->created = common_sql_now();
99 $this->profile_id = $profile->insert();
101 //throw new GroupNoProfileException($this);
104 $this->_profile[$this->profile_id] = $profile;
106 return $this->_profile[$this->profile_id];
109 public function getNickname()
111 return $this->getProfile()->getNickname();
114 public static function defaultLogo($size)
116 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
117 AVATAR_STREAM_SIZE => 'stream',
118 AVATAR_MINI_SIZE => 'mini');
119 return Theme::path('default-avatar-'.$sizenames[$size].'.png');
125 if (Event::handle('StartUserGroupHomeUrl', array($this, &$url))) {
126 // normally stored in mainpage, but older ones may be null
127 if (!empty($this->mainpage)) {
128 $url = $this->mainpage;
129 } elseif ($this->isLocal()) {
130 $url = common_local_url('showgroup',
131 array('nickname' => $this->nickname));
134 Event::handle('EndUserGroupHomeUrl', array($this, &$url));
141 if (Event::handle('StartUserGroupGetUri', array($this, &$uri))) {
142 if (!empty($this->uri)) {
144 } elseif ($this->isLocal()) {
145 $uri = common_local_url('groupbyid',
146 array('id' => $this->id));
149 Event::handle('EndUserGroupGetUri', array($this, &$uri));
156 if (Event::handle('StartUserGroupPermalink', array($this, &$url))) {
157 if ($this->isLocal()) {
158 $url = common_local_url('groupbyid',
159 array('id' => $this->id));
162 Event::handle('EndUserGroupPermalink', array($this, &$url));
166 function getNotices($offset, $limit, $since_id=null, $max_id=null)
168 $stream = new GroupNoticeStream($this);
170 return $stream->getNotices($offset, $limit, $since_id, $max_id);
173 function getMembers($offset=0, $limit=null) {
175 if (is_null($limit) || $offset + $limit > User_group::CACHE_WINDOW) {
176 $ids = $this->getMemberIDs($offset,
179 $key = sprintf('group:member_ids:%d', $this->id);
180 $window = self::cacheGet($key);
181 if ($window === false) {
182 $window = $this->getMemberIDs(0,
183 User_group::CACHE_WINDOW);
184 self::cacheSet($key, $window);
187 $ids = array_slice($window,
192 return Profile::multiGet('id', $ids);
195 function getMemberIDs($offset=0, $limit=null)
197 $gm = new Group_member();
200 $gm->selectAdd('profile_id');
202 $gm->group_id = $this->id;
204 $gm->orderBy('created DESC');
206 if (!is_null($limit)) {
207 $gm->limit($offset, $limit);
213 while ($gm->fetch()) {
214 $ids[] = $gm->profile_id;
222 * Get pending members, who have not yet been approved.
228 function getRequests($offset=0, $limit=null)
231 'SELECT profile.* ' .
232 'FROM profile JOIN group_join_queue '.
233 'ON profile.id = group_join_queue.profile_id ' .
234 'WHERE group_join_queue.group_id = %d ' .
235 'ORDER BY group_join_queue.created DESC ';
237 if ($limit != null) {
238 if (common_config('db','type') == 'pgsql') {
239 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
241 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
245 $members = new Profile();
247 $members->query(sprintf($qry, $this->id));
251 public function getAdminCount()
253 $block = new Group_member();
254 $block->group_id = $this->id;
255 $block->is_admin = 1;
257 return $block->count();
260 public function getMemberCount()
262 $key = sprintf("group:member_count:%d", $this->id);
264 $cnt = self::cacheGet($key);
266 if (is_integer($cnt)) {
270 $mem = new Group_member();
271 $mem->group_id = $this->id;
273 // XXX: why 'distinct'?
275 $cnt = (int) $mem->count('distinct profile_id');
277 self::cacheSet($key, $cnt);
282 function getBlockedCount()
284 // XXX: WORM cache this
286 $block = new Group_block();
287 $block->group_id = $this->id;
289 return $block->count();
292 function getQueueCount()
294 // XXX: WORM cache this
296 $queue = new Group_join_queue();
297 $queue->group_id = $this->id;
299 return $queue->count();
302 function getAdmins($offset=null, $limit=null) // offset is null because DataObject wants it, 0 would mean no results
304 $admins = new Profile();
305 $admins->joinAdd(array('id', 'group_member:profile_id'));
306 $admins->whereAdd(sprintf('group_member.group_id = %u AND group_member.is_admin = 1', $this->id));
307 $admins->orderBy('group_member.modified ASC');
308 $admins->limit($offset, $limit);
314 function getBlocked($offset=null, $limit=null) // offset is null because DataObject wants it, 0 would mean no results
316 $blocked = new Profile();
317 $blocked->joinAdd(array('id', 'group_block:blocked'));
318 $blocked->whereAdd(sprintf('group_block.group_id = %u', $this->id));
319 $blocked->orderBy('group_block.modified DESC');
320 $blocked->limit($offset, $limit);
326 function setOriginal($filename)
328 // This should be handled by the Profile->setOriginal function so user and group avatars are handled the same
329 $imagefile = new ImageFile(null, Avatar::path($filename));
331 $sizes = array('homepage_logo' => AVATAR_PROFILE_SIZE,
332 'stream_logo' => AVATAR_STREAM_SIZE,
333 'mini_logo' => AVATAR_MINI_SIZE);
335 $orig = clone($this);
336 $this->original_logo = Avatar::url($filename);
337 foreach ($sizes as $name=>$size) {
338 $filename = Avatar::filename($this->profile_id, image_type_to_extension($imagefile->preferredType()),
339 $size, common_timestamp());
340 $imagefile->resizeTo(Avatar::path($filename), array('width'=>$size, 'height'=>$size));
341 $this->$name = Avatar::url($filename);
343 common_debug(common_log_objstring($this));
344 return $this->update($orig);
347 function getBestName()
349 return ($this->fullname) ? $this->fullname : $this->nickname;
353 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
354 * if no fullname is provided.
358 function getFancyName()
360 if ($this->fullname) {
361 // TRANS: Full name of a profile or group followed by nickname in parens
362 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
364 return $this->nickname;
368 function getAliases()
374 $alias = new Group_alias();
376 $alias->group_id = $this->id;
378 if ($alias->find()) {
379 while ($alias->fetch()) {
380 $aliases[] = $alias->alias;
389 function setAliases($newaliases) {
391 $newaliases = array_unique($newaliases);
393 $oldaliases = $this->getAliases();
395 // Delete stuff that's old that not in new
397 $to_delete = array_diff($oldaliases, $newaliases);
399 // Insert stuff that's in new and not in old
401 $to_insert = array_diff($newaliases, $oldaliases);
403 $alias = new Group_alias();
405 $alias->group_id = $this->id;
407 foreach ($to_delete as $delalias) {
408 $alias->alias = $delalias;
409 $result = $alias->delete();
411 common_log_db_error($alias, 'DELETE', __FILE__);
416 foreach ($to_insert as $insalias) {
417 if ($insalias === $this->nickname) {
420 $alias->alias = Nickname::normalize($insalias, true);
421 $result = $alias->insert();
423 common_log_db_error($alias, 'INSERT', __FILE__);
431 static function getForNickname($nickname, Profile $profile=null)
433 $nickname = Nickname::normalize($nickname);
435 // Are there any matching remote groups this profile's in?
436 if ($profile instanceof Profile) {
437 $group = $profile->getGroups(0, null);
438 while ($group instanceof User_group && $group->fetch()) {
439 if ($group->nickname == $nickname) {
440 // @fixme is this the best way?
441 return clone($group);
446 // If not, check local groups.
447 $group = Local_group::getKV('nickname', $nickname);
448 if ($group instanceof Local_group) {
449 return User_group::getKV('id', $group->group_id);
451 $alias = Group_alias::getKV('alias', $nickname);
452 if ($alias instanceof Group_alias) {
453 return User_group::getKV('id', $alias->group_id);
458 function getUserMembers()
463 if(common_config('db','quote_identifiers'))
464 $user_table = '"user"';
465 else $user_table = 'user';
469 'FROM '. $user_table .' JOIN group_member '.
470 'ON '. $user_table .'.id = group_member.profile_id ' .
471 'WHERE group_member.group_id = %d ';
473 $user->query(sprintf($qry, $this->id));
477 while ($user->fetch()) {
486 static function maxDescription()
488 $desclimit = common_config('group', 'desclimit');
489 // null => use global limit (distinct from 0!)
490 if (is_null($desclimit)) {
491 $desclimit = common_config('site', 'textlimit');
496 static function descriptionTooLong($desc)
498 $desclimit = self::maxDescription();
499 return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
502 function asAtomEntry($namespace=false, $source=false)
504 $xs = new XMLStringer(true);
507 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
508 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
513 $xs->elementStart('entry', $attrs);
516 $xs->elementStart('source');
517 $xs->element('id', null, $this->permalink());
518 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
519 $xs->element('link', array('href' => $this->permalink()));
520 $xs->element('updated', null, $this->modified);
521 $xs->elementEnd('source');
524 $xs->element('title', null, $this->nickname);
525 $xs->element('summary', null, common_xml_safe_str($this->description));
527 $xs->element('link', array('rel' => 'alternate',
528 'href' => $this->permalink()));
530 $xs->element('id', null, $this->permalink());
532 $xs->element('published', null, common_date_w3dtf($this->created));
533 $xs->element('updated', null, common_date_w3dtf($this->modified));
537 array('type' => 'html'),
538 common_xml_safe_str($this->description)
541 $xs->elementEnd('entry');
543 return $xs->getString();
546 function asAtomAuthor()
548 $xs = new XMLStringer(true);
550 $xs->elementStart('author');
551 $xs->element('name', null, $this->nickname);
552 $xs->element('uri', null, $this->permalink());
553 $xs->elementEnd('author');
555 return $xs->getString();
559 * Returns an XML string fragment with group information as an
560 * Activity Streams noun object with the given element type.
562 * Assumes that 'activity', 'georss', and 'poco' namespace has been
563 * previously defined.
565 * @param string $element one of 'actor', 'subject', 'object', 'target'
569 function asActivityNoun($element)
571 $noun = ActivityObject::fromGroup($this);
572 return $noun->asString('activity:' . $element);
577 return empty($this->homepage_logo)
578 ? User_group::defaultLogo(AVATAR_PROFILE_SIZE)
579 : $this->homepage_logo;
582 static function register($fields) {
583 if (!empty($fields['userid'])) {
584 $profile = Profile::getKV('id', $fields['userid']);
585 if ($profile && !$profile->hasRight(Right::CREATEGROUP)) {
586 common_log(LOG_WARNING, "Attempted group creation from banned user: " . $profile->nickname);
588 // TRANS: Client exception thrown when a user tries to create a group while banned.
589 throw new ClientException(_('You are not allowed to create groups on this site.'), 403);
593 $fields['nickname'] = Nickname::normalize($fields['nickname']);
595 // MAGICALLY put fields into current scope
596 // @fixme kill extract(); it makes debugging absurdly hard
598 $defaults = array('nickname' => null,
601 'description' => null,
605 'aliases' => array(),
608 $fields = array_merge($defaults, $fields);
612 $group = new User_group();
618 if (empty($mainpage)) {
619 $mainpage = common_local_url('showgroup', array('nickname' => $nickname));
622 // We must create a new, incrementally assigned profile_id
623 $profile = new Profile();
624 $profile->nickname = $nickname;
625 $profile->fullname = $fullname;
626 $profile->profileurl = $mainpage;
627 $profile->homepage = $homepage;
628 $profile->bio = $description;
629 $profile->location = $location;
630 $profile->created = common_sql_now();
632 $group->nickname = $profile->nickname;
633 $group->fullname = $profile->fullname;
634 $group->homepage = $profile->homepage;
635 $group->description = $profile->bio;
636 $group->location = $profile->location;
637 $group->mainpage = $profile->profileurl;
638 $group->created = $profile->created;
640 $profile->query('BEGIN');
641 $id = $profile->insert();
643 $profile->query('ROLLBACK');
644 throw new ServerException(_('Profile insertion failed'));
647 $group->profile_id = $id;
650 if (isset($fields['join_policy'])) {
651 $group->join_policy = intval($fields['join_policy']);
653 $group->join_policy = 0;
656 if (isset($fields['force_scope'])) {
657 $group->force_scope = intval($fields['force_scope']);
659 $group->force_scope = 0;
662 if (Event::handle('StartGroupSave', array(&$group))) {
664 $result = $group->insert();
666 if ($result === false) {
667 common_log_db_error($group, 'INSERT', __FILE__);
668 // TRANS: Server exception thrown when creating a group failed.
669 throw new ServerException(_('Could not create group.'));
672 if (!isset($uri) || empty($uri)) {
673 $orig = clone($group);
674 $group->uri = common_local_url('groupbyid', array('id' => $group->id));
675 $result = $group->update($orig);
677 common_log_db_error($group, 'UPDATE', __FILE__);
678 // TRANS: Server exception thrown when updating a group URI failed.
679 throw new ServerException(_('Could not set group URI.'));
683 $result = $group->setAliases($aliases);
686 // TRANS: Server exception thrown when creating group aliases failed.
687 throw new ServerException(_('Could not create aliases.'));
690 $member = new Group_member();
692 $member->group_id = $group->id;
693 $member->profile_id = $userid;
694 $member->is_admin = 1;
695 $member->created = $group->created;
697 $result = $member->insert();
700 common_log_db_error($member, 'INSERT', __FILE__);
701 // TRANS: Server exception thrown when setting group membership failed.
702 throw new ServerException(_('Could not set group membership.'));
705 self::blow('profile:groups:%d', $userid);
708 $local_group = new Local_group();
710 $local_group->group_id = $group->id;
711 $local_group->nickname = $nickname;
712 $local_group->created = common_sql_now();
714 $result = $local_group->insert();
717 common_log_db_error($local_group, 'INSERT', __FILE__);
718 // TRANS: Server exception thrown when saving local group information failed.
719 throw new ServerException(_('Could not save local group info.'));
723 Event::handle('EndGroupSave', array($group));
726 $profile->query('COMMIT');
732 * Handle cascading deletion, on the model of notice and profile.
734 * This should handle freeing up cached entries for the group's
735 * id, nickname, URI, and aliases. There may be other areas that
736 * are not de-cached in the UI, including the sidebar lists on
739 function delete($useWhere=false)
741 if (empty($this->id)) {
742 common_log(LOG_WARNING, "Ambiguous User_group->delete(); skipping related tables.");
743 return parent::delete($useWhere);
747 $profile = $this->getProfile();
749 } catch (GroupNoProfileException $unp) {
750 common_log(LOG_INFO, "Group {$this->nickname} has no profile; continuing deletion.");
753 // Safe to delete in bulk for now
755 $related = array('Group_inbox',
760 Event::handle('UserGroupDeleteRelated', array($this, &$related));
762 foreach ($related as $cls) {
764 $inst->group_id = $this->id;
767 while ($inst->fetch()) {
774 // And related groups in the other direction...
775 $inst = new Related_group();
776 $inst->related_group_id = $this->id;
779 // Aliases and the local_group entry need to be cleared explicitly
780 // or we'll miss clearing some cache keys; that can make it hard
781 // to create a new group with one of those names or aliases.
782 $this->setAliases(array());
784 // $this->isLocal() but we're using the resulting object
785 $local = Local_group::getKV('group_id', $this->id);
786 if ($local instanceof Local_group) {
790 // blow the cached ids
791 self::blow('user_group:notice_ids:%d', $this->id);
793 return parent::delete($useWhere);
796 public function update($dataObject=false)
798 // Whenever the User_group is updated, find the Local_group
799 // and update its nickname too.
800 if ($this->nickname != $dataObject->nickname) {
801 $local = Local_group::getKV('group_id', $this->id);
802 if ($local instanceof Local_group) {
803 common_debug("Updating Local_group ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
804 $local->setNickname($this->nickname);
808 // Also make sure the Profile table is up to date!
809 $fields = array(/*group field => profile field*/
810 'nickname' => 'nickname',
811 'fullname' => 'fullname',
812 'mainpage' => 'profileurl',
813 'homepage' => 'homepage',
814 'description' => 'bio',
815 'location' => 'location',
816 'created' => 'created',
817 'modified' => 'modified',
819 $profile = $this->getProfile();
820 $origpro = clone($profile);
821 foreach ($fields as $gf=>$pf) {
822 $profile->$pf = $this->$gf;
824 if ($profile->update($origpro) === false) {
825 throw new ServerException(_('Unable to update profile'));
828 return parent::update($dataObject);
833 return ($this->join_policy == self::JOIN_POLICY_MODERATE &&
834 $this->force_scope == 1);
837 public function isLocal()
839 $local = Local_group::getKV('group_id', $this->id);
840 return ($local instanceof Local_group);
843 static function groupsFromText($text, Profile $profile)
847 /* extract all !group */
848 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
856 foreach (array_unique($match[1]) as $nickname) {
857 $group = self::getForNickname($nickname, $profile);
858 if ($group instanceof User_group && $profile->isMember($group)) {
859 $groups[] = clone($group);
866 static function idsFromText($text, Profile $profile)
869 $groups = self::groupsFromText($text, $profile);
870 foreach ($groups as $group) {
871 $ids[$group->id] = true;
873 return array_keys($ids);