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