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 = null;
82 * @throws UserNoProfileException if user has no profile
84 public function getProfile()
86 if (!($this->_profile instanceof Profile)) {
87 $this->_profile = Profile::getKV('id', $this->profile_id);
88 if (!($this->_profile instanceof Profile)) {
89 throw new GroupNoProfileException($this);
93 return $this->_profile;
96 public static function defaultLogo($size)
98 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
99 AVATAR_STREAM_SIZE => 'stream',
100 AVATAR_MINI_SIZE => 'mini');
101 return Theme::path('default-avatar-'.$sizenames[$size].'.png');
107 if (Event::handle('StartUserGroupHomeUrl', array($this, &$url))) {
108 // normally stored in mainpage, but older ones may be null
109 if (!empty($this->mainpage)) {
110 $url = $this->mainpage;
112 $url = common_local_url('showgroup',
113 array('nickname' => $this->nickname));
116 Event::handle('EndUserGroupHomeUrl', array($this, &$url));
123 if (Event::handle('StartUserGroupGetUri', array($this, &$uri))) {
124 if (!empty($this->uri)) {
127 $uri = common_local_url('groupbyid',
128 array('id' => $this->id));
131 Event::handle('EndUserGroupGetUri', array($this, &$uri));
138 if (Event::handle('StartUserGroupPermalink', array($this, &$url))) {
139 $url = common_local_url('groupbyid',
140 array('id' => $this->id));
142 Event::handle('EndUserGroupPermalink', array($this, &$url));
146 function getNotices($offset, $limit, $since_id=null, $max_id=null)
148 $stream = new GroupNoticeStream($this);
150 return $stream->getNotices($offset, $limit, $since_id, $max_id);
153 function getMembers($offset=0, $limit=null) {
155 if (is_null($limit) || $offset + $limit > User_group::CACHE_WINDOW) {
156 $ids = $this->getMemberIDs($offset,
159 $key = sprintf('group:member_ids:%d', $this->id);
160 $window = self::cacheGet($key);
161 if ($window === false) {
162 $window = $this->getMemberIDs(0,
163 User_group::CACHE_WINDOW);
164 self::cacheSet($key, $window);
167 $ids = array_slice($window,
172 return Profile::multiGet('id', $ids);
175 function getMemberIDs($offset=0, $limit=null)
177 $gm = new Group_member();
180 $gm->selectAdd('profile_id');
182 $gm->group_id = $this->id;
184 $gm->orderBy('created DESC');
186 if (!is_null($limit)) {
187 $gm->limit($offset, $limit);
193 while ($gm->fetch()) {
194 $ids[] = $gm->profile_id;
202 * Get pending members, who have not yet been approved.
208 function getRequests($offset=0, $limit=null)
211 'SELECT profile.* ' .
212 'FROM profile JOIN group_join_queue '.
213 'ON profile.id = group_join_queue.profile_id ' .
214 'WHERE group_join_queue.group_id = %d ' .
215 'ORDER BY group_join_queue.created DESC ';
217 if ($limit != null) {
218 if (common_config('db','type') == 'pgsql') {
219 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
221 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
225 $members = new Profile();
227 $members->query(sprintf($qry, $this->id));
231 public function getAdminCount()
233 return $this->getAdmins()->N;
236 public function getMemberCount()
238 $key = sprintf("group:member_count:%d", $this->id);
240 $cnt = self::cacheGet($key);
242 if (is_integer($cnt)) {
246 $mem = new Group_member();
247 $mem->group_id = $this->id;
249 // XXX: why 'distinct'?
251 $cnt = (int) $mem->count('distinct profile_id');
253 self::cacheSet($key, $cnt);
258 function getBlockedCount()
260 // XXX: WORM cache this
262 $block = new Group_block();
263 $block->group_id = $this->id;
265 return $block->count();
268 function getQueueCount()
270 // XXX: WORM cache this
272 $queue = new Group_join_queue();
273 $queue->group_id = $this->id;
275 return $queue->count();
278 function getAdmins($offset=0, $limit=null)
281 'SELECT profile.* ' .
282 'FROM profile JOIN group_member '.
283 'ON profile.id = group_member.profile_id ' .
284 'WHERE group_member.group_id = %d ' .
285 'AND group_member.is_admin = 1 ' .
286 'ORDER BY group_member.modified ASC ';
288 if ($limit != null) {
289 if (common_config('db','type') == 'pgsql') {
290 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
292 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
296 $admins = new Profile();
298 $admins->query(sprintf($qry, $this->id));
302 function getBlocked($offset=0, $limit=null)
305 'SELECT profile.* ' .
306 'FROM profile JOIN group_block '.
307 'ON profile.id = group_block.blocked ' .
308 'WHERE group_block.group_id = %d ' .
309 'ORDER BY group_block.modified DESC ';
311 if ($limit != null) {
312 if (common_config('db','type') == 'pgsql') {
313 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
315 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
319 $blocked = new Profile();
321 $blocked->query(sprintf($qry, $this->id));
325 function setOriginal($filename)
327 $imagefile = new ImageFile($this->id, Avatar::path($filename));
329 $orig = clone($this);
330 $this->original_logo = Avatar::url($filename);
331 $this->homepage_logo = Avatar::url($imagefile->resize(AVATAR_PROFILE_SIZE));
332 $this->stream_logo = Avatar::url($imagefile->resize(AVATAR_STREAM_SIZE));
333 $this->mini_logo = Avatar::url($imagefile->resize(AVATAR_MINI_SIZE));
334 common_debug(common_log_objstring($this));
335 return $this->update($orig);
338 function getBestName()
340 return ($this->fullname) ? $this->fullname : $this->nickname;
344 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
345 * if no fullname is provided.
349 function getFancyName()
351 if ($this->fullname) {
352 // TRANS: Full name of a profile or group followed by nickname in parens
353 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
355 return $this->nickname;
359 function getAliases()
365 $alias = new Group_alias();
367 $alias->group_id = $this->id;
369 if ($alias->find()) {
370 while ($alias->fetch()) {
371 $aliases[] = $alias->alias;
380 function setAliases($newaliases) {
382 $newaliases = array_unique($newaliases);
384 $oldaliases = $this->getAliases();
386 // Delete stuff that's old that not in new
388 $to_delete = array_diff($oldaliases, $newaliases);
390 // Insert stuff that's in new and not in old
392 $to_insert = array_diff($newaliases, $oldaliases);
394 $alias = new Group_alias();
396 $alias->group_id = $this->id;
398 foreach ($to_delete as $delalias) {
399 $alias->alias = $delalias;
400 $result = $alias->delete();
402 common_log_db_error($alias, 'DELETE', __FILE__);
407 foreach ($to_insert as $insalias) {
408 if ($insalias === $this->nickname) {
411 $alias->alias = Nickname::normalize($insalias, true);
412 $result = $alias->insert();
414 common_log_db_error($alias, 'INSERT', __FILE__);
422 static function getForNickname($nickname, Profile $profile=null)
424 $nickname = Nickname::normalize($nickname);
426 // Are there any matching remote groups this profile's in?
427 if ($profile instanceof Profile) {
428 $group = $profile->getGroups(0, null);
429 while ($group instanceof User_group && $group->fetch()) {
430 if ($group->nickname == $nickname) {
431 // @fixme is this the best way?
432 return clone($group);
437 // If not, check local groups.
438 $group = Local_group::getKV('nickname', $nickname);
439 if ($group instanceof Local_group) {
440 return User_group::getKV('id', $group->group_id);
442 $alias = Group_alias::getKV('alias', $nickname);
443 if ($alias instanceof Group_alias) {
444 return User_group::getKV('id', $alias->group_id);
449 function getUserMembers()
454 if(common_config('db','quote_identifiers'))
455 $user_table = '"user"';
456 else $user_table = 'user';
460 'FROM '. $user_table .' JOIN group_member '.
461 'ON '. $user_table .'.id = group_member.profile_id ' .
462 'WHERE group_member.group_id = %d ';
464 $user->query(sprintf($qry, $this->id));
468 while ($user->fetch()) {
477 static function maxDescription()
479 $desclimit = common_config('group', 'desclimit');
480 // null => use global limit (distinct from 0!)
481 if (is_null($desclimit)) {
482 $desclimit = common_config('site', 'textlimit');
487 static function descriptionTooLong($desc)
489 $desclimit = self::maxDescription();
490 return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
493 function asAtomEntry($namespace=false, $source=false)
495 $xs = new XMLStringer(true);
498 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
499 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
504 $xs->elementStart('entry', $attrs);
507 $xs->elementStart('source');
508 $xs->element('id', null, $this->permalink());
509 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
510 $xs->element('link', array('href' => $this->permalink()));
511 $xs->element('updated', null, $this->modified);
512 $xs->elementEnd('source');
515 $xs->element('title', null, $this->nickname);
516 $xs->element('summary', null, common_xml_safe_str($this->description));
518 $xs->element('link', array('rel' => 'alternate',
519 'href' => $this->permalink()));
521 $xs->element('id', null, $this->permalink());
523 $xs->element('published', null, common_date_w3dtf($this->created));
524 $xs->element('updated', null, common_date_w3dtf($this->modified));
528 array('type' => 'html'),
529 common_xml_safe_str($this->description)
532 $xs->elementEnd('entry');
534 return $xs->getString();
537 function asAtomAuthor()
539 $xs = new XMLStringer(true);
541 $xs->elementStart('author');
542 $xs->element('name', null, $this->nickname);
543 $xs->element('uri', null, $this->permalink());
544 $xs->elementEnd('author');
546 return $xs->getString();
550 * Returns an XML string fragment with group information as an
551 * Activity Streams noun object with the given element type.
553 * Assumes that 'activity', 'georss', and 'poco' namespace has been
554 * previously defined.
556 * @param string $element one of 'actor', 'subject', 'object', 'target'
560 function asActivityNoun($element)
562 $noun = ActivityObject::fromGroup($this);
563 return $noun->asString('activity:' . $element);
568 return empty($this->homepage_logo)
569 ? User_group::defaultLogo(AVATAR_PROFILE_SIZE)
570 : $this->homepage_logo;
573 static function register($fields) {
574 if (!empty($fields['userid'])) {
575 $profile = Profile::getKV('id', $fields['userid']);
576 if ($profile && !$profile->hasRight(Right::CREATEGROUP)) {
577 common_log(LOG_WARNING, "Attempted group creation from banned user: " . $profile->nickname);
579 // TRANS: Client exception thrown when a user tries to create a group while banned.
580 throw new ClientException(_('You are not allowed to create groups on this site.'), 403);
584 $fields['nickname'] = Nickname::normalize($fields['nickname']);
586 // MAGICALLY put fields into current scope
587 // @fixme kill extract(); it makes debugging absurdly hard
589 $defaults = array('nickname' => null,
592 'description' => null,
596 'aliases' => array(),
599 $fields = array_merge($defaults, $fields);
603 $group = new User_group();
609 if (empty($mainpage)) {
610 $mainpage = common_local_url('showgroup', array('nickname' => $nickname));
613 // We must create a new, incrementally assigned profile_id
614 $profile = new Profile();
615 $profile->nickname = $nickname;
616 $profile->fullname = $fullname;
617 $profile->profileurl = $mainpage;
618 $profile->homepage = $homepage;
619 $profile->bio = $description;
620 $profile->location = $location;
621 $profile->created = common_sql_now();
623 $group->nickname = $profile->nickname;
624 $group->fullname = $profile->fullname;
625 $group->homepage = $profile->homepage;
626 $group->description = $profile->bio;
627 $group->location = $profile->location;
628 $group->mainpage = $profile->profileurl;
629 $group->created = $profile->created;
631 $profile->query('BEGIN');
632 $id = $profile->insert();
634 $profile->query('ROLLBACK');
635 throw new ServerException(_('Profile insertion failed'));
638 $group->profile_id = $id;
641 if (isset($fields['join_policy'])) {
642 $group->join_policy = intval($fields['join_policy']);
644 $group->join_policy = 0;
647 if (isset($fields['force_scope'])) {
648 $group->force_scope = intval($fields['force_scope']);
650 $group->force_scope = 0;
653 if (Event::handle('StartGroupSave', array(&$group))) {
655 $result = $group->insert();
657 if ($result === false) {
658 common_log_db_error($group, 'INSERT', __FILE__);
659 // TRANS: Server exception thrown when creating a group failed.
660 throw new ServerException(_('Could not create group.'));
663 if (!isset($uri) || empty($uri)) {
664 $orig = clone($group);
665 $group->uri = common_local_url('groupbyid', array('id' => $group->id));
666 $result = $group->update($orig);
668 common_log_db_error($group, 'UPDATE', __FILE__);
669 // TRANS: Server exception thrown when updating a group URI failed.
670 throw new ServerException(_('Could not set group URI.'));
674 $result = $group->setAliases($aliases);
677 // TRANS: Server exception thrown when creating group aliases failed.
678 throw new ServerException(_('Could not create aliases.'));
681 $member = new Group_member();
683 $member->group_id = $group->id;
684 $member->profile_id = $userid;
685 $member->is_admin = 1;
686 $member->created = $group->created;
688 $result = $member->insert();
691 common_log_db_error($member, 'INSERT', __FILE__);
692 // TRANS: Server exception thrown when setting group membership failed.
693 throw new ServerException(_('Could not set group membership.'));
696 self::blow('profile:groups:%d', $userid);
699 $local_group = new Local_group();
701 $local_group->group_id = $group->id;
702 $local_group->nickname = $nickname;
703 $local_group->created = common_sql_now();
705 $result = $local_group->insert();
708 common_log_db_error($local_group, 'INSERT', __FILE__);
709 // TRANS: Server exception thrown when saving local group information failed.
710 throw new ServerException(_('Could not save local group info.'));
714 Event::handle('EndGroupSave', array($group));
717 $profile->query('COMMIT');
723 * Handle cascading deletion, on the model of notice and profile.
725 * This should handle freeing up cached entries for the group's
726 * id, nickname, URI, and aliases. There may be other areas that
727 * are not de-cached in the UI, including the sidebar lists on
730 function delete($useWhere=false)
732 if (empty($this->id)) {
733 common_log(LOG_WARNING, "Ambiguous User_group->delete(); skipping related tables.");
734 return parent::delete($useWhere);
738 $profile = $this->getProfile();
740 } catch (GroupNoProfileException $unp) {
741 common_log(LOG_INFO, "Group {$this->nickname} has no profile; continuing deletion.");
744 // Safe to delete in bulk for now
746 $related = array('Group_inbox',
751 Event::handle('UserGroupDeleteRelated', array($this, &$related));
753 foreach ($related as $cls) {
755 $inst->group_id = $this->id;
758 while ($inst->fetch()) {
765 // And related groups in the other direction...
766 $inst = new Related_group();
767 $inst->related_group_id = $this->id;
770 // Aliases and the local_group entry need to be cleared explicitly
771 // or we'll miss clearing some cache keys; that can make it hard
772 // to create a new group with one of those names or aliases.
773 $this->setAliases(array());
774 $local = Local_group::getKV('group_id', $this->id);
775 if ($local instanceof Local_group) {
779 // blow the cached ids
780 self::blow('user_group:notice_ids:%d', $this->id);
782 return parent::delete($useWhere);
785 public function update($dataObject=false)
787 // Whenever the User_group is updated, find the Local_group
788 // and update its nickname too.
789 if ($this->nickname != $dataObject->nickname) {
790 $local = Local_group::getKV('group_id', $this->id);
791 if ($local instanceof Local_group) {
792 common_debug("Updating Local_group ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
793 $local->setNickname($this->nickname);
797 // Also make sure the Profile table is up to date!
798 $fields = array(/*group field => profile field*/
799 'nickname' => 'nickname',
800 'fullname' => 'fullname',
801 'mainpage' => 'profileurl',
802 'homepage' => 'homepage',
803 'description' => 'bio',
804 'location' => 'location',
805 'created' => 'created',
806 'modified' => 'modified',
808 $profile = $this->getProfile();
809 $origpro = clone($profile);
810 foreach ($fields as $gf=>$pf) {
811 $profile->$pf = $this->$gf;
813 if ($profile->update($origpro) === false) {
814 throw new ServerException(_('Unable to update profile'));
817 return parent::update($dataObject);
822 return ($this->join_policy == self::JOIN_POLICY_MODERATE &&
823 $this->force_scope == 1);
826 static function groupsFromText($text, Profile $profile)
830 /* extract all !group */
831 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
839 foreach (array_unique($match[1]) as $nickname) {
840 $group = self::getForNickname($nickname, $profile);
841 if ($group instanceof User_group && $profile->isMember($group)) {
842 $groups[] = clone($group);
849 static function idsFromText($text, Profile $profile)
852 $groups = self::groupsFromText($text, $profile);
853 foreach ($groups as $group) {
854 $ids[$group->id] = true;
856 return array_keys($ids);