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