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