]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/User_group.php
Merge branch '1.1.x'
[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         $ids = null;
147         if (is_null($limit) || $offset + $limit > User_group::CACHE_WINDOW) {
148             $ids = $this->getMemberIDs($offset,
149                                        $limit);
150         } else {
151             $key = sprintf('group:member_ids:%d', $this->id);
152             $window = self::cacheGet($key);
153             if ($window === false) {
154                 $window = $this->getMemberIDs(0,
155                                               User_group::CACHE_WINDOW);
156                 self::cacheSet($key, $window);
157             }
158
159             $ids = array_slice($window,
160                                $offset,
161                                $limit);
162         }
163
164         return Profile::multiGet('id', $ids);
165     }
166
167     function getMemberIDs($offset=0, $limit=null)
168     {
169         $gm = new Group_member();
170
171         $gm->selectAdd();
172         $gm->selectAdd('profile_id');
173
174         $gm->group_id = $this->id;
175
176         $gm->orderBy('created DESC');
177
178         if (!is_null($limit)) {
179             $gm->limit($offset, $limit);
180         }
181
182         $ids = array();
183
184         if ($gm->find()) {
185             while ($gm->fetch()) {
186                 $ids[] = $gm->profile_id;
187             }
188         }
189
190         return $ids;
191     }
192
193     /**
194      * Get pending members, who have not yet been approved.
195      *
196      * @param int $offset
197      * @param int $limit
198      * @return Profile
199      */
200     function getRequests($offset=0, $limit=null)
201     {
202         $qry =
203           'SELECT profile.* ' .
204           'FROM profile JOIN group_join_queue '.
205           'ON profile.id = group_join_queue.profile_id ' .
206           'WHERE group_join_queue.group_id = %d ' .
207           'ORDER BY group_join_queue.created DESC ';
208
209         if ($limit != null) {
210             if (common_config('db','type') == 'pgsql') {
211                 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
212             } else {
213                 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
214             }
215         }
216
217         $members = new Profile();
218
219         $members->query(sprintf($qry, $this->id));
220         return $members;
221     }
222
223     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();
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::staticGet('nickname', $nickname);
424         if (!empty($group)) {
425             return User_group::staticGet('id', $group->group_id);
426         }
427         $alias = Group_alias::staticGet('alias', $nickname);
428         if (!empty($alias)) {
429             return User_group::staticGet('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 <activity:subject> element.
537      *
538      * Assumes that 'activity' namespace has been previously defined.
539      *
540      * @return string
541      */
542     function asActivitySubject()
543     {
544         return $this->asActivityNoun('subject');
545     }
546
547     /**
548      * Returns an XML string fragment with group information as an
549      * Activity Streams noun object with the given element type.
550      *
551      * Assumes that 'activity', 'georss', and 'poco' namespace has been
552      * previously defined.
553      *
554      * @param string $element one of 'actor', 'subject', 'object', 'target'
555      *
556      * @return string
557      */
558     function asActivityNoun($element)
559     {
560         $noun = ActivityObject::fromGroup($this);
561         return $noun->asString('activity:' . $element);
562     }
563
564     function getAvatar()
565     {
566         return empty($this->homepage_logo)
567             ? User_group::defaultLogo(AVATAR_PROFILE_SIZE)
568             : $this->homepage_logo;
569     }
570
571     static function register($fields) {
572         if (!empty($fields['userid'])) {
573             $profile = Profile::staticGet('id', $fields['userid']);
574             if ($profile && !$profile->hasRight(Right::CREATEGROUP)) {
575                 common_log(LOG_WARNING, "Attempted group creation from banned user: " . $profile->nickname);
576
577                 // TRANS: Client exception thrown when a user tries to create a group while banned.
578                 throw new ClientException(_('You are not allowed to create groups on this site.'), 403);
579             }
580         }
581
582         // MAGICALLY put fields into current scope
583         // @fixme kill extract(); it makes debugging absurdly hard
584
585                 $defaults = array('nickname' => null,
586                                                   'fullname' => null,
587                                                   'homepage' => null,
588                                                   'description' => null,
589                                                   'location' => null,
590                                                   'uri' => null,
591                                                   'mainpage' => null,
592                                                   'aliases' => array(),
593                                                   'userid' => null);
594                 
595                 $fields = array_merge($defaults, $fields);
596                 
597         extract($fields);
598
599         $group = new User_group();
600
601         $group->query('BEGIN');
602
603         if (empty($uri)) {
604             // fill in later...
605             $uri = null;
606         }
607         if (empty($mainpage)) {
608             $mainpage = common_local_url('showgroup', array('nickname' => $nickname));
609         }
610
611         $group->nickname    = $nickname;
612         $group->fullname    = $fullname;
613         $group->homepage    = $homepage;
614         $group->description = $description;
615         $group->location    = $location;
616         $group->uri         = $uri;
617         $group->mainpage    = $mainpage;
618         $group->created     = common_sql_now();
619
620         if (isset($fields['join_policy'])) {
621             $group->join_policy = intval($fields['join_policy']);
622         } else {
623             $group->join_policy = 0;
624         }
625
626         if (isset($fields['force_scope'])) {
627             $group->force_scope = intval($fields['force_scope']);
628         } else {
629             $group->force_scope = 0;
630         }
631
632         if (Event::handle('StartGroupSave', array(&$group))) {
633
634             $result = $group->insert();
635
636             if (!$result) {
637                 common_log_db_error($group, 'INSERT', __FILE__);
638                 // TRANS: Server exception thrown when creating a group failed.
639                 throw new ServerException(_('Could not create group.'));
640             }
641
642             if (!isset($uri) || empty($uri)) {
643                 $orig = clone($group);
644                 $group->uri = common_local_url('groupbyid', array('id' => $group->id));
645                 $result = $group->update($orig);
646                 if (!$result) {
647                     common_log_db_error($group, 'UPDATE', __FILE__);
648                     // TRANS: Server exception thrown when updating a group URI failed.
649                     throw new ServerException(_('Could not set group URI.'));
650                 }
651             }
652
653             $result = $group->setAliases($aliases);
654
655             if (!$result) {
656                 // TRANS: Server exception thrown when creating group aliases failed.
657                 throw new ServerException(_('Could not create aliases.'));
658             }
659
660             $member = new Group_member();
661
662             $member->group_id   = $group->id;
663             $member->profile_id = $userid;
664             $member->is_admin   = 1;
665             $member->created    = $group->created;
666
667             $result = $member->insert();
668
669             if (!$result) {
670                 common_log_db_error($member, 'INSERT', __FILE__);
671                 // TRANS: Server exception thrown when setting group membership failed.
672                 throw new ServerException(_('Could not set group membership.'));
673             }
674
675             self::blow('profile:groups:%d', $userid);
676             
677             if ($local) {
678                 $local_group = new Local_group();
679
680                 $local_group->group_id = $group->id;
681                 $local_group->nickname = $nickname;
682                 $local_group->created  = common_sql_now();
683
684                 $result = $local_group->insert();
685
686                 if (!$result) {
687                     common_log_db_error($local_group, 'INSERT', __FILE__);
688                     // TRANS: Server exception thrown when saving local group information failed.
689                     throw new ServerException(_('Could not save local group info.'));
690                 }
691             }
692
693             $group->query('COMMIT');
694
695             Event::handle('EndGroupSave', array($group));
696         }
697
698         return $group;
699     }
700
701     /**
702      * Handle cascading deletion, on the model of notice and profile.
703      *
704      * This should handle freeing up cached entries for the group's
705      * id, nickname, URI, and aliases. There may be other areas that
706      * are not de-cached in the UI, including the sidebar lists on
707      * GroupsAction
708      */
709     function delete()
710     {
711         if ($this->id) {
712
713             // Safe to delete in bulk for now
714
715             $related = array('Group_inbox',
716                              'Group_block',
717                              'Group_member',
718                              'Related_group');
719
720             Event::handle('UserGroupDeleteRelated', array($this, &$related));
721
722             foreach ($related as $cls) {
723
724                 $inst = new $cls();
725                 $inst->group_id = $this->id;
726
727                 if ($inst->find()) {
728                     while ($inst->fetch()) {
729                         $dup = clone($inst);
730                         $dup->delete();
731                     }
732                 }
733             }
734
735             // And related groups in the other direction...
736             $inst = new Related_group();
737             $inst->related_group_id = $this->id;
738             $inst->delete();
739
740             // Aliases and the local_group entry need to be cleared explicitly
741             // or we'll miss clearing some cache keys; that can make it hard
742             // to create a new group with one of those names or aliases.
743             $this->setAliases(array());
744             $local = Local_group::staticGet('group_id', $this->id);
745             if ($local) {
746                 $local->delete();
747             }
748
749             // blow the cached ids
750             self::blow('user_group:notice_ids:%d', $this->id);
751
752         } else {
753             common_log(LOG_WARN, "Ambiguous user_group->delete(); skipping related tables.");
754         }
755         parent::delete();
756     }
757
758     function isPrivate()
759     {
760         return ($this->join_policy == self::JOIN_POLICY_MODERATE &&
761                 $this->force_scope == 1);
762     }
763 }