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