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;
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)) {
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 $url = common_local_url('groupbyid',
145 array('id' => $this->id));
147 Event::handle('EndUserGroupPermalink', array($this, &$url));
151 function getNotices($offset, $limit, $since_id=null, $max_id=null)
153 $stream = new GroupNoticeStream($this);
155 return $stream->getNotices($offset, $limit, $since_id, $max_id);
158 function getMembers($offset=0, $limit=null) {
160 if (is_null($limit) || $offset + $limit > User_group::CACHE_WINDOW) {
161 $ids = $this->getMemberIDs($offset,
164 $key = sprintf('group:member_ids:%d', $this->id);
165 $window = self::cacheGet($key);
166 if ($window === false) {
167 $window = $this->getMemberIDs(0,
168 User_group::CACHE_WINDOW);
169 self::cacheSet($key, $window);
172 $ids = array_slice($window,
177 return Profile::multiGet('id', $ids);
180 function getMemberIDs($offset=0, $limit=null)
182 $gm = new Group_member();
185 $gm->selectAdd('profile_id');
187 $gm->group_id = $this->id;
189 $gm->orderBy('created DESC');
191 if (!is_null($limit)) {
192 $gm->limit($offset, $limit);
198 while ($gm->fetch()) {
199 $ids[] = $gm->profile_id;
207 * Get pending members, who have not yet been approved.
213 function getRequests($offset=0, $limit=null)
216 'SELECT profile.* ' .
217 'FROM profile JOIN group_join_queue '.
218 'ON profile.id = group_join_queue.profile_id ' .
219 'WHERE group_join_queue.group_id = %d ' .
220 'ORDER BY group_join_queue.created DESC ';
222 if ($limit != null) {
223 if (common_config('db','type') == 'pgsql') {
224 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
226 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
230 $members = new Profile();
232 $members->query(sprintf($qry, $this->id));
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 $imagefile = new ImageFile($this->id, Avatar::path($filename));
315 $orig = clone($this);
316 $this->original_logo = Avatar::url($filename);
317 $this->homepage_logo = Avatar::url($imagefile->resize(AVATAR_PROFILE_SIZE));
318 $this->stream_logo = Avatar::url($imagefile->resize(AVATAR_STREAM_SIZE));
319 $this->mini_logo = Avatar::url($imagefile->resize(AVATAR_MINI_SIZE));
320 common_debug(common_log_objstring($this));
321 return $this->update($orig);
324 function getBestName()
326 return ($this->fullname) ? $this->fullname : $this->nickname;
330 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
331 * if no fullname is provided.
335 function getFancyName()
337 if ($this->fullname) {
338 // TRANS: Full name of a profile or group followed by nickname in parens
339 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
341 return $this->nickname;
345 function getAliases()
351 $alias = new Group_alias();
353 $alias->group_id = $this->id;
355 if ($alias->find()) {
356 while ($alias->fetch()) {
357 $aliases[] = $alias->alias;
366 function setAliases($newaliases) {
368 $newaliases = array_unique($newaliases);
370 $oldaliases = $this->getAliases();
372 // Delete stuff that's old that not in new
374 $to_delete = array_diff($oldaliases, $newaliases);
376 // Insert stuff that's in new and not in old
378 $to_insert = array_diff($newaliases, $oldaliases);
380 $alias = new Group_alias();
382 $alias->group_id = $this->id;
384 foreach ($to_delete as $delalias) {
385 $alias->alias = $delalias;
386 $result = $alias->delete();
388 common_log_db_error($alias, 'DELETE', __FILE__);
393 foreach ($to_insert as $insalias) {
394 if ($insalias === $this->nickname) {
397 $alias->alias = Nickname::normalize($insalias, true);
398 $result = $alias->insert();
400 common_log_db_error($alias, 'INSERT', __FILE__);
408 static function getForNickname($nickname, Profile $profile=null)
410 $nickname = Nickname::normalize($nickname);
412 // Are there any matching remote groups this profile's in?
413 if ($profile instanceof Profile) {
414 $group = $profile->getGroups(0, null);
415 while ($group instanceof User_group && $group->fetch()) {
416 if ($group->nickname == $nickname) {
417 // @fixme is this the best way?
418 return clone($group);
423 // If not, check local groups.
424 $group = Local_group::getKV('nickname', $nickname);
425 if ($group instanceof Local_group) {
426 return User_group::getKV('id', $group->group_id);
428 $alias = Group_alias::getKV('alias', $nickname);
429 if ($alias instanceof Group_alias) {
430 return User_group::getKV('id', $alias->group_id);
435 function getUserMembers()
440 if(common_config('db','quote_identifiers'))
441 $user_table = '"user"';
442 else $user_table = 'user';
446 'FROM '. $user_table .' JOIN group_member '.
447 'ON '. $user_table .'.id = group_member.profile_id ' .
448 'WHERE group_member.group_id = %d ';
450 $user->query(sprintf($qry, $this->id));
454 while ($user->fetch()) {
463 static function maxDescription()
465 $desclimit = common_config('group', 'desclimit');
466 // null => use global limit (distinct from 0!)
467 if (is_null($desclimit)) {
468 $desclimit = common_config('site', 'textlimit');
473 static function descriptionTooLong($desc)
475 $desclimit = self::maxDescription();
476 return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
479 function asAtomEntry($namespace=false, $source=false)
481 $xs = new XMLStringer(true);
484 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
485 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
490 $xs->elementStart('entry', $attrs);
493 $xs->elementStart('source');
494 $xs->element('id', null, $this->permalink());
495 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
496 $xs->element('link', array('href' => $this->permalink()));
497 $xs->element('updated', null, $this->modified);
498 $xs->elementEnd('source');
501 $xs->element('title', null, $this->nickname);
502 $xs->element('summary', null, common_xml_safe_str($this->description));
504 $xs->element('link', array('rel' => 'alternate',
505 'href' => $this->permalink()));
507 $xs->element('id', null, $this->permalink());
509 $xs->element('published', null, common_date_w3dtf($this->created));
510 $xs->element('updated', null, common_date_w3dtf($this->modified));
514 array('type' => 'html'),
515 common_xml_safe_str($this->description)
518 $xs->elementEnd('entry');
520 return $xs->getString();
523 function asAtomAuthor()
525 $xs = new XMLStringer(true);
527 $xs->elementStart('author');
528 $xs->element('name', null, $this->nickname);
529 $xs->element('uri', null, $this->permalink());
530 $xs->elementEnd('author');
532 return $xs->getString();
536 * Returns an XML string fragment with group information as an
537 * Activity Streams noun object with the given element type.
539 * Assumes that 'activity', 'georss', and 'poco' namespace has been
540 * previously defined.
542 * @param string $element one of 'actor', 'subject', 'object', 'target'
546 function asActivityNoun($element)
548 $noun = ActivityObject::fromGroup($this);
549 return $noun->asString('activity:' . $element);
554 return empty($this->homepage_logo)
555 ? User_group::defaultLogo(AVATAR_PROFILE_SIZE)
556 : $this->homepage_logo;
559 static function register($fields) {
560 if (!empty($fields['userid'])) {
561 $profile = Profile::getKV('id', $fields['userid']);
562 if ($profile && !$profile->hasRight(Right::CREATEGROUP)) {
563 common_log(LOG_WARNING, "Attempted group creation from banned user: " . $profile->nickname);
565 // TRANS: Client exception thrown when a user tries to create a group while banned.
566 throw new ClientException(_('You are not allowed to create groups on this site.'), 403);
570 $fields['nickname'] = Nickname::normalize($fields['nickname']);
572 // MAGICALLY put fields into current scope
573 // @fixme kill extract(); it makes debugging absurdly hard
575 $defaults = array('nickname' => null,
578 'description' => null,
582 'aliases' => array(),
585 $fields = array_merge($defaults, $fields);
589 $group = new User_group();
595 if (empty($mainpage)) {
596 $mainpage = common_local_url('showgroup', array('nickname' => $nickname));
599 // We must create a new, incrementally assigned profile_id
600 $profile = new Profile();
601 $profile->nickname = $nickname;
602 $profile->fullname = $fullname;
603 $profile->profileurl = $mainpage;
604 $profile->homepage = $homepage;
605 $profile->bio = $description;
606 $profile->location = $location;
607 $profile->created = common_sql_now();
609 $group->nickname = $profile->nickname;
610 $group->fullname = $profile->fullname;
611 $group->homepage = $profile->homepage;
612 $group->description = $profile->bio;
613 $group->location = $profile->location;
614 $group->mainpage = $profile->profileurl;
615 $group->created = $profile->created;
617 $profile->query('BEGIN');
618 $id = $profile->insert();
620 $profile->query('ROLLBACK');
621 throw new ServerException(_('Profile insertion failed'));
624 $group->profile_id = $id;
627 if (isset($fields['join_policy'])) {
628 $group->join_policy = intval($fields['join_policy']);
630 $group->join_policy = 0;
633 if (isset($fields['force_scope'])) {
634 $group->force_scope = intval($fields['force_scope']);
636 $group->force_scope = 0;
639 if (Event::handle('StartGroupSave', array(&$group))) {
641 $result = $group->insert();
643 if ($result === false) {
644 common_log_db_error($group, 'INSERT', __FILE__);
645 // TRANS: Server exception thrown when creating a group failed.
646 throw new ServerException(_('Could not create group.'));
649 if (!isset($uri) || empty($uri)) {
650 $orig = clone($group);
651 $group->uri = common_local_url('groupbyid', array('id' => $group->id));
652 $result = $group->update($orig);
654 common_log_db_error($group, 'UPDATE', __FILE__);
655 // TRANS: Server exception thrown when updating a group URI failed.
656 throw new ServerException(_('Could not set group URI.'));
660 $result = $group->setAliases($aliases);
663 // TRANS: Server exception thrown when creating group aliases failed.
664 throw new ServerException(_('Could not create aliases.'));
667 $member = new Group_member();
669 $member->group_id = $group->id;
670 $member->profile_id = $userid;
671 $member->is_admin = 1;
672 $member->created = $group->created;
674 $result = $member->insert();
677 common_log_db_error($member, 'INSERT', __FILE__);
678 // TRANS: Server exception thrown when setting group membership failed.
679 throw new ServerException(_('Could not set group membership.'));
682 self::blow('profile:groups:%d', $userid);
685 $local_group = new Local_group();
687 $local_group->group_id = $group->id;
688 $local_group->nickname = $nickname;
689 $local_group->created = common_sql_now();
691 $result = $local_group->insert();
694 common_log_db_error($local_group, 'INSERT', __FILE__);
695 // TRANS: Server exception thrown when saving local group information failed.
696 throw new ServerException(_('Could not save local group info.'));
700 Event::handle('EndGroupSave', array($group));
703 $profile->query('COMMIT');
709 * Handle cascading deletion, on the model of notice and profile.
711 * This should handle freeing up cached entries for the group's
712 * id, nickname, URI, and aliases. There may be other areas that
713 * are not de-cached in the UI, including the sidebar lists on
716 function delete($useWhere=false)
718 if (empty($this->id)) {
719 common_log(LOG_WARNING, "Ambiguous User_group->delete(); skipping related tables.");
720 return parent::delete($useWhere);
724 $profile = $this->getProfile();
726 } catch (GroupNoProfileException $unp) {
727 common_log(LOG_INFO, "Group {$this->nickname} has no profile; continuing deletion.");
730 // Safe to delete in bulk for now
732 $related = array('Group_inbox',
737 Event::handle('UserGroupDeleteRelated', array($this, &$related));
739 foreach ($related as $cls) {
741 $inst->group_id = $this->id;
744 while ($inst->fetch()) {
751 // And related groups in the other direction...
752 $inst = new Related_group();
753 $inst->related_group_id = $this->id;
756 // Aliases and the local_group entry need to be cleared explicitly
757 // or we'll miss clearing some cache keys; that can make it hard
758 // to create a new group with one of those names or aliases.
759 $this->setAliases(array());
761 // $this->isLocal() but we're using the resulting object
762 $local = Local_group::getKV('group_id', $this->id);
763 if ($local instanceof Local_group) {
767 // blow the cached ids
768 self::blow('user_group:notice_ids:%d', $this->id);
770 return parent::delete($useWhere);
773 public function update($dataObject=false)
775 // Whenever the User_group is updated, find the Local_group
776 // and update its nickname too.
777 if ($this->nickname != $dataObject->nickname) {
778 $local = Local_group::getKV('group_id', $this->id);
779 if ($local instanceof Local_group) {
780 common_debug("Updating Local_group ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
781 $local->setNickname($this->nickname);
785 // Also make sure the Profile table is up to date!
786 $fields = array(/*group field => profile field*/
787 'nickname' => 'nickname',
788 'fullname' => 'fullname',
789 'mainpage' => 'profileurl',
790 'homepage' => 'homepage',
791 'description' => 'bio',
792 'location' => 'location',
793 'created' => 'created',
794 'modified' => 'modified',
796 $profile = $this->getProfile();
797 $origpro = clone($profile);
798 foreach ($fields as $gf=>$pf) {
799 $profile->$pf = $this->$gf;
801 if ($profile->update($origpro) === false) {
802 throw new ServerException(_('Unable to update profile'));
805 return parent::update($dataObject);
810 return ($this->join_policy == self::JOIN_POLICY_MODERATE &&
811 $this->force_scope == 1);
814 public function isLocal()
816 $local = Local_group::getKV('group_id', $this->id);
817 return ($local instanceof Local_group);
820 static function groupsFromText($text, Profile $profile)
824 /* extract all !group */
825 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
833 foreach (array_unique($match[1]) as $nickname) {
834 $group = self::getForNickname($nickname, $profile);
835 if ($group instanceof User_group && $profile->isMember($group)) {
836 $groups[] = clone($group);
843 static function idsFromText($text, Profile $profile)
846 $groups = self::groupsFromText($text, $profile);
847 foreach ($groups as $group) {
848 $ids[$group->id] = true;
850 return array_keys($ids);