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