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