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'),
42 'nickname' => array('type' => 'varchar', 'length' => 64, 'description' => 'nickname for addressing'),
43 'fullname' => array('type' => 'varchar', 'length' => 255, 'description' => 'display name'),
44 'homepage' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL, cached so we dont regenerate'),
45 'description' => array('type' => 'text', 'description' => 'group description'),
46 'location' => array('type' => 'varchar', 'length' => 255, 'description' => 'related physical location, if any'),
48 'original_logo' => array('type' => 'varchar', 'length' => 255, 'description' => 'original size logo'),
49 'homepage_logo' => array('type' => 'varchar', 'length' => 255, 'description' => 'homepage (profile) size logo'),
50 'stream_logo' => array('type' => 'varchar', 'length' => 255, 'description' => 'stream-sized logo'),
51 'mini_logo' => array('type' => 'varchar', 'length' => 255, 'description' => 'mini logo'),
53 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
54 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
56 'uri' => array('type' => 'varchar', 'length' => 255, 'description' => 'universal identifier'),
57 'mainpage' => array('type' => 'varchar', 'length' => 255, 'description' => 'page for group info to link to'),
58 'join_policy' => array('type' => 'int', 'size' => 'tiny', 'description' => '0=open; 1=requires admin approval'),
59 'force_scope' => array('type' => 'int', 'size' => 'tiny', 'description' => '0=never,1=sometimes,-1=always'),
61 'primary key' => array('id'),
62 'unique keys' => array(
63 'user_group_uri_key' => array('uri'),
66 'user_group_nickname_idx' => array('nickname'),
71 public static function defaultLogo($size)
73 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
74 AVATAR_STREAM_SIZE => 'stream',
75 AVATAR_MINI_SIZE => 'mini');
76 return Theme::path('default-avatar-'.$sizenames[$size].'.png');
82 if (Event::handle('StartUserGroupHomeUrl', array($this, &$url))) {
83 // normally stored in mainpage, but older ones may be null
84 if (!empty($this->mainpage)) {
85 $url = $this->mainpage;
87 $url = common_local_url('showgroup',
88 array('nickname' => $this->nickname));
91 Event::handle('EndUserGroupHomeUrl', array($this, &$url));
98 if (Event::handle('StartUserGroupGetUri', array($this, &$uri))) {
99 if (!empty($this->uri)) {
102 $uri = common_local_url('groupbyid',
103 array('id' => $this->id));
106 Event::handle('EndUserGroupGetUri', array($this, &$uri));
113 if (Event::handle('StartUserGroupPermalink', array($this, &$url))) {
114 $url = common_local_url('groupbyid',
115 array('id' => $this->id));
117 Event::handle('EndUserGroupPermalink', array($this, &$url));
121 function getNotices($offset, $limit, $since_id=null, $max_id=null)
123 $stream = new GroupNoticeStream($this);
125 return $stream->getNotices($offset, $limit, $since_id, $max_id);
129 function allowedNickname($nickname)
131 static $blacklist = array('new');
132 return !in_array($nickname, $blacklist);
135 function getMembers($offset=0, $limit=null) {
137 if (is_null($limit) || $offset + $limit > User_group::CACHE_WINDOW) {
138 $ids = $this->getMemberIDs($offset,
141 $key = sprintf('group:member_ids:%d', $this->id);
142 $window = self::cacheGet($key);
143 if ($window === false) {
144 $window = $this->getMemberIDs(0,
145 User_group::CACHE_WINDOW);
146 self::cacheSet($key, $window);
149 $ids = array_slice($window,
154 return Profile::multiGet('id', $ids);
157 function getMemberIDs($offset=0, $limit=null)
159 $gm = new Group_member();
162 $gm->selectAdd('profile_id');
164 $gm->group_id = $this->id;
166 $gm->orderBy('created DESC');
168 if (!is_null($limit)) {
169 $gm->limit($offset, $limit);
175 while ($gm->fetch()) {
176 $ids[] = $gm->profile_id;
184 * Get pending members, who have not yet been approved.
190 function getRequests($offset=0, $limit=null)
193 'SELECT profile.* ' .
194 'FROM profile JOIN group_join_queue '.
195 'ON profile.id = group_join_queue.profile_id ' .
196 'WHERE group_join_queue.group_id = %d ' .
197 'ORDER BY group_join_queue.created DESC ';
199 if ($limit != null) {
200 if (common_config('db','type') == 'pgsql') {
201 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
203 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
207 $members = new Profile();
209 $members->query(sprintf($qry, $this->id));
213 public function getAdminCount()
215 return $this->getAdmins()->N;
218 public function getMemberCount()
220 $key = sprintf("group:member_count:%d", $this->id);
222 $cnt = self::cacheGet($key);
224 if (is_integer($cnt)) {
228 $mem = new Group_member();
229 $mem->group_id = $this->id;
231 // XXX: why 'distinct'?
233 $cnt = (int) $mem->count('distinct profile_id');
235 self::cacheSet($key, $cnt);
240 function getBlockedCount()
242 // XXX: WORM cache this
244 $block = new Group_block();
245 $block->group_id = $this->id;
247 return $block->count();
250 function getQueueCount()
252 // XXX: WORM cache this
254 $queue = new Group_join_queue();
255 $queue->group_id = $this->id;
257 return $queue->count();
260 function getAdmins($offset=0, $limit=null)
263 'SELECT profile.* ' .
264 'FROM profile JOIN group_member '.
265 'ON profile.id = group_member.profile_id ' .
266 'WHERE group_member.group_id = %d ' .
267 'AND group_member.is_admin = 1 ' .
268 'ORDER BY group_member.modified ASC ';
270 if ($limit != null) {
271 if (common_config('db','type') == 'pgsql') {
272 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
274 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
278 $admins = new Profile();
280 $admins->query(sprintf($qry, $this->id));
284 function getBlocked($offset=0, $limit=null)
287 'SELECT profile.* ' .
288 'FROM profile JOIN group_block '.
289 'ON profile.id = group_block.blocked ' .
290 'WHERE group_block.group_id = %d ' .
291 'ORDER BY group_block.modified DESC ';
293 if ($limit != null) {
294 if (common_config('db','type') == 'pgsql') {
295 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
297 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
301 $blocked = new Profile();
303 $blocked->query(sprintf($qry, $this->id));
307 function setOriginal($filename)
309 $imagefile = new ImageFile($this->id, Avatar::path($filename));
311 $orig = clone($this);
312 $this->original_logo = Avatar::url($filename);
313 $this->homepage_logo = Avatar::url($imagefile->resize(AVATAR_PROFILE_SIZE));
314 $this->stream_logo = Avatar::url($imagefile->resize(AVATAR_STREAM_SIZE));
315 $this->mini_logo = Avatar::url($imagefile->resize(AVATAR_MINI_SIZE));
316 common_debug(common_log_objstring($this));
317 return $this->update($orig);
320 function getBestName()
322 return ($this->fullname) ? $this->fullname : $this->nickname;
326 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
327 * if no fullname is provided.
331 function getFancyName()
333 if ($this->fullname) {
334 // TRANS: Full name of a profile or group followed by nickname in parens
335 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
337 return $this->nickname;
341 function getAliases()
347 $alias = new Group_alias();
349 $alias->group_id = $this->id;
351 if ($alias->find()) {
352 while ($alias->fetch()) {
353 $aliases[] = $alias->alias;
362 function setAliases($newaliases) {
364 $newaliases = array_unique($newaliases);
366 $oldaliases = $this->getAliases();
368 // Delete stuff that's old that not in new
370 $to_delete = array_diff($oldaliases, $newaliases);
372 // Insert stuff that's in new and not in old
374 $to_insert = array_diff($newaliases, $oldaliases);
376 $alias = new Group_alias();
378 $alias->group_id = $this->id;
380 foreach ($to_delete as $delalias) {
381 $alias->alias = $delalias;
382 $result = $alias->delete();
384 common_log_db_error($alias, 'DELETE', __FILE__);
389 foreach ($to_insert as $insalias) {
390 $alias->alias = $insalias;
391 $result = $alias->insert();
393 common_log_db_error($alias, 'INSERT', __FILE__);
401 static function getForNickname($nickname, $profile=null)
403 $nickname = common_canonical_nickname($nickname);
405 // Are there any matching remote groups this profile's in?
407 $group = $profile->getGroups(0, null);
408 while ($group->fetch()) {
409 if ($group->nickname == $nickname) {
410 // @fixme is this the best way?
411 return clone($group);
416 // If not, check local groups.
418 $group = Local_group::getKV('nickname', $nickname);
419 if (!empty($group)) {
420 return User_group::getKV('id', $group->group_id);
422 $alias = Group_alias::getKV('alias', $nickname);
423 if (!empty($alias)) {
424 return User_group::getKV('id', $alias->group_id);
429 function getUserMembers()
434 if(common_config('db','quote_identifiers'))
435 $user_table = '"user"';
436 else $user_table = 'user';
440 'FROM '. $user_table .' JOIN group_member '.
441 'ON '. $user_table .'.id = group_member.profile_id ' .
442 'WHERE group_member.group_id = %d ';
444 $user->query(sprintf($qry, $this->id));
448 while ($user->fetch()) {
457 static function maxDescription()
459 $desclimit = common_config('group', 'desclimit');
460 // null => use global limit (distinct from 0!)
461 if (is_null($desclimit)) {
462 $desclimit = common_config('site', 'textlimit');
467 static function descriptionTooLong($desc)
469 $desclimit = self::maxDescription();
470 return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
473 function asAtomEntry($namespace=false, $source=false)
475 $xs = new XMLStringer(true);
478 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
479 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
484 $xs->elementStart('entry', $attrs);
487 $xs->elementStart('source');
488 $xs->element('id', null, $this->permalink());
489 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
490 $xs->element('link', array('href' => $this->permalink()));
491 $xs->element('updated', null, $this->modified);
492 $xs->elementEnd('source');
495 $xs->element('title', null, $this->nickname);
496 $xs->element('summary', null, common_xml_safe_str($this->description));
498 $xs->element('link', array('rel' => 'alternate',
499 'href' => $this->permalink()));
501 $xs->element('id', null, $this->permalink());
503 $xs->element('published', null, common_date_w3dtf($this->created));
504 $xs->element('updated', null, common_date_w3dtf($this->modified));
508 array('type' => 'html'),
509 common_xml_safe_str($this->description)
512 $xs->elementEnd('entry');
514 return $xs->getString();
517 function asAtomAuthor()
519 $xs = new XMLStringer(true);
521 $xs->elementStart('author');
522 $xs->element('name', null, $this->nickname);
523 $xs->element('uri', null, $this->permalink());
524 $xs->elementEnd('author');
526 return $xs->getString();
530 * Returns an XML string fragment with group information as an
531 * Activity Streams <activity:subject> element.
533 * Assumes that 'activity' namespace has been previously defined.
537 function asActivitySubject()
539 return $this->asActivityNoun('subject');
543 * Returns an XML string fragment with group information as an
544 * Activity Streams noun object with the given element type.
546 * Assumes that 'activity', 'georss', and 'poco' namespace has been
547 * previously defined.
549 * @param string $element one of 'actor', 'subject', 'object', 'target'
553 function asActivityNoun($element)
555 $noun = ActivityObject::fromGroup($this);
556 return $noun->asString('activity:' . $element);
561 return empty($this->homepage_logo)
562 ? User_group::defaultLogo(AVATAR_PROFILE_SIZE)
563 : $this->homepage_logo;
566 static function register($fields) {
567 if (!empty($fields['userid'])) {
568 $profile = Profile::getKV('id', $fields['userid']);
569 if ($profile && !$profile->hasRight(Right::CREATEGROUP)) {
570 common_log(LOG_WARNING, "Attempted group creation from banned user: " . $profile->nickname);
572 // TRANS: Client exception thrown when a user tries to create a group while banned.
573 throw new ClientException(_('You are not allowed to create groups on this site.'), 403);
577 // MAGICALLY put fields into current scope
578 // @fixme kill extract(); it makes debugging absurdly hard
580 $defaults = array('nickname' => null,
583 'description' => null,
587 'aliases' => array(),
590 $fields = array_merge($defaults, $fields);
594 $group = new User_group();
596 $group->query('BEGIN');
602 if (empty($mainpage)) {
603 $mainpage = common_local_url('showgroup', array('nickname' => $nickname));
606 $group->nickname = $nickname;
607 $group->fullname = $fullname;
608 $group->homepage = $homepage;
609 $group->description = $description;
610 $group->location = $location;
612 $group->mainpage = $mainpage;
613 $group->created = common_sql_now();
615 if (isset($fields['join_policy'])) {
616 $group->join_policy = intval($fields['join_policy']);
618 $group->join_policy = 0;
621 if (isset($fields['force_scope'])) {
622 $group->force_scope = intval($fields['force_scope']);
624 $group->force_scope = 0;
627 if (Event::handle('StartGroupSave', array(&$group))) {
629 $result = $group->insert();
632 common_log_db_error($group, 'INSERT', __FILE__);
633 // TRANS: Server exception thrown when creating a group failed.
634 throw new ServerException(_('Could not create group.'));
637 if (!isset($uri) || empty($uri)) {
638 $orig = clone($group);
639 $group->uri = common_local_url('groupbyid', array('id' => $group->id));
640 $result = $group->update($orig);
642 common_log_db_error($group, 'UPDATE', __FILE__);
643 // TRANS: Server exception thrown when updating a group URI failed.
644 throw new ServerException(_('Could not set group URI.'));
648 $result = $group->setAliases($aliases);
651 // TRANS: Server exception thrown when creating group aliases failed.
652 throw new ServerException(_('Could not create aliases.'));
655 $member = new Group_member();
657 $member->group_id = $group->id;
658 $member->profile_id = $userid;
659 $member->is_admin = 1;
660 $member->created = $group->created;
662 $result = $member->insert();
665 common_log_db_error($member, 'INSERT', __FILE__);
666 // TRANS: Server exception thrown when setting group membership failed.
667 throw new ServerException(_('Could not set group membership.'));
670 self::blow('profile:groups:%d', $userid);
673 $local_group = new Local_group();
675 $local_group->group_id = $group->id;
676 $local_group->nickname = $nickname;
677 $local_group->created = common_sql_now();
679 $result = $local_group->insert();
682 common_log_db_error($local_group, 'INSERT', __FILE__);
683 // TRANS: Server exception thrown when saving local group information failed.
684 throw new ServerException(_('Could not save local group info.'));
688 $group->query('COMMIT');
690 Event::handle('EndGroupSave', array($group));
697 * Handle cascading deletion, on the model of notice and profile.
699 * This should handle freeing up cached entries for the group's
700 * id, nickname, URI, and aliases. There may be other areas that
701 * are not de-cached in the UI, including the sidebar lists on
708 // Safe to delete in bulk for now
710 $related = array('Group_inbox',
715 Event::handle('UserGroupDeleteRelated', array($this, &$related));
717 foreach ($related as $cls) {
720 $inst->group_id = $this->id;
723 while ($inst->fetch()) {
730 // And related groups in the other direction...
731 $inst = new Related_group();
732 $inst->related_group_id = $this->id;
735 // Aliases and the local_group entry need to be cleared explicitly
736 // or we'll miss clearing some cache keys; that can make it hard
737 // to create a new group with one of those names or aliases.
738 $this->setAliases(array());
739 $local = Local_group::getKV('group_id', $this->id);
744 // blow the cached ids
745 self::blow('user_group:notice_ids:%d', $this->id);
748 common_log(LOG_WARNING, "Ambiguous user_group->delete(); skipping related tables.");
755 return ($this->join_policy == self::JOIN_POLICY_MODERATE &&
756 $this->force_scope == 1);