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