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