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