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