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