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