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