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