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