]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/User.php
c529b82e0bb6457e1955c6c241374f6fb60da567
[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' will not 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         $blacklist = common_config('nickname', 'blacklist');
121
122         //all directory and file names should be blacklisted
123         $d = dir(INSTALLDIR);
124         while (false !== ($entry = $d->read())) {
125             $blacklist[]=$entry;
126         }
127         $d->close();
128
129         //all top level names in the router should be blacklisted
130         $router = Router::get();
131         foreach(array_keys($router->m->getPaths()) as $path){
132             if(preg_match('/^\/(.*?)[\/\?]/',$path,$matches)){
133                 $blacklist[]=$matches[1];
134             }
135         }
136         return !in_array($nickname, $blacklist);
137     }
138
139     function getCurrentNotice($dt=null)
140     {
141         $profile = $this->getProfile();
142         if (!$profile) {
143             return null;
144         }
145         return $profile->getCurrentNotice($dt);
146     }
147
148     function getCarrier()
149     {
150         return Sms_carrier::staticGet('id', $this->carrier);
151     }
152
153     function subscribeTo($other)
154     {
155         $sub = new Subscription();
156         $sub->subscriber = $this->id;
157         $sub->subscribed = $other->id;
158
159         $sub->created = common_sql_now(); // current time
160
161         if (!$sub->insert()) {
162             return false;
163         }
164
165         return true;
166     }
167
168     function hasBlocked($other)
169     {
170
171         $block = Profile_block::get($this->id, $other->id);
172
173         if (is_null($block)) {
174             $result = false;
175         } else {
176             $result = true;
177             $block->free();
178         }
179
180         return $result;
181     }
182
183     static function register($fields) {
184
185         // MAGICALLY put fields into current scope
186
187         extract($fields);
188
189         $profile = new Profile();
190
191         $profile->query('BEGIN');
192
193         $profile->nickname = $nickname;
194         $profile->profileurl = common_profile_url($nickname);
195
196         if (!empty($fullname)) {
197             $profile->fullname = $fullname;
198         }
199         if (!empty($homepage)) {
200             $profile->homepage = $homepage;
201         }
202         if (!empty($bio)) {
203             $profile->bio = $bio;
204         }
205         if (!empty($location)) {
206             $profile->location = $location;
207
208             $loc = Location::fromName($location);
209
210             if (!empty($loc)) {
211                 $profile->lat         = $loc->lat;
212                 $profile->lon         = $loc->lon;
213                 $profile->location_id = $loc->location_id;
214                 $profile->location_ns = $loc->location_ns;
215             }
216         }
217
218         $profile->created = common_sql_now();
219
220         $id = $profile->insert();
221
222         if (empty($id)) {
223             common_log_db_error($profile, 'INSERT', __FILE__);
224             return false;
225         }
226
227         $user = new User();
228
229         $user->id = $id;
230         $user->nickname = $nickname;
231
232         if (!empty($password)) { // may not have a password for OpenID users
233             $user->password = common_munge_password($password, $id);
234         }
235
236         // Users who respond to invite email have proven their ownership of that address
237
238         if (!empty($code)) {
239             $invite = Invitation::staticGet($code);
240             if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
241                 $user->email = $invite->address;
242             }
243         }
244
245         // This flag is ignored but still set to 1
246
247         $user->inboxed = 1;
248
249         $user->created = common_sql_now();
250         $user->uri = common_user_uri($user);
251
252         $result = $user->insert();
253
254         if (!$result) {
255             common_log_db_error($user, 'INSERT', __FILE__);
256             return false;
257         }
258
259         // Everyone is subscribed to themself
260
261         $subscription = new Subscription();
262         $subscription->subscriber = $user->id;
263         $subscription->subscribed = $user->id;
264         $subscription->created = $user->created;
265
266         $result = $subscription->insert();
267
268         if (!$result) {
269             common_log_db_error($subscription, 'INSERT', __FILE__);
270             return false;
271         }
272
273         if (!empty($email) && !$user->email) {
274
275             $confirm = new Confirm_address();
276             $confirm->code = common_confirmation_code(128);
277             $confirm->user_id = $user->id;
278             $confirm->address = $email;
279             $confirm->address_type = 'email';
280
281             $result = $confirm->insert();
282             if (!$result) {
283                 common_log_db_error($confirm, 'INSERT', __FILE__);
284                 return false;
285             }
286         }
287
288         if (!empty($code) && $user->email) {
289             $user->emailChanged();
290         }
291
292         // Default system subscription
293
294         $defnick = common_config('newuser', 'default');
295
296         if (!empty($defnick)) {
297             $defuser = User::staticGet('nickname', $defnick);
298             if (empty($defuser)) {
299                 common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
300                            __FILE__);
301             } else {
302                 $defsub = new Subscription();
303                 $defsub->subscriber = $user->id;
304                 $defsub->subscribed = $defuser->id;
305                 $defsub->created = $user->created;
306
307                 $result = $defsub->insert();
308
309                 if (!$result) {
310                     common_log_db_error($defsub, 'INSERT', __FILE__);
311                     return false;
312                 }
313             }
314         }
315
316         $profile->query('COMMIT');
317
318         if ($email && !$user->email) {
319             mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
320         }
321
322         // Welcome message
323
324         $welcome = common_config('newuser', 'welcome');
325
326         if (!empty($welcome)) {
327             $welcomeuser = User::staticGet('nickname', $welcome);
328             if (empty($welcomeuser)) {
329                 common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
330                            __FILE__);
331             } else {
332                 $notice = Notice::saveNew($welcomeuser->id,
333                                           sprintf(_('Welcome to %1$s, @%2$s!'),
334                                                   common_config('site', 'name'),
335                                                   $user->nickname),
336                                           'system');
337                 common_broadcast_notice($notice);
338             }
339         }
340
341         return $user;
342     }
343
344     // Things we do when the email changes
345
346     function emailChanged()
347     {
348
349         $invites = new Invitation();
350         $invites->address = $this->email;
351         $invites->address_type = 'email';
352
353         if ($invites->find()) {
354             while ($invites->fetch()) {
355                 $other = User::staticGet($invites->user_id);
356                 subs_subscribe_to($other, $this);
357             }
358         }
359     }
360
361     function hasFave($notice)
362     {
363         $cache = common_memcache();
364
365         // XXX: Kind of a hack.
366
367         if ($cache) {
368             // This is the stream of favorite notices, in rev chron
369             // order. This forces it into cache.
370
371             $ids = Fave::stream($this->id, 0, NOTICE_CACHE_WINDOW);
372
373             // If it's in the list, then it's a fave
374
375             if (in_array($notice->id, $ids)) {
376                 return true;
377             }
378
379             // If we're not past the end of the cache window,
380             // then the cache has all available faves, so this one
381             // is not a fave.
382
383             if (count($ids) < NOTICE_CACHE_WINDOW) {
384                 return false;
385             }
386
387             // Otherwise, cache does not have all faves;
388             // fall through to the default
389         }
390
391         $fave = Fave::pkeyGet(array('user_id' => $this->id,
392                                     'notice_id' => $notice->id));
393         return ((is_null($fave)) ? false : true);
394     }
395
396     function mutuallySubscribed($other)
397     {
398         return $this->isSubscribed($other) &&
399           $other->isSubscribed($this);
400     }
401
402     function mutuallySubscribedUsers()
403     {
404         // 3-way join; probably should get cached
405         $UT = common_config('db','type')=='pgsql'?'"user"':'user';
406         $qry = "SELECT $UT.* " .
407           "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
408           "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
409           'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
410           "ORDER BY $UT.nickname";
411         $user = new User();
412         $user->query(sprintf($qry, $this->id, $this->id));
413
414         return $user;
415     }
416
417     function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
418     {
419         $ids = Reply::stream($this->id, $offset, $limit, $since_id, $before_id, $since);
420         return Notice::getStreamByIds($ids);
421     }
422
423     function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null) {
424         $profile = $this->getProfile();
425         if (!$profile) {
426             return null;
427         } else {
428             return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id, $since);
429         }
430     }
431
432     function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
433     {
434         $profile = $this->getProfile();
435         if (!$profile) {
436             return null;
437         } else {
438             return $profile->getNotices($offset, $limit, $since_id, $before_id, $since);
439         }
440     }
441
442     function favoriteNotices($offset=0, $limit=NOTICES_PER_PAGE, $own=false)
443     {
444         $ids = Fave::stream($this->id, $offset, $limit, $own);
445         return Notice::getStreamByIds($ids);
446     }
447
448     function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
449     {
450         $ids = Notice_inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, false);
451
452         return Notice::getStreamByIds($ids);
453     }
454
455     function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
456     {
457         $ids = Notice_inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, true);
458
459         return Notice::getStreamByIds($ids);
460     }
461
462     function blowFavesCache()
463     {
464         $cache = common_memcache();
465         if ($cache) {
466             // Faves do not happen chronologically, so we need to blow
467             // ;last cache, too
468             $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id));
469             $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id.';last'));
470             $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id));
471             $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id.';last'));
472         }
473         $profile = $this->getProfile();
474         $profile->blowFaveCount();
475     }
476
477     function getSelfTags()
478     {
479         return Profile_tag::getTags($this->id, $this->id);
480     }
481
482     function setSelfTags($newtags)
483     {
484         return Profile_tag::setTags($this->id, $this->id, $newtags);
485     }
486
487     function block($other)
488     {
489         // Add a new block record
490
491         $block = new Profile_block();
492
493         // Begin a transaction
494
495         $block->query('BEGIN');
496
497         $block->blocker = $this->id;
498         $block->blocked = $other->id;
499
500         $result = $block->insert();
501
502         if (!$result) {
503             common_log_db_error($block, 'INSERT', __FILE__);
504             return false;
505         }
506
507         // Cancel their subscription, if it exists
508
509         $sub = Subscription::pkeyGet(array('subscriber' => $other->id,
510                                            'subscribed' => $this->id));
511
512         if ($sub) {
513             $result = $sub->delete();
514             if (!$result) {
515                 common_log_db_error($sub, 'DELETE', __FILE__);
516                 return false;
517             }
518         }
519
520         $block->query('COMMIT');
521
522         return true;
523     }
524
525     function unblock($other)
526     {
527         // Get the block record
528
529         $block = Profile_block::get($this->id, $other->id);
530
531         if (!$block) {
532             return false;
533         }
534
535         $result = $block->delete();
536
537         if (!$result) {
538             common_log_db_error($block, 'DELETE', __FILE__);
539             return false;
540         }
541
542         return true;
543     }
544
545     function isMember($group)
546     {
547         $profile = $this->getProfile();
548         return $profile->isMember($group);
549     }
550
551     function isAdmin($group)
552     {
553         $profile = $this->getProfile();
554         return $profile->isAdmin($group);
555     }
556
557     function getGroups($offset=0, $limit=null)
558     {
559         $qry =
560           'SELECT user_group.* ' .
561           'FROM user_group JOIN group_member '.
562           'ON user_group.id = group_member.group_id ' .
563           'WHERE group_member.profile_id = %d ' .
564           'ORDER BY group_member.created DESC ';
565
566         if ($offset) {
567             if (common_config('db','type') == 'pgsql') {
568                 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
569             } else {
570                 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
571             }
572         }
573
574         $groups = new User_group();
575
576         $cnt = $groups->query(sprintf($qry, $this->id));
577
578         return $groups;
579     }
580
581     function getSubscriptions($offset=0, $limit=null)
582     {
583         $profile = $this->getProfile();
584         assert(!empty($profile));
585         return $profile->getSubscriptions($offset, $limit);
586     }
587
588     function getSubscribers($offset=0, $limit=null)
589     {
590         $profile = $this->getProfile();
591         assert(!empty($profile));
592         return $profile->getSubscribers($offset, $limit);
593     }
594
595     function getTaggedSubscribers($tag, $offset=0, $limit=null)
596     {
597         $qry =
598           'SELECT profile.* ' .
599           'FROM profile JOIN subscription ' .
600           'ON profile.id = subscription.subscriber ' .
601           'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
602           'AND profile_tag.tagger = subscription.subscribed) ' .
603           'WHERE subscription.subscribed = %d ' .
604           "AND profile_tag.tag = '%s' " .
605           'AND subscription.subscribed != subscription.subscriber ' .
606           'ORDER BY subscription.created DESC ';
607
608         if ($offset) {
609             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
610         }
611
612         $profile = new Profile();
613
614         $cnt = $profile->query(sprintf($qry, $this->id, $tag));
615
616         return $profile;
617     }
618
619     function getTaggedSubscriptions($tag, $offset=0, $limit=null)
620     {
621         $qry =
622           'SELECT profile.* ' .
623           'FROM profile JOIN subscription ' .
624           'ON profile.id = subscription.subscribed ' .
625           'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
626           'AND profile_tag.tagger = subscription.subscriber) ' .
627           'WHERE subscription.subscriber = %d ' .
628           "AND profile_tag.tag = '%s' " .
629           'AND subscription.subscribed != subscription.subscriber ' .
630           'ORDER BY subscription.created DESC ';
631
632         $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
633
634         $profile = new Profile();
635
636         $profile->query(sprintf($qry, $this->id, $tag));
637
638         return $profile;
639     }
640
641     function getDesign()
642     {
643         return Design::staticGet('id', $this->design_id);
644     }
645
646     function hasRole($name)
647     {
648         $role = User_role::pkeyGet(array('user_id' => $this->id,
649                                          'role' => $name));
650         return (!empty($role));
651     }
652
653     function grantRole($name)
654     {
655         $role = new User_role();
656
657         $role->user_id = $this->id;
658         $role->role    = $name;
659         $role->created = common_sql_now();
660
661         $result = $role->insert();
662
663         if (!$result) {
664             common_log_db_error($role, 'INSERT', __FILE__);
665             return false;
666         }
667
668         return true;
669     }
670
671     function revokeRole($name)
672     {
673         $role = User_role::pkeyGet(array('user_id' => $this->id,
674                                          'role' => $name));
675
676         if (empty($role)) {
677             throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; does not exist.');
678         }
679
680         $result = $role->delete();
681
682         if (!$result) {
683             common_log_db_error($role, 'DELETE', __FILE__);
684             throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; database error.');
685         }
686
687         return true;
688     }
689
690     /**
691      * Does this user have the right to do X?
692      *
693      * With our role-based authorization, this is merely a lookup for whether the user
694      * has a particular role. The implementation currently uses a switch statement
695      * to determine if the user has the pre-defined role to exercise the right. Future
696      * implementations may allow per-site roles, and different mappings of roles to rights.
697      *
698      * @param $right string Name of the right, usually a constant in class Right
699      * @return boolean whether the user has the right in question
700      */
701
702     function hasRight($right)
703     {
704         $result = false;
705         if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
706             switch ($right)
707             {
708             case Right::DELETEOTHERSNOTICE:
709                 $result = $this->hasRole(User_role::MODERATOR);
710                 break;
711             case Right::CONFIGURESITE:
712                 $result = $this->hasRole(User_role::ADMINISTRATOR);
713             default:
714                 $result = false;
715                 break;
716             }
717         }
718         return $result;
719     }
720
721     function delete()
722     {
723         $profile = $this->getProfile();
724         if ($profile) {
725             $profile->delete();
726         }
727
728         $related = array('Fave',
729                          'Confirm_address',
730                          'Remember_me',
731                          'Foreign_link',
732                          'Invitation',
733                          'Notice_inbox',
734                          );
735         Event::handle('UserDeleteRelated', array($this, &$related));
736
737         foreach ($related as $cls) {
738             $inst = new $cls();
739             $inst->user_id = $this->id;
740             $inst->delete();
741         }
742
743         $this->_deleteTags();
744         $this->_deleteBlocks();
745
746         parent::delete();
747     }
748
749     function _deleteTags()
750     {
751         $tag = new Profile_tag();
752         $tag->tagger = $this->id;
753         $tag->delete();
754     }
755
756     function _deleteBlocks()
757     {
758         $block = new Profile_block();
759         $block->blocker = $this->id;
760         $block->delete();
761         // XXX delete group block? Reset blocker?
762     }
763 }