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
34 function staticGet($k,$v=NULL) {
35 return Memcached_DataObject::staticGet('User_group',$k,$v);
38 function multiGet($keyCol, $keyVals, $skipNulls=true)
40 return parent::multiGet('User_group', $keyCol, $keyVals, $skipNulls);
43 /* the code above is auto generated do not remove the tag below */
46 public static function schemaDef()
50 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
52 'nickname' => array('type' => 'varchar', 'length' => 64, 'description' => 'nickname for addressing'),
53 'fullname' => array('type' => 'varchar', 'length' => 255, 'description' => 'display name'),
54 'homepage' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL, cached so we dont regenerate'),
55 'description' => array('type' => 'text', 'description' => 'group description'),
56 'location' => array('type' => 'varchar', 'length' => 255, 'description' => 'related physical location, if any'),
58 'original_logo' => array('type' => 'varchar', 'length' => 255, 'description' => 'original size logo'),
59 'homepage_logo' => array('type' => 'varchar', 'length' => 255, 'description' => 'homepage (profile) size logo'),
60 'stream_logo' => array('type' => 'varchar', 'length' => 255, 'description' => 'stream-sized logo'),
61 'mini_logo' => array('type' => 'varchar', 'length' => 255, 'description' => 'mini logo'),
63 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
64 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
66 'uri' => array('type' => 'varchar', 'length' => 255, 'description' => 'universal identifier'),
67 'mainpage' => array('type' => 'varchar', 'length' => 255, 'description' => 'page for group info to link to'),
68 'join_policy' => array('type' => 'int', 'size' => 'tiny', 'description' => '0=open; 1=requires admin approval'),
69 'force_scope' => array('type' => 'int', 'size' => 'tiny', 'description' => '0=never,1=sometimes,-1=always'),
71 'primary key' => array('id'),
72 'unique keys' => array(
73 'user_group_uri_key' => array('uri'),
76 'user_group_nickname_idx' => array('nickname'),
81 function defaultLogo($size)
83 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
84 AVATAR_STREAM_SIZE => 'stream',
85 AVATAR_MINI_SIZE => 'mini');
86 return Theme::path('default-avatar-'.$sizenames[$size].'.png');
92 if (Event::handle('StartUserGroupHomeUrl', array($this, &$url))) {
93 // normally stored in mainpage, but older ones may be null
94 if (!empty($this->mainpage)) {
95 $url = $this->mainpage;
97 $url = common_local_url('showgroup',
98 array('nickname' => $this->nickname));
101 Event::handle('EndUserGroupHomeUrl', array($this, &$url));
108 if (Event::handle('StartUserGroupGetUri', array($this, &$uri))) {
109 if (!empty($this->uri)) {
112 $uri = common_local_url('groupbyid',
113 array('id' => $this->id));
116 Event::handle('EndUserGroupGetUri', array($this, &$uri));
123 if (Event::handle('StartUserGroupPermalink', array($this, &$url))) {
124 $url = common_local_url('groupbyid',
125 array('id' => $this->id));
127 Event::handle('EndUserGroupPermalink', array($this, &$url));
131 function getNotices($offset, $limit, $since_id=null, $max_id=null)
133 $stream = new GroupNoticeStream($this);
135 return $stream->getNotices($offset, $limit, $since_id, $max_id);
139 function allowedNickname($nickname)
141 static $blacklist = array('new');
142 return !in_array($nickname, $blacklist);
145 function getMembers($offset=0, $limit=null) {
147 if (is_null($limit) || $offset + $limit > User_group::CACHE_WINDOW) {
148 $ids = $this->getMemberIDs($offset,
151 $key = sprintf('group:members:%d', $this->id);
152 $window = self::cacheGet($key);
153 if ($window === false) {
154 $window = $this->getMemberIDs(0,
155 User_group::CACHE_WINDOW);
156 self::cacheSet($key, $window);
159 $ids = array_slice($window,
164 return Profile::multiGet('id', $ids);
167 function getMemberIDs($offset=0, $limit=null)
169 $gm = new Group_member();
172 $gm->selectAdd('profile_id');
174 $gm->group_id = $this->id;
176 $gm->orderBy('created DESC');
178 if (!is_null($limit)) {
179 $gm->limit($offset, $limit);
185 while ($gm->fetch()) {
186 $ids[] = $gm->profile_id;
194 * Get pending members, who have not yet been approved.
200 function getRequests($offset=0, $limit=null)
203 'SELECT profile.* ' .
204 'FROM profile JOIN group_join_queue '.
205 'ON profile.id = group_join_queue.profile_id ' .
206 'WHERE group_join_queue.group_id = %d ' .
207 'ORDER BY group_join_queue.created DESC ';
209 if ($limit != null) {
210 if (common_config('db','type') == 'pgsql') {
211 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
213 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
217 $members = new Profile();
219 $members->query(sprintf($qry, $this->id));
223 function getMemberCount()
225 $key = sprintf("group:member_count:%d", $this->id);
227 $cnt = self::cacheGet($key);
229 if (is_integer($cnt)) {
233 $mem = new Group_member();
234 $mem->group_id = $this->id;
236 // XXX: why 'distinct'?
238 $cnt = (int) $mem->count('distinct profile_id');
240 self::cacheSet($key, $cnt);
245 function getBlockedCount()
247 // XXX: WORM cache this
249 $block = new Group_block();
250 $block->group_id = $this->id;
252 return $block->count();
255 function getQueueCount()
257 // XXX: WORM cache this
259 $queue = new Group_join_queue();
260 $queue->group_id = $this->id;
262 return $queue->count();
265 function getAdmins($offset=0, $limit=null)
268 'SELECT profile.* ' .
269 'FROM profile JOIN group_member '.
270 'ON profile.id = group_member.profile_id ' .
271 'WHERE group_member.group_id = %d ' .
272 'AND group_member.is_admin = 1 ' .
273 'ORDER BY group_member.modified ASC ';
275 if ($limit != null) {
276 if (common_config('db','type') == 'pgsql') {
277 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
279 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
283 $admins = new Profile();
285 $admins->query(sprintf($qry, $this->id));
289 function getBlocked($offset=0, $limit=null)
292 'SELECT profile.* ' .
293 'FROM profile JOIN group_block '.
294 'ON profile.id = group_block.blocked ' .
295 'WHERE group_block.group_id = %d ' .
296 'ORDER BY group_block.modified DESC ';
298 if ($limit != null) {
299 if (common_config('db','type') == 'pgsql') {
300 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
302 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
306 $blocked = new Profile();
308 $blocked->query(sprintf($qry, $this->id));
312 function setOriginal($filename)
314 $imagefile = new ImageFile($this->id, Avatar::path($filename));
316 $orig = clone($this);
317 $this->original_logo = Avatar::url($filename);
318 $this->homepage_logo = Avatar::url($imagefile->resize(AVATAR_PROFILE_SIZE));
319 $this->stream_logo = Avatar::url($imagefile->resize(AVATAR_STREAM_SIZE));
320 $this->mini_logo = Avatar::url($imagefile->resize(AVATAR_MINI_SIZE));
321 common_debug(common_log_objstring($this));
322 return $this->update($orig);
325 function getBestName()
327 return ($this->fullname) ? $this->fullname : $this->nickname;
331 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
332 * if no fullname is provided.
336 function getFancyName()
338 if ($this->fullname) {
339 // TRANS: Full name of a profile or group followed by nickname in parens
340 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
342 return $this->nickname;
346 function getAliases()
352 $alias = new Group_alias();
354 $alias->group_id = $this->id;
356 if ($alias->find()) {
357 while ($alias->fetch()) {
358 $aliases[] = $alias->alias;
367 function setAliases($newaliases) {
369 $newaliases = array_unique($newaliases);
371 $oldaliases = $this->getAliases();
373 // Delete stuff that's old that not in new
375 $to_delete = array_diff($oldaliases, $newaliases);
377 // Insert stuff that's in new and not in old
379 $to_insert = array_diff($newaliases, $oldaliases);
381 $alias = new Group_alias();
383 $alias->group_id = $this->id;
385 foreach ($to_delete as $delalias) {
386 $alias->alias = $delalias;
387 $result = $alias->delete();
389 common_log_db_error($alias, 'DELETE', __FILE__);
394 foreach ($to_insert as $insalias) {
395 $alias->alias = $insalias;
396 $result = $alias->insert();
398 common_log_db_error($alias, 'INSERT', __FILE__);
406 static function getForNickname($nickname, $profile=null)
408 $nickname = common_canonical_nickname($nickname);
410 // Are there any matching remote groups this profile's in?
412 $group = $profile->getGroups();
413 while ($group->fetch()) {
414 if ($group->nickname == $nickname) {
415 // @fixme is this the best way?
416 return clone($group);
421 // If not, check local groups.
423 $group = Local_group::staticGet('nickname', $nickname);
424 if (!empty($group)) {
425 return User_group::staticGet('id', $group->group_id);
427 $alias = Group_alias::staticGet('alias', $nickname);
428 if (!empty($alias)) {
429 return User_group::staticGet('id', $alias->group_id);
434 function getUserMembers()
439 if(common_config('db','quote_identifiers'))
440 $user_table = '"user"';
441 else $user_table = 'user';
445 'FROM '. $user_table .' JOIN group_member '.
446 'ON '. $user_table .'.id = group_member.profile_id ' .
447 'WHERE group_member.group_id = %d ';
449 $user->query(sprintf($qry, $this->id));
453 while ($user->fetch()) {
462 static function maxDescription()
464 $desclimit = common_config('group', 'desclimit');
465 // null => use global limit (distinct from 0!)
466 if (is_null($desclimit)) {
467 $desclimit = common_config('site', 'textlimit');
472 static function descriptionTooLong($desc)
474 $desclimit = self::maxDescription();
475 return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
478 function asAtomEntry($namespace=false, $source=false)
480 $xs = new XMLStringer(true);
483 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
484 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
489 $xs->elementStart('entry', $attrs);
492 $xs->elementStart('source');
493 $xs->element('id', null, $this->permalink());
494 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
495 $xs->element('link', array('href' => $this->permalink()));
496 $xs->element('updated', null, $this->modified);
497 $xs->elementEnd('source');
500 $xs->element('title', null, $this->nickname);
501 $xs->element('summary', null, common_xml_safe_str($this->description));
503 $xs->element('link', array('rel' => 'alternate',
504 'href' => $this->permalink()));
506 $xs->element('id', null, $this->permalink());
508 $xs->element('published', null, common_date_w3dtf($this->created));
509 $xs->element('updated', null, common_date_w3dtf($this->modified));
513 array('type' => 'html'),
514 common_xml_safe_str($this->description)
517 $xs->elementEnd('entry');
519 return $xs->getString();
522 function asAtomAuthor()
524 $xs = new XMLStringer(true);
526 $xs->elementStart('author');
527 $xs->element('name', null, $this->nickname);
528 $xs->element('uri', null, $this->permalink());
529 $xs->elementEnd('author');
531 return $xs->getString();
535 * Returns an XML string fragment with group information as an
536 * Activity Streams <activity:subject> element.
538 * Assumes that 'activity' namespace has been previously defined.
542 function asActivitySubject()
544 return $this->asActivityNoun('subject');
548 * Returns an XML string fragment with group information as an
549 * Activity Streams noun object with the given element type.
551 * Assumes that 'activity', 'georss', and 'poco' namespace has been
552 * previously defined.
554 * @param string $element one of 'actor', 'subject', 'object', 'target'
558 function asActivityNoun($element)
560 $noun = ActivityObject::fromGroup($this);
561 return $noun->asString('activity:' . $element);
566 return empty($this->homepage_logo)
567 ? User_group::defaultLogo(AVATAR_PROFILE_SIZE)
568 : $this->homepage_logo;
571 static function register($fields) {
572 if (!empty($fields['userid'])) {
573 $profile = Profile::staticGet('id', $fields['userid']);
574 if ($profile && !$profile->hasRight(Right::CREATEGROUP)) {
575 common_log(LOG_WARNING, "Attempted group creation from banned user: " . $profile->nickname);
577 // TRANS: Client exception thrown when a user tries to create a group while banned.
578 throw new ClientException(_('You are not allowed to create groups on this site.'), 403);
582 // MAGICALLY put fields into current scope
583 // @fixme kill extract(); it makes debugging absurdly hard
585 $defaults = array('nickname' => null,
588 'description' => null,
592 'aliases' => array(),
595 $fields = array_merge($defaults, $fields);
599 $group = new User_group();
601 $group->query('BEGIN');
607 if (empty($mainpage)) {
608 $mainpage = common_local_url('showgroup', array('nickname' => $nickname));
611 $group->nickname = $nickname;
612 $group->fullname = $fullname;
613 $group->homepage = $homepage;
614 $group->description = $description;
615 $group->location = $location;
617 $group->mainpage = $mainpage;
618 $group->created = common_sql_now();
620 if (isset($fields['join_policy'])) {
621 $group->join_policy = intval($fields['join_policy']);
623 $group->join_policy = 0;
626 if (isset($fields['force_scope'])) {
627 $group->force_scope = intval($fields['force_scope']);
629 $group->force_scope = 0;
632 if (Event::handle('StartGroupSave', array(&$group))) {
634 $result = $group->insert();
637 common_log_db_error($group, 'INSERT', __FILE__);
638 // TRANS: Server exception thrown when creating a group failed.
639 throw new ServerException(_('Could not create group.'));
642 if (!isset($uri) || empty($uri)) {
643 $orig = clone($group);
644 $group->uri = common_local_url('groupbyid', array('id' => $group->id));
645 $result = $group->update($orig);
647 common_log_db_error($group, 'UPDATE', __FILE__);
648 // TRANS: Server exception thrown when updating a group URI failed.
649 throw new ServerException(_('Could not set group URI.'));
653 $result = $group->setAliases($aliases);
656 // TRANS: Server exception thrown when creating group aliases failed.
657 throw new ServerException(_('Could not create aliases.'));
660 $member = new Group_member();
662 $member->group_id = $group->id;
663 $member->profile_id = $userid;
664 $member->is_admin = 1;
665 $member->created = $group->created;
667 $result = $member->insert();
670 common_log_db_error($member, 'INSERT', __FILE__);
671 // TRANS: Server exception thrown when setting group membership failed.
672 throw new ServerException(_('Could not set group membership.'));
675 self::blow('profile:groups:%d', $userid);
678 $local_group = new Local_group();
680 $local_group->group_id = $group->id;
681 $local_group->nickname = $nickname;
682 $local_group->created = common_sql_now();
684 $result = $local_group->insert();
687 common_log_db_error($local_group, 'INSERT', __FILE__);
688 // TRANS: Server exception thrown when saving local group information failed.
689 throw new ServerException(_('Could not save local group info.'));
693 $group->query('COMMIT');
695 Event::handle('EndGroupSave', array($group));
702 * Handle cascading deletion, on the model of notice and profile.
704 * This should handle freeing up cached entries for the group's
705 * id, nickname, URI, and aliases. There may be other areas that
706 * are not de-cached in the UI, including the sidebar lists on
713 // Safe to delete in bulk for now
715 $related = array('Group_inbox',
720 Event::handle('UserGroupDeleteRelated', array($this, &$related));
722 foreach ($related as $cls) {
725 $inst->group_id = $this->id;
728 while ($inst->fetch()) {
735 // And related groups in the other direction...
736 $inst = new Related_group();
737 $inst->related_group_id = $this->id;
740 // Aliases and the local_group entry need to be cleared explicitly
741 // or we'll miss clearing some cache keys; that can make it hard
742 // to create a new group with one of those names or aliases.
743 $this->setAliases(array());
744 $local = Local_group::staticGet('group_id', $this->id);
749 // blow the cached ids
750 self::blow('user_group:notice_ids:%d', $this->id);
753 common_log(LOG_WARN, "Ambiguous user_group->delete(); skipping related tables.");
760 return ($this->join_policy == self::JOIN_POLICY_MODERATE &&
761 $this->force_scope == 1);