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