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