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