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