]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/User.php
whitespace adjustments for doxygen
[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                 common_broadcast_notice($notice);
332             }
333         }
334
335         return $user;
336     }
337
338     // Things we do when the email changes
339
340     function emailChanged()
341     {
342
343         $invites = new Invitation();
344         $invites->address = $this->email;
345         $invites->address_type = 'email';
346
347         if ($invites->find()) {
348             while ($invites->fetch()) {
349                 $other = User::staticGet($invites->user_id);
350                 subs_subscribe_to($other, $this);
351             }
352         }
353     }
354
355     function hasFave($notice)
356     {
357         $cache = common_memcache();
358
359         // XXX: Kind of a hack.
360
361         if ($cache) {
362             // This is the stream of favorite notices, in rev chron
363             // order. This forces it into cache.
364
365             $ids = Fave::stream($this->id, 0, NOTICE_CACHE_WINDOW);
366
367             // If it's in the list, then it's a fave
368
369             if (in_array($notice->id, $ids)) {
370                 return true;
371             }
372
373             // If we're not past the end of the cache window,
374             // then the cache has all available faves, so this one
375             // is not a fave.
376
377             if (count($ids) < NOTICE_CACHE_WINDOW) {
378                 return false;
379             }
380
381             // Otherwise, cache doesn't have all faves;
382             // fall through to the default
383         }
384
385         $fave = Fave::pkeyGet(array('user_id' => $this->id,
386                                     'notice_id' => $notice->id));
387         return ((is_null($fave)) ? false : true);
388     }
389
390     function mutuallySubscribed($other)
391     {
392         return $this->isSubscribed($other) &&
393           $other->isSubscribed($this);
394     }
395
396     function mutuallySubscribedUsers()
397     {
398         // 3-way join; probably should get cached
399         $UT = common_config('db','type')=='pgsql'?'"user"':'user';
400         $qry = "SELECT $UT.* " .
401           "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
402           "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
403           'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
404           "ORDER BY $UT.nickname";
405         $user = new User();
406         $user->query(sprintf($qry, $this->id, $this->id));
407
408         return $user;
409     }
410
411     function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
412     {
413         $ids = Reply::stream($this->id, $offset, $limit, $since_id, $before_id, $since);
414         return Notice::getStreamByIds($ids);
415     }
416
417     function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null) {
418         $profile = $this->getProfile();
419         if (!$profile) {
420             return null;
421         } else {
422             return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id, $since);
423         }
424     }
425
426     function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
427     {
428         $profile = $this->getProfile();
429         if (!$profile) {
430             return null;
431         } else {
432             return $profile->getNotices($offset, $limit, $since_id, $before_id, $since);
433         }
434     }
435
436     function favoriteNotices($offset=0, $limit=NOTICES_PER_PAGE, $own=false)
437     {
438         $ids = Fave::stream($this->id, $offset, $limit, $own);
439         return Notice::getStreamByIds($ids);
440     }
441
442     function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
443     {
444         $ids = Notice_inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, false);
445
446         return Notice::getStreamByIds($ids);
447     }
448
449     function noticeInbox($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, true);
452
453         return Notice::getStreamByIds($ids);
454     }
455
456     function blowFavesCache()
457     {
458         $cache = common_memcache();
459         if ($cache) {
460             // Faves don't happen chronologically, so we need to blow
461             // ;last cache, too
462             $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id));
463             $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id.';last'));
464             $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id));
465             $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id.';last'));
466         }
467         $profile = $this->getProfile();
468         $profile->blowFaveCount();
469     }
470
471     function getSelfTags()
472     {
473         return Profile_tag::getTags($this->id, $this->id);
474     }
475
476     function setSelfTags($newtags)
477     {
478         return Profile_tag::setTags($this->id, $this->id, $newtags);
479     }
480
481     function block($other)
482     {
483         // Add a new block record
484
485         $block = new Profile_block();
486
487         // Begin a transaction
488
489         $block->query('BEGIN');
490
491         $block->blocker = $this->id;
492         $block->blocked = $other->id;
493
494         $result = $block->insert();
495
496         if (!$result) {
497             common_log_db_error($block, 'INSERT', __FILE__);
498             return false;
499         }
500
501         // Cancel their subscription, if it exists
502
503         $sub = Subscription::pkeyGet(array('subscriber' => $other->id,
504                                            'subscribed' => $this->id));
505
506         if ($sub) {
507             $result = $sub->delete();
508             if (!$result) {
509                 common_log_db_error($sub, 'DELETE', __FILE__);
510                 return false;
511             }
512         }
513
514         $block->query('COMMIT');
515
516         return true;
517     }
518
519     function unblock($other)
520     {
521         // Get the block record
522
523         $block = Profile_block::get($this->id, $other->id);
524
525         if (!$block) {
526             return false;
527         }
528
529         $result = $block->delete();
530
531         if (!$result) {
532             common_log_db_error($block, 'DELETE', __FILE__);
533             return false;
534         }
535
536         return true;
537     }
538
539     function isMember($group)
540     {
541         $profile = $this->getProfile();
542         return $profile->isMember($group);
543     }
544
545     function isAdmin($group)
546     {
547         $profile = $this->getProfile();
548         return $profile->isAdmin($group);
549     }
550
551     function getGroups($offset=0, $limit=null)
552     {
553         $qry =
554           'SELECT user_group.* ' .
555           'FROM user_group JOIN group_member '.
556           'ON user_group.id = group_member.group_id ' .
557           'WHERE group_member.profile_id = %d ' .
558           'ORDER BY group_member.created DESC ';
559
560         if ($offset) {
561             if (common_config('db','type') == 'pgsql') {
562                 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
563             } else {
564                 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
565             }
566         }
567
568         $groups = new User_group();
569
570         $cnt = $groups->query(sprintf($qry, $this->id));
571
572         return $groups;
573     }
574
575     function getSubscriptions($offset=0, $limit=null)
576     {
577         $profile = $this->getProfile();
578         assert(!empty($profile));
579         return $profile->getSubscriptions($offset, $limit);
580     }
581
582     function getSubscribers($offset=0, $limit=null)
583     {
584         $profile = $this->getProfile();
585         assert(!empty($profile));
586         return $profile->getSubscribers($offset, $limit);
587     }
588
589     function getTaggedSubscribers($tag, $offset=0, $limit=null)
590     {
591         $qry =
592           'SELECT profile.* ' .
593           'FROM profile JOIN subscription ' .
594           'ON profile.id = subscription.subscriber ' .
595           'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
596           'AND profile_tag.tagger = subscription.subscribed) ' .
597           'WHERE subscription.subscribed = %d ' .
598           "AND profile_tag.tag = '%s' " .
599           'AND subscription.subscribed != subscription.subscriber ' .
600           'ORDER BY subscription.created DESC ';
601
602         if ($offset) {
603             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
604         }
605
606         $profile = new Profile();
607
608         $cnt = $profile->query(sprintf($qry, $this->id, $tag));
609
610         return $profile;
611     }
612
613     function getTaggedSubscriptions($tag, $offset=0, $limit=null)
614     {
615         $qry =
616           'SELECT profile.* ' .
617           'FROM profile JOIN subscription ' .
618           'ON profile.id = subscription.subscribed ' .
619           'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
620           'AND profile_tag.tagger = subscription.subscriber) ' .
621           'WHERE subscription.subscriber = %d ' .
622           "AND profile_tag.tag = '%s' " .
623           'AND subscription.subscribed != subscription.subscriber ' .
624           'ORDER BY subscription.created DESC ';
625
626         $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
627
628         $profile = new Profile();
629
630         $profile->query(sprintf($qry, $this->id, $tag));
631
632         return $profile;
633     }
634
635     function getDesign()
636     {
637         return Design::staticGet('id', $this->design_id);
638     }
639
640     function hasRole($name)
641     {
642         $role = User_role::pkeyGet(array('user_id' => $this->id,
643                                          'role' => $name));
644         return (!empty($role));
645     }
646
647     function grantRole($name)
648     {
649         $role = new User_role();
650
651         $role->user_id = $this->id;
652         $role->role    = $name;
653         $role->created = common_sql_now();
654
655         $result = $role->insert();
656
657         if (!$result) {
658             common_log_db_error($role, 'INSERT', __FILE__);
659             return false;
660         }
661
662         return true;
663     }
664
665     function revokeRole($name)
666     {
667         $role = User_role::pkeyGet(array('user_id' => $this->id,
668                                          'role' => $name));
669
670         if (empty($role)) {
671             throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; does not exist.');
672         }
673
674         $result = $role->delete();
675
676         if (!$result) {
677             common_log_db_error($role, 'DELETE', __FILE__);
678             throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; database error.');
679         }
680
681         return true;
682     }
683
684     /**
685      * Does this user have the right to do X?
686      *
687      * With our role-based authorization, this is merely a lookup for whether the user
688      * has a particular role. The implementation currently uses a switch statement
689      * to determine if the user has the pre-defined role to exercise the right. Future
690      * implementations may allow per-site roles, and different mappings of roles to rights.
691      *
692      * @param $right string Name of the right, usually a constant in class Right
693      * @return boolean whether the user has the right in question
694      */
695
696     function hasRight($right)
697     {
698         $result = false;
699         if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
700             switch ($right)
701             {
702              case Right::deleteOthersNotice:
703                 $result = $this->hasRole('moderator');
704                 break;
705              default:
706                 $result = false;
707                 break;
708             }
709         }
710         return $result;
711     }
712
713     function delete()
714     {
715         $profile = $this->getProfile();
716         $profile->delete();
717
718         $related = array('Fave',
719                          'User_openid',
720                          'Confirm_address',
721                          'Remember_me',
722                          'Foreign_link',
723                          'Invitation',
724                          'Notice_inbox',
725                          );
726
727         foreach ($related as $cls) {
728             $inst = new $cls();
729             $inst->user_id = $this->id;
730             $inst->delete();
731         }
732
733         $this->_deleteTags();
734         $this->_deleteBlocks();
735
736         parent::delete();
737     }
738
739     function _deleteTags()
740     {
741         $tag = new Profile_tag();
742         $tag->tagger = $this->id;
743         $tag->delete();
744     }
745
746     function _deleteBlocks()
747     {
748         $block = new Profile_block();
749         $block->blocker = $this->id;
750         $block->delete();
751         // XXX delete group block? Reset blocker?
752     }
753 }