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