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