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