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(255)
19 public $homepage; // varchar(255)
20 public $description; // text
21 public $location; // varchar(255)
22 public $original_logo; // varchar(255)
23 public $homepage_logo; // varchar(255)
24 public $stream_logo; // varchar(255)
25 public $mini_logo; // varchar(255)
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(255) unique_key
29 public $mainpage; // varchar(255)
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' => 255, 'description' => 'display name'),
45 'homepage' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL, cached so we dont regenerate'),
46 'description' => array('type' => 'text', 'description' => 'group description'),
47 'location' => array('type' => 'varchar', 'length' => 255, 'description' => 'related physical location, if any'),
49 'original_logo' => array('type' => 'varchar', 'length' => 255, 'description' => 'original size logo'),
50 'homepage_logo' => array('type' => 'varchar', 'length' => 255, 'description' => 'homepage (profile) size logo'),
51 'stream_logo' => array('type' => 'varchar', 'length' => 255, 'description' => 'stream-sized logo'),
52 'mini_logo' => array('type' => 'varchar', 'length' => 255, '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' => 255, 'description' => 'universal identifier'),
58 'mainpage' => array('type' => 'varchar', 'length' => 255, '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);
88 if (!$profile instanceof Profile) {
89 throw new GroupNoProfileException($this);
91 $this->_profile[$this->profile_id] = $profile;
93 return $this->_profile[$this->profile_id];
96 public function getNickname()
98 return $this->getProfile()->getNickname();
101 public static function defaultLogo($size)
103 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
104 AVATAR_STREAM_SIZE => 'stream',
105 AVATAR_MINI_SIZE => 'mini');
106 return Theme::path('default-avatar-'.$sizenames[$size].'.png');
112 if (Event::handle('StartUserGroupHomeUrl', array($this, &$url))) {
113 // normally stored in mainpage, but older ones may be null
114 if (!empty($this->mainpage)) {
115 $url = $this->mainpage;
116 } elseif ($this->isLocal()) {
117 $url = common_local_url('showgroup',
118 array('nickname' => $this->nickname));
121 Event::handle('EndUserGroupHomeUrl', array($this, &$url));
128 if (Event::handle('StartUserGroupGetUri', array($this, &$uri))) {
129 if (!empty($this->uri)) {
131 } elseif ($this->isLocal()) {
132 $uri = common_local_url('groupbyid',
133 array('id' => $this->id));
136 Event::handle('EndUserGroupGetUri', array($this, &$uri));
143 if (Event::handle('StartUserGroupPermalink', array($this, &$url))) {
144 if ($this->isLocal()) {
145 $url = common_local_url('groupbyid',
146 array('id' => $this->id));
149 Event::handle('EndUserGroupPermalink', array($this, &$url));
153 function getNotices($offset, $limit, $since_id=null, $max_id=null)
155 $stream = new GroupNoticeStream($this);
157 return $stream->getNotices($offset, $limit, $since_id, $max_id);
160 function getMembers($offset=0, $limit=null) {
162 if (is_null($limit) || $offset + $limit > User_group::CACHE_WINDOW) {
163 $ids = $this->getMemberIDs($offset,
166 $key = sprintf('group:member_ids:%d', $this->id);
167 $window = self::cacheGet($key);
168 if ($window === false) {
169 $window = $this->getMemberIDs(0,
170 User_group::CACHE_WINDOW);
171 self::cacheSet($key, $window);
174 $ids = array_slice($window,
179 return Profile::multiGet('id', $ids);
182 function getMemberIDs($offset=0, $limit=null)
184 $gm = new Group_member();
187 $gm->selectAdd('profile_id');
189 $gm->group_id = $this->id;
191 $gm->orderBy('created DESC');
193 if (!is_null($limit)) {
194 $gm->limit($offset, $limit);
200 while ($gm->fetch()) {
201 $ids[] = $gm->profile_id;
209 * Get pending members, who have not yet been approved.
215 function getRequests($offset=0, $limit=null)
218 'SELECT profile.* ' .
219 'FROM profile JOIN group_join_queue '.
220 'ON profile.id = group_join_queue.profile_id ' .
221 'WHERE group_join_queue.group_id = %d ' .
222 'ORDER BY group_join_queue.created DESC ';
224 if ($limit != null) {
225 if (common_config('db','type') == 'pgsql') {
226 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
228 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
232 $members = new Profile();
234 $members->query(sprintf($qry, $this->id));
238 public function getAdminCount()
240 $block = new Group_member();
241 $block->group_id = $this->id;
242 $block->is_admin = 1;
244 return $block->count();
247 public function getMemberCount()
249 $key = sprintf("group:member_count:%d", $this->id);
251 $cnt = self::cacheGet($key);
253 if (is_integer($cnt)) {
257 $mem = new Group_member();
258 $mem->group_id = $this->id;
260 // XXX: why 'distinct'?
262 $cnt = (int) $mem->count('distinct profile_id');
264 self::cacheSet($key, $cnt);
269 function getBlockedCount()
271 // XXX: WORM cache this
273 $block = new Group_block();
274 $block->group_id = $this->id;
276 return $block->count();
279 function getQueueCount()
281 // XXX: WORM cache this
283 $queue = new Group_join_queue();
284 $queue->group_id = $this->id;
286 return $queue->count();
289 function getAdmins($offset=null, $limit=null) // offset is null because DataObject wants it, 0 would mean no results
291 $admins = new Profile();
292 $admins->joinAdd(array('id', 'group_member:profile_id'));
293 $admins->whereAdd(sprintf('group_member.group_id = %u AND group_member.is_admin = 1', $this->id));
294 $admins->orderBy('group_member.modified ASC');
295 $admins->limit($offset, $limit);
301 function getBlocked($offset=null, $limit=null) // offset is null because DataObject wants it, 0 would mean no results
303 $blocked = new Profile();
304 $blocked->joinAdd(array('id', 'group_block:blocked'));
305 $blocked->whereAdd(sprintf('group_block.group_id = %u', $this->id));
306 $blocked->orderBy('group_block.modified DESC');
307 $blocked->limit($offset, $limit);
313 function setOriginal($filename)
315 $imagefile = new ImageFile($this->id, Avatar::path($filename));
317 $orig = clone($this);
318 $this->original_logo = Avatar::url($filename);
319 $this->homepage_logo = Avatar::url($imagefile->resize(AVATAR_PROFILE_SIZE));
320 $this->stream_logo = Avatar::url($imagefile->resize(AVATAR_STREAM_SIZE));
321 $this->mini_logo = Avatar::url($imagefile->resize(AVATAR_MINI_SIZE));
322 common_debug(common_log_objstring($this));
323 return $this->update($orig);
326 function getBestName()
328 return ($this->fullname) ? $this->fullname : $this->nickname;
332 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
333 * if no fullname is provided.
337 function getFancyName()
339 if ($this->fullname) {
340 // TRANS: Full name of a profile or group followed by nickname in parens
341 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
343 return $this->nickname;
347 function getAliases()
353 $alias = new Group_alias();
355 $alias->group_id = $this->id;
357 if ($alias->find()) {
358 while ($alias->fetch()) {
359 $aliases[] = $alias->alias;
368 function setAliases($newaliases) {
370 $newaliases = array_unique($newaliases);
372 $oldaliases = $this->getAliases();
374 // Delete stuff that's old that not in new
376 $to_delete = array_diff($oldaliases, $newaliases);
378 // Insert stuff that's in new and not in old
380 $to_insert = array_diff($newaliases, $oldaliases);
382 $alias = new Group_alias();
384 $alias->group_id = $this->id;
386 foreach ($to_delete as $delalias) {
387 $alias->alias = $delalias;
388 $result = $alias->delete();
390 common_log_db_error($alias, 'DELETE', __FILE__);
395 foreach ($to_insert as $insalias) {
396 if ($insalias === $this->nickname) {
399 $alias->alias = Nickname::normalize($insalias, true);
400 $result = $alias->insert();
402 common_log_db_error($alias, 'INSERT', __FILE__);
410 static function getForNickname($nickname, Profile $profile=null)
412 $nickname = Nickname::normalize($nickname);
414 // Are there any matching remote groups this profile's in?
415 if ($profile instanceof Profile) {
416 $group = $profile->getGroups(0, null);
417 while ($group instanceof User_group && $group->fetch()) {
418 if ($group->nickname == $nickname) {
419 // @fixme is this the best way?
420 return clone($group);
425 // If not, check local groups.
426 $group = Local_group::getKV('nickname', $nickname);
427 if ($group instanceof Local_group) {
428 return User_group::getKV('id', $group->group_id);
430 $alias = Group_alias::getKV('alias', $nickname);
431 if ($alias instanceof Group_alias) {
432 return User_group::getKV('id', $alias->group_id);
437 function getUserMembers()
442 if(common_config('db','quote_identifiers'))
443 $user_table = '"user"';
444 else $user_table = 'user';
448 'FROM '. $user_table .' JOIN group_member '.
449 'ON '. $user_table .'.id = group_member.profile_id ' .
450 'WHERE group_member.group_id = %d ';
452 $user->query(sprintf($qry, $this->id));
456 while ($user->fetch()) {
465 static function maxDescription()
467 $desclimit = common_config('group', 'desclimit');
468 // null => use global limit (distinct from 0!)
469 if (is_null($desclimit)) {
470 $desclimit = common_config('site', 'textlimit');
475 static function descriptionTooLong($desc)
477 $desclimit = self::maxDescription();
478 return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
481 function asAtomEntry($namespace=false, $source=false)
483 $xs = new XMLStringer(true);
486 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
487 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
492 $xs->elementStart('entry', $attrs);
495 $xs->elementStart('source');
496 $xs->element('id', null, $this->permalink());
497 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
498 $xs->element('link', array('href' => $this->permalink()));
499 $xs->element('updated', null, $this->modified);
500 $xs->elementEnd('source');
503 $xs->element('title', null, $this->nickname);
504 $xs->element('summary', null, common_xml_safe_str($this->description));
506 $xs->element('link', array('rel' => 'alternate',
507 'href' => $this->permalink()));
509 $xs->element('id', null, $this->permalink());
511 $xs->element('published', null, common_date_w3dtf($this->created));
512 $xs->element('updated', null, common_date_w3dtf($this->modified));
516 array('type' => 'html'),
517 common_xml_safe_str($this->description)
520 $xs->elementEnd('entry');
522 return $xs->getString();
525 function asAtomAuthor()
527 $xs = new XMLStringer(true);
529 $xs->elementStart('author');
530 $xs->element('name', null, $this->nickname);
531 $xs->element('uri', null, $this->permalink());
532 $xs->elementEnd('author');
534 return $xs->getString();
538 * Returns an XML string fragment with group information as an
539 * Activity Streams noun object with the given element type.
541 * Assumes that 'activity', 'georss', and 'poco' namespace has been
542 * previously defined.
544 * @param string $element one of 'actor', 'subject', 'object', 'target'
548 function asActivityNoun($element)
550 $noun = ActivityObject::fromGroup($this);
551 return $noun->asString('activity:' . $element);
556 return empty($this->homepage_logo)
557 ? User_group::defaultLogo(AVATAR_PROFILE_SIZE)
558 : $this->homepage_logo;
561 static function register($fields) {
562 if (!empty($fields['userid'])) {
563 $profile = Profile::getKV('id', $fields['userid']);
564 if ($profile && !$profile->hasRight(Right::CREATEGROUP)) {
565 common_log(LOG_WARNING, "Attempted group creation from banned user: " . $profile->nickname);
567 // TRANS: Client exception thrown when a user tries to create a group while banned.
568 throw new ClientException(_('You are not allowed to create groups on this site.'), 403);
572 $fields['nickname'] = Nickname::normalize($fields['nickname']);
574 // MAGICALLY put fields into current scope
575 // @fixme kill extract(); it makes debugging absurdly hard
577 $defaults = array('nickname' => null,
580 'description' => null,
584 'aliases' => array(),
587 $fields = array_merge($defaults, $fields);
591 $group = new User_group();
597 if (empty($mainpage)) {
598 $mainpage = common_local_url('showgroup', array('nickname' => $nickname));
601 // We must create a new, incrementally assigned profile_id
602 $profile = new Profile();
603 $profile->nickname = $nickname;
604 $profile->fullname = $fullname;
605 $profile->profileurl = $mainpage;
606 $profile->homepage = $homepage;
607 $profile->bio = $description;
608 $profile->location = $location;
609 $profile->created = common_sql_now();
611 $group->nickname = $profile->nickname;
612 $group->fullname = $profile->fullname;
613 $group->homepage = $profile->homepage;
614 $group->description = $profile->bio;
615 $group->location = $profile->location;
616 $group->mainpage = $profile->profileurl;
617 $group->created = $profile->created;
619 $profile->query('BEGIN');
620 $id = $profile->insert();
622 $profile->query('ROLLBACK');
623 throw new ServerException(_('Profile insertion failed'));
626 $group->profile_id = $id;
629 if (isset($fields['join_policy'])) {
630 $group->join_policy = intval($fields['join_policy']);
632 $group->join_policy = 0;
635 if (isset($fields['force_scope'])) {
636 $group->force_scope = intval($fields['force_scope']);
638 $group->force_scope = 0;
641 if (Event::handle('StartGroupSave', array(&$group))) {
643 $result = $group->insert();
645 if ($result === false) {
646 common_log_db_error($group, 'INSERT', __FILE__);
647 // TRANS: Server exception thrown when creating a group failed.
648 throw new ServerException(_('Could not create group.'));
651 if (!isset($uri) || empty($uri)) {
652 $orig = clone($group);
653 $group->uri = common_local_url('groupbyid', array('id' => $group->id));
654 $result = $group->update($orig);
656 common_log_db_error($group, 'UPDATE', __FILE__);
657 // TRANS: Server exception thrown when updating a group URI failed.
658 throw new ServerException(_('Could not set group URI.'));
662 $result = $group->setAliases($aliases);
665 // TRANS: Server exception thrown when creating group aliases failed.
666 throw new ServerException(_('Could not create aliases.'));
669 $member = new Group_member();
671 $member->group_id = $group->id;
672 $member->profile_id = $userid;
673 $member->is_admin = 1;
674 $member->created = $group->created;
676 $result = $member->insert();
679 common_log_db_error($member, 'INSERT', __FILE__);
680 // TRANS: Server exception thrown when setting group membership failed.
681 throw new ServerException(_('Could not set group membership.'));
684 self::blow('profile:groups:%d', $userid);
687 $local_group = new Local_group();
689 $local_group->group_id = $group->id;
690 $local_group->nickname = $nickname;
691 $local_group->created = common_sql_now();
693 $result = $local_group->insert();
696 common_log_db_error($local_group, 'INSERT', __FILE__);
697 // TRANS: Server exception thrown when saving local group information failed.
698 throw new ServerException(_('Could not save local group info.'));
702 Event::handle('EndGroupSave', array($group));
705 $profile->query('COMMIT');
711 * Handle cascading deletion, on the model of notice and profile.
713 * This should handle freeing up cached entries for the group's
714 * id, nickname, URI, and aliases. There may be other areas that
715 * are not de-cached in the UI, including the sidebar lists on
718 function delete($useWhere=false)
720 if (empty($this->id)) {
721 common_log(LOG_WARNING, "Ambiguous User_group->delete(); skipping related tables.");
722 return parent::delete($useWhere);
726 $profile = $this->getProfile();
728 } catch (GroupNoProfileException $unp) {
729 common_log(LOG_INFO, "Group {$this->nickname} has no profile; continuing deletion.");
732 // Safe to delete in bulk for now
734 $related = array('Group_inbox',
739 Event::handle('UserGroupDeleteRelated', array($this, &$related));
741 foreach ($related as $cls) {
743 $inst->group_id = $this->id;
746 while ($inst->fetch()) {
753 // And related groups in the other direction...
754 $inst = new Related_group();
755 $inst->related_group_id = $this->id;
758 // Aliases and the local_group entry need to be cleared explicitly
759 // or we'll miss clearing some cache keys; that can make it hard
760 // to create a new group with one of those names or aliases.
761 $this->setAliases(array());
763 // $this->isLocal() but we're using the resulting object
764 $local = Local_group::getKV('group_id', $this->id);
765 if ($local instanceof Local_group) {
769 // blow the cached ids
770 self::blow('user_group:notice_ids:%d', $this->id);
772 return parent::delete($useWhere);
775 public function update($dataObject=false)
777 // Whenever the User_group is updated, find the Local_group
778 // and update its nickname too.
779 if ($this->nickname != $dataObject->nickname) {
780 $local = Local_group::getKV('group_id', $this->id);
781 if ($local instanceof Local_group) {
782 common_debug("Updating Local_group ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
783 $local->setNickname($this->nickname);
787 // Also make sure the Profile table is up to date!
788 $fields = array(/*group field => profile field*/
789 'nickname' => 'nickname',
790 'fullname' => 'fullname',
791 'mainpage' => 'profileurl',
792 'homepage' => 'homepage',
793 'description' => 'bio',
794 'location' => 'location',
795 'created' => 'created',
796 'modified' => 'modified',
798 $profile = $this->getProfile();
799 $origpro = clone($profile);
800 foreach ($fields as $gf=>$pf) {
801 $profile->$pf = $this->$gf;
803 if ($profile->update($origpro) === false) {
804 throw new ServerException(_('Unable to update profile'));
807 return parent::update($dataObject);
812 return ($this->join_policy == self::JOIN_POLICY_MODERATE &&
813 $this->force_scope == 1);
816 public function isLocal()
818 $local = Local_group::getKV('group_id', $this->id);
819 return ($local instanceof Local_group);
822 static function groupsFromText($text, Profile $profile)
826 /* extract all !group */
827 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
835 foreach (array_unique($match[1]) as $nickname) {
836 $group = self::getForNickname($nickname, $profile);
837 if ($group instanceof User_group && $profile->isMember($group)) {
838 $groups[] = clone($group);
845 static function idsFromText($text, Profile $profile)
848 $groups = self::groupsFromText($text, $profile);
849 foreach ($groups as $group) {
850 $ids[$group->id] = true;
852 return array_keys($ids);