]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Profile.php
NoticeListItem attentions showed double for User_group
[quix0rs-gnu-social.git] / classes / Profile.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008-2011, 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')) { exit(1); }
21
22 /**
23  * Table Definition for profile
24  */
25 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
26
27 class Profile extends Managed_DataObject
28 {
29     ###START_AUTOCODE
30     /* the code below is auto generated do not remove the above tag */
31
32     public $__table = 'profile';                         // table name
33     public $id;                              // int(4)  primary_key not_null
34     public $nickname;                        // varchar(64)  multiple_key not_null
35     public $fullname;                        // varchar(255)  multiple_key
36     public $profileurl;                      // varchar(255)
37     public $homepage;                        // varchar(255)  multiple_key
38     public $bio;                             // text()  multiple_key
39     public $location;                        // varchar(255)  multiple_key
40     public $lat;                             // decimal(10,7)
41     public $lon;                             // decimal(10,7)
42     public $location_id;                     // int(4)
43     public $location_ns;                     // int(4)
44     public $created;                         // datetime()   not_null
45     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
46
47     public static function schemaDef()
48     {
49         $def = array(
50             'description' => 'local and remote users have profiles',
51             'fields' => array(
52                 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
53                 'nickname' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'nickname or username', 'collate' => 'utf8_general_ci'),
54                 'fullname' => array('type' => 'varchar', 'length' => 255, 'description' => 'display name', 'collate' => 'utf8_general_ci'),
55                 'profileurl' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL, cached so we dont regenerate'),
56                 'homepage' => array('type' => 'varchar', 'length' => 255, 'description' => 'identifying URL', 'collate' => 'utf8_general_ci'),
57                 'bio' => array('type' => 'text', 'description' => 'descriptive biography', 'collate' => 'utf8_general_ci'),
58                 'location' => array('type' => 'varchar', 'length' => 255, 'description' => 'physical location', 'collate' => 'utf8_general_ci'),
59                 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
60                 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
61                 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
62                 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
63
64                 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
65                 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
66             ),
67             'primary key' => array('id'),
68             'indexes' => array(
69                 'profile_nickname_idx' => array('nickname'),
70             )
71         );
72
73         // Add a fulltext index
74
75         if (common_config('search', 'type') == 'fulltext') {
76             $def['fulltext indexes'] = array('nickname' => array('nickname', 'fullname', 'location', 'bio', 'homepage'));
77         }
78
79         return $def;
80     }
81         
82     /* the code above is auto generated do not remove the tag below */
83     ###END_AUTOCODE
84
85     public static function getByEmail($email)
86     {
87         // in the future, profiles should have emails stored...
88         $user = User::getKV('email', $email);
89         if (!($user instanceof User)) {
90             throw new NoSuchUserException(array('email'=>$email));
91         }
92         return $user->getProfile();
93     } 
94
95     protected $_user = -1;  // Uninitialized value distinct from null
96
97     public function getUser()
98     {
99         if ($this->_user === -1) {
100             $this->_user = User::getKV('id', $this->id);
101         }
102         if (!$this->_user instanceof User) {
103             throw new NoSuchUserException(array('id'=>$this->id));
104         }
105
106         return $this->_user;
107     }
108
109     protected $_group = -1;
110
111     public function getGroup()
112     {
113         if ($this->_group === -1) {
114             $this->_group = User_group::getKV('profile_id', $this->id);
115         }
116         if (!$this->_group instanceof User_group) {
117             throw new NoSuchGroupException(array('profile_id'=>$this->id));
118         }
119
120         return $this->_group;
121     }
122
123     public function isGroup()
124     {
125         try {
126             $this->getGroup();
127             return true;
128         } catch (NoSuchGroupException $e) {
129             return false;
130         }
131     }
132
133     public function isLocal()
134     {
135         try {
136             $this->getUser();
137         } catch (NoSuchUserException $e) {
138             return false;
139         }
140         return true;
141     }
142
143     protected $_avatars = array();
144
145     public function getAvatar($width, $height=null)
146     {
147         return Avatar::byProfile($this, $width, $height);
148     }
149
150     public function setOriginal($filename)
151     {
152         $imagefile = new ImageFile($this->id, Avatar::path($filename));
153
154         $avatar = new Avatar();
155         $avatar->profile_id = $this->id;
156         $avatar->width = $imagefile->width;
157         $avatar->height = $imagefile->height;
158         $avatar->mediatype = image_type_to_mime_type($imagefile->type);
159         $avatar->filename = $filename;
160         $avatar->original = true;
161         $avatar->url = Avatar::url($filename);
162         $avatar->created = common_sql_now();
163
164         // XXX: start a transaction here
165         if (!Avatar::deleteFromProfile($this, true) || !$avatar->insert()) {
166             // If we can't delete the old avatars, let's abort right here.
167             @unlink(Avatar::path($filename));
168             return null;
169         }
170
171         foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
172             // We don't do a scaled one if original is our scaled size
173             if (!($avatar->width == $size && $avatar->height == $size)) {
174                 try {
175                     Avatar::newSize($this, $size);
176                 } catch (Exception $e) {
177                     // should we abort the generation and live without smaller avatars?
178                 }
179             }
180         }
181
182         return $avatar;
183     }
184
185     /**
186      * Gets either the full name (if filled) or the nickname.
187      *
188      * @return string
189      */
190     function getBestName()
191     {
192         return ($this->fullname) ? $this->fullname : $this->nickname;
193     }
194
195     /**
196      * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
197      * if no fullname is provided.
198      *
199      * @return string
200      */
201     function getFancyName()
202     {
203         if ($this->fullname) {
204             // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
205             return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
206         } else {
207             return $this->nickname;
208         }
209     }
210
211     /**
212      * Get the most recent notice posted by this user, if any.
213      *
214      * @return mixed Notice or null
215      */
216     function getCurrentNotice()
217     {
218         $notice = $this->getNotices(0, 1);
219
220         if ($notice->fetch()) {
221             if ($notice instanceof ArrayWrapper) {
222                 // hack for things trying to work with single notices
223                 return $notice->_items[0];
224             }
225             return $notice;
226         } else {
227             return null;
228         }
229     }
230
231     function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
232     {
233         $stream = new TaggedProfileNoticeStream($this, $tag);
234
235         return $stream->getNotices($offset, $limit, $since_id, $max_id);
236     }
237
238     function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0, Profile $scoped=null)
239     {
240         $stream = new ProfileNoticeStream($this, $scoped);
241
242         return $stream->getNotices($offset, $limit, $since_id, $max_id);
243     }
244
245     function isMember($group)
246     {
247         $groups = $this->getGroups(0, null);
248         while ($groups instanceof User_group && $groups->fetch()) {
249             if ($groups->id == $group->id) {
250                 return true;
251             }
252         }
253         return false;
254     }
255
256     function isAdmin($group)
257     {
258         $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
259                                           'group_id' => $group->id));
260         return (!empty($gm) && $gm->is_admin);
261     }
262
263     function isPendingMember($group)
264     {
265         $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
266                                                    'group_id' => $group->id));
267         return !empty($request);
268     }
269
270     function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
271     {
272         $ids = array();
273
274         $keypart = sprintf('profile:groups:%d', $this->id);
275
276         $idstring = self::cacheGet($keypart);
277
278         if ($idstring !== false) {
279             $ids = explode(',', $idstring);
280         } else {
281             $gm = new Group_member();
282
283             $gm->profile_id = $this->id;
284
285             if ($gm->find()) {
286                 while ($gm->fetch()) {
287                     $ids[] = $gm->group_id;
288                 }
289             }
290
291             self::cacheSet($keypart, implode(',', $ids));
292         }
293
294         if (!is_null($offset) && !is_null($limit)) {
295             $ids = array_slice($ids, $offset, $limit);
296         }
297
298         try {
299             return User_group::listFind('id', $ids);
300         } catch (NoResultException $e) {
301             return null;    // throw exception when we handle it everywhere
302         }
303     }
304
305     function getGroupCount() {
306         $groups = $this->getGroups(0, null);
307         return $groups instanceof User_group
308                 ? $groups->N
309                 : 0;
310     }
311
312     function isTagged($peopletag)
313     {
314         $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
315                                           'tagged' => $this->id,
316                                           'tag'    => $peopletag->tag));
317         return !empty($tag);
318     }
319
320     function canTag($tagged)
321     {
322         if (empty($tagged)) {
323             return false;
324         }
325
326         if ($tagged->id == $this->id) {
327             return true;
328         }
329
330         $all = common_config('peopletag', 'allow_tagging', 'all');
331         $local = common_config('peopletag', 'allow_tagging', 'local');
332         $remote = common_config('peopletag', 'allow_tagging', 'remote');
333         $subs = common_config('peopletag', 'allow_tagging', 'subs');
334
335         if ($all) {
336             return true;
337         }
338
339         $tagged_user = $tagged->getUser();
340         if (!empty($tagged_user)) {
341             if ($local) {
342                 return true;
343             }
344         } else if ($subs) {
345             return (Subscription::exists($this, $tagged) ||
346                     Subscription::exists($tagged, $this));
347         } else if ($remote) {
348             return true;
349         }
350         return false;
351     }
352
353     function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
354     {
355         $ids = array();
356
357         $keypart = sprintf('profile:lists:%d', $this->id);
358
359         $idstr = self::cacheGet($keypart);
360
361         if ($idstr !== false) {
362             $ids = explode(',', $idstr);
363         } else {
364             $list = new Profile_list();
365             $list->selectAdd();
366             $list->selectAdd('id');
367             $list->tagger = $this->id;
368             $list->selectAdd('id as "cursor"');
369
370             if ($since_id>0) {
371                $list->whereAdd('id > '.$since_id);
372             }
373
374             if ($max_id>0) {
375                 $list->whereAdd('id <= '.$max_id);
376             }
377
378             if($offset>=0 && !is_null($limit)) {
379                 $list->limit($offset, $limit);
380             }
381
382             $list->orderBy('id DESC');
383
384             if ($list->find()) {
385                 while ($list->fetch()) {
386                     $ids[] = $list->id;
387                 }
388             }
389
390             self::cacheSet($keypart, implode(',', $ids));
391         }
392
393         $showPrivate = (($auth_user instanceof User ||
394                             $auth_user instanceof Profile) &&
395                         $auth_user->id === $this->id);
396
397         $lists = array();
398
399         foreach ($ids as $id) {
400             $list = Profile_list::getKV('id', $id);
401             if (!empty($list) &&
402                 ($showPrivate || !$list->private)) {
403
404                 if (!isset($list->cursor)) {
405                     $list->cursor = $list->id;
406                 }
407
408                 $lists[] = $list;
409             }
410         }
411
412         return new ArrayWrapper($lists);
413     }
414
415     /**
416      * Get tags that other people put on this profile, in reverse-chron order
417      *
418      * @param (Profile|User) $auth_user  Authorized user (used for privacy)
419      * @param int            $offset     Offset from latest
420      * @param int            $limit      Max number to get
421      * @param datetime       $since_id   max date
422      * @param datetime       $max_id     min date
423      *
424      * @return Profile_list resulting lists
425      */
426
427     function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
428     {
429         $list = new Profile_list();
430
431         $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
432                        'from profile_tag join profile_list '.
433                        'on (profile_tag.tagger = profile_list.tagger ' .
434                        '    and profile_tag.tag = profile_list.tag) ' .
435                        'where profile_tag.tagged = %d ',
436                        $this->id);
437
438
439         if ($auth_user instanceof User || $auth_user instanceof Profile) {
440             $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
441                             'OR ( profile_list.tagger = %d AND ' .
442                             'profile_list.private = true ) )',
443                             $auth_user->id);
444         } else {
445             $qry .= 'AND profile_list.private = 0 ';
446         }
447
448         if ($since_id > 0) {
449             $qry .= sprintf('AND (cursor > %d) ', $since_id);
450         }
451
452         if ($max_id > 0) {
453             $qry .= sprintf('AND (cursor < %d) ', $max_id);
454         }
455
456         $qry .= 'ORDER BY profile_tag.modified DESC ';
457
458         if ($offset >= 0 && !is_null($limit)) {
459             $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
460         }
461
462         $list->query($qry);
463         return $list;
464     }
465
466     function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
467     {
468         $tags = new Profile_list();
469         $tags->private = true;
470         $tags->tagger = $this->id;
471
472         if ($since_id>0) {
473            $tags->whereAdd('id > '.$since_id);
474         }
475
476         if ($max_id>0) {
477             $tags->whereAdd('id <= '.$max_id);
478         }
479
480         if($offset>=0 && !is_null($limit)) {
481             $tags->limit($offset, $limit);
482         }
483
484         $tags->orderBy('id DESC');
485         $tags->find();
486
487         return $tags;
488     }
489
490     function hasLocalTags()
491     {
492         $tags = new Profile_tag();
493
494         $tags->joinAdd(array('tagger', 'user:id'));
495         $tags->whereAdd('tagged  = '.$this->id);
496         $tags->whereAdd('tagger != '.$this->id);
497
498         $tags->limit(0, 1);
499         $tags->fetch();
500
501         return ($tags->N == 0) ? false : true;
502     }
503
504     function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
505     {
506         $lists = new Profile_list();
507         $subs = new Profile_tag_subscription();
508
509         $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
510
511         #@fixme: postgres (round(date_part('epoch', my_date)))
512         $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
513
514         $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
515
516         if ($since_id>0) {
517            $lists->whereAdd('cursor > '.$since_id);
518         }
519
520         if ($max_id>0) {
521             $lists->whereAdd('cursor <= '.$max_id);
522         }
523
524         if($offset>=0 && !is_null($limit)) {
525             $lists->limit($offset, $limit);
526         }
527
528         $lists->orderBy('"cursor" DESC');
529         $lists->find();
530
531         return $lists;
532     }
533
534     /**
535      * Request to join the given group.
536      * May throw exceptions on failure.
537      *
538      * @param User_group $group
539      * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
540      */
541     function joinGroup(User_group $group)
542     {
543         $join = null;
544         if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
545             $join = Group_join_queue::saveNew($this, $group);
546         } else {
547             if (Event::handle('StartJoinGroup', array($group, $this))) {
548                 $join = Group_member::join($group->id, $this->id);
549                 self::blow('profile:groups:%d', $this->id);
550                 self::blow('group:member_ids:%d', $group->id);
551                 self::blow('group:member_count:%d', $group->id);
552                 Event::handle('EndJoinGroup', array($group, $this));
553             }
554         }
555         if ($join) {
556             // Send any applicable notifications...
557             $join->notify();
558         }
559         return $join;
560     }
561
562     /**
563      * Leave a group that this profile is a member of.
564      *
565      * @param User_group $group
566      */
567     function leaveGroup(User_group $group)
568     {
569         if (Event::handle('StartLeaveGroup', array($group, $this))) {
570             Group_member::leave($group->id, $this->id);
571             self::blow('profile:groups:%d', $this->id);
572             self::blow('group:member_ids:%d', $group->id);
573             self::blow('group:member_count:%d', $group->id);
574             Event::handle('EndLeaveGroup', array($group, $this));
575         }
576     }
577
578     function avatarUrl($size=AVATAR_PROFILE_SIZE)
579     {
580         return Avatar::urlByProfile($this, $size);
581     }
582
583     function getSubscribed($offset=0, $limit=null)
584     {
585         $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
586         try {
587             $profiles = Profile::listFind('id', $subs);
588         } catch (NoResultException $e) {
589             return $e->obj;
590         }
591         return $profiles;
592     }
593
594     function getSubscribers($offset=0, $limit=null)
595     {
596         $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
597         try {
598             $profiles = Profile::listFind('id', $subs);
599         } catch (NoResultException $e) {
600             return $e->obj;
601         }
602         return $profiles;
603     }
604
605     function getTaggedSubscribers($tag, $offset=0, $limit=null)
606     {
607         $qry =
608           'SELECT profile.* ' .
609           'FROM profile JOIN subscription ' .
610           'ON profile.id = subscription.subscriber ' .
611           'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
612           'AND profile_tag.tagger = subscription.subscribed) ' .
613           'WHERE subscription.subscribed = %d ' .
614           "AND profile_tag.tag = '%s' " .
615           'AND subscription.subscribed != subscription.subscriber ' .
616           'ORDER BY subscription.created DESC ';
617
618         if ($offset) {
619             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
620         }
621
622         $profile = new Profile();
623
624         $cnt = $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
625
626         return $profile;
627     }
628
629     function getTaggedSubscriptions($tag, $offset=0, $limit=null)
630     {
631         $qry =
632           'SELECT profile.* ' .
633           'FROM profile JOIN subscription ' .
634           'ON profile.id = subscription.subscribed ' .
635           'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
636           'AND profile_tag.tagger = subscription.subscriber) ' .
637           'WHERE subscription.subscriber = %d ' .
638           "AND profile_tag.tag = '%s' " .
639           'AND subscription.subscribed != subscription.subscriber ' .
640           'ORDER BY subscription.created DESC ';
641
642         $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
643
644         $profile = new Profile();
645
646         $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
647
648         return $profile;
649     }
650
651     /**
652      * Get pending subscribers, who have not yet been approved.
653      *
654      * @param int $offset
655      * @param int $limit
656      * @return Profile
657      */
658     function getRequests($offset=0, $limit=null)
659     {
660         $qry =
661           'SELECT profile.* ' .
662           'FROM profile JOIN subscription_queue '.
663           'ON profile.id = subscription_queue.subscriber ' .
664           'WHERE subscription_queue.subscribed = %d ' .
665           'ORDER BY subscription_queue.created DESC ';
666
667         if ($limit != null) {
668             if (common_config('db','type') == 'pgsql') {
669                 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
670             } else {
671                 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
672             }
673         }
674
675         $members = new Profile();
676
677         $members->query(sprintf($qry, $this->id));
678         return $members;
679     }
680
681     function subscriptionCount()
682     {
683         $c = Cache::instance();
684
685         if (!empty($c)) {
686             $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
687             if (is_integer($cnt)) {
688                 return (int) $cnt;
689             }
690         }
691
692         $sub = new Subscription();
693         $sub->subscriber = $this->id;
694
695         $cnt = (int) $sub->count('distinct subscribed');
696
697         $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
698
699         if (!empty($c)) {
700             $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
701         }
702
703         return $cnt;
704     }
705
706     function subscriberCount()
707     {
708         $c = Cache::instance();
709         if (!empty($c)) {
710             $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
711             if (is_integer($cnt)) {
712                 return (int) $cnt;
713             }
714         }
715
716         $sub = new Subscription();
717         $sub->subscribed = $this->id;
718         $sub->whereAdd('subscriber != subscribed');
719         $cnt = (int) $sub->count('distinct subscriber');
720
721         if (!empty($c)) {
722             $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
723         }
724
725         return $cnt;
726     }
727
728     /**
729      * Is this profile subscribed to another profile?
730      *
731      * @param Profile $other
732      * @return boolean
733      */
734     function isSubscribed($other)
735     {
736         return Subscription::exists($this, $other);
737     }
738
739     /**
740      * Check if a pending subscription request is outstanding for this...
741      *
742      * @param Profile $other
743      * @return boolean
744      */
745     function hasPendingSubscription($other)
746     {
747         return Subscription_queue::exists($this, $other);
748     }
749
750     /**
751      * Are these two profiles subscribed to each other?
752      *
753      * @param Profile $other
754      * @return boolean
755      */
756     function mutuallySubscribed($other)
757     {
758         return $this->isSubscribed($other) &&
759           $other->isSubscribed($this);
760     }
761
762     function hasFave($notice)
763     {
764         $fave = Fave::pkeyGet(array('user_id' => $this->id,
765                                     'notice_id' => $notice->id));
766         return ((is_null($fave)) ? false : true);
767     }
768
769     function faveCount()
770     {
771         $c = Cache::instance();
772         if (!empty($c)) {
773             $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
774             if (is_integer($cnt)) {
775                 return (int) $cnt;
776             }
777         }
778
779         $faves = new Fave();
780         $faves->user_id = $this->id;
781         $cnt = (int) $faves->count('notice_id');
782
783         if (!empty($c)) {
784             $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
785         }
786
787         return $cnt;
788     }
789
790     function favoriteNotices($own=false, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
791     {
792         return Fave::stream($this->id, $offset, $limit, $own, $since_id, $max_id);
793     }
794
795     function noticeCount()
796     {
797         $c = Cache::instance();
798
799         if (!empty($c)) {
800             $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
801             if (is_integer($cnt)) {
802                 return (int) $cnt;
803             }
804         }
805
806         $notices = new Notice();
807         $notices->profile_id = $this->id;
808         $cnt = (int) $notices->count('distinct id');
809
810         if (!empty($c)) {
811             $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
812         }
813
814         return $cnt;
815     }
816
817     function blowFavesCache()
818     {
819         $cache = Cache::instance();
820         if ($cache) {
821             // Faves don't happen chronologically, so we need to blow
822             // ;last cache, too
823             $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
824             $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
825             $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
826             $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
827         }
828         $this->blowFaveCount();
829     }
830
831     function blowSubscriberCount()
832     {
833         $c = Cache::instance();
834         if (!empty($c)) {
835             $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
836         }
837     }
838
839     function blowSubscriptionCount()
840     {
841         $c = Cache::instance();
842         if (!empty($c)) {
843             $c->delete(Cache::key('profile:subscription_count:'.$this->id));
844         }
845     }
846
847     function blowFaveCount()
848     {
849         $c = Cache::instance();
850         if (!empty($c)) {
851             $c->delete(Cache::key('profile:fave_count:'.$this->id));
852         }
853     }
854
855     function blowNoticeCount()
856     {
857         $c = Cache::instance();
858         if (!empty($c)) {
859             $c->delete(Cache::key('profile:notice_count:'.$this->id));
860         }
861     }
862
863     static function maxBio()
864     {
865         $biolimit = common_config('profile', 'biolimit');
866         // null => use global limit (distinct from 0!)
867         if (is_null($biolimit)) {
868             $biolimit = common_config('site', 'textlimit');
869         }
870         return $biolimit;
871     }
872
873     static function bioTooLong($bio)
874     {
875         $biolimit = self::maxBio();
876         return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
877     }
878
879     function update($dataObject=false)
880     {
881         if (is_object($dataObject) && $this->nickname != $dataObject->nickname) {
882             try {
883                 $local = $this->getUser();
884                 common_debug("Updating User ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
885                 $origuser = clone($local);
886                 $local->nickname = $this->nickname;
887                 $result = $local->updateKeys($origuser);
888                 if ($result === false) {
889                     common_log_db_error($local, 'UPDATE', __FILE__);
890                     // TRANS: Server error thrown when user profile settings could not be updated.
891                     throw new ServerException(_('Could not update user nickname.'));
892                 }
893
894                 // Clear the site owner, in case nickname changed
895                 if ($local->hasRole(Profile_role::OWNER)) {
896                     User::blow('user:site_owner');
897                 }
898             } catch (NoSuchUserException $e) {
899                 // Nevermind...
900             }
901         }
902
903         return parent::update($dataObject);
904     }
905
906     function delete($useWhere=false)
907     {
908         $this->_deleteNotices();
909         $this->_deleteSubscriptions();
910         $this->_deleteMessages();
911         $this->_deleteTags();
912         $this->_deleteBlocks();
913         Avatar::deleteFromProfile($this, true);
914
915         // Warning: delete() will run on the batch objects,
916         // not on individual objects.
917         $related = array('Reply',
918                          'Group_member',
919                          );
920         Event::handle('ProfileDeleteRelated', array($this, &$related));
921
922         foreach ($related as $cls) {
923             $inst = new $cls();
924             $inst->profile_id = $this->id;
925             $inst->delete();
926         }
927
928         return parent::delete($useWhere);
929     }
930
931     function _deleteNotices()
932     {
933         $notice = new Notice();
934         $notice->profile_id = $this->id;
935
936         if ($notice->find()) {
937             while ($notice->fetch()) {
938                 $other = clone($notice);
939                 $other->delete();
940             }
941         }
942     }
943
944     function _deleteSubscriptions()
945     {
946         $sub = new Subscription();
947         $sub->subscriber = $this->id;
948
949         $sub->find();
950
951         while ($sub->fetch()) {
952             $other = Profile::getKV('id', $sub->subscribed);
953             if (empty($other)) {
954                 continue;
955             }
956             if ($other->id == $this->id) {
957                 continue;
958             }
959             Subscription::cancel($this, $other);
960         }
961
962         $subd = new Subscription();
963         $subd->subscribed = $this->id;
964         $subd->find();
965
966         while ($subd->fetch()) {
967             $other = Profile::getKV('id', $subd->subscriber);
968             if (empty($other)) {
969                 continue;
970             }
971             if ($other->id == $this->id) {
972                 continue;
973             }
974             Subscription::cancel($other, $this);
975         }
976
977         $self = new Subscription();
978
979         $self->subscriber = $this->id;
980         $self->subscribed = $this->id;
981
982         $self->delete();
983     }
984
985     function _deleteMessages()
986     {
987         $msg = new Message();
988         $msg->from_profile = $this->id;
989         $msg->delete();
990
991         $msg = new Message();
992         $msg->to_profile = $this->id;
993         $msg->delete();
994     }
995
996     function _deleteTags()
997     {
998         $tag = new Profile_tag();
999         $tag->tagged = $this->id;
1000         $tag->delete();
1001     }
1002
1003     function _deleteBlocks()
1004     {
1005         $block = new Profile_block();
1006         $block->blocked = $this->id;
1007         $block->delete();
1008
1009         $block = new Group_block();
1010         $block->blocked = $this->id;
1011         $block->delete();
1012     }
1013
1014     // XXX: identical to Notice::getLocation.
1015
1016     public function getLocation()
1017     {
1018         $location = null;
1019
1020         if (!empty($this->location_id) && !empty($this->location_ns)) {
1021             $location = Location::fromId($this->location_id, $this->location_ns);
1022         }
1023
1024         if (is_null($location)) { // no ID, or Location::fromId() failed
1025             if (!empty($this->lat) && !empty($this->lon)) {
1026                 $location = Location::fromLatLon($this->lat, $this->lon);
1027             }
1028         }
1029
1030         if (is_null($location)) { // still haven't found it!
1031             if (!empty($this->location)) {
1032                 $location = Location::fromName($this->location);
1033             }
1034         }
1035
1036         return $location;
1037     }
1038
1039     public function shareLocation()
1040     {
1041         $cfg = common_config('location', 'share');
1042
1043         if ($cfg == 'always') {
1044             return true;
1045         } else if ($cfg == 'never') {
1046             return false;
1047         } else { // user
1048             $share = common_config('location', 'sharedefault');
1049
1050             // Check if user has a personal setting for this
1051             $prefs = User_location_prefs::getKV('user_id', $this->id);
1052
1053             if (!empty($prefs)) {
1054                 $share = $prefs->share_location;
1055                 $prefs->free();
1056             }
1057
1058             return $share;
1059         }
1060     }
1061
1062     function hasRole($name)
1063     {
1064         $has_role = false;
1065         if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1066             $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1067                                                 'role' => $name));
1068             $has_role = !empty($role);
1069             Event::handle('EndHasRole', array($this, $name, $has_role));
1070         }
1071         return $has_role;
1072     }
1073
1074     function grantRole($name)
1075     {
1076         if (Event::handle('StartGrantRole', array($this, $name))) {
1077
1078             $role = new Profile_role();
1079
1080             $role->profile_id = $this->id;
1081             $role->role       = $name;
1082             $role->created    = common_sql_now();
1083
1084             $result = $role->insert();
1085
1086             if (!$result) {
1087                 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1088             }
1089
1090             if ($name == 'owner') {
1091                 User::blow('user:site_owner');
1092             }
1093
1094             Event::handle('EndGrantRole', array($this, $name));
1095         }
1096
1097         return $result;
1098     }
1099
1100     function revokeRole($name)
1101     {
1102         if (Event::handle('StartRevokeRole', array($this, $name))) {
1103
1104             $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1105                                                 'role' => $name));
1106
1107             if (empty($role)) {
1108                 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1109                 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1110                 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1111             }
1112
1113             $result = $role->delete();
1114
1115             if (!$result) {
1116                 common_log_db_error($role, 'DELETE', __FILE__);
1117                 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1118                 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1119                 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1120             }
1121
1122             if ($name == 'owner') {
1123                 User::blow('user:site_owner');
1124             }
1125
1126             Event::handle('EndRevokeRole', array($this, $name));
1127
1128             return true;
1129         }
1130     }
1131
1132     function isSandboxed()
1133     {
1134         return $this->hasRole(Profile_role::SANDBOXED);
1135     }
1136
1137     function isSilenced()
1138     {
1139         return $this->hasRole(Profile_role::SILENCED);
1140     }
1141
1142     function sandbox()
1143     {
1144         $this->grantRole(Profile_role::SANDBOXED);
1145     }
1146
1147     function unsandbox()
1148     {
1149         $this->revokeRole(Profile_role::SANDBOXED);
1150     }
1151
1152     function silence()
1153     {
1154         $this->grantRole(Profile_role::SILENCED);
1155         if (common_config('notice', 'hidespam')) {
1156             $this->flushVisibility();
1157         }
1158     }
1159
1160     function unsilence()
1161     {
1162         $this->revokeRole(Profile_role::SILENCED);
1163         if (common_config('notice', 'hidespam')) {
1164             $this->flushVisibility();
1165         }
1166     }
1167
1168     function flushVisibility()
1169     {
1170         // Get all notices
1171         $stream = new ProfileNoticeStream($this, $this);
1172         $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1173         foreach ($ids as $id) {
1174             self::blow('notice:in-scope-for:%d:null', $id);
1175         }
1176     }
1177
1178     /**
1179      * Does this user have the right to do X?
1180      *
1181      * With our role-based authorization, this is merely a lookup for whether the user
1182      * has a particular role. The implementation currently uses a switch statement
1183      * to determine if the user has the pre-defined role to exercise the right. Future
1184      * implementations may allow per-site roles, and different mappings of roles to rights.
1185      *
1186      * @param $right string Name of the right, usually a constant in class Right
1187      * @return boolean whether the user has the right in question
1188      */
1189     public function hasRight($right)
1190     {
1191         $result = false;
1192
1193         if ($this->hasRole(Profile_role::DELETED)) {
1194             return false;
1195         }
1196
1197         if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1198             switch ($right)
1199             {
1200             case Right::DELETEOTHERSNOTICE:
1201             case Right::MAKEGROUPADMIN:
1202             case Right::SANDBOXUSER:
1203             case Right::SILENCEUSER:
1204             case Right::DELETEUSER:
1205             case Right::DELETEGROUP:
1206             case Right::TRAINSPAM:
1207             case Right::REVIEWSPAM:
1208                 $result = $this->hasRole(Profile_role::MODERATOR);
1209                 break;
1210             case Right::CONFIGURESITE:
1211                 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1212                 break;
1213             case Right::GRANTROLE:
1214             case Right::REVOKEROLE:
1215                 $result = $this->hasRole(Profile_role::OWNER);
1216                 break;
1217             case Right::NEWNOTICE:
1218             case Right::NEWMESSAGE:
1219             case Right::SUBSCRIBE:
1220             case Right::CREATEGROUP:
1221                 $result = !$this->isSilenced();
1222                 break;
1223             case Right::PUBLICNOTICE:
1224             case Right::EMAILONREPLY:
1225             case Right::EMAILONSUBSCRIBE:
1226             case Right::EMAILONFAVE:
1227                 $result = !$this->isSandboxed();
1228                 break;
1229             case Right::WEBLOGIN:
1230                 $result = !$this->isSilenced();
1231                 break;
1232             case Right::API:
1233                 $result = !$this->isSilenced();
1234                 break;
1235             case Right::BACKUPACCOUNT:
1236                 $result = common_config('profile', 'backup');
1237                 break;
1238             case Right::RESTOREACCOUNT:
1239                 $result = common_config('profile', 'restore');
1240                 break;
1241             case Right::DELETEACCOUNT:
1242                 $result = common_config('profile', 'delete');
1243                 break;
1244             case Right::MOVEACCOUNT:
1245                 $result = common_config('profile', 'move');
1246                 break;
1247             default:
1248                 $result = false;
1249                 break;
1250             }
1251         }
1252         return $result;
1253     }
1254
1255     // FIXME: Can't put Notice typing here due to ArrayWrapper
1256     public function hasRepeated($notice)
1257     {
1258         // XXX: not really a pkey, but should work
1259
1260         $notice = Notice::pkeyGet(array('profile_id' => $this->id,
1261                                         'repeat_of' => $notice->id));
1262
1263         return !empty($notice);
1264     }
1265
1266     /**
1267      * Returns an XML string fragment with limited profile information
1268      * as an Atom <author> element.
1269      *
1270      * Assumes that Atom has been previously set up as the base namespace.
1271      *
1272      * @param Profile $cur the current authenticated user
1273      *
1274      * @return string
1275      */
1276     function asAtomAuthor($cur = null)
1277     {
1278         $xs = new XMLStringer(true);
1279
1280         $xs->elementStart('author');
1281         $xs->element('name', null, $this->nickname);
1282         $xs->element('uri', null, $this->getUri());
1283         if ($cur != null) {
1284             $attrs = Array();
1285             $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1286             $attrs['blocking']  = $cur->hasBlocked($this) ? 'true' : 'false';
1287             $xs->element('statusnet:profile_info', $attrs, null);
1288         }
1289         $xs->elementEnd('author');
1290
1291         return $xs->getString();
1292     }
1293
1294     /**
1295      * Extra profile info for atom entries
1296      *
1297      * Clients use some extra profile info in the atom stream.
1298      * This gives it to them.
1299      *
1300      * @param User $cur Current user
1301      *
1302      * @return array representation of <statusnet:profile_info> element or null
1303      */
1304
1305     function profileInfo($cur)
1306     {
1307         $profileInfoAttr = array('local_id' => $this->id);
1308
1309         if ($cur != null) {
1310             // Whether the current user is a subscribed to this profile
1311             $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1312             // Whether the current user is has blocked this profile
1313             $profileInfoAttr['blocking']  = $cur->hasBlocked($this) ? 'true' : 'false';
1314         }
1315
1316         return array('statusnet:profile_info', $profileInfoAttr, null);
1317     }
1318
1319     /**
1320      * Returns an XML string fragment with profile information as an
1321      * Activity Streams <activity:actor> element.
1322      *
1323      * Assumes that 'activity' namespace has been previously defined.
1324      *
1325      * @return string
1326      */
1327     function asActivityActor()
1328     {
1329         return $this->asActivityNoun('actor');
1330     }
1331
1332     /**
1333      * Returns an XML string fragment with profile information as an
1334      * Activity Streams noun object with the given element type.
1335      *
1336      * Assumes that 'activity', 'georss', and 'poco' namespace has been
1337      * previously defined.
1338      *
1339      * @param string $element one of 'actor', 'subject', 'object', 'target'
1340      *
1341      * @return string
1342      */
1343     function asActivityNoun($element)
1344     {
1345         $noun = ActivityObject::fromProfile($this);
1346         return $noun->asString('activity:' . $element);
1347     }
1348
1349     /**
1350      * Returns the profile's canonical url, not necessarily a uri/unique id
1351      *
1352      * @return string $profileurl
1353      */
1354     public function getUrl()
1355     {
1356         if (empty($this->profileurl) ||
1357                 !filter_var($this->profileurl, FILTER_VALIDATE_URL)) {
1358             throw new InvalidUrlException($this->profileurl);
1359         }
1360         return $this->profileurl;
1361     }
1362
1363     /**
1364      * Returns the best URI for a profile. Plugins may override.
1365      *
1366      * @return string $uri
1367      */
1368     public function getUri()
1369     {
1370         $uri = null;
1371
1372         // give plugins a chance to set the URI
1373         if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1374
1375             // check for a local user first
1376             $user = User::getKV('id', $this->id);
1377
1378             if (!empty($user)) {
1379                 $uri = $user->uri;
1380             }
1381
1382             Event::handle('EndGetProfileUri', array($this, &$uri));
1383         }
1384
1385         return $uri;
1386     }
1387
1388     /**
1389      * Returns an assumed acct: URI for a profile. Plugins are required.
1390      *
1391      * @return string $uri
1392      */
1393     public function getAcctUri()
1394     {
1395         $acct = null;
1396
1397         if (Event::handle('StartGetProfileAcctUri', array($this, &$acct))) {
1398             Event::handle('EndGetProfileAcctUri', array($this, &$acct));
1399         }
1400
1401         if ($acct === null) {
1402             throw new ProfileNoAcctUriException($this);
1403         }
1404
1405         return $acct;
1406     }
1407
1408     function hasBlocked($other)
1409     {
1410         $block = Profile_block::exists($this, $other);
1411         return !empty($block);
1412     }
1413
1414     function getAtomFeed()
1415     {
1416         $feed = null;
1417
1418         if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1419             $user = User::getKV('id', $this->id);
1420             if (!empty($user)) {
1421                 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1422                                                                   'format' => 'atom'));
1423             }
1424             Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1425         }
1426
1427         return $feed;
1428     }
1429
1430     static function fromURI($uri)
1431     {
1432         $profile = null;
1433
1434         if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1435             // Get a local user
1436             $user = User::getKV('uri', $uri);
1437             if (!empty($user)) {
1438                 $profile = $user->getProfile();
1439             }
1440             Event::handle('EndGetProfileFromURI', array($uri, $profile));
1441         }
1442
1443         return $profile;
1444     }
1445
1446     function canRead(Notice $notice)
1447     {
1448         if ($notice->scope & Notice::SITE_SCOPE) {
1449             $user = $this->getUser();
1450             if (empty($user)) {
1451                 return false;
1452             }
1453         }
1454
1455         if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1456             $replies = $notice->getReplies();
1457
1458             if (!in_array($this->id, $replies)) {
1459                 $groups = $notice->getGroups();
1460
1461                 $foundOne = false;
1462
1463                 foreach ($groups as $group) {
1464                     if ($this->isMember($group)) {
1465                         $foundOne = true;
1466                         break;
1467                     }
1468                 }
1469
1470                 if (!$foundOne) {
1471                     return false;
1472                 }
1473             }
1474         }
1475
1476         if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1477             $author = $notice->getProfile();
1478             if (!Subscription::exists($this, $author)) {
1479                 return false;
1480             }
1481         }
1482
1483         return true;
1484     }
1485
1486     static function current()
1487     {
1488         $user = common_current_user();
1489         if (empty($user)) {
1490             $profile = null;
1491         } else {
1492             $profile = $user->getProfile();
1493         }
1494         return $profile;
1495     }
1496
1497     /**
1498      * Magic function called at serialize() time.
1499      *
1500      * We use this to drop a couple process-specific references
1501      * from DB_DataObject which can cause trouble in future
1502      * processes.
1503      *
1504      * @return array of variable names to include in serialization.
1505      */
1506
1507     function __sleep()
1508     {
1509         $vars = parent::__sleep();
1510         $skip = array('_user', '_avatars');
1511         return array_diff($vars, $skip);
1512     }
1513
1514     public function getProfile()
1515     {
1516         return $this;
1517     }
1518 }