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