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