]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/User.php
Merge branch '0.8.x' of git://gitorious.org/laconica/fmarani-clone into fmarani/0.8.x
[quix0rs-gnu-social.git] / classes / User.php
1 <?php
2 /*
3  * Laconica - a distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, Control Yourself, 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('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 $created;                         // datetime()   not_null
66     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
67
68     /* Static get */
69     function staticGet($k,$v=NULL)
70     {
71         return Memcached_DataObject::staticGet('User',$k,$v);
72     }
73
74     /* the code above is auto generated do not remove the tag below */
75     ###END_AUTOCODE
76
77     function getProfile()
78     {
79         return Profile::staticGet('id', $this->id);
80     }
81
82     function isSubscribed($other)
83     {
84         assert(!is_null($other));
85         // XXX: cache results of this query
86         $sub = Subscription::pkeyGet(array('subscriber' => $this->id,
87                                            'subscribed' => $other->id));
88         return (is_null($sub)) ? false : true;
89     }
90
91     // 'update' won't write key columns, so we have to do it ourselves.
92
93     function updateKeys(&$orig)
94     {
95         $parts = array();
96         foreach (array('nickname', 'email', 'jabber', 'incomingemail', 'sms', 'carrier', 'smsemail', 'language', 'timezone') as $k) {
97             if (strcmp($this->$k, $orig->$k) != 0) {
98                 $parts[] = $k . ' = ' . $this->_quote($this->$k);
99             }
100         }
101         if (count($parts) == 0) {
102             // No changes
103             return true;
104         }
105         $toupdate = implode(', ', $parts);
106
107         $table = $this->tableName();
108         if(common_config('db','quote_identifiers')) {
109             $table = '"' . $table . '"';
110         }
111         $qry = 'UPDATE ' . $table . ' SET ' . $toupdate .
112           ' WHERE id = ' . $this->id;
113         $orig->decache();
114         $result = $this->query($qry);
115         if ($result) {
116             $this->encache();
117         }
118         return $result;
119     }
120
121     function allowed_nickname($nickname)
122     {
123         // XXX: should already be validated for size, content, etc.
124         static $blacklist = array('rss', 'xrds', 'doc', 'main',
125                                   'settings', 'notice', 'user',
126                                   'search', 'avatar', 'tag', 'tags',
127                                   'api', 'message', 'group', 'groups',
128                                   'local');
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
203         $profile->created = common_sql_now();
204
205         $id = $profile->insert();
206
207         if (empty($id)) {
208             common_log_db_error($profile, 'INSERT', __FILE__);
209             return false;
210         }
211
212         $user = new User();
213
214         $user->id = $id;
215         $user->nickname = $nickname;
216
217         if (!empty($password)) { // may not have a password for OpenID users
218             $user->password = common_munge_password($password, $id);
219         }
220
221         // Users who respond to invite email have proven their ownership of that address
222
223         if (!empty($code)) {
224             $invite = Invitation::staticGet($code);
225             if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
226                 $user->email = $invite->address;
227             }
228         }
229
230         $inboxes = common_config('inboxes', 'enabled');
231
232         if ($inboxes === true || $inboxes == 'transitional') {
233             $user->inboxed = 1;
234         }
235
236         $user->created = common_sql_now();
237         $user->uri = common_user_uri($user);
238
239         $result = $user->insert();
240
241         if (!$result) {
242             common_log_db_error($user, 'INSERT', __FILE__);
243             return false;
244         }
245
246         // Everyone is subscribed to themself
247
248         $subscription = new Subscription();
249         $subscription->subscriber = $user->id;
250         $subscription->subscribed = $user->id;
251         $subscription->created = $user->created;
252
253         $result = $subscription->insert();
254
255         if (!$result) {
256             common_log_db_error($subscription, 'INSERT', __FILE__);
257             return false;
258         }
259
260         if (!empty($email) && !$user->email) {
261
262             $confirm = new Confirm_address();
263             $confirm->code = common_confirmation_code(128);
264             $confirm->user_id = $user->id;
265             $confirm->address = $email;
266             $confirm->address_type = 'email';
267
268             $result = $confirm->insert();
269             if (!$result) {
270                 common_log_db_error($confirm, 'INSERT', __FILE__);
271                 return false;
272             }
273         }
274
275         if (!empty($code) && $user->email) {
276             $user->emailChanged();
277         }
278
279         // Default system subscription
280
281         $defnick = common_config('newuser', 'default');
282
283         if (!empty($defnick)) {
284             $defuser = User::staticGet('nickname', $defnick);
285             if (empty($defuser)) {
286                 common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
287                            __FILE__);
288             } else {
289                 $defsub = new Subscription();
290                 $defsub->subscriber = $user->id;
291                 $defsub->subscribed = $defuser->id;
292                 $defsub->created = $user->created;
293
294                 $result = $defsub->insert();
295
296                 if (!$result) {
297                     common_log_db_error($defsub, 'INSERT', __FILE__);
298                     return false;
299                 }
300             }
301         }
302
303         $profile->query('COMMIT');
304
305         if ($email && !$user->email) {
306             mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
307         }
308
309         // Welcome message
310
311         $welcome = common_config('newuser', 'welcome');
312
313         if (!empty($welcome)) {
314             $welcomeuser = User::staticGet('nickname', $welcome);
315             if (empty($welcomeuser)) {
316                 common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
317                            __FILE__);
318             } else {
319                 $notice = Notice::saveNew($welcomeuser->id,
320                                           sprintf(_('Welcome to %1$s, @%2$s!'),
321                                                   common_config('site', 'name'),
322                                                   $user->nickname),
323                                           'system');
324             }
325         }
326
327         return $user;
328     }
329
330     // Things we do when the email changes
331
332     function emailChanged()
333     {
334
335         $invites = new Invitation();
336         $invites->address = $this->email;
337         $invites->address_type = 'email';
338
339         if ($invites->find()) {
340             while ($invites->fetch()) {
341                 $other = User::staticGet($invites->user_id);
342                 subs_subscribe_to($other, $this);
343             }
344         }
345     }
346
347     function hasFave($notice)
348     {
349         $cache = common_memcache();
350
351         // XXX: Kind of a hack.
352         if ($cache) {
353             // This is the stream of favorite notices, in rev chron
354             // order. This forces it into cache.
355             $faves = $this->favoriteNotices(0, NOTICE_CACHE_WINDOW);
356             $cnt = 0;
357             while ($faves->fetch()) {
358                 if ($faves->id < $notice->id) {
359                     // If we passed it, it's not a fave
360                     return false;
361                 } else if ($faves->id == $notice->id) {
362                     // If it matches a cached notice, then it's a fave
363                     return true;
364                 }
365                 $cnt++;
366             }
367             // If we're not past the end of the cache window,
368             // then the cache has all available faves, so this one
369             // is not a fave.
370             if ($cnt < NOTICE_CACHE_WINDOW) {
371                 return false;
372             }
373             // Otherwise, cache doesn't have all faves;
374             // fall through to the default
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         $qry =
405           'SELECT notice.* ' .
406           'FROM notice JOIN reply ON notice.id = reply.notice_id ' .
407           'WHERE reply.profile_id = %d ';
408         return Notice::getStream(sprintf($qry, $this->id),
409                                  'user:replies:'.$this->id,
410                                  $offset, $limit, $since_id, $before_id, null, $since);
411     }
412
413     function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
414     {
415         $profile = $this->getProfile();
416         if (!$profile) {
417             return null;
418         } else {
419             return $profile->getNotices($offset, $limit, $since_id, $before_id);
420         }
421     }
422
423     function favoriteNotices($offset=0, $limit=NOTICES_PER_PAGE)
424     {
425         $qry =
426           'SELECT notice.* ' .
427           'FROM notice JOIN fave ON notice.id = fave.notice_id ' .
428           'WHERE fave.user_id = %d ';
429         return Notice::getStream(sprintf($qry, $this->id),
430                                  'user:faves:'.$this->id,
431                                  $offset, $limit);
432     }
433
434     function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
435     {
436         $enabled = common_config('inboxes', 'enabled');
437
438         // Complicated code, depending on whether we support inboxes yet
439         // XXX: make this go away when inboxes become mandatory
440
441         if ($enabled === false ||
442             ($enabled == 'transitional' && $this->inboxed == 0)) {
443             $qry =
444               'SELECT notice.* ' .
445               'FROM notice JOIN subscription ON notice.profile_id = subscription.subscribed ' .
446               'WHERE subscription.subscriber = %d ';
447             $order = null;
448         } else if ($enabled === true ||
449                    ($enabled == 'transitional' && $this->inboxed == 1)) {
450
451             $qry =
452               'SELECT notice.* ' .
453               'FROM notice JOIN notice_inbox ON notice.id = notice_inbox.notice_id ' .
454               'WHERE notice_inbox.user_id = %d ';
455             // NOTE: we override ORDER
456             $order = null;
457         }
458         return Notice::getStream(sprintf($qry, $this->id),
459                                  'user:notices_with_friends:' . $this->id,
460                                  $offset, $limit, $since_id, $before_id,
461                                  $order, $since);
462     }
463
464     function blowFavesCache()
465     {
466         $cache = common_memcache();
467         if ($cache) {
468             // Faves don't happen chronologically, so we need to blow
469             // ;last cache, too
470             $cache->delete(common_cache_key('user:faves:'.$this->id));
471             $cache->delete(common_cache_key('user:faves:'.$this->id).';last');
472         }
473     }
474
475     function getSelfTags()
476     {
477         return Profile_tag::getTags($this->id, $this->id);
478     }
479
480     function setSelfTags($newtags)
481     {
482         return Profile_tag::setTags($this->id, $this->id, $newtags);
483     }
484
485     function block($other)
486     {
487         // Add a new block record
488
489         $block = new Profile_block();
490
491         // Begin a transaction
492
493         $block->query('BEGIN');
494
495         $block->blocker = $this->id;
496         $block->blocked = $other->id;
497
498         $result = $block->insert();
499
500         if (!$result) {
501             common_log_db_error($block, 'INSERT', __FILE__);
502             return false;
503         }
504
505         // Cancel their subscription, if it exists
506
507         $sub = Subscription::pkeyGet(array('subscriber' => $other->id,
508                                            'subscribed' => $this->id));
509
510         if ($sub) {
511             $result = $sub->delete();
512             if (!$result) {
513                 common_log_db_error($sub, 'DELETE', __FILE__);
514                 return false;
515             }
516         }
517
518         $block->query('COMMIT');
519
520         return true;
521     }
522
523     function unblock($other)
524     {
525         // Get the block record
526
527         $block = Profile_block::get($this->id, $other->id);
528
529         if (!$block) {
530             return false;
531         }
532
533         $result = $block->delete();
534
535         if (!$result) {
536             common_log_db_error($block, 'DELETE', __FILE__);
537             return false;
538         }
539
540         return true;
541     }
542
543     function isMember($group)
544     {
545         $profile = $this->getProfile();
546         return $profile->isMember($group);
547     }
548
549     function isAdmin($group)
550     {
551         $profile = $this->getProfile();
552         return $profile->isAdmin($group);
553     }
554
555     function getGroups($offset=0, $limit=null)
556     {
557         $qry =
558           'SELECT user_group.* ' .
559           'FROM user_group JOIN group_member '.
560           'ON user_group.id = group_member.group_id ' .
561           'WHERE group_member.profile_id = %d ' .
562           'ORDER BY group_member.created DESC ';
563
564         if ($offset) {
565             if (common_config('db','type') == 'pgsql') {
566                 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
567             } else {
568                 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
569             }
570         }
571
572         $groups = new User_group();
573
574         $cnt = $groups->query(sprintf($qry, $this->id));
575
576         return $groups;
577     }
578
579     function getSubscriptions($offset=0, $limit=null)
580     {
581         $qry =
582           'SELECT profile.* ' .
583           'FROM profile JOIN subscription ' .
584           'ON profile.id = subscription.subscribed ' .
585           'WHERE subscription.subscriber = %d ' .
586           'AND subscription.subscribed != subscription.subscriber ' .
587           'ORDER BY subscription.created DESC ';
588
589         if (common_config('db','type') == 'pgsql') {
590             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
591         } else {
592             $qry .= ' LIMIT ' . $offset . ', ' . $limit;
593         }
594
595         $profile = new Profile();
596
597         $profile->query(sprintf($qry, $this->id));
598
599         return $profile;
600     }
601
602     function getSubscribers($offset=0, $limit=null)
603     {
604         $qry =
605           'SELECT profile.* ' .
606           'FROM profile JOIN subscription ' .
607           'ON profile.id = subscription.subscriber ' .
608           'WHERE subscription.subscribed = %d ' .
609           'AND subscription.subscribed != subscription.subscriber ' .
610           'ORDER BY subscription.created DESC ';
611
612         if ($offset) {
613             if (common_config('db','type') == 'pgsql') {
614                 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
615             } else {
616                 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
617             }
618         }
619
620         $profile = new Profile();
621
622         $cnt = $profile->query(sprintf($qry, $this->id));
623
624         return $profile;
625     }
626
627     function getTaggedSubscribers($tag, $offset=0, $limit=null)
628     {
629         $qry =
630           'SELECT profile.* ' .
631           'FROM profile JOIN subscription ' .
632           'ON profile.id = subscription.subscriber ' .
633           'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
634           'AND profile_tag.tagger = subscription.subscribed) ' .
635           'WHERE subscription.subscribed = %d ' .
636           "AND profile_tag.tag = '%s' " .
637           'AND subscription.subscribed != subscription.subscriber ' .
638           'ORDER BY subscription.created DESC ';
639
640         if ($offset) {
641             if (common_config('db','type') == 'pgsql') {
642                 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
643             } else {
644                 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
645             }
646         }
647
648         $profile = new Profile();
649
650         $cnt = $profile->query(sprintf($qry, $this->id, $tag));
651
652         return $profile;
653     }
654
655     function getTaggedSubscriptions($tag, $offset=0, $limit=null)
656     {
657         $qry =
658           'SELECT profile.* ' .
659           'FROM profile JOIN subscription ' .
660           'ON profile.id = subscription.subscribed ' .
661           'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
662           'AND profile_tag.tagger = subscription.subscriber) ' .
663           'WHERE subscription.subscriber = %d ' .
664           "AND profile_tag.tag = '%s' " .
665           'AND subscription.subscribed != subscription.subscriber ' .
666           'ORDER BY subscription.created DESC ';
667
668         if (common_config('db','type') == 'pgsql') {
669             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
670         } else {
671             $qry .= ' LIMIT ' . $offset . ', ' . $limit;
672         }
673
674         $profile = new Profile();
675
676         $profile->query(sprintf($qry, $this->id, $tag));
677
678         return $profile;
679     }
680
681     function hasOpenID()
682     {
683         $oid = new User_openid();
684
685         $oid->user_id = $this->id;
686
687         $cnt = $oid->find();
688
689         return ($cnt > 0);
690     }
691 }