]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/User.php
4baa6d1b33f70c59dc09503b58cc1491e689f708
[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 $sms;                             // varchar(64)  unique_key
52     public $carrier;                         // int(4)
53     public $smsnotify;                       // tinyint(1)
54     public $smsreplies;                      // tinyint(1)
55     public $smsemail;                        // varchar(255)
56     public $uri;                             // varchar(255)  unique_key
57     public $autosubscribe;                   // tinyint(1)
58     public $urlshorteningservice;            // varchar(50)   default_ur1.ca
59     public $inboxed;                         // tinyint(1)
60     public $design_id;                       // int(4)
61     public $viewdesigns;                     // tinyint(1)   default_1
62     public $created;                         // datetime()   not_null
63     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
64
65     /* Static get */
66     function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('User',$k,$v); }
67
68     /* the code above is auto generated do not remove the tag below */
69     ###END_AUTOCODE
70
71     function getProfile()
72     {
73         $profile = Profile::staticGet('id', $this->id);
74         if (empty($profile)) {
75             throw new UserNoProfileException($this);
76         }
77         return $profile;
78     }
79
80     function isSubscribed($other)
81     {
82         $profile = $this->getProfile();
83         return $profile->isSubscribed($other);
84     }
85
86     // 'update' won't write key columns, so we have to do it ourselves.
87
88     function updateKeys(&$orig)
89     {
90         $this->_connect();
91         $parts = array();
92         foreach (array('nickname', 'email', 'incomingemail', 'sms', 'carrier', 'smsemail', 'language', 'timezone') as $k) {
93             if (strcmp($this->$k, $orig->$k) != 0) {
94                 $parts[] = $k . ' = ' . $this->_quote($this->$k);
95             }
96         }
97         if (count($parts) == 0) {
98             // No changes
99             return true;
100         }
101         $toupdate = implode(', ', $parts);
102
103         $table = common_database_tablename($this->tableName());
104         $qry = 'UPDATE ' . $table . ' SET ' . $toupdate .
105           ' WHERE id = ' . $this->id;
106         $orig->decache();
107         $result = $this->query($qry);
108         if ($result) {
109             $this->encache();
110         }
111         return $result;
112     }
113
114     /**
115      * Check whether the given nickname is potentially usable, or if it's
116      * excluded by any blacklists on this system.
117      *
118      * WARNING: INPUT IS NOT VALIDATED OR NORMALIZED. NON-NORMALIZED INPUT
119      * OR INVALID INPUT MAY LEAD TO FALSE RESULTS.
120      *
121      * @param string $nickname
122      * @return boolean true if clear, false if blacklisted
123      */
124     static function allowed_nickname($nickname)
125     {
126         // XXX: should already be validated for size, content, etc.
127         $blacklist = common_config('nickname', 'blacklist');
128
129         //all directory and file names should be blacklisted
130         $d = dir(INSTALLDIR);
131         while (false !== ($entry = $d->read())) {
132             $blacklist[]=$entry;
133         }
134         $d->close();
135
136         //all top level names in the router should be blacklisted
137         $router = Router::get();
138         foreach(array_keys($router->m->getPaths()) as $path){
139             if(preg_match('/^\/(.*?)[\/\?]/',$path,$matches)){
140                 $blacklist[]=$matches[1];
141             }
142         }
143         return !in_array($nickname, $blacklist);
144     }
145
146     /**
147      * Get the most recent notice posted by this user, if any.
148      *
149      * @return mixed Notice or null
150      */
151     function getCurrentNotice()
152     {
153         $profile = $this->getProfile();
154         return $profile->getCurrentNotice();
155     }
156
157     function getCarrier()
158     {
159         return Sms_carrier::staticGet('id', $this->carrier);
160     }
161
162     /**
163      * @deprecated use Subscription::start($sub, $other);
164      */
165     function subscribeTo($other)
166     {
167         return Subscription::start($this->getProfile(), $other);
168     }
169
170     function hasBlocked($other)
171     {
172         $profile = $this->getProfile();
173         return $profile->hasBlocked($other);
174     }
175
176     /**
177      * Register a new user account and profile and set up default subscriptions.
178      * If a new-user welcome message is configured, this will be sent.
179      *
180      * @param array $fields associative array of optional properties
181      *              string 'bio'
182      *              string 'email'
183      *              bool 'email_confirmed' pass true to mark email as pre-confirmed
184      *              string 'fullname'
185      *              string 'homepage'
186      *              string 'location' informal string description of geolocation
187      *              float 'lat' decimal latitude for geolocation
188      *              float 'lon' decimal longitude for geolocation
189      *              int 'location_id' geoname identifier
190      *              int 'location_ns' geoname namespace to interpret location_id
191      *              string 'nickname' REQUIRED
192      *              string 'password' (may be missing for eg OpenID registrations)
193      *              string 'code' invite code
194      *              ?string 'uri' permalink to notice; defaults to local notice URL
195      * @return mixed User object or false on failure
196      */
197     static function register($fields) {
198
199         // MAGICALLY put fields into current scope
200
201         extract($fields);
202
203         $profile = new Profile();
204
205         if(!empty($email))
206         {
207             $email = common_canonical_email($email);
208         }
209
210         $nickname = common_canonical_nickname($nickname);
211         $profile->nickname = $nickname;
212         if(! User::allowed_nickname($nickname)){
213             common_log(LOG_WARNING, sprintf("Attempted to register a nickname that is not allowed: %s", $profile->nickname),
214                        __FILE__);
215             return false;
216         }
217         $profile->profileurl = common_profile_url($nickname);
218
219         if (!empty($fullname)) {
220             $profile->fullname = $fullname;
221         }
222         if (!empty($homepage)) {
223             $profile->homepage = $homepage;
224         }
225         if (!empty($bio)) {
226             $profile->bio = $bio;
227         }
228         if (!empty($location)) {
229             $profile->location = $location;
230
231             $loc = Location::fromName($location);
232
233             if (!empty($loc)) {
234                 $profile->lat         = $loc->lat;
235                 $profile->lon         = $loc->lon;
236                 $profile->location_id = $loc->location_id;
237                 $profile->location_ns = $loc->location_ns;
238             }
239         }
240
241         $profile->created = common_sql_now();
242
243         $user = new User();
244
245         $user->nickname = $nickname;
246
247         // Users who respond to invite email have proven their ownership of that address
248
249         if (!empty($code)) {
250             $invite = Invitation::staticGet($code);
251             if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
252                 $user->email = $invite->address;
253             }
254         }
255
256         if(isset($email_confirmed) && $email_confirmed) {
257             $user->email = $email;
258         }
259
260         // This flag is ignored but still set to 1
261
262         $user->inboxed = 1;
263
264         // Set default-on options here, otherwise they'll be disabled
265         // initially for sites using caching, since the initial encache
266         // doesn't know about the defaults in the database.
267         $user->emailnotifysub = 1;
268         $user->emailnotifyfav = 1;
269         $user->emailnotifynudge = 1;
270         $user->emailnotifymsg = 1;
271         $user->emailnotifyattn = 1;
272         $user->emailmicroid = 1;
273         $user->emailpost = 1;
274         $user->jabbermicroid = 1;
275         $user->viewdesigns = 1;
276
277         $user->created = common_sql_now();
278
279         if (Event::handle('StartUserRegister', array(&$user, &$profile))) {
280
281             $profile->query('BEGIN');
282
283             $id = $profile->insert();
284
285             if (empty($id)) {
286                 common_log_db_error($profile, 'INSERT', __FILE__);
287                 return false;
288             }
289
290             $user->id = $id;
291
292             if (!empty($uri)) {
293                 $user->uri = $uri;
294             } else {
295                 $user->uri = common_user_uri($user);
296             }
297
298             if (!empty($password)) { // may not have a password for OpenID users
299                 $user->password = common_munge_password($password, $id);
300             }
301
302             $result = $user->insert();
303
304             if (!$result) {
305                 common_log_db_error($user, 'INSERT', __FILE__);
306                 return false;
307             }
308
309             // Everyone gets an inbox
310
311             $inbox = new Inbox();
312
313             $inbox->user_id = $user->id;
314             $inbox->notice_ids = '';
315
316             $result = $inbox->insert();
317
318             if (!$result) {
319                 common_log_db_error($inbox, 'INSERT', __FILE__);
320                 return false;
321             }
322
323             // Everyone is subscribed to themself
324
325             $subscription = new Subscription();
326             $subscription->subscriber = $user->id;
327             $subscription->subscribed = $user->id;
328             $subscription->created = $user->created;
329
330             $result = $subscription->insert();
331
332             if (!$result) {
333                 common_log_db_error($subscription, 'INSERT', __FILE__);
334                 return false;
335             }
336
337             if (!empty($email) && !$user->email) {
338
339                 $confirm = new Confirm_address();
340                 $confirm->code = common_confirmation_code(128);
341                 $confirm->user_id = $user->id;
342                 $confirm->address = $email;
343                 $confirm->address_type = 'email';
344
345                 $result = $confirm->insert();
346
347                 if (!$result) {
348                     common_log_db_error($confirm, 'INSERT', __FILE__);
349                     return false;
350                 }
351             }
352
353             if (!empty($code) && $user->email) {
354                 $user->emailChanged();
355             }
356
357             // Default system subscription
358
359             $defnick = common_config('newuser', 'default');
360
361             if (!empty($defnick)) {
362                 $defuser = User::staticGet('nickname', $defnick);
363                 if (empty($defuser)) {
364                     common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
365                                __FILE__);
366                 } else {
367                     Subscription::start($user, $defuser);
368                 }
369             }
370
371             $profile->query('COMMIT');
372
373             if (!empty($email) && !$user->email) {
374                 mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
375             }
376
377             // Welcome message
378
379             $welcome = common_config('newuser', 'welcome');
380
381             if (!empty($welcome)) {
382                 $welcomeuser = User::staticGet('nickname', $welcome);
383                 if (empty($welcomeuser)) {
384                     common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
385                                __FILE__);
386                 } else {
387                     $notice = Notice::saveNew($welcomeuser->id,
388                                               // TRANS: Notice given on user registration.
389                                               // TRANS: %1$s is the sitename, $2$s is the registering user's nickname.
390                                               sprintf(_('Welcome to %1$s, @%2$s!'),
391                                                       common_config('site', 'name'),
392                                                       $user->nickname),
393                                               'system');
394                 }
395             }
396
397             Event::handle('EndUserRegister', array(&$profile, &$user));
398         }
399
400         return $user;
401     }
402
403     // Things we do when the email changes
404     function emailChanged()
405     {
406
407         $invites = new Invitation();
408         $invites->address = $this->email;
409         $invites->address_type = 'email';
410
411         if ($invites->find()) {
412             while ($invites->fetch()) {
413                 $other = User::staticGet($invites->user_id);
414                 subs_subscribe_to($other, $this);
415             }
416         }
417     }
418
419     function hasFave($notice)
420     {
421         $profile = $this->getProfile();
422         return $profile->hasFave($notice);
423     }
424
425     function mutuallySubscribed($other)
426     {
427         $profile = $this->getProfile();
428         return $profile->mutuallySubscribed($other);
429     }
430
431     function mutuallySubscribedUsers()
432     {
433         // 3-way join; probably should get cached
434         $UT = common_config('db','type')=='pgsql'?'"user"':'user';
435         $qry = "SELECT $UT.* " .
436           "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
437           "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
438           'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
439           "ORDER BY $UT.nickname";
440         $user = new User();
441         $user->query(sprintf($qry, $this->id, $this->id));
442
443         return $user;
444     }
445
446     function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
447     {
448         $ids = Reply::stream($this->id, $offset, $limit, $since_id, $before_id);
449         return Notice::getStreamByIds($ids);
450     }
451
452     function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0) {
453         $profile = $this->getProfile();
454         return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id);
455     }
456
457     function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
458     {
459         $profile = $this->getProfile();
460         return $profile->getNotices($offset, $limit, $since_id, $before_id);
461     }
462
463     function favoriteNotices($own=false, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
464     {
465         $ids = Fave::stream($this->id, $offset, $limit, $own, $since_id, $max_id);
466         return Notice::getStreamByIds($ids);
467     }
468
469     function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
470     {
471         return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, false);
472     }
473
474     function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
475     {
476         return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, true);
477     }
478
479     function friendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
480     {
481         return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, false);
482     }
483
484     function ownFriendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
485     {
486         return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, true);
487     }
488
489     function blowFavesCache()
490     {
491         $profile = $this->getProfile();
492         $profile->blowFavesCache();
493     }
494
495     function getSelfTags()
496     {
497         return Profile_tag::getTags($this->id, $this->id);
498     }
499
500     function setSelfTags($newtags)
501     {
502         return Profile_tag::setTags($this->id, $this->id, $newtags);
503     }
504
505     function block($other)
506     {
507         // Add a new block record
508
509         // no blocking (and thus unsubbing from) yourself
510
511         if ($this->id == $other->id) {
512             common_log(LOG_WARNING,
513                 sprintf(
514                     "Profile ID %d (%s) tried to block themself.",
515                     $this->id,
516                     $this->nickname
517                 )
518             );
519             return false;
520         }
521
522         $block = new Profile_block();
523
524         // Begin a transaction
525
526         $block->query('BEGIN');
527
528         $block->blocker = $this->id;
529         $block->blocked = $other->id;
530
531         $result = $block->insert();
532
533         if (!$result) {
534             common_log_db_error($block, 'INSERT', __FILE__);
535             return false;
536         }
537
538         $self = $this->getProfile();
539         if (Subscription::exists($other, $self)) {
540             Subscription::cancel($other, $self);
541         }
542         if (Subscription::exists($self, $other)) {
543             Subscription::cancel($self, $other);
544         }
545
546         $block->query('COMMIT');
547
548         return true;
549     }
550
551     function unblock($other)
552     {
553         // Get the block record
554
555         $block = Profile_block::get($this->id, $other->id);
556
557         if (!$block) {
558             return false;
559         }
560
561         $result = $block->delete();
562
563         if (!$result) {
564             common_log_db_error($block, 'DELETE', __FILE__);
565             return false;
566         }
567
568         return true;
569     }
570
571     function isMember($group)
572     {
573         $profile = $this->getProfile();
574         return $profile->isMember($group);
575     }
576
577     function isAdmin($group)
578     {
579         $profile = $this->getProfile();
580         return $profile->isAdmin($group);
581     }
582
583     function getGroups($offset=0, $limit=null)
584     {
585         $profile = $this->getProfile();
586         return $profile->getGroups($offset, $limit);
587     }
588
589     function getSubscriptions($offset=0, $limit=null)
590     {
591         $profile = $this->getProfile();
592         return $profile->getSubscriptions($offset, $limit);
593     }
594
595     function getSubscribers($offset=0, $limit=null)
596     {
597         $profile = $this->getProfile();
598         return $profile->getSubscribers($offset, $limit);
599     }
600
601     function getTaggedSubscribers($tag, $offset=0, $limit=null)
602     {
603         $qry =
604           'SELECT profile.* ' .
605           'FROM profile JOIN subscription ' .
606           'ON profile.id = subscription.subscriber ' .
607           'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
608           'AND profile_tag.tagger = subscription.subscribed) ' .
609           'WHERE subscription.subscribed = %d ' .
610           "AND profile_tag.tag = '%s' " .
611           'AND subscription.subscribed != subscription.subscriber ' .
612           'ORDER BY subscription.created DESC ';
613
614         if ($offset) {
615             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
616         }
617
618         $profile = new Profile();
619
620         $cnt = $profile->query(sprintf($qry, $this->id, $tag));
621
622         return $profile;
623     }
624
625     function getTaggedSubscriptions($tag, $offset=0, $limit=null)
626     {
627         $qry =
628           'SELECT profile.* ' .
629           'FROM profile JOIN subscription ' .
630           'ON profile.id = subscription.subscribed ' .
631           'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
632           'AND profile_tag.tagger = subscription.subscriber) ' .
633           'WHERE subscription.subscriber = %d ' .
634           "AND profile_tag.tag = '%s' " .
635           'AND subscription.subscribed != subscription.subscriber ' .
636           'ORDER BY subscription.created DESC ';
637
638         $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
639
640         $profile = new Profile();
641
642         $profile->query(sprintf($qry, $this->id, $tag));
643
644         return $profile;
645     }
646
647     function getDesign()
648     {
649         return Design::staticGet('id', $this->design_id);
650     }
651
652     function hasRight($right)
653     {
654         $profile = $this->getProfile();
655         return $profile->hasRight($right);
656     }
657
658     function delete()
659     {
660         try {
661             $profile = $this->getProfile();
662             $profile->delete();
663         } catch (UserNoProfileException $unp) {
664             common_log(LOG_INFO, "User {$this->nickname} has no profile; continuing deletion.");
665         }
666
667         $related = array('Fave',
668                          'Confirm_address',
669                          'Remember_me',
670                          'Foreign_link',
671                          'Invitation',
672                          );
673
674         Event::handle('UserDeleteRelated', array($this, &$related));
675
676         foreach ($related as $cls) {
677             $inst = new $cls();
678             $inst->user_id = $this->id;
679             $inst->delete();
680         }
681
682         $this->_deleteTags();
683         $this->_deleteBlocks();
684
685         parent::delete();
686     }
687
688     function _deleteTags()
689     {
690         $tag = new Profile_tag();
691         $tag->tagger = $this->id;
692         $tag->delete();
693     }
694
695     function _deleteBlocks()
696     {
697         $block = new Profile_block();
698         $block->blocker = $this->id;
699         $block->delete();
700         // XXX delete group block? Reset blocker?
701     }
702
703     function hasRole($name)
704     {
705         $profile = $this->getProfile();
706         return $profile->hasRole($name);
707     }
708
709     function grantRole($name)
710     {
711         $profile = $this->getProfile();
712         return $profile->grantRole($name);
713     }
714
715     function revokeRole($name)
716     {
717         $profile = $this->getProfile();
718         return $profile->revokeRole($name);
719     }
720
721     function isSandboxed()
722     {
723         $profile = $this->getProfile();
724         return $profile->isSandboxed();
725     }
726
727     function isSilenced()
728     {
729         $profile = $this->getProfile();
730         return $profile->isSilenced();
731     }
732
733     function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
734     {
735         $ids = Notice::stream(array($this, '_repeatedByMeDirect'),
736                               array(),
737                               'user:repeated_by_me:'.$this->id,
738                               $offset, $limit, $since_id, $max_id, null);
739
740         return Notice::getStreamByIds($ids);
741     }
742
743     function _repeatedByMeDirect($offset, $limit, $since_id, $max_id)
744     {
745         $notice = new Notice();
746
747         $notice->selectAdd(); // clears it
748         $notice->selectAdd('id');
749
750         $notice->profile_id = $this->id;
751         $notice->whereAdd('repeat_of IS NOT NULL');
752
753         $notice->orderBy('id DESC');
754
755         if (!is_null($offset)) {
756             $notice->limit($offset, $limit);
757         }
758
759         if ($since_id != 0) {
760             $notice->whereAdd('id > ' . $since_id);
761         }
762
763         if ($max_id != 0) {
764             $notice->whereAdd('id <= ' . $max_id);
765         }
766
767         $ids = array();
768
769         if ($notice->find()) {
770             while ($notice->fetch()) {
771                 $ids[] = $notice->id;
772             }
773         }
774
775         $notice->free();
776         $notice = NULL;
777
778         return $ids;
779     }
780
781     function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
782     {
783         $ids = Notice::stream(array($this, '_repeatsOfMeDirect'),
784                               array(),
785                               'user:repeats_of_me:'.$this->id,
786                               $offset, $limit, $since_id, $max_id);
787
788         return Notice::getStreamByIds($ids);
789     }
790
791     function _repeatsOfMeDirect($offset, $limit, $since_id, $max_id)
792     {
793         $qry =
794           'SELECT DISTINCT original.id AS id ' .
795           'FROM notice original JOIN notice rept ON original.id = rept.repeat_of ' .
796           'WHERE original.profile_id = ' . $this->id . ' ';
797
798         if ($since_id != 0) {
799             $qry .= 'AND original.id > ' . $since_id . ' ';
800         }
801
802         if ($max_id != 0) {
803             $qry .= 'AND original.id <= ' . $max_id . ' ';
804         }
805
806         // NOTE: we sort by fave time, not by notice time!
807
808         $qry .= 'ORDER BY original.id DESC ';
809
810         if (!is_null($offset)) {
811             $qry .= "LIMIT $limit OFFSET $offset";
812         }
813
814         $ids = array();
815
816         $notice = new Notice();
817
818         $notice->query($qry);
819
820         while ($notice->fetch()) {
821             $ids[] = $notice->id;
822         }
823
824         $notice->free();
825         $notice = NULL;
826
827         return $ids;
828     }
829
830     function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
831     {
832         throw new Exception("Not implemented since inbox change.");
833     }
834
835     function shareLocation()
836     {
837         $cfg = common_config('location', 'share');
838
839         if ($cfg == 'always') {
840             return true;
841         } else if ($cfg == 'never') {
842             return false;
843         } else { // user
844             $share = true;
845
846             $prefs = User_location_prefs::staticGet('user_id', $this->id);
847
848             if (empty($prefs)) {
849                 $share = common_config('location', 'sharedefault');
850             } else {
851                 $share = $prefs->share_location;
852                 $prefs->free();
853             }
854
855             return $share;
856         }
857     }
858
859     static function siteOwner()
860     {
861         $owner = self::cacheGet('user:site_owner');
862
863         if ($owner === false) { // cache miss
864
865             $pr = new Profile_role();
866
867             $pr->role = Profile_role::OWNER;
868
869             $pr->orderBy('created');
870
871             $pr->limit(1);
872
873             if ($pr->find(true)) {
874                 $owner = User::staticGet('id', $pr->profile_id);
875             } else {
876                 $owner = null;
877             }
878
879             self::cacheSet('user:site_owner', $owner);
880         }
881
882         return $owner;
883     }
884
885     /**
886      * Pull the primary site account to use in single-user mode.
887      * If a valid user nickname is listed in 'singleuser':'nickname'
888      * in the config, this will be used; otherwise the site owner
889      * account is taken by default.
890      *
891      * @return User
892      * @throws ServerException if no valid single user account is present
893      * @throws ServerException if called when not in single-user mode
894      */
895     static function singleUser()
896     {
897         if (common_config('singleuser', 'enabled')) {
898
899             $user = null;
900
901             $nickname = common_config('singleuser', 'nickname');
902
903             if (!empty($nickname)) {
904                 $user = User::staticGet('nickname', $nickname);
905             }
906
907             // if there was no nickname or no user by that nickname,
908             // try the site owner.
909
910             if (empty($user)) {
911                 $user = User::siteOwner();
912             }
913
914             if (!empty($user)) {
915                 return $user;
916             } else {
917                 // TRANS: Server exception.
918                 throw new ServerException(_('No single user defined for single-user mode.'));
919             }
920         } else {
921             // TRANS: Server exception.
922             throw new ServerException(_('Single-user mode code called when not enabled.'));
923         }
924     }
925
926     /**
927      * This is kind of a hack for using external setup code that's trying to
928      * build single-user sites.
929      *
930      * Will still return a username if the config singleuser/nickname is set
931      * even if the account doesn't exist, which normally indicates that the
932      * site is horribly misconfigured.
933      *
934      * At the moment, we need to let it through so that router setup can
935      * complete, otherwise we won't be able to create the account.
936      *
937      * This will be easier when we can more easily create the account and
938      * *then* switch the site to 1user mode without jumping through hoops.
939      *
940      * @return string
941      * @throws ServerException if no valid single user account is present
942      * @throws ServerException if called when not in single-user mode
943      */
944     static function singleUserNickname()
945     {
946         try {
947             $user = User::singleUser();
948             return $user->nickname;
949         } catch (Exception $e) {
950             if (common_config('singleuser', 'enabled') && common_config('singleuser', 'nickname')) {
951                 common_log(LOG_WARN, "Warning: code attempting to pull single-user nickname when the account does not exist. If this is not setup time, this is probably a bug.");
952                 return common_config('singleuser', 'nickname');
953             }
954             throw $e;
955         }
956     }
957
958     /**
959      * Find and shorten links in the given text using this user's URL shortening
960      * settings.
961      *
962      * By default, links will be left untouched if the text is shorter than the
963      * configured maximum notice length. Pass true for the $always parameter
964      * to force all links to be shortened regardless.
965      *
966      * Side effects: may save file and file_redirection records for referenced URLs.
967      *
968      * @param string $text
969      * @param boolean $always
970      * @return string
971      */
972     public function shortenLinks($text, $always=false)
973     {
974         return common_shorten_links($text, $always, $this);
975     }
976
977     /*
978      * Get a list of OAuth client application that have access to this
979      * user's account.
980      */
981     function getConnectedApps($offset = 0, $limit = null)
982     {
983         $qry =
984           'SELECT u.* ' .
985           'FROM oauth_application_user u, oauth_application a ' .
986           'WHERE u.profile_id = %d ' .
987           'AND a.id = u.application_id ' .
988           'AND u.access_type > 0 ' .
989           'ORDER BY u.created DESC ';
990
991         if ($offset > 0) {
992             if (common_config('db','type') == 'pgsql') {
993                 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
994             } else {
995                 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
996             }
997         }
998
999         $apps = new Oauth_application_user();
1000
1001         $cnt = $apps->query(sprintf($qry, $this->id));
1002
1003         return $apps;
1004     }
1005
1006 }