]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/User.php
allowed_nickname blocks top level url router names
[quix0rs-gnu-social.git] / classes / User.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('STATUSNET') && !defined('LACONICA')) {
21     exit(1);
22 }
23
24 /**
25  * Table Definition for user
26  */
27
28 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
29 require_once 'Validate.php';
30
31 class User extends Memcached_DataObject
32 {
33     ###START_AUTOCODE
34     /* the code below is auto generated do not remove the above tag */
35
36     public $__table = 'user';                            // table name
37     public $id;                              // int(4)  primary_key not_null
38     public $nickname;                        // varchar(64)  unique_key
39     public $password;                        // varchar(255)
40     public $email;                           // varchar(255)  unique_key
41     public $incomingemail;                   // varchar(255)  unique_key
42     public $emailnotifysub;                  // tinyint(1)   default_1
43     public $emailnotifyfav;                  // tinyint(1)   default_1
44     public $emailnotifynudge;                // tinyint(1)   default_1
45     public $emailnotifymsg;                  // tinyint(1)   default_1
46     public $emailnotifyattn;                 // tinyint(1)   default_1
47     public $emailmicroid;                    // tinyint(1)   default_1
48     public $language;                        // varchar(50)
49     public $timezone;                        // varchar(50)
50     public $emailpost;                       // tinyint(1)   default_1
51     public $jabber;                          // varchar(255)  unique_key
52     public $jabbernotify;                    // tinyint(1)
53     public $jabberreplies;                   // tinyint(1)
54     public $jabbermicroid;                   // tinyint(1)   default_1
55     public $updatefrompresence;              // tinyint(1)
56     public $sms;                             // varchar(64)  unique_key
57     public $carrier;                         // int(4)
58     public $smsnotify;                       // tinyint(1)
59     public $smsreplies;                      // tinyint(1)
60     public $smsemail;                        // varchar(255)
61     public $uri;                             // varchar(255)  unique_key
62     public $autosubscribe;                   // tinyint(1)
63     public $urlshorteningservice;            // varchar(50)   default_ur1.ca
64     public $inboxed;                         // tinyint(1)
65     public $design_id;                       // int(4)
66     public $viewdesigns;                     // tinyint(1)   default_1
67     public $created;                         // datetime()   not_null
68     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
69
70     /* Static get */
71     function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('User',$k,$v); }
72
73     /* the code above is auto generated do not remove the tag below */
74     ###END_AUTOCODE
75
76     function getProfile()
77     {
78         return Profile::staticGet('id', $this->id);
79     }
80
81     function isSubscribed($other)
82     {
83         assert(!is_null($other));
84         // XXX: cache results of this query
85         $sub = Subscription::pkeyGet(array('subscriber' => $this->id,
86                                            'subscribed' => $other->id));
87         return (is_null($sub)) ? false : true;
88     }
89
90     // 'update' won't write key columns, so we have to do it ourselves.
91
92     function updateKeys(&$orig)
93     {
94         $parts = array();
95         foreach (array('nickname', 'email', 'jabber', 'incomingemail', 'sms', 'carrier', 'smsemail', 'language', 'timezone') as $k) {
96             if (strcmp($this->$k, $orig->$k) != 0) {
97                 $parts[] = $k . ' = ' . $this->_quote($this->$k);
98             }
99         }
100         if (count($parts) == 0) {
101             // No changes
102             return true;
103         }
104         $toupdate = implode(', ', $parts);
105
106         $table = common_database_tablename($this->tableName());
107         $qry = 'UPDATE ' . $table . ' SET ' . $toupdate .
108           ' WHERE id = ' . $this->id;
109         $orig->decache();
110         $result = $this->query($qry);
111         if ($result) {
112             $this->encache();
113         }
114         return $result;
115     }
116
117     function allowed_nickname($nickname)
118     {
119         // XXX: should already be validated for size, content, etc.
120
121         $blacklist = common_config('nickname', 'blacklist');
122
123         //all directory and file names should be blacklisted
124         $d = dir(INSTALLDIR);
125         while (false !== ($entry = $d->read())) {
126             $blacklist[]=$entry;
127         }
128         $d->close();
129
130         //all top level names in the router should be blacklisted
131         $router = Router::get();
132         foreach(array_keys($router->m->getPaths()) as $path){
133             if(preg_match('/^\/(.*?)[\/\?]/',$path,$matches)){
134                 $blacklist[]=$matches[1];
135             }
136         }
137         return !in_array($nickname, $blacklist);
138     }
139
140     function getCurrentNotice($dt=null)
141     {
142         $profile = $this->getProfile();
143         if (!$profile) {
144             return null;
145         }
146         return $profile->getCurrentNotice($dt);
147     }
148
149     function getCarrier()
150     {
151         return Sms_carrier::staticGet('id', $this->carrier);
152     }
153
154     function subscribeTo($other)
155     {
156         $sub = new Subscription();
157         $sub->subscriber = $this->id;
158         $sub->subscribed = $other->id;
159
160         $sub->created = common_sql_now(); // current time
161
162         if (!$sub->insert()) {
163             return false;
164         }
165
166         return true;
167     }
168
169     function hasBlocked($other)
170     {
171
172         $block = Profile_block::get($this->id, $other->id);
173
174         if (is_null($block)) {
175             $result = false;
176         } else {
177             $result = true;
178             $block->free();
179         }
180
181         return $result;
182     }
183
184     static function register($fields) {
185
186         // MAGICALLY put fields into current scope
187
188         extract($fields);
189
190         $profile = new Profile();
191
192         $profile->query('BEGIN');
193
194         $profile->nickname = $nickname;
195         $profile->profileurl = common_profile_url($nickname);
196
197         if (!empty($fullname)) {
198             $profile->fullname = $fullname;
199         }
200         if (!empty($homepage)) {
201             $profile->homepage = $homepage;
202         }
203         if (!empty($bio)) {
204             $profile->bio = $bio;
205         }
206         if (!empty($location)) {
207             $profile->location = $location;
208
209             $loc = Location::fromName($location);
210
211             if (!empty($loc)) {
212                 $profile->lat         = $loc->lat;
213                 $profile->lon         = $loc->lon;
214                 $profile->location_id = $loc->location_id;
215                 $profile->location_ns = $loc->location_ns;
216             }
217         }
218
219         $profile->created = common_sql_now();
220
221         $id = $profile->insert();
222
223         if (empty($id)) {
224             common_log_db_error($profile, 'INSERT', __FILE__);
225             return false;
226         }
227
228         $user = new User();
229
230         $user->id = $id;
231         $user->nickname = $nickname;
232
233         if (!empty($password)) { // may not have a password for OpenID users
234             $user->password = common_munge_password($password, $id);
235         }
236
237         // Users who respond to invite email have proven their ownership of that address
238
239         if (!empty($code)) {
240             $invite = Invitation::staticGet($code);
241             if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
242                 $user->email = $invite->address;
243             }
244         }
245
246         // This flag is ignored but still set to 1
247
248         $user->inboxed = 1;
249
250         $user->created = common_sql_now();
251         $user->uri = common_user_uri($user);
252
253         $result = $user->insert();
254
255         if (!$result) {
256             common_log_db_error($user, 'INSERT', __FILE__);
257             return false;
258         }
259
260         // Everyone is subscribed to themself
261
262         $subscription = new Subscription();
263         $subscription->subscriber = $user->id;
264         $subscription->subscribed = $user->id;
265         $subscription->created = $user->created;
266
267         $result = $subscription->insert();
268
269         if (!$result) {
270             common_log_db_error($subscription, 'INSERT', __FILE__);
271             return false;
272         }
273
274         if (!empty($email) && !$user->email) {
275
276             $confirm = new Confirm_address();
277             $confirm->code = common_confirmation_code(128);
278             $confirm->user_id = $user->id;
279             $confirm->address = $email;
280             $confirm->address_type = 'email';
281
282             $result = $confirm->insert();
283             if (!$result) {
284                 common_log_db_error($confirm, 'INSERT', __FILE__);
285                 return false;
286             }
287         }
288
289         if (!empty($code) && $user->email) {
290             $user->emailChanged();
291         }
292
293         // Default system subscription
294
295         $defnick = common_config('newuser', 'default');
296
297         if (!empty($defnick)) {
298             $defuser = User::staticGet('nickname', $defnick);
299             if (empty($defuser)) {
300                 common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
301                            __FILE__);
302             } else {
303                 $defsub = new Subscription();
304                 $defsub->subscriber = $user->id;
305                 $defsub->subscribed = $defuser->id;
306                 $defsub->created = $user->created;
307
308                 $result = $defsub->insert();
309
310                 if (!$result) {
311                     common_log_db_error($defsub, 'INSERT', __FILE__);
312                     return false;
313                 }
314             }
315         }
316
317         $profile->query('COMMIT');
318
319         if ($email && !$user->email) {
320             mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
321         }
322
323         // Welcome message
324
325         $welcome = common_config('newuser', 'welcome');
326
327         if (!empty($welcome)) {
328             $welcomeuser = User::staticGet('nickname', $welcome);
329             if (empty($welcomeuser)) {
330                 common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
331                            __FILE__);
332             } else {
333                 $notice = Notice::saveNew($welcomeuser->id,
334                                           sprintf(_('Welcome to %1$s, @%2$s!'),
335                                                   common_config('site', 'name'),
336                                                   $user->nickname),
337                                           'system');
338                 common_broadcast_notice($notice);
339             }
340         }
341
342         return $user;
343     }
344
345     // Things we do when the email changes
346
347     function emailChanged()
348     {
349
350         $invites = new Invitation();
351         $invites->address = $this->email;
352         $invites->address_type = 'email';
353
354         if ($invites->find()) {
355             while ($invites->fetch()) {
356                 $other = User::staticGet($invites->user_id);
357                 subs_subscribe_to($other, $this);
358             }
359         }
360     }
361
362     function hasFave($notice)
363     {
364         $cache = common_memcache();
365
366         // XXX: Kind of a hack.
367
368         if ($cache) {
369             // This is the stream of favorite notices, in rev chron
370             // order. This forces it into cache.
371
372             $ids = Fave::stream($this->id, 0, NOTICE_CACHE_WINDOW);
373
374             // If it's in the list, then it's a fave
375
376             if (in_array($notice->id, $ids)) {
377                 return true;
378             }
379
380             // If we're not past the end of the cache window,
381             // then the cache has all available faves, so this one
382             // is not a fave.
383
384             if (count($ids) < NOTICE_CACHE_WINDOW) {
385                 return false;
386             }
387
388             // Otherwise, cache doesn't have all faves;
389             // fall through to the default
390         }
391
392         $fave = Fave::pkeyGet(array('user_id' => $this->id,
393                                     'notice_id' => $notice->id));
394         return ((is_null($fave)) ? false : true);
395     }
396
397     function mutuallySubscribed($other)
398     {
399         return $this->isSubscribed($other) &&
400           $other->isSubscribed($this);
401     }
402
403     function mutuallySubscribedUsers()
404     {
405         // 3-way join; probably should get cached
406         $UT = common_config('db','type')=='pgsql'?'"user"':'user';
407         $qry = "SELECT $UT.* " .
408           "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
409           "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
410           'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
411           "ORDER BY $UT.nickname";
412         $user = new User();
413         $user->query(sprintf($qry, $this->id, $this->id));
414
415         return $user;
416     }
417
418     function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
419     {
420         $ids = Reply::stream($this->id, $offset, $limit, $since_id, $before_id, $since);
421         return Notice::getStreamByIds($ids);
422     }
423
424     function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null) {
425         $profile = $this->getProfile();
426         if (!$profile) {
427             return null;
428         } else {
429             return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id, $since);
430         }
431     }
432
433     function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
434     {
435         $profile = $this->getProfile();
436         if (!$profile) {
437             return null;
438         } else {
439             return $profile->getNotices($offset, $limit, $since_id, $before_id, $since);
440         }
441     }
442
443     function favoriteNotices($offset=0, $limit=NOTICES_PER_PAGE, $own=false)
444     {
445         $ids = Fave::stream($this->id, $offset, $limit, $own);
446         return Notice::getStreamByIds($ids);
447     }
448
449     function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
450     {
451         $ids = Notice_inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, false);
452
453         return Notice::getStreamByIds($ids);
454     }
455
456     function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
457     {
458         $ids = Notice_inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, true);
459
460         return Notice::getStreamByIds($ids);
461     }
462
463     function blowFavesCache()
464     {
465         $cache = common_memcache();
466         if ($cache) {
467             // Faves don't happen chronologically, so we need to blow
468             // ;last cache, too
469             $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id));
470             $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id.';last'));
471             $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id));
472             $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id.';last'));
473         }
474         $profile = $this->getProfile();
475         $profile->blowFaveCount();
476     }
477
478     function getSelfTags()
479     {
480         return Profile_tag::getTags($this->id, $this->id);
481     }
482
483     function setSelfTags($newtags)
484     {
485         return Profile_tag::setTags($this->id, $this->id, $newtags);
486     }
487
488     function block($other)
489     {
490         // Add a new block record
491
492         $block = new Profile_block();
493
494         // Begin a transaction
495
496         $block->query('BEGIN');
497
498         $block->blocker = $this->id;
499         $block->blocked = $other->id;
500
501         $result = $block->insert();
502
503         if (!$result) {
504             common_log_db_error($block, 'INSERT', __FILE__);
505             return false;
506         }
507
508         // Cancel their subscription, if it exists
509
510         $sub = Subscription::pkeyGet(array('subscriber' => $other->id,
511                                            'subscribed' => $this->id));
512
513         if ($sub) {
514             $result = $sub->delete();
515             if (!$result) {
516                 common_log_db_error($sub, 'DELETE', __FILE__);
517                 return false;
518             }
519         }
520
521         $block->query('COMMIT');
522
523         return true;
524     }
525
526     function unblock($other)
527     {
528         // Get the block record
529
530         $block = Profile_block::get($this->id, $other->id);
531
532         if (!$block) {
533             return false;
534         }
535
536         $result = $block->delete();
537
538         if (!$result) {
539             common_log_db_error($block, 'DELETE', __FILE__);
540             return false;
541         }
542
543         return true;
544     }
545
546     function isMember($group)
547     {
548         $profile = $this->getProfile();
549         return $profile->isMember($group);
550     }
551
552     function isAdmin($group)
553     {
554         $profile = $this->getProfile();
555         return $profile->isAdmin($group);
556     }
557
558     function getGroups($offset=0, $limit=null)
559     {
560         $qry =
561           'SELECT user_group.* ' .
562           'FROM user_group JOIN group_member '.
563           'ON user_group.id = group_member.group_id ' .
564           'WHERE group_member.profile_id = %d ' .
565           'ORDER BY group_member.created DESC ';
566
567         if ($offset) {
568             if (common_config('db','type') == 'pgsql') {
569                 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
570             } else {
571                 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
572             }
573         }
574
575         $groups = new User_group();
576
577         $cnt = $groups->query(sprintf($qry, $this->id));
578
579         return $groups;
580     }
581
582     function getSubscriptions($offset=0, $limit=null)
583     {
584         $profile = $this->getProfile();
585         assert(!empty($profile));
586         return $profile->getSubscriptions($offset, $limit);
587     }
588
589     function getSubscribers($offset=0, $limit=null)
590     {
591         $profile = $this->getProfile();
592         assert(!empty($profile));
593         return $profile->getSubscribers($offset, $limit);
594     }
595
596     function getTaggedSubscribers($tag, $offset=0, $limit=null)
597     {
598         $qry =
599           'SELECT profile.* ' .
600           'FROM profile JOIN subscription ' .
601           'ON profile.id = subscription.subscriber ' .
602           'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
603           'AND profile_tag.tagger = subscription.subscribed) ' .
604           'WHERE subscription.subscribed = %d ' .
605           "AND profile_tag.tag = '%s' " .
606           'AND subscription.subscribed != subscription.subscriber ' .
607           'ORDER BY subscription.created DESC ';
608
609         if ($offset) {
610             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
611         }
612
613         $profile = new Profile();
614
615         $cnt = $profile->query(sprintf($qry, $this->id, $tag));
616
617         return $profile;
618     }
619
620     function getTaggedSubscriptions($tag, $offset=0, $limit=null)
621     {
622         $qry =
623           'SELECT profile.* ' .
624           'FROM profile JOIN subscription ' .
625           'ON profile.id = subscription.subscribed ' .
626           'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
627           'AND profile_tag.tagger = subscription.subscriber) ' .
628           'WHERE subscription.subscriber = %d ' .
629           "AND profile_tag.tag = '%s' " .
630           'AND subscription.subscribed != subscription.subscriber ' .
631           'ORDER BY subscription.created DESC ';
632
633         $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
634
635         $profile = new Profile();
636
637         $profile->query(sprintf($qry, $this->id, $tag));
638
639         return $profile;
640     }
641
642     function getDesign()
643     {
644         return Design::staticGet('id', $this->design_id);
645     }
646
647     function hasRole($name)
648     {
649         $role = User_role::pkeyGet(array('user_id' => $this->id,
650                                          'role' => $name));
651         return (!empty($role));
652     }
653
654     function grantRole($name)
655     {
656         $role = new User_role();
657
658         $role->user_id = $this->id;
659         $role->role    = $name;
660         $role->created = common_sql_now();
661
662         $result = $role->insert();
663
664         if (!$result) {
665             common_log_db_error($role, 'INSERT', __FILE__);
666             return false;
667         }
668
669         return true;
670     }
671
672     function revokeRole($name)
673     {
674         $role = User_role::pkeyGet(array('user_id' => $this->id,
675                                          'role' => $name));
676
677         if (empty($role)) {
678             throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; does not exist.');
679         }
680
681         $result = $role->delete();
682
683         if (!$result) {
684             common_log_db_error($role, 'DELETE', __FILE__);
685             throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; database error.');
686         }
687
688         return true;
689     }
690
691     /**
692      * Does this user have the right to do X?
693      *
694      * With our role-based authorization, this is merely a lookup for whether the user
695      * has a particular role. The implementation currently uses a switch statement
696      * to determine if the user has the pre-defined role to exercise the right. Future
697      * implementations may allow per-site roles, and different mappings of roles to rights.
698      *
699      * @param $right string Name of the right, usually a constant in class Right
700      * @return boolean whether the user has the right in question
701      */
702
703     function hasRight($right)
704     {
705         $result = false;
706         if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
707             switch ($right)
708             {
709              case Right::deleteOthersNotice:
710                 $result = $this->hasRole('moderator');
711                 break;
712              default:
713                 $result = false;
714                 break;
715             }
716         }
717         return $result;
718     }
719
720     function delete()
721     {
722         $profile = $this->getProfile();
723         $profile->delete();
724
725         $related = array('Fave',
726                          'User_openid',
727                          'Confirm_address',
728                          'Remember_me',
729                          'Foreign_link',
730                          'Invitation',
731                          'Notice_inbox',
732                          );
733
734         foreach ($related as $cls) {
735             $inst = new $cls();
736             $inst->user_id = $this->id;
737             $inst->delete();
738         }
739
740         $this->_deleteTags();
741         $this->_deleteBlocks();
742
743         parent::delete();
744     }
745
746     function _deleteTags()
747     {
748         $tag = new Profile_tag();
749         $tag->tagger = $this->id;
750         $tag->delete();
751     }
752
753     function _deleteBlocks()
754     {
755         $block = new Profile_block();
756         $block->blocker = $this->id;
757         $block->delete();
758         // XXX delete group block? Reset blocker?
759     }
760 }