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