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