]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/User_group.php
Pending members queue list -- doesn't yet allow approval.
[quix0rs-gnu-social.git] / classes / User_group.php
1 <?php
2 /**
3  * Table Definition for user_group
4  */
5
6 class User_group extends Memcached_DataObject
7 {
8     const JOIN_POLICY_OPEN = 0;
9     const JOIN_POLICY_MODERATE = 1;
10
11     ###START_AUTOCODE
12     /* the code below is auto generated do not remove the above tag */
13
14     public $__table = 'user_group';                      // table name
15     public $id;                              // int(4)  primary_key not_null
16     public $nickname;                        // varchar(64)
17     public $fullname;                        // varchar(255)
18     public $homepage;                        // varchar(255)
19     public $description;                     // text
20     public $location;                        // varchar(255)
21     public $original_logo;                   // varchar(255)
22     public $homepage_logo;                   // varchar(255)
23     public $stream_logo;                     // varchar(255)
24     public $mini_logo;                       // varchar(255)
25     public $design_id;                       // int(4)
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
32     /* Static get */
33     function staticGet($k,$v=NULL) { return DB_DataObject::staticGet('User_group',$k,$v); }
34
35     /* the code above is auto generated do not remove the tag below */
36     ###END_AUTOCODE
37
38     function defaultLogo($size)
39     {
40         static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
41                                   AVATAR_STREAM_SIZE => 'stream',
42                                   AVATAR_MINI_SIZE => 'mini');
43         return Theme::path('default-avatar-'.$sizenames[$size].'.png');
44     }
45
46     function homeUrl()
47     {
48         $url = null;
49         if (Event::handle('StartUserGroupHomeUrl', array($this, &$url))) {
50             // normally stored in mainpage, but older ones may be null
51             if (!empty($this->mainpage)) {
52                 $url = $this->mainpage;
53             } else {
54                 $url = common_local_url('showgroup',
55                                         array('nickname' => $this->nickname));
56             }
57         }
58         Event::handle('EndUserGroupHomeUrl', array($this, &$url));
59         return $url;
60     }
61
62     function getUri()
63     {
64         $uri = null;
65         if (Event::handle('StartUserGroupGetUri', array($this, &$uri))) {
66             if (!empty($this->uri)) {
67                 $uri = $this->uri;
68             } else {
69                 $uri = common_local_url('groupbyid',
70                                         array('id' => $this->id));
71             }
72         }
73         Event::handle('EndUserGroupGetUri', array($this, &$uri));
74         return $uri;
75     }
76
77     function permalink()
78     {
79         $url = null;
80         if (Event::handle('StartUserGroupPermalink', array($this, &$url))) {
81             $url = common_local_url('groupbyid',
82                                     array('id' => $this->id));
83         }
84         Event::handle('EndUserGroupPermalink', array($this, &$url));
85         return $url;
86     }
87
88     function getNotices($offset, $limit, $since_id=null, $max_id=null)
89     {
90         $ids = Notice::stream(array($this, '_streamDirect'),
91                               array(),
92                               'user_group:notice_ids:' . $this->id,
93                               $offset, $limit, $since_id, $max_id);
94
95         return Notice::getStreamByIds($ids);
96     }
97
98     function _streamDirect($offset, $limit, $since_id, $max_id)
99     {
100         $inbox = new Group_inbox();
101
102         $inbox->group_id = $this->id;
103
104         $inbox->selectAdd();
105         $inbox->selectAdd('notice_id');
106
107         Notice::addWhereSinceId($inbox, $since_id, 'notice_id');
108         Notice::addWhereMaxId($inbox, $max_id, 'notice_id');
109
110         $inbox->orderBy('created DESC, notice_id DESC');
111
112         if (!is_null($offset)) {
113             $inbox->limit($offset, $limit);
114         }
115
116         $ids = array();
117
118         if ($inbox->find()) {
119             while ($inbox->fetch()) {
120                 $ids[] = $inbox->notice_id;
121             }
122         }
123
124         return $ids;
125     }
126
127     function allowedNickname($nickname)
128     {
129         static $blacklist = array('new');
130         return !in_array($nickname, $blacklist);
131     }
132
133     function getMembers($offset=0, $limit=null)
134     {
135         $qry =
136           'SELECT profile.* ' .
137           'FROM profile JOIN group_member '.
138           'ON profile.id = group_member.profile_id ' .
139           'WHERE group_member.group_id = %d ' .
140           'ORDER BY group_member.created DESC ';
141
142         if ($limit != null) {
143             if (common_config('db','type') == 'pgsql') {
144                 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
145             } else {
146                 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
147             }
148         }
149
150         $members = new Profile();
151
152         $members->query(sprintf($qry, $this->id));
153         return $members;
154     }
155
156     /**
157      * Get pending members, who have not yet been approved.
158      *
159      * @param int $offset
160      * @param int $limit
161      * @return Profile
162      */
163     function getRequests($offset=0, $limit=null)
164     {
165         $qry =
166           'SELECT profile.* ' .
167           'FROM profile JOIN group_join_queue '.
168           'ON profile.id = group_join_queue.profile_id ' .
169           'WHERE group_join_queue.group_id = %d ' .
170           'ORDER BY group_join_queue.created DESC ';
171
172         if ($limit != null) {
173             if (common_config('db','type') == 'pgsql') {
174                 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
175             } else {
176                 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
177             }
178         }
179
180         $members = new Profile();
181
182         $members->query(sprintf($qry, $this->id));
183         return $members;
184     }
185
186     function getMemberCount()
187     {
188         // XXX: WORM cache this
189
190         $members = $this->getMembers();
191         $member_count = 0;
192
193         /** $member->count() doesn't work. */
194         while ($members->fetch()) {
195             $member_count++;
196         }
197
198         return $member_count;
199     }
200
201     function getAdmins($offset=0, $limit=null)
202     {
203         $qry =
204           'SELECT profile.* ' .
205           'FROM profile JOIN group_member '.
206           'ON profile.id = group_member.profile_id ' .
207           'WHERE group_member.group_id = %d ' .
208           'AND group_member.is_admin = 1 ' .
209           'ORDER BY group_member.modified ASC ';
210
211         if ($limit != null) {
212             if (common_config('db','type') == 'pgsql') {
213                 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
214             } else {
215                 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
216             }
217         }
218
219         $admins = new Profile();
220
221         $admins->query(sprintf($qry, $this->id));
222         return $admins;
223     }
224
225     function getBlocked($offset=0, $limit=null)
226     {
227         $qry =
228           'SELECT profile.* ' .
229           'FROM profile JOIN group_block '.
230           'ON profile.id = group_block.blocked ' .
231           'WHERE group_block.group_id = %d ' .
232           'ORDER BY group_block.modified DESC ';
233
234         if ($limit != null) {
235             if (common_config('db','type') == 'pgsql') {
236                 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
237             } else {
238                 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
239             }
240         }
241
242         $blocked = new Profile();
243
244         $blocked->query(sprintf($qry, $this->id));
245         return $blocked;
246     }
247
248     function setOriginal($filename)
249     {
250         $imagefile = new ImageFile($this->id, Avatar::path($filename));
251
252         $orig = clone($this);
253         $this->original_logo = Avatar::url($filename);
254         $this->homepage_logo = Avatar::url($imagefile->resize(AVATAR_PROFILE_SIZE));
255         $this->stream_logo = Avatar::url($imagefile->resize(AVATAR_STREAM_SIZE));
256         $this->mini_logo = Avatar::url($imagefile->resize(AVATAR_MINI_SIZE));
257         common_debug(common_log_objstring($this));
258         return $this->update($orig);
259     }
260
261     function getBestName()
262     {
263         return ($this->fullname) ? $this->fullname : $this->nickname;
264     }
265
266     /**
267      * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
268      * if no fullname is provided.
269      *
270      * @return string
271      */
272     function getFancyName()
273     {
274         if ($this->fullname) {
275             // TRANS: Full name of a profile or group followed by nickname in parens
276             return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
277         } else {
278             return $this->nickname;
279         }
280     }
281
282     function getAliases()
283     {
284         $aliases = array();
285
286         // XXX: cache this
287
288         $alias = new Group_alias();
289
290         $alias->group_id = $this->id;
291
292         if ($alias->find()) {
293             while ($alias->fetch()) {
294                 $aliases[] = $alias->alias;
295             }
296         }
297
298         $alias->free();
299
300         return $aliases;
301     }
302
303     function setAliases($newaliases) {
304
305         $newaliases = array_unique($newaliases);
306
307         $oldaliases = $this->getAliases();
308
309         # Delete stuff that's old that not in new
310
311         $to_delete = array_diff($oldaliases, $newaliases);
312
313         # Insert stuff that's in new and not in old
314
315         $to_insert = array_diff($newaliases, $oldaliases);
316
317         $alias = new Group_alias();
318
319         $alias->group_id = $this->id;
320
321         foreach ($to_delete as $delalias) {
322             $alias->alias = $delalias;
323             $result = $alias->delete();
324             if (!$result) {
325                 common_log_db_error($alias, 'DELETE', __FILE__);
326                 return false;
327             }
328         }
329
330         foreach ($to_insert as $insalias) {
331             $alias->alias = $insalias;
332             $result = $alias->insert();
333             if (!$result) {
334                 common_log_db_error($alias, 'INSERT', __FILE__);
335                 return false;
336             }
337         }
338
339         return true;
340     }
341
342     static function getForNickname($nickname, $profile=null)
343     {
344         $nickname = common_canonical_nickname($nickname);
345
346         // Are there any matching remote groups this profile's in?
347         if ($profile) {
348             $group = $profile->getGroups();
349             while ($group->fetch()) {
350                 if ($group->nickname == $nickname) {
351                     // @fixme is this the best way?
352                     return clone($group);
353                 }
354             }
355         }
356
357         // If not, check local groups.
358
359         $group = Local_group::staticGet('nickname', $nickname);
360         if (!empty($group)) {
361             return User_group::staticGet('id', $group->group_id);
362         }
363         $alias = Group_alias::staticGet('alias', $nickname);
364         if (!empty($alias)) {
365             return User_group::staticGet('id', $alias->group_id);
366         }
367         return null;
368     }
369
370     function getDesign()
371     {
372         return Design::staticGet('id', $this->design_id);
373     }
374
375     function getUserMembers()
376     {
377         // XXX: cache this
378
379         $user = new User();
380         if(common_config('db','quote_identifiers'))
381             $user_table = '"user"';
382         else $user_table = 'user';
383
384         $qry =
385           'SELECT id ' .
386           'FROM '. $user_table .' JOIN group_member '.
387           'ON '. $user_table .'.id = group_member.profile_id ' .
388           'WHERE group_member.group_id = %d ';
389
390         $user->query(sprintf($qry, $this->id));
391
392         $ids = array();
393
394         while ($user->fetch()) {
395             $ids[] = $user->id;
396         }
397
398         $user->free();
399
400         return $ids;
401     }
402
403     static function maxDescription()
404     {
405         $desclimit = common_config('group', 'desclimit');
406         // null => use global limit (distinct from 0!)
407         if (is_null($desclimit)) {
408             $desclimit = common_config('site', 'textlimit');
409         }
410         return $desclimit;
411     }
412
413     static function descriptionTooLong($desc)
414     {
415         $desclimit = self::maxDescription();
416         return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
417     }
418
419     function asAtomEntry($namespace=false, $source=false)
420     {
421         $xs = new XMLStringer(true);
422
423         if ($namespace) {
424             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
425                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
426         } else {
427             $attrs = array();
428         }
429
430         $xs->elementStart('entry', $attrs);
431
432         if ($source) {
433             $xs->elementStart('source');
434             $xs->element('id', null, $this->permalink());
435             $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
436             $xs->element('link', array('href' => $this->permalink()));
437             $xs->element('updated', null, $this->modified);
438             $xs->elementEnd('source');
439         }
440
441         $xs->element('title', null, $this->nickname);
442         $xs->element('summary', null, common_xml_safe_str($this->description));
443
444         $xs->element('link', array('rel' => 'alternate',
445                                    'href' => $this->permalink()));
446
447         $xs->element('id', null, $this->permalink());
448
449         $xs->element('published', null, common_date_w3dtf($this->created));
450         $xs->element('updated', null, common_date_w3dtf($this->modified));
451
452         $xs->element(
453             'content',
454             array('type' => 'html'),
455             common_xml_safe_str($this->description)
456         );
457
458         $xs->elementEnd('entry');
459
460         return $xs->getString();
461     }
462
463     function asAtomAuthor()
464     {
465         $xs = new XMLStringer(true);
466
467         $xs->elementStart('author');
468         $xs->element('name', null, $this->nickname);
469         $xs->element('uri', null, $this->permalink());
470         $xs->elementEnd('author');
471
472         return $xs->getString();
473     }
474
475     /**
476      * Returns an XML string fragment with group information as an
477      * Activity Streams <activity:subject> element.
478      *
479      * Assumes that 'activity' namespace has been previously defined.
480      *
481      * @return string
482      */
483     function asActivitySubject()
484     {
485         return $this->asActivityNoun('subject');
486     }
487
488     /**
489      * Returns an XML string fragment with group information as an
490      * Activity Streams noun object with the given element type.
491      *
492      * Assumes that 'activity', 'georss', and 'poco' namespace has been
493      * previously defined.
494      *
495      * @param string $element one of 'actor', 'subject', 'object', 'target'
496      *
497      * @return string
498      */
499     function asActivityNoun($element)
500     {
501         $noun = ActivityObject::fromGroup($this);
502         return $noun->asString('activity:' . $element);
503     }
504
505     function getAvatar()
506     {
507         return empty($this->homepage_logo)
508             ? User_group::defaultLogo(AVATAR_PROFILE_SIZE)
509             : $this->homepage_logo;
510     }
511
512     static function register($fields) {
513         if (!empty($fields['userid'])) {
514             $profile = Profile::staticGet('id', $fields['userid']);
515             if ($profile && !$profile->hasRight(Right::CREATEGROUP)) {
516                 common_log(LOG_WARNING, "Attempted group creation from banned user: " . $profile->nickname);
517
518                 // TRANS: Client exception thrown when a user tries to create a group while banned.
519                 throw new ClientException(_('You are not allowed to create groups on this site.'), 403);
520             }
521         }
522
523         // MAGICALLY put fields into current scope
524         // @fixme kill extract(); it makes debugging absurdly hard
525
526         extract($fields);
527
528         $group = new User_group();
529
530         $group->query('BEGIN');
531
532         if (empty($uri)) {
533             // fill in later...
534             $uri = null;
535         }
536         if (empty($mainpage)) {
537             $mainpage = common_local_url('showgroup', array('nickname' => $nickname));
538         }
539
540         $group->nickname    = $nickname;
541         $group->fullname    = $fullname;
542         $group->homepage    = $homepage;
543         $group->description = $description;
544         $group->location    = $location;
545         $group->uri         = $uri;
546         $group->mainpage    = $mainpage;
547         $group->created     = common_sql_now();
548         if (isset($fields['join_policy'])) {
549             $group->join_policy = intval($fields['join_policy']);
550         } else {
551             $group->join_policy = 0;
552         }
553
554         if (Event::handle('StartGroupSave', array(&$group))) {
555
556             $result = $group->insert();
557
558             if (!$result) {
559                 common_log_db_error($group, 'INSERT', __FILE__);
560                 // TRANS: Server exception thrown when creating a group failed.
561                 throw new ServerException(_('Could not create group.'));
562             }
563
564             if (!isset($uri) || empty($uri)) {
565                 $orig = clone($group);
566                 $group->uri = common_local_url('groupbyid', array('id' => $group->id));
567                 $result = $group->update($orig);
568                 if (!$result) {
569                     common_log_db_error($group, 'UPDATE', __FILE__);
570                     // TRANS: Server exception thrown when updating a group URI failed.
571                     throw new ServerException(_('Could not set group URI.'));
572                 }
573             }
574
575             $result = $group->setAliases($aliases);
576
577             if (!$result) {
578                 // TRANS: Server exception thrown when creating group aliases failed.
579                 throw new ServerException(_('Could not create aliases.'));
580             }
581
582             $member = new Group_member();
583
584             $member->group_id   = $group->id;
585             $member->profile_id = $userid;
586             $member->is_admin   = 1;
587             $member->created    = $group->created;
588
589             $result = $member->insert();
590
591             if (!$result) {
592                 common_log_db_error($member, 'INSERT', __FILE__);
593                 // TRANS: Server exception thrown when setting group membership failed.
594                 throw new ServerException(_('Could not set group membership.'));
595             }
596
597             if ($local) {
598                 $local_group = new Local_group();
599
600                 $local_group->group_id = $group->id;
601                 $local_group->nickname = $nickname;
602                 $local_group->created  = common_sql_now();
603
604                 $result = $local_group->insert();
605
606                 if (!$result) {
607                     common_log_db_error($local_group, 'INSERT', __FILE__);
608                     // TRANS: Server exception thrown when saving local group information failed.
609                     throw new ServerException(_('Could not save local group info.'));
610                 }
611             }
612
613             $group->query('COMMIT');
614
615             Event::handle('EndGroupSave', array($group));
616         }
617
618         return $group;
619     }
620
621     /**
622      * Handle cascading deletion, on the model of notice and profile.
623      *
624      * This should handle freeing up cached entries for the group's
625      * id, nickname, URI, and aliases. There may be other areas that
626      * are not de-cached in the UI, including the sidebar lists on
627      * GroupsAction
628      */
629     function delete()
630     {
631         if ($this->id) {
632
633             // Safe to delete in bulk for now
634
635             $related = array('Group_inbox',
636                              'Group_block',
637                              'Group_member',
638                              'Related_group');
639
640             Event::handle('UserGroupDeleteRelated', array($this, &$related));
641
642             foreach ($related as $cls) {
643
644                 $inst = new $cls();
645                 $inst->group_id = $this->id;
646
647                 if ($inst->find()) {
648                     while ($inst->fetch()) {
649                         $dup = clone($inst);
650                         $dup->delete();
651                     }
652                 }
653             }
654
655             // And related groups in the other direction...
656             $inst = new Related_group();
657             $inst->related_group_id = $this->id;
658             $inst->delete();
659
660             // Aliases and the local_group entry need to be cleared explicitly
661             // or we'll miss clearing some cache keys; that can make it hard
662             // to create a new group with one of those names or aliases.
663             $this->setAliases(array());
664             $local = Local_group::staticGet('group_id', $this->id);
665             if ($local) {
666                 $local->delete();
667             }
668
669             // blow the cached ids
670             self::blow('user_group:notice_ids:%d', $this->id);
671
672         } else {
673             common_log(LOG_WARN, "Ambiguous user_group->delete(); skipping related tables.");
674         }
675         parent::delete();
676     }
677 }