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;
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)) {
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 $url = common_local_url('groupbyid',
158 array('id' => $this->id));
160 Event::handle('EndUserGroupPermalink', array($this, &$url));
164 function getNotices($offset, $limit, $since_id=null, $max_id=null)
166 $stream = new GroupNoticeStream($this);
168 return $stream->getNotices($offset, $limit, $since_id, $max_id);
171 function getMembers($offset=0, $limit=null) {
173 if (is_null($limit) || $offset + $limit > User_group::CACHE_WINDOW) {
174 $ids = $this->getMemberIDs($offset,
177 $key = sprintf('group:member_ids:%d', $this->id);
178 $window = self::cacheGet($key);
179 if ($window === false) {
180 $window = $this->getMemberIDs(0,
181 User_group::CACHE_WINDOW);
182 self::cacheSet($key, $window);
185 $ids = array_slice($window,
190 return Profile::multiGet('id', $ids);
193 function getMemberIDs($offset=0, $limit=null)
195 $gm = new Group_member();
198 $gm->selectAdd('profile_id');
200 $gm->group_id = $this->id;
202 $gm->orderBy('created DESC');
204 if (!is_null($limit)) {
205 $gm->limit($offset, $limit);
211 while ($gm->fetch()) {
212 $ids[] = $gm->profile_id;
220 * Get pending members, who have not yet been approved.
226 function getRequests($offset=0, $limit=null)
229 'SELECT profile.* ' .
230 'FROM profile JOIN group_join_queue '.
231 'ON profile.id = group_join_queue.profile_id ' .
232 'WHERE group_join_queue.group_id = %d ' .
233 'ORDER BY group_join_queue.created DESC ';
235 if ($limit != null) {
236 if (common_config('db','type') == 'pgsql') {
237 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
239 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
243 $members = new Profile();
245 $members->query(sprintf($qry, $this->id));
249 public function getAdminCount()
251 $block = new Group_member();
252 $block->group_id = $this->id;
253 $block->is_admin = 1;
255 return $block->count();
258 public function getMemberCount()
260 $key = sprintf("group:member_count:%d", $this->id);
262 $cnt = self::cacheGet($key);
264 if (is_integer($cnt)) {
268 $mem = new Group_member();
269 $mem->group_id = $this->id;
271 // XXX: why 'distinct'?
273 $cnt = (int) $mem->count('distinct profile_id');
275 self::cacheSet($key, $cnt);
280 function getBlockedCount()
282 // XXX: WORM cache this
284 $block = new Group_block();
285 $block->group_id = $this->id;
287 return $block->count();
290 function getQueueCount()
292 // XXX: WORM cache this
294 $queue = new Group_join_queue();
295 $queue->group_id = $this->id;
297 return $queue->count();
300 function getAdmins($offset=null, $limit=null) // offset is null because DataObject wants it, 0 would mean no results
302 $admins = new Profile();
303 $admins->joinAdd(array('id', 'group_member:profile_id'));
304 $admins->whereAdd(sprintf('group_member.group_id = %u AND group_member.is_admin = 1', $this->id));
305 $admins->orderBy('group_member.modified ASC');
306 $admins->limit($offset, $limit);
312 function getBlocked($offset=null, $limit=null) // offset is null because DataObject wants it, 0 would mean no results
314 $blocked = new Profile();
315 $blocked->joinAdd(array('id', 'group_block:blocked'));
316 $blocked->whereAdd(sprintf('group_block.group_id = %u', $this->id));
317 $blocked->orderBy('group_block.modified DESC');
318 $blocked->limit($offset, $limit);
324 function setOriginal($filename)
326 $imagefile = new ImageFile($this->id, Avatar::path($filename));
328 $orig = clone($this);
329 $this->original_logo = Avatar::url($filename);
330 $this->homepage_logo = Avatar::url($imagefile->resize(AVATAR_PROFILE_SIZE));
331 $this->stream_logo = Avatar::url($imagefile->resize(AVATAR_STREAM_SIZE));
332 $this->mini_logo = Avatar::url($imagefile->resize(AVATAR_MINI_SIZE));
333 common_debug(common_log_objstring($this));
334 return $this->update($orig);
337 function getBestName()
339 return ($this->fullname) ? $this->fullname : $this->nickname;
343 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
344 * if no fullname is provided.
348 function getFancyName()
350 if ($this->fullname) {
351 // TRANS: Full name of a profile or group followed by nickname in parens
352 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
354 return $this->nickname;
358 function getAliases()
364 $alias = new Group_alias();
366 $alias->group_id = $this->id;
368 if ($alias->find()) {
369 while ($alias->fetch()) {
370 $aliases[] = $alias->alias;
379 function setAliases($newaliases) {
381 $newaliases = array_unique($newaliases);
383 $oldaliases = $this->getAliases();
385 // Delete stuff that's old that not in new
387 $to_delete = array_diff($oldaliases, $newaliases);
389 // Insert stuff that's in new and not in old
391 $to_insert = array_diff($newaliases, $oldaliases);
393 $alias = new Group_alias();
395 $alias->group_id = $this->id;
397 foreach ($to_delete as $delalias) {
398 $alias->alias = $delalias;
399 $result = $alias->delete();
401 common_log_db_error($alias, 'DELETE', __FILE__);
406 foreach ($to_insert as $insalias) {
407 if ($insalias === $this->nickname) {
410 $alias->alias = Nickname::normalize($insalias, true);
411 $result = $alias->insert();
413 common_log_db_error($alias, 'INSERT', __FILE__);
421 static function getForNickname($nickname, Profile $profile=null)
423 $nickname = Nickname::normalize($nickname);
425 // Are there any matching remote groups this profile's in?
426 if ($profile instanceof Profile) {
427 $group = $profile->getGroups(0, null);
428 while ($group instanceof User_group && $group->fetch()) {
429 if ($group->nickname == $nickname) {
430 // @fixme is this the best way?
431 return clone($group);
436 // If not, check local groups.
437 $group = Local_group::getKV('nickname', $nickname);
438 if ($group instanceof Local_group) {
439 return User_group::getKV('id', $group->group_id);
441 $alias = Group_alias::getKV('alias', $nickname);
442 if ($alias instanceof Group_alias) {
443 return User_group::getKV('id', $alias->group_id);
448 function getUserMembers()
453 if(common_config('db','quote_identifiers'))
454 $user_table = '"user"';
455 else $user_table = 'user';
459 'FROM '. $user_table .' JOIN group_member '.
460 'ON '. $user_table .'.id = group_member.profile_id ' .
461 'WHERE group_member.group_id = %d ';
463 $user->query(sprintf($qry, $this->id));
467 while ($user->fetch()) {
476 static function maxDescription()
478 $desclimit = common_config('group', 'desclimit');
479 // null => use global limit (distinct from 0!)
480 if (is_null($desclimit)) {
481 $desclimit = common_config('site', 'textlimit');
486 static function descriptionTooLong($desc)
488 $desclimit = self::maxDescription();
489 return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
492 function asAtomEntry($namespace=false, $source=false)
494 $xs = new XMLStringer(true);
497 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
498 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
503 $xs->elementStart('entry', $attrs);
506 $xs->elementStart('source');
507 $xs->element('id', null, $this->permalink());
508 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
509 $xs->element('link', array('href' => $this->permalink()));
510 $xs->element('updated', null, $this->modified);
511 $xs->elementEnd('source');
514 $xs->element('title', null, $this->nickname);
515 $xs->element('summary', null, common_xml_safe_str($this->description));
517 $xs->element('link', array('rel' => 'alternate',
518 'href' => $this->permalink()));
520 $xs->element('id', null, $this->permalink());
522 $xs->element('published', null, common_date_w3dtf($this->created));
523 $xs->element('updated', null, common_date_w3dtf($this->modified));
527 array('type' => 'html'),
528 common_xml_safe_str($this->description)
531 $xs->elementEnd('entry');
533 return $xs->getString();
536 function asAtomAuthor()
538 $xs = new XMLStringer(true);
540 $xs->elementStart('author');
541 $xs->element('name', null, $this->nickname);
542 $xs->element('uri', null, $this->permalink());
543 $xs->elementEnd('author');
545 return $xs->getString();
549 * Returns an XML string fragment with group information as an
550 * Activity Streams noun object with the given element type.
552 * Assumes that 'activity', 'georss', and 'poco' namespace has been
553 * previously defined.
555 * @param string $element one of 'actor', 'subject', 'object', 'target'
559 function asActivityNoun($element)
561 $noun = ActivityObject::fromGroup($this);
562 return $noun->asString('activity:' . $element);
567 return empty($this->homepage_logo)
568 ? User_group::defaultLogo(AVATAR_PROFILE_SIZE)
569 : $this->homepage_logo;
572 static function register($fields) {
573 if (!empty($fields['userid'])) {
574 $profile = Profile::getKV('id', $fields['userid']);
575 if ($profile && !$profile->hasRight(Right::CREATEGROUP)) {
576 common_log(LOG_WARNING, "Attempted group creation from banned user: " . $profile->nickname);
578 // TRANS: Client exception thrown when a user tries to create a group while banned.
579 throw new ClientException(_('You are not allowed to create groups on this site.'), 403);
583 $fields['nickname'] = Nickname::normalize($fields['nickname']);
585 // MAGICALLY put fields into current scope
586 // @fixme kill extract(); it makes debugging absurdly hard
588 $defaults = array('nickname' => null,
591 'description' => null,
595 'aliases' => array(),
598 $fields = array_merge($defaults, $fields);
602 $group = new User_group();
608 if (empty($mainpage)) {
609 $mainpage = common_local_url('showgroup', array('nickname' => $nickname));
612 // We must create a new, incrementally assigned profile_id
613 $profile = new Profile();
614 $profile->nickname = $nickname;
615 $profile->fullname = $fullname;
616 $profile->profileurl = $mainpage;
617 $profile->homepage = $homepage;
618 $profile->bio = $description;
619 $profile->location = $location;
620 $profile->created = common_sql_now();
622 $group->nickname = $profile->nickname;
623 $group->fullname = $profile->fullname;
624 $group->homepage = $profile->homepage;
625 $group->description = $profile->bio;
626 $group->location = $profile->location;
627 $group->mainpage = $profile->profileurl;
628 $group->created = $profile->created;
630 $profile->query('BEGIN');
631 $id = $profile->insert();
633 $profile->query('ROLLBACK');
634 throw new ServerException(_('Profile insertion failed'));
637 $group->profile_id = $id;
640 if (isset($fields['join_policy'])) {
641 $group->join_policy = intval($fields['join_policy']);
643 $group->join_policy = 0;
646 if (isset($fields['force_scope'])) {
647 $group->force_scope = intval($fields['force_scope']);
649 $group->force_scope = 0;
652 if (Event::handle('StartGroupSave', array(&$group))) {
654 $result = $group->insert();
656 if ($result === false) {
657 common_log_db_error($group, 'INSERT', __FILE__);
658 // TRANS: Server exception thrown when creating a group failed.
659 throw new ServerException(_('Could not create group.'));
662 if (!isset($uri) || empty($uri)) {
663 $orig = clone($group);
664 $group->uri = common_local_url('groupbyid', array('id' => $group->id));
665 $result = $group->update($orig);
667 common_log_db_error($group, 'UPDATE', __FILE__);
668 // TRANS: Server exception thrown when updating a group URI failed.
669 throw new ServerException(_('Could not set group URI.'));
673 $result = $group->setAliases($aliases);
676 // TRANS: Server exception thrown when creating group aliases failed.
677 throw new ServerException(_('Could not create aliases.'));
680 $member = new Group_member();
682 $member->group_id = $group->id;
683 $member->profile_id = $userid;
684 $member->is_admin = 1;
685 $member->created = $group->created;
687 $result = $member->insert();
690 common_log_db_error($member, 'INSERT', __FILE__);
691 // TRANS: Server exception thrown when setting group membership failed.
692 throw new ServerException(_('Could not set group membership.'));
695 self::blow('profile:groups:%d', $userid);
698 $local_group = new Local_group();
700 $local_group->group_id = $group->id;
701 $local_group->nickname = $nickname;
702 $local_group->created = common_sql_now();
704 $result = $local_group->insert();
707 common_log_db_error($local_group, 'INSERT', __FILE__);
708 // TRANS: Server exception thrown when saving local group information failed.
709 throw new ServerException(_('Could not save local group info.'));
713 Event::handle('EndGroupSave', array($group));
716 $profile->query('COMMIT');
722 * Handle cascading deletion, on the model of notice and profile.
724 * This should handle freeing up cached entries for the group's
725 * id, nickname, URI, and aliases. There may be other areas that
726 * are not de-cached in the UI, including the sidebar lists on
729 function delete($useWhere=false)
731 if (empty($this->id)) {
732 common_log(LOG_WARNING, "Ambiguous User_group->delete(); skipping related tables.");
733 return parent::delete($useWhere);
737 $profile = $this->getProfile();
739 } catch (GroupNoProfileException $unp) {
740 common_log(LOG_INFO, "Group {$this->nickname} has no profile; continuing deletion.");
743 // Safe to delete in bulk for now
745 $related = array('Group_inbox',
750 Event::handle('UserGroupDeleteRelated', array($this, &$related));
752 foreach ($related as $cls) {
754 $inst->group_id = $this->id;
757 while ($inst->fetch()) {
764 // And related groups in the other direction...
765 $inst = new Related_group();
766 $inst->related_group_id = $this->id;
769 // Aliases and the local_group entry need to be cleared explicitly
770 // or we'll miss clearing some cache keys; that can make it hard
771 // to create a new group with one of those names or aliases.
772 $this->setAliases(array());
774 // $this->isLocal() but we're using the resulting object
775 $local = Local_group::getKV('group_id', $this->id);
776 if ($local instanceof Local_group) {
780 // blow the cached ids
781 self::blow('user_group:notice_ids:%d', $this->id);
783 return parent::delete($useWhere);
786 public function update($dataObject=false)
788 // Whenever the User_group is updated, find the Local_group
789 // and update its nickname too.
790 if ($this->nickname != $dataObject->nickname) {
791 $local = Local_group::getKV('group_id', $this->id);
792 if ($local instanceof Local_group) {
793 common_debug("Updating Local_group ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
794 $local->setNickname($this->nickname);
798 // Also make sure the Profile table is up to date!
799 $fields = array(/*group field => profile field*/
800 'nickname' => 'nickname',
801 'fullname' => 'fullname',
802 'mainpage' => 'profileurl',
803 'homepage' => 'homepage',
804 'description' => 'bio',
805 'location' => 'location',
806 'created' => 'created',
807 'modified' => 'modified',
809 $profile = $this->getProfile();
810 $origpro = clone($profile);
811 foreach ($fields as $gf=>$pf) {
812 $profile->$pf = $this->$gf;
814 if ($profile->update($origpro) === false) {
815 throw new ServerException(_('Unable to update profile'));
818 return parent::update($dataObject);
823 return ($this->join_policy == self::JOIN_POLICY_MODERATE &&
824 $this->force_scope == 1);
827 public function isLocal()
829 $local = Local_group::getKV('group_id', $this->id);
830 return ($local instanceof Local_group);
833 static function groupsFromText($text, Profile $profile)
837 /* extract all !group */
838 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
846 foreach (array_unique($match[1]) as $nickname) {
847 $group = self::getForNickname($nickname, $profile);
848 if ($group instanceof User_group && $profile->isMember($group)) {
849 $groups[] = clone($group);
856 static function idsFromText($text, Profile $profile)
859 $groups = self::groupsFromText($text, $profile);
860 foreach ($groups as $group) {
861 $ids[$group->id] = true;
863 return array_keys($ids);