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