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