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