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