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);
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 $imagefile = new ImageFile($this->id, Avatar::path($filename));
330 $orig = clone($this);
331 $this->original_logo = Avatar::url($filename);
332 $this->homepage_logo = Avatar::url($imagefile->resize(AVATAR_PROFILE_SIZE));
333 $this->stream_logo = Avatar::url($imagefile->resize(AVATAR_STREAM_SIZE));
334 $this->mini_logo = Avatar::url($imagefile->resize(AVATAR_MINI_SIZE));
335 common_debug(common_log_objstring($this));
336 return $this->update($orig);
339 function getBestName()
341 return ($this->fullname) ? $this->fullname : $this->nickname;
345 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
346 * if no fullname is provided.
350 function getFancyName()
352 if ($this->fullname) {
353 // TRANS: Full name of a profile or group followed by nickname in parens
354 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
356 return $this->nickname;
360 function getAliases()
366 $alias = new Group_alias();
368 $alias->group_id = $this->id;
370 if ($alias->find()) {
371 while ($alias->fetch()) {
372 $aliases[] = $alias->alias;
381 function setAliases($newaliases) {
383 $newaliases = array_unique($newaliases);
385 $oldaliases = $this->getAliases();
387 // Delete stuff that's old that not in new
389 $to_delete = array_diff($oldaliases, $newaliases);
391 // Insert stuff that's in new and not in old
393 $to_insert = array_diff($newaliases, $oldaliases);
395 $alias = new Group_alias();
397 $alias->group_id = $this->id;
399 foreach ($to_delete as $delalias) {
400 $alias->alias = $delalias;
401 $result = $alias->delete();
403 common_log_db_error($alias, 'DELETE', __FILE__);
408 foreach ($to_insert as $insalias) {
409 if ($insalias === $this->nickname) {
412 $alias->alias = Nickname::normalize($insalias, true);
413 $result = $alias->insert();
415 common_log_db_error($alias, 'INSERT', __FILE__);
423 static function getForNickname($nickname, Profile $profile=null)
425 $nickname = Nickname::normalize($nickname);
427 // Are there any matching remote groups this profile's in?
428 if ($profile instanceof Profile) {
429 $group = $profile->getGroups(0, null);
430 while ($group instanceof User_group && $group->fetch()) {
431 if ($group->nickname == $nickname) {
432 // @fixme is this the best way?
433 return clone($group);
438 // If not, check local groups.
439 $group = Local_group::getKV('nickname', $nickname);
440 if ($group instanceof Local_group) {
441 return User_group::getKV('id', $group->group_id);
443 $alias = Group_alias::getKV('alias', $nickname);
444 if ($alias instanceof Group_alias) {
445 return User_group::getKV('id', $alias->group_id);
450 function getUserMembers()
455 if(common_config('db','quote_identifiers'))
456 $user_table = '"user"';
457 else $user_table = 'user';
461 'FROM '. $user_table .' JOIN group_member '.
462 'ON '. $user_table .'.id = group_member.profile_id ' .
463 'WHERE group_member.group_id = %d ';
465 $user->query(sprintf($qry, $this->id));
469 while ($user->fetch()) {
478 static function maxDescription()
480 $desclimit = common_config('group', 'desclimit');
481 // null => use global limit (distinct from 0!)
482 if (is_null($desclimit)) {
483 $desclimit = common_config('site', 'textlimit');
488 static function descriptionTooLong($desc)
490 $desclimit = self::maxDescription();
491 return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
494 function asAtomEntry($namespace=false, $source=false)
496 $xs = new XMLStringer(true);
499 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
500 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
505 $xs->elementStart('entry', $attrs);
508 $xs->elementStart('source');
509 $xs->element('id', null, $this->permalink());
510 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
511 $xs->element('link', array('href' => $this->permalink()));
512 $xs->element('updated', null, $this->modified);
513 $xs->elementEnd('source');
516 $xs->element('title', null, $this->nickname);
517 $xs->element('summary', null, common_xml_safe_str($this->description));
519 $xs->element('link', array('rel' => 'alternate',
520 'href' => $this->permalink()));
522 $xs->element('id', null, $this->permalink());
524 $xs->element('published', null, common_date_w3dtf($this->created));
525 $xs->element('updated', null, common_date_w3dtf($this->modified));
529 array('type' => 'html'),
530 common_xml_safe_str($this->description)
533 $xs->elementEnd('entry');
535 return $xs->getString();
538 function asAtomAuthor()
540 $xs = new XMLStringer(true);
542 $xs->elementStart('author');
543 $xs->element('name', null, $this->nickname);
544 $xs->element('uri', null, $this->permalink());
545 $xs->elementEnd('author');
547 return $xs->getString();
551 * Returns an XML string fragment with group information as an
552 * Activity Streams noun object with the given element type.
554 * Assumes that 'activity', 'georss', and 'poco' namespace has been
555 * previously defined.
557 * @param string $element one of 'actor', 'subject', 'object', 'target'
561 function asActivityNoun($element)
563 $noun = ActivityObject::fromGroup($this);
564 return $noun->asString('activity:' . $element);
569 return empty($this->homepage_logo)
570 ? User_group::defaultLogo(AVATAR_PROFILE_SIZE)
571 : $this->homepage_logo;
574 static function register($fields) {
575 if (!empty($fields['userid'])) {
576 $profile = Profile::getKV('id', $fields['userid']);
577 if ($profile && !$profile->hasRight(Right::CREATEGROUP)) {
578 common_log(LOG_WARNING, "Attempted group creation from banned user: " . $profile->nickname);
580 // TRANS: Client exception thrown when a user tries to create a group while banned.
581 throw new ClientException(_('You are not allowed to create groups on this site.'), 403);
585 $fields['nickname'] = Nickname::normalize($fields['nickname']);
587 // MAGICALLY put fields into current scope
588 // @fixme kill extract(); it makes debugging absurdly hard
590 $defaults = array('nickname' => null,
593 'description' => null,
597 'aliases' => array(),
600 $fields = array_merge($defaults, $fields);
604 $group = new User_group();
610 if (empty($mainpage)) {
611 $mainpage = common_local_url('showgroup', array('nickname' => $nickname));
614 // We must create a new, incrementally assigned profile_id
615 $profile = new Profile();
616 $profile->nickname = $nickname;
617 $profile->fullname = $fullname;
618 $profile->profileurl = $mainpage;
619 $profile->homepage = $homepage;
620 $profile->bio = $description;
621 $profile->location = $location;
622 $profile->created = common_sql_now();
624 $group->nickname = $profile->nickname;
625 $group->fullname = $profile->fullname;
626 $group->homepage = $profile->homepage;
627 $group->description = $profile->bio;
628 $group->location = $profile->location;
629 $group->mainpage = $profile->profileurl;
630 $group->created = $profile->created;
632 $profile->query('BEGIN');
633 $id = $profile->insert();
635 $profile->query('ROLLBACK');
636 throw new ServerException(_('Profile insertion failed'));
639 $group->profile_id = $id;
642 if (isset($fields['join_policy'])) {
643 $group->join_policy = intval($fields['join_policy']);
645 $group->join_policy = 0;
648 if (isset($fields['force_scope'])) {
649 $group->force_scope = intval($fields['force_scope']);
651 $group->force_scope = 0;
654 if (Event::handle('StartGroupSave', array(&$group))) {
656 $result = $group->insert();
658 if ($result === false) {
659 common_log_db_error($group, 'INSERT', __FILE__);
660 // TRANS: Server exception thrown when creating a group failed.
661 throw new ServerException(_('Could not create group.'));
664 if (!isset($uri) || empty($uri)) {
665 $orig = clone($group);
666 $group->uri = common_local_url('groupbyid', array('id' => $group->id));
667 $result = $group->update($orig);
669 common_log_db_error($group, 'UPDATE', __FILE__);
670 // TRANS: Server exception thrown when updating a group URI failed.
671 throw new ServerException(_('Could not set group URI.'));
675 $result = $group->setAliases($aliases);
678 // TRANS: Server exception thrown when creating group aliases failed.
679 throw new ServerException(_('Could not create aliases.'));
682 $member = new Group_member();
684 $member->group_id = $group->id;
685 $member->profile_id = $userid;
686 $member->is_admin = 1;
687 $member->created = $group->created;
689 $result = $member->insert();
692 common_log_db_error($member, 'INSERT', __FILE__);
693 // TRANS: Server exception thrown when setting group membership failed.
694 throw new ServerException(_('Could not set group membership.'));
697 self::blow('profile:groups:%d', $userid);
700 $local_group = new Local_group();
702 $local_group->group_id = $group->id;
703 $local_group->nickname = $nickname;
704 $local_group->created = common_sql_now();
706 $result = $local_group->insert();
709 common_log_db_error($local_group, 'INSERT', __FILE__);
710 // TRANS: Server exception thrown when saving local group information failed.
711 throw new ServerException(_('Could not save local group info.'));
715 Event::handle('EndGroupSave', array($group));
718 $profile->query('COMMIT');
724 * Handle cascading deletion, on the model of notice and profile.
726 * This should handle freeing up cached entries for the group's
727 * id, nickname, URI, and aliases. There may be other areas that
728 * are not de-cached in the UI, including the sidebar lists on
731 function delete($useWhere=false)
733 if (empty($this->id)) {
734 common_log(LOG_WARNING, "Ambiguous User_group->delete(); skipping related tables.");
735 return parent::delete($useWhere);
739 $profile = $this->getProfile();
741 } catch (GroupNoProfileException $unp) {
742 common_log(LOG_INFO, "Group {$this->nickname} has no profile; continuing deletion.");
745 // Safe to delete in bulk for now
747 $related = array('Group_inbox',
752 Event::handle('UserGroupDeleteRelated', array($this, &$related));
754 foreach ($related as $cls) {
756 $inst->group_id = $this->id;
759 while ($inst->fetch()) {
766 // And related groups in the other direction...
767 $inst = new Related_group();
768 $inst->related_group_id = $this->id;
771 // Aliases and the local_group entry need to be cleared explicitly
772 // or we'll miss clearing some cache keys; that can make it hard
773 // to create a new group with one of those names or aliases.
774 $this->setAliases(array());
776 // $this->isLocal() but we're using the resulting object
777 $local = Local_group::getKV('group_id', $this->id);
778 if ($local instanceof Local_group) {
782 // blow the cached ids
783 self::blow('user_group:notice_ids:%d', $this->id);
785 return parent::delete($useWhere);
788 public function update($dataObject=false)
790 // Whenever the User_group is updated, find the Local_group
791 // and update its nickname too.
792 if ($this->nickname != $dataObject->nickname) {
793 $local = Local_group::getKV('group_id', $this->id);
794 if ($local instanceof Local_group) {
795 common_debug("Updating Local_group ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
796 $local->setNickname($this->nickname);
800 // Also make sure the Profile table is up to date!
801 $fields = array(/*group field => profile field*/
802 'nickname' => 'nickname',
803 'fullname' => 'fullname',
804 'mainpage' => 'profileurl',
805 'homepage' => 'homepage',
806 'description' => 'bio',
807 'location' => 'location',
808 'created' => 'created',
809 'modified' => 'modified',
811 $profile = $this->getProfile();
812 $origpro = clone($profile);
813 foreach ($fields as $gf=>$pf) {
814 $profile->$pf = $this->$gf;
816 if ($profile->update($origpro) === false) {
817 throw new ServerException(_('Unable to update profile'));
820 return parent::update($dataObject);
825 return ($this->join_policy == self::JOIN_POLICY_MODERATE &&
826 $this->force_scope == 1);
829 public function isLocal()
831 $local = Local_group::getKV('group_id', $this->id);
832 return ($local instanceof Local_group);
835 static function groupsFromText($text, Profile $profile)
839 /* extract all !group */
840 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
848 foreach (array_unique($match[1]) as $nickname) {
849 $group = self::getForNickname($nickname, $profile);
850 if ($group instanceof User_group && $profile->isMember($group)) {
851 $groups[] = clone($group);
858 static function idsFromText($text, Profile $profile)
861 $groups = self::groupsFromText($text, $profile);
862 foreach ($groups as $group) {
863 $ids[$group->id] = true;
865 return array_keys($ids);