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) {
146 if (is_null($limit) || $offset + $limit > User_group::CACHE_WINDOW) {
147 return $this->realGetMembers($offset,
150 $key = sprintf('group:members:%d', $this->id);
151 $window = self::cacheGet($key);
152 if ($window === false) {
153 $members = $this->realGetMembers(0,
154 User_group::CACHE_WINDOW);
155 $window = $members->fetchAll();
156 self::cacheSet($key, $window);
158 return new ArrayWrapper(array_slice($window,
164 function realGetMembers($offset=0, $limit=null)
166 $gm = new Group_member();
169 $gm->selectAdd('profile_id');
171 $gm->group_id = $this->id;
173 $gm->orderBy('created DESC');
175 if (!is_null($limit)) {
176 $gm->limit($offset, $limit);
182 while ($gm->fetch()) {
183 $ids[] = $gm->profile_id;
187 $members = Profile::multiGet('id', $ids);
193 * Get pending members, who have not yet been approved.
199 function getRequests($offset=0, $limit=null)
202 'SELECT profile.* ' .
203 'FROM profile JOIN group_join_queue '.
204 'ON profile.id = group_join_queue.profile_id ' .
205 'WHERE group_join_queue.group_id = %d ' .
206 'ORDER BY group_join_queue.created DESC ';
208 if ($limit != null) {
209 if (common_config('db','type') == 'pgsql') {
210 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
212 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
216 $members = new Profile();
218 $members->query(sprintf($qry, $this->id));
222 function getMemberCount()
224 $key = sprintf("group:member_count:%d", $this->id);
226 $cnt = self::cacheGet($key);
228 if (is_integer($cnt)) {
232 $mem = new Group_member();
233 $mem->group_id = $this->id;
235 // XXX: why 'distinct'?
237 $cnt = (int) $mem->count('distinct profile_id');
239 self::cacheSet($key, $cnt);
244 function getBlockedCount()
246 // XXX: WORM cache this
248 $block = new Group_block();
249 $block->group_id = $this->id;
251 return $block->count();
254 function getQueueCount()
256 // XXX: WORM cache this
258 $queue = new Group_join_queue();
259 $queue->group_id = $this->id;
261 return $queue->count();
264 function getAdmins($offset=0, $limit=null)
267 'SELECT profile.* ' .
268 'FROM profile JOIN group_member '.
269 'ON profile.id = group_member.profile_id ' .
270 'WHERE group_member.group_id = %d ' .
271 'AND group_member.is_admin = 1 ' .
272 'ORDER BY group_member.modified ASC ';
274 if ($limit != null) {
275 if (common_config('db','type') == 'pgsql') {
276 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
278 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
282 $admins = new Profile();
284 $admins->query(sprintf($qry, $this->id));
288 function getBlocked($offset=0, $limit=null)
291 'SELECT profile.* ' .
292 'FROM profile JOIN group_block '.
293 'ON profile.id = group_block.blocked ' .
294 'WHERE group_block.group_id = %d ' .
295 'ORDER BY group_block.modified DESC ';
297 if ($limit != null) {
298 if (common_config('db','type') == 'pgsql') {
299 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
301 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
305 $blocked = new Profile();
307 $blocked->query(sprintf($qry, $this->id));
311 function setOriginal($filename)
313 $imagefile = new ImageFile($this->id, Avatar::path($filename));
315 $orig = clone($this);
316 $this->original_logo = Avatar::url($filename);
317 $this->homepage_logo = Avatar::url($imagefile->resize(AVATAR_PROFILE_SIZE));
318 $this->stream_logo = Avatar::url($imagefile->resize(AVATAR_STREAM_SIZE));
319 $this->mini_logo = Avatar::url($imagefile->resize(AVATAR_MINI_SIZE));
320 common_debug(common_log_objstring($this));
321 return $this->update($orig);
324 function getBestName()
326 return ($this->fullname) ? $this->fullname : $this->nickname;
330 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
331 * if no fullname is provided.
335 function getFancyName()
337 if ($this->fullname) {
338 // TRANS: Full name of a profile or group followed by nickname in parens
339 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
341 return $this->nickname;
345 function getAliases()
351 $alias = new Group_alias();
353 $alias->group_id = $this->id;
355 if ($alias->find()) {
356 while ($alias->fetch()) {
357 $aliases[] = $alias->alias;
366 function setAliases($newaliases) {
368 $newaliases = array_unique($newaliases);
370 $oldaliases = $this->getAliases();
372 // Delete stuff that's old that not in new
374 $to_delete = array_diff($oldaliases, $newaliases);
376 // Insert stuff that's in new and not in old
378 $to_insert = array_diff($newaliases, $oldaliases);
380 $alias = new Group_alias();
382 $alias->group_id = $this->id;
384 foreach ($to_delete as $delalias) {
385 $alias->alias = $delalias;
386 $result = $alias->delete();
388 common_log_db_error($alias, 'DELETE', __FILE__);
393 foreach ($to_insert as $insalias) {
394 $alias->alias = $insalias;
395 $result = $alias->insert();
397 common_log_db_error($alias, 'INSERT', __FILE__);
405 static function getForNickname($nickname, $profile=null)
407 $nickname = common_canonical_nickname($nickname);
409 // Are there any matching remote groups this profile's in?
411 $group = $profile->getGroups();
412 while ($group->fetch()) {
413 if ($group->nickname == $nickname) {
414 // @fixme is this the best way?
415 return clone($group);
420 // If not, check local groups.
422 $group = Local_group::staticGet('nickname', $nickname);
423 if (!empty($group)) {
424 return User_group::staticGet('id', $group->group_id);
426 $alias = Group_alias::staticGet('alias', $nickname);
427 if (!empty($alias)) {
428 return User_group::staticGet('id', $alias->group_id);
433 function getUserMembers()
438 if(common_config('db','quote_identifiers'))
439 $user_table = '"user"';
440 else $user_table = 'user';
444 'FROM '. $user_table .' JOIN group_member '.
445 'ON '. $user_table .'.id = group_member.profile_id ' .
446 'WHERE group_member.group_id = %d ';
448 $user->query(sprintf($qry, $this->id));
452 while ($user->fetch()) {
461 static function maxDescription()
463 $desclimit = common_config('group', 'desclimit');
464 // null => use global limit (distinct from 0!)
465 if (is_null($desclimit)) {
466 $desclimit = common_config('site', 'textlimit');
471 static function descriptionTooLong($desc)
473 $desclimit = self::maxDescription();
474 return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
477 function asAtomEntry($namespace=false, $source=false)
479 $xs = new XMLStringer(true);
482 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
483 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
488 $xs->elementStart('entry', $attrs);
491 $xs->elementStart('source');
492 $xs->element('id', null, $this->permalink());
493 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
494 $xs->element('link', array('href' => $this->permalink()));
495 $xs->element('updated', null, $this->modified);
496 $xs->elementEnd('source');
499 $xs->element('title', null, $this->nickname);
500 $xs->element('summary', null, common_xml_safe_str($this->description));
502 $xs->element('link', array('rel' => 'alternate',
503 'href' => $this->permalink()));
505 $xs->element('id', null, $this->permalink());
507 $xs->element('published', null, common_date_w3dtf($this->created));
508 $xs->element('updated', null, common_date_w3dtf($this->modified));
512 array('type' => 'html'),
513 common_xml_safe_str($this->description)
516 $xs->elementEnd('entry');
518 return $xs->getString();
521 function asAtomAuthor()
523 $xs = new XMLStringer(true);
525 $xs->elementStart('author');
526 $xs->element('name', null, $this->nickname);
527 $xs->element('uri', null, $this->permalink());
528 $xs->elementEnd('author');
530 return $xs->getString();
534 * Returns an XML string fragment with group information as an
535 * Activity Streams <activity:subject> element.
537 * Assumes that 'activity' namespace has been previously defined.
541 function asActivitySubject()
543 return $this->asActivityNoun('subject');
547 * Returns an XML string fragment with group information as an
548 * Activity Streams noun object with the given element type.
550 * Assumes that 'activity', 'georss', and 'poco' namespace has been
551 * previously defined.
553 * @param string $element one of 'actor', 'subject', 'object', 'target'
557 function asActivityNoun($element)
559 $noun = ActivityObject::fromGroup($this);
560 return $noun->asString('activity:' . $element);
565 return empty($this->homepage_logo)
566 ? User_group::defaultLogo(AVATAR_PROFILE_SIZE)
567 : $this->homepage_logo;
570 static function register($fields) {
571 if (!empty($fields['userid'])) {
572 $profile = Profile::staticGet('id', $fields['userid']);
573 if ($profile && !$profile->hasRight(Right::CREATEGROUP)) {
574 common_log(LOG_WARNING, "Attempted group creation from banned user: " . $profile->nickname);
576 // TRANS: Client exception thrown when a user tries to create a group while banned.
577 throw new ClientException(_('You are not allowed to create groups on this site.'), 403);
581 // MAGICALLY put fields into current scope
582 // @fixme kill extract(); it makes debugging absurdly hard
584 $defaults = array('nickname' => null,
587 'description' => null,
591 'aliases' => array(),
594 $fields = array_merge($defaults, $fields);
598 $group = new User_group();
600 $group->query('BEGIN');
606 if (empty($mainpage)) {
607 $mainpage = common_local_url('showgroup', array('nickname' => $nickname));
610 $group->nickname = $nickname;
611 $group->fullname = $fullname;
612 $group->homepage = $homepage;
613 $group->description = $description;
614 $group->location = $location;
616 $group->mainpage = $mainpage;
617 $group->created = common_sql_now();
619 if (isset($fields['join_policy'])) {
620 $group->join_policy = intval($fields['join_policy']);
622 $group->join_policy = 0;
625 if (isset($fields['force_scope'])) {
626 $group->force_scope = intval($fields['force_scope']);
628 $group->force_scope = 0;
631 if (Event::handle('StartGroupSave', array(&$group))) {
633 $result = $group->insert();
636 common_log_db_error($group, 'INSERT', __FILE__);
637 // TRANS: Server exception thrown when creating a group failed.
638 throw new ServerException(_('Could not create group.'));
641 if (!isset($uri) || empty($uri)) {
642 $orig = clone($group);
643 $group->uri = common_local_url('groupbyid', array('id' => $group->id));
644 $result = $group->update($orig);
646 common_log_db_error($group, 'UPDATE', __FILE__);
647 // TRANS: Server exception thrown when updating a group URI failed.
648 throw new ServerException(_('Could not set group URI.'));
652 $result = $group->setAliases($aliases);
655 // TRANS: Server exception thrown when creating group aliases failed.
656 throw new ServerException(_('Could not create aliases.'));
659 $member = new Group_member();
661 $member->group_id = $group->id;
662 $member->profile_id = $userid;
663 $member->is_admin = 1;
664 $member->created = $group->created;
666 $result = $member->insert();
669 common_log_db_error($member, 'INSERT', __FILE__);
670 // TRANS: Server exception thrown when setting group membership failed.
671 throw new ServerException(_('Could not set group membership.'));
674 self::blow('profile:groups:%d', $userid);
677 $local_group = new Local_group();
679 $local_group->group_id = $group->id;
680 $local_group->nickname = $nickname;
681 $local_group->created = common_sql_now();
683 $result = $local_group->insert();
686 common_log_db_error($local_group, 'INSERT', __FILE__);
687 // TRANS: Server exception thrown when saving local group information failed.
688 throw new ServerException(_('Could not save local group info.'));
692 $group->query('COMMIT');
694 Event::handle('EndGroupSave', array($group));
701 * Handle cascading deletion, on the model of notice and profile.
703 * This should handle freeing up cached entries for the group's
704 * id, nickname, URI, and aliases. There may be other areas that
705 * are not de-cached in the UI, including the sidebar lists on
712 // Safe to delete in bulk for now
714 $related = array('Group_inbox',
719 Event::handle('UserGroupDeleteRelated', array($this, &$related));
721 foreach ($related as $cls) {
724 $inst->group_id = $this->id;
727 while ($inst->fetch()) {
734 // And related groups in the other direction...
735 $inst = new Related_group();
736 $inst->related_group_id = $this->id;
739 // Aliases and the local_group entry need to be cleared explicitly
740 // or we'll miss clearing some cache keys; that can make it hard
741 // to create a new group with one of those names or aliases.
742 $this->setAliases(array());
743 $local = Local_group::staticGet('group_id', $this->id);
748 // blow the cached ids
749 self::blow('user_group:notice_ids:%d', $this->id);
752 common_log(LOG_WARN, "Ambiguous user_group->delete(); skipping related tables.");
759 return ($this->join_policy == self::JOIN_POLICY_MODERATE &&
760 $this->force_scope == 1);