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