]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Profile.php
Automatically add or drop fulltext indexes
[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     function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
440     {
441         $lists = new Profile_list();
442
443         $tags = new Profile_tag();
444         $tags->tagged = $this->id;
445
446         $lists->joinAdd($tags);
447
448         #@fixme: postgres (round(date_part('epoch', my_date)))
449         $lists->selectAdd('unix_timestamp(profile_tag.modified) as "cursor"');
450
451         if ($auth_user instanceof User || $auth_user instanceof Profile) {
452             $lists->whereAdd('( ( profile_list.private = false ) ' .
453                              'OR ( profile_list.tagger = ' . $auth_user->id . ' AND ' .
454                              'profile_list.private = true ) )');
455         } else {
456             $lists->private = false;
457         }
458
459         if ($since_id>0) {
460            $lists->whereAdd('cursor > '.$since_id);
461         }
462
463         if ($max_id>0) {
464             $lists->whereAdd('cursor <= '.$max_id);
465         }
466
467         if($offset>=0 && !is_null($limit)) {
468             $lists->limit($offset, $limit);
469         }
470
471         $lists->orderBy('profile_tag.modified DESC');
472         $lists->find();
473
474         return $lists;
475     }
476
477     function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
478     {
479         $tags = new Profile_list();
480         $tags->private = true;
481         $tags->tagger = $this->id;
482
483         if ($since_id>0) {
484            $tags->whereAdd('id > '.$since_id);
485         }
486
487         if ($max_id>0) {
488             $tags->whereAdd('id <= '.$max_id);
489         }
490
491         if($offset>=0 && !is_null($limit)) {
492             $tags->limit($offset, $limit);
493         }
494
495         $tags->orderBy('id DESC');
496         $tags->find();
497
498         return $tags;
499     }
500
501     function hasLocalTags()
502     {
503         $tags = new Profile_tag();
504
505         $tags->joinAdd(array('tagger', 'user:id'));
506         $tags->whereAdd('tagged  = '.$this->id);
507         $tags->whereAdd('tagger != '.$this->id);
508
509         $tags->limit(0, 1);
510         $tags->fetch();
511
512         return ($tags->N == 0) ? false : true;
513     }
514
515     function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
516     {
517         $lists = new Profile_list();
518         $subs = new Profile_tag_subscription();
519
520         $lists->joinAdd('id', 'profile_tag_subscription:profile_tag_id');
521
522         #@fixme: postgres (round(date_part('epoch', my_date)))
523         $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
524
525         $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
526
527         if ($since_id>0) {
528            $lists->whereAdd('cursor > '.$since_id);
529         }
530
531         if ($max_id>0) {
532             $lists->whereAdd('cursor <= '.$max_id);
533         }
534
535         if($offset>=0 && !is_null($limit)) {
536             $lists->limit($offset, $limit);
537         }
538
539         $lists->orderBy('"cursor" DESC');
540         $lists->find();
541
542         return $lists;
543     }
544
545     /**
546      * Request to join the given group.
547      * May throw exceptions on failure.
548      *
549      * @param User_group $group
550      * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
551      */
552     function joinGroup(User_group $group)
553     {
554         $join = null;
555         if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
556             $join = Group_join_queue::saveNew($this, $group);
557         } else {
558             if (Event::handle('StartJoinGroup', array($group, $this))) {
559                 $join = Group_member::join($group->id, $this->id);
560                 self::blow('profile:groups:%d', $this->id);
561                 Event::handle('EndJoinGroup', array($group, $this));
562             }
563         }
564         if ($join) {
565             // Send any applicable notifications...
566             $join->notify();
567         }
568         return $join;
569     }
570
571     /**
572      * Leave a group that this profile is a member of.
573      *
574      * @param User_group $group
575      */
576     function leaveGroup(User_group $group)
577     {
578         if (Event::handle('StartLeaveGroup', array($group, $this))) {
579             Group_member::leave($group->id, $this->id);
580             self::blow('profile:groups:%d', $this->id);
581             Event::handle('EndLeaveGroup', array($group, $this));
582         }
583     }
584
585     function avatarUrl($size=AVATAR_PROFILE_SIZE)
586     {
587         $avatar = $this->getAvatar($size);
588         if ($avatar) {
589             return $avatar->displayUrl();
590         } else {
591             return Avatar::defaultImage($size);
592         }
593     }
594
595     function getSubscriptions($offset=0, $limit=null)
596     {
597         $subs = Subscription::bySubscriber($this->id,
598                                            $offset,
599                                            $limit);
600
601         $profiles = array();
602
603         while ($subs->fetch()) {
604             $profile = Profile::staticGet($subs->subscribed);
605             if ($profile) {
606                 $profiles[] = $profile;
607             }
608         }
609
610         return new ArrayWrapper($profiles);
611     }
612
613     function getSubscribers($offset=0, $limit=null)
614     {
615         $subs = Subscription::bySubscribed($this->id,
616                                            $offset,
617                                            $limit);
618
619         $profiles = array();
620
621         while ($subs->fetch()) {
622             $profile = Profile::staticGet($subs->subscriber);
623             if ($profile) {
624                 $profiles[] = $profile;
625             }
626         }
627
628         return new ArrayWrapper($profiles);
629     }
630
631     function getTaggedSubscribers($tag)
632     {
633         $qry =
634           'SELECT profile.* ' .
635           'FROM profile JOIN (subscription, profile_tag, profile_list) ' .
636           'ON profile.id = subscription.subscriber ' .
637           'AND profile.id = profile_tag.tagged ' .
638           'AND profile_tag.tagger = profile_list.tagger AND profile_tag.tag = profile_list.tag ' .
639           'WHERE subscription.subscribed = %d ' .
640           'AND subscription.subscribed != subscription.subscriber ' .
641           'AND profile_tag.tagger = %d AND profile_tag.tag = "%s" ' .
642           'AND profile_list.private = false ' .
643           'ORDER BY subscription.created DESC';
644
645         $profile = new Profile();
646         $tagged = array();
647
648         $cnt = $profile->query(sprintf($qry, $this->id, $this->id, $tag));
649
650         while ($profile->fetch()) {
651             $tagged[] = clone($profile);
652         }
653         return $tagged;
654     }
655
656     /**
657      * Get pending subscribers, who have not yet been approved.
658      *
659      * @param int $offset
660      * @param int $limit
661      * @return Profile
662      */
663     function getRequests($offset=0, $limit=null)
664     {
665         $qry =
666           'SELECT profile.* ' .
667           'FROM profile JOIN subscription_queue '.
668           'ON profile.id = subscription_queue.subscriber ' .
669           'WHERE subscription_queue.subscribed = %d ' .
670           'ORDER BY subscription_queue.created DESC ';
671
672         if ($limit != null) {
673             if (common_config('db','type') == 'pgsql') {
674                 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
675             } else {
676                 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
677             }
678         }
679
680         $members = new Profile();
681
682         $members->query(sprintf($qry, $this->id));
683         return $members;
684     }
685
686     function subscriptionCount()
687     {
688         $c = Cache::instance();
689
690         if (!empty($c)) {
691             $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
692             if (is_integer($cnt)) {
693                 return (int) $cnt;
694             }
695         }
696
697         $sub = new Subscription();
698         $sub->subscriber = $this->id;
699
700         $cnt = (int) $sub->count('distinct subscribed');
701
702         $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
703
704         if (!empty($c)) {
705             $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
706         }
707
708         return $cnt;
709     }
710
711     function subscriberCount()
712     {
713         $c = Cache::instance();
714         if (!empty($c)) {
715             $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
716             if (is_integer($cnt)) {
717                 return (int) $cnt;
718             }
719         }
720
721         $sub = new Subscription();
722         $sub->subscribed = $this->id;
723         $sub->whereAdd('subscriber != subscribed');
724         $cnt = (int) $sub->count('distinct subscriber');
725
726         if (!empty($c)) {
727             $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
728         }
729
730         return $cnt;
731     }
732
733     /**
734      * Is this profile subscribed to another profile?
735      *
736      * @param Profile $other
737      * @return boolean
738      */
739     function isSubscribed($other)
740     {
741         return Subscription::exists($this, $other);
742     }
743
744     /**
745      * Check if a pending subscription request is outstanding for this...
746      *
747      * @param Profile $other
748      * @return boolean
749      */
750     function hasPendingSubscription($other)
751     {
752         return Subscription_queue::exists($this, $other);
753     }
754
755     /**
756      * Are these two profiles subscribed to each other?
757      *
758      * @param Profile $other
759      * @return boolean
760      */
761     function mutuallySubscribed($other)
762     {
763         return $this->isSubscribed($other) &&
764           $other->isSubscribed($this);
765     }
766
767     function hasFave($notice)
768     {
769         $fave = Fave::pkeyGet(array('user_id' => $this->id,
770                                     'notice_id' => $notice->id));
771         return ((is_null($fave)) ? false : true);
772     }
773
774     function faveCount()
775     {
776         $c = Cache::instance();
777         if (!empty($c)) {
778             $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
779             if (is_integer($cnt)) {
780                 return (int) $cnt;
781             }
782         }
783
784         $faves = new Fave();
785         $faves->user_id = $this->id;
786         $cnt = (int) $faves->count('notice_id');
787
788         if (!empty($c)) {
789             $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
790         }
791
792         return $cnt;
793     }
794
795     function noticeCount()
796     {
797         $c = Cache::instance();
798
799         if (!empty($c)) {
800             $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
801             if (is_integer($cnt)) {
802                 return (int) $cnt;
803             }
804         }
805
806         $notices = new Notice();
807         $notices->profile_id = $this->id;
808         $cnt = (int) $notices->count('distinct id');
809
810         if (!empty($c)) {
811             $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
812         }
813
814         return $cnt;
815     }
816
817     function blowFavesCache()
818     {
819         $cache = Cache::instance();
820         if ($cache) {
821             // Faves don't happen chronologically, so we need to blow
822             // ;last cache, too
823             $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
824             $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
825             $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
826             $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
827         }
828         $this->blowFaveCount();
829     }
830
831     function blowSubscriberCount()
832     {
833         $c = Cache::instance();
834         if (!empty($c)) {
835             $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
836         }
837     }
838
839     function blowSubscriptionCount()
840     {
841         $c = Cache::instance();
842         if (!empty($c)) {
843             $c->delete(Cache::key('profile:subscription_count:'.$this->id));
844         }
845     }
846
847     function blowFaveCount()
848     {
849         $c = Cache::instance();
850         if (!empty($c)) {
851             $c->delete(Cache::key('profile:fave_count:'.$this->id));
852         }
853     }
854
855     function blowNoticeCount()
856     {
857         $c = Cache::instance();
858         if (!empty($c)) {
859             $c->delete(Cache::key('profile:notice_count:'.$this->id));
860         }
861     }
862
863     static function maxBio()
864     {
865         $biolimit = common_config('profile', 'biolimit');
866         // null => use global limit (distinct from 0!)
867         if (is_null($biolimit)) {
868             $biolimit = common_config('site', 'textlimit');
869         }
870         return $biolimit;
871     }
872
873     static function bioTooLong($bio)
874     {
875         $biolimit = self::maxBio();
876         return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
877     }
878
879     function delete()
880     {
881         $this->_deleteNotices();
882         $this->_deleteSubscriptions();
883         $this->_deleteMessages();
884         $this->_deleteTags();
885         $this->_deleteBlocks();
886         $this->delete_avatars();
887
888         // Warning: delete() will run on the batch objects,
889         // not on individual objects.
890         $related = array('Reply',
891                          'Group_member',
892                          );
893         Event::handle('ProfileDeleteRelated', array($this, &$related));
894
895         foreach ($related as $cls) {
896             $inst = new $cls();
897             $inst->profile_id = $this->id;
898             $inst->delete();
899         }
900
901         parent::delete();
902     }
903
904     function _deleteNotices()
905     {
906         $notice = new Notice();
907         $notice->profile_id = $this->id;
908
909         if ($notice->find()) {
910             while ($notice->fetch()) {
911                 $other = clone($notice);
912                 $other->delete();
913             }
914         }
915     }
916
917     function _deleteSubscriptions()
918     {
919         $sub = new Subscription();
920         $sub->subscriber = $this->id;
921
922         $sub->find();
923
924         while ($sub->fetch()) {
925             $other = Profile::staticGet('id', $sub->subscribed);
926             if (empty($other)) {
927                 continue;
928             }
929             if ($other->id == $this->id) {
930                 continue;
931             }
932             Subscription::cancel($this, $other);
933         }
934
935         $subd = new Subscription();
936         $subd->subscribed = $this->id;
937         $subd->find();
938
939         while ($subd->fetch()) {
940             $other = Profile::staticGet('id', $subd->subscriber);
941             if (empty($other)) {
942                 continue;
943             }
944             if ($other->id == $this->id) {
945                 continue;
946             }
947             Subscription::cancel($other, $this);
948         }
949
950         $self = new Subscription();
951
952         $self->subscriber = $this->id;
953         $self->subscribed = $this->id;
954
955         $self->delete();
956     }
957
958     function _deleteMessages()
959     {
960         $msg = new Message();
961         $msg->from_profile = $this->id;
962         $msg->delete();
963
964         $msg = new Message();
965         $msg->to_profile = $this->id;
966         $msg->delete();
967     }
968
969     function _deleteTags()
970     {
971         $tag = new Profile_tag();
972         $tag->tagged = $this->id;
973         $tag->delete();
974     }
975
976     function _deleteBlocks()
977     {
978         $block = new Profile_block();
979         $block->blocked = $this->id;
980         $block->delete();
981
982         $block = new Group_block();
983         $block->blocked = $this->id;
984         $block->delete();
985     }
986
987     // XXX: identical to Notice::getLocation.
988
989     function getLocation()
990     {
991         $location = null;
992
993         if (!empty($this->location_id) && !empty($this->location_ns)) {
994             $location = Location::fromId($this->location_id, $this->location_ns);
995         }
996
997         if (is_null($location)) { // no ID, or Location::fromId() failed
998             if (!empty($this->lat) && !empty($this->lon)) {
999                 $location = Location::fromLatLon($this->lat, $this->lon);
1000             }
1001         }
1002
1003         if (is_null($location)) { // still haven't found it!
1004             if (!empty($this->location)) {
1005                 $location = Location::fromName($this->location);
1006             }
1007         }
1008
1009         return $location;
1010     }
1011
1012     function hasRole($name)
1013     {
1014         $has_role = false;
1015         if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1016             $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1017                                                 'role' => $name));
1018             $has_role = !empty($role);
1019             Event::handle('EndHasRole', array($this, $name, $has_role));
1020         }
1021         return $has_role;
1022     }
1023
1024     function grantRole($name)
1025     {
1026         if (Event::handle('StartGrantRole', array($this, $name))) {
1027
1028             $role = new Profile_role();
1029
1030             $role->profile_id = $this->id;
1031             $role->role       = $name;
1032             $role->created    = common_sql_now();
1033
1034             $result = $role->insert();
1035
1036             if (!$result) {
1037                 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1038             }
1039
1040             if ($name == 'owner') {
1041                 User::blow('user:site_owner');
1042             }
1043
1044             Event::handle('EndGrantRole', array($this, $name));
1045         }
1046
1047         return $result;
1048     }
1049
1050     function revokeRole($name)
1051     {
1052         if (Event::handle('StartRevokeRole', array($this, $name))) {
1053
1054             $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1055                                                 'role' => $name));
1056
1057             if (empty($role)) {
1058                 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
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; does not exist.'),$name, $this->id));
1061             }
1062
1063             $result = $role->delete();
1064
1065             if (!$result) {
1066                 common_log_db_error($role, 'DELETE', __FILE__);
1067                 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1068                 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1069                 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1070             }
1071
1072             if ($name == 'owner') {
1073                 User::blow('user:site_owner');
1074             }
1075
1076             Event::handle('EndRevokeRole', array($this, $name));
1077
1078             return true;
1079         }
1080     }
1081
1082     function isSandboxed()
1083     {
1084         return $this->hasRole(Profile_role::SANDBOXED);
1085     }
1086
1087     function isSilenced()
1088     {
1089         return $this->hasRole(Profile_role::SILENCED);
1090     }
1091
1092     function sandbox()
1093     {
1094         $this->grantRole(Profile_role::SANDBOXED);
1095     }
1096
1097     function unsandbox()
1098     {
1099         $this->revokeRole(Profile_role::SANDBOXED);
1100     }
1101
1102     function silence()
1103     {
1104         $this->grantRole(Profile_role::SILENCED);
1105     }
1106
1107     function unsilence()
1108     {
1109         $this->revokeRole(Profile_role::SILENCED);
1110     }
1111
1112     /**
1113      * Does this user have the right to do X?
1114      *
1115      * With our role-based authorization, this is merely a lookup for whether the user
1116      * has a particular role. The implementation currently uses a switch statement
1117      * to determine if the user has the pre-defined role to exercise the right. Future
1118      * implementations may allow per-site roles, and different mappings of roles to rights.
1119      *
1120      * @param $right string Name of the right, usually a constant in class Right
1121      * @return boolean whether the user has the right in question
1122      */
1123     function hasRight($right)
1124     {
1125         $result = false;
1126
1127         if ($this->hasRole(Profile_role::DELETED)) {
1128             return false;
1129         }
1130
1131         if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1132             switch ($right)
1133             {
1134             case Right::DELETEOTHERSNOTICE:
1135             case Right::MAKEGROUPADMIN:
1136             case Right::SANDBOXUSER:
1137             case Right::SILENCEUSER:
1138             case Right::DELETEUSER:
1139             case Right::DELETEGROUP:
1140                 $result = $this->hasRole(Profile_role::MODERATOR);
1141                 break;
1142             case Right::CONFIGURESITE:
1143                 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1144                 break;
1145             case Right::GRANTROLE:
1146             case Right::REVOKEROLE:
1147                 $result = $this->hasRole(Profile_role::OWNER);
1148                 break;
1149             case Right::NEWNOTICE:
1150             case Right::NEWMESSAGE:
1151             case Right::SUBSCRIBE:
1152             case Right::CREATEGROUP:
1153                 $result = !$this->isSilenced();
1154                 break;
1155             case Right::PUBLICNOTICE:
1156             case Right::EMAILONREPLY:
1157             case Right::EMAILONSUBSCRIBE:
1158             case Right::EMAILONFAVE:
1159                 $result = !$this->isSandboxed();
1160                 break;
1161             case Right::WEBLOGIN:
1162                 $result = !$this->isSilenced();
1163                 break;
1164             case Right::API:
1165                 $result = !$this->isSilenced();
1166                 break;
1167             case Right::BACKUPACCOUNT:
1168                 $result = common_config('profile', 'backup');
1169                 break;
1170             case Right::RESTOREACCOUNT:
1171                 $result = common_config('profile', 'restore');
1172                 break;
1173             case Right::DELETEACCOUNT:
1174                 $result = common_config('profile', 'delete');
1175                 break;
1176             case Right::MOVEACCOUNT:
1177                 $result = common_config('profile', 'move');
1178                 break;
1179             default:
1180                 $result = false;
1181                 break;
1182             }
1183         }
1184         return $result;
1185     }
1186
1187     function hasRepeated($notice_id)
1188     {
1189         // XXX: not really a pkey, but should work
1190
1191         $notice = Memcached_DataObject::pkeyGet('Notice',
1192                                                 array('profile_id' => $this->id,
1193                                                       'repeat_of' => $notice_id));
1194
1195         return !empty($notice);
1196     }
1197
1198     /**
1199      * Returns an XML string fragment with limited profile information
1200      * as an Atom <author> element.
1201      *
1202      * Assumes that Atom has been previously set up as the base namespace.
1203      *
1204      * @param Profile $cur the current authenticated user
1205      *
1206      * @return string
1207      */
1208     function asAtomAuthor($cur = null)
1209     {
1210         $xs = new XMLStringer(true);
1211
1212         $xs->elementStart('author');
1213         $xs->element('name', null, $this->nickname);
1214         $xs->element('uri', null, $this->getUri());
1215         if ($cur != null) {
1216             $attrs = Array();
1217             $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1218             $attrs['blocking']  = $cur->hasBlocked($this) ? 'true' : 'false';
1219             $xs->element('statusnet:profile_info', $attrs, null);
1220         }
1221         $xs->elementEnd('author');
1222
1223         return $xs->getString();
1224     }
1225
1226     /**
1227      * Extra profile info for atom entries
1228      *
1229      * Clients use some extra profile info in the atom stream.
1230      * This gives it to them.
1231      *
1232      * @param User $cur Current user
1233      *
1234      * @return array representation of <statusnet:profile_info> element or null
1235      */
1236
1237     function profileInfo($cur)
1238     {
1239         $profileInfoAttr = array('local_id' => $this->id);
1240
1241         if ($cur != null) {
1242             // Whether the current user is a subscribed to this profile
1243             $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1244             // Whether the current user is has blocked this profile
1245             $profileInfoAttr['blocking']  = $cur->hasBlocked($this) ? 'true' : 'false';
1246         }
1247
1248         return array('statusnet:profile_info', $profileInfoAttr, null);
1249     }
1250
1251     /**
1252      * Returns an XML string fragment with profile information as an
1253      * Activity Streams <activity:actor> element.
1254      *
1255      * Assumes that 'activity' namespace has been previously defined.
1256      *
1257      * @return string
1258      */
1259     function asActivityActor()
1260     {
1261         return $this->asActivityNoun('actor');
1262     }
1263
1264     /**
1265      * Returns an XML string fragment with profile information as an
1266      * Activity Streams noun object with the given element type.
1267      *
1268      * Assumes that 'activity', 'georss', and 'poco' namespace has been
1269      * previously defined.
1270      *
1271      * @param string $element one of 'actor', 'subject', 'object', 'target'
1272      *
1273      * @return string
1274      */
1275     function asActivityNoun($element)
1276     {
1277         $noun = ActivityObject::fromProfile($this);
1278         return $noun->asString('activity:' . $element);
1279     }
1280
1281     /**
1282      * Returns the best URI for a profile. Plugins may override.
1283      *
1284      * @return string $uri
1285      */
1286     function getUri()
1287     {
1288         $uri = null;
1289
1290         // give plugins a chance to set the URI
1291         if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1292
1293             // check for a local user first
1294             $user = User::staticGet('id', $this->id);
1295
1296             if (!empty($user)) {
1297                 $uri = $user->uri;
1298             }
1299
1300             Event::handle('EndGetProfileUri', array($this, &$uri));
1301         }
1302
1303         return $uri;
1304     }
1305
1306     function hasBlocked($other)
1307     {
1308         $block = Profile_block::get($this->id, $other->id);
1309
1310         if (empty($block)) {
1311             $result = false;
1312         } else {
1313             $result = true;
1314         }
1315
1316         return $result;
1317     }
1318
1319     function getAtomFeed()
1320     {
1321         $feed = null;
1322
1323         if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1324             $user = User::staticGet('id', $this->id);
1325             if (!empty($user)) {
1326                 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1327                                                                   'format' => 'atom'));
1328             }
1329             Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1330         }
1331
1332         return $feed;
1333     }
1334
1335     static function fromURI($uri)
1336     {
1337         $profile = null;
1338
1339         if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1340             // Get a local user or remote (OMB 0.1) profile
1341             $user = User::staticGet('uri', $uri);
1342             if (!empty($user)) {
1343                 $profile = $user->getProfile();
1344             }
1345             Event::handle('EndGetProfileFromURI', array($uri, $profile));
1346         }
1347
1348         return $profile;
1349     }
1350
1351     function canRead(Notice $notice)
1352     {
1353         if ($notice->scope & Notice::SITE_SCOPE) {
1354             $user = $this->getUser();
1355             if (empty($user)) {
1356                 return false;
1357             }
1358         }
1359
1360         if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1361             $replies = $notice->getReplies();
1362
1363             if (!in_array($this->id, $replies)) {
1364                 $groups = $notice->getGroups();
1365
1366                 $foundOne = false;
1367
1368                 foreach ($groups as $group) {
1369                     if ($this->isMember($group)) {
1370                         $foundOne = true;
1371                         break;
1372                     }
1373                 }
1374
1375                 if (!$foundOne) {
1376                     return false;
1377                 }
1378             }
1379         }
1380
1381         if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1382             $author = $notice->getProfile();
1383             if (!Subscription::exists($this, $author)) {
1384                 return false;
1385             }
1386         }
1387
1388         return true;
1389     }
1390
1391     static function current()
1392     {
1393         $user = common_current_user();
1394         if (empty($user)) {
1395             $profile = null;
1396         } else {
1397             $profile = $user->getProfile();
1398         }
1399         return $profile;
1400     }
1401
1402     /**
1403      * Magic function called at serialize() time.
1404      *
1405      * We use this to drop a couple process-specific references
1406      * from DB_DataObject which can cause trouble in future
1407      * processes.
1408      *
1409      * @return array of variable names to include in serialization.
1410      */
1411
1412     function __sleep()
1413     {
1414         $vars = parent::__sleep();
1415         $skip = array('_user', '_avatars');
1416         return array_diff($vars, $skip);
1417     }
1418     
1419     static function fillAvatars(&$profiles, $width)
1420     {
1421         $ids = array();
1422         foreach ($profiles as $profile) {
1423             $ids[] = $profile->id;
1424         }
1425         
1426         $avatars = Avatar::pivotGet('profile_id', $ids, array('width' => $width,
1427                                                                                                                           'height' => $width));
1428         
1429         foreach ($profiles as $profile) {
1430             $profile->_fillAvatar($width, $avatars[$profile->id]);
1431         }
1432     }
1433 }