]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Profile.php
Better detial in connected OAuth applications list
[quix0rs-gnu-social.git] / classes / Profile.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, 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 Memcached_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     /* the code above is auto generated do not remove the tag below */
53     ###END_AUTOCODE
54
55     function getUser()
56     {
57         return User::staticGet('id', $this->id);
58     }
59
60     function getAvatar($width, $height=null)
61     {
62         if (is_null($height)) {
63             $height = $width;
64         }
65         return Avatar::pkeyGet(array('profile_id' => $this->id,
66                                      'width' => $width,
67                                      'height' => $height));
68     }
69
70     function getOriginalAvatar()
71     {
72         $avatar = DB_DataObject::factory('avatar');
73         $avatar->profile_id = $this->id;
74         $avatar->original = true;
75         if ($avatar->find(true)) {
76             return $avatar;
77         } else {
78             return null;
79         }
80     }
81
82     function setOriginal($filename)
83     {
84         $imagefile = new ImageFile($this->id, Avatar::path($filename));
85
86         $avatar = new Avatar();
87         $avatar->profile_id = $this->id;
88         $avatar->width = $imagefile->width;
89         $avatar->height = $imagefile->height;
90         $avatar->mediatype = image_type_to_mime_type($imagefile->type);
91         $avatar->filename = $filename;
92         $avatar->original = true;
93         $avatar->url = Avatar::url($filename);
94         $avatar->created = DB_DataObject_Cast::dateTime(); # current time
95
96         # XXX: start a transaction here
97
98         if (!$this->delete_avatars() || !$avatar->insert()) {
99             @unlink(Avatar::path($filename));
100             return null;
101         }
102
103         foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
104             # We don't do a scaled one if original is our scaled size
105             if (!($avatar->width == $size && $avatar->height == $size)) {
106
107                 $scaled_filename = $imagefile->resize($size);
108
109                 //$scaled = DB_DataObject::factory('avatar');
110                 $scaled = new Avatar();
111                 $scaled->profile_id = $this->id;
112                 $scaled->width = $size;
113                 $scaled->height = $size;
114                 $scaled->original = false;
115                 $scaled->mediatype = image_type_to_mime_type($imagefile->type);
116                 $scaled->filename = $scaled_filename;
117                 $scaled->url = Avatar::url($scaled_filename);
118                 $scaled->created = DB_DataObject_Cast::dateTime(); # current time
119
120                 if (!$scaled->insert()) {
121                     return null;
122                 }
123             }
124         }
125
126         return $avatar;
127     }
128
129     function delete_avatars($original=true)
130     {
131         $avatar = new Avatar();
132         $avatar->profile_id = $this->id;
133         $avatar->find();
134         while ($avatar->fetch()) {
135             if ($avatar->original) {
136                 if ($original == false) {
137                     continue;
138                 }
139             }
140             $avatar->delete();
141         }
142         return true;
143     }
144
145     function getBestName()
146     {
147         return ($this->fullname) ? $this->fullname : $this->nickname;
148     }
149
150     # Get latest notice on or before date; default now
151     function getCurrentNotice($dt=null)
152     {
153         $notice = new Notice();
154         $notice->profile_id = $this->id;
155         if ($dt) {
156             $notice->whereAdd('created < "' . $dt . '"');
157         }
158         $notice->orderBy('created DESC, notice.id DESC');
159         $notice->limit(1);
160         if ($notice->find(true)) {
161             return $notice;
162         }
163         return null;
164     }
165
166     function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0, $since=null)
167     {
168         $ids = Notice::stream(array($this, '_streamTaggedDirect'),
169                               array($tag),
170                               'profile:notice_ids_tagged:' . $this->id . ':' . $tag,
171                               $offset, $limit, $since_id, $max_id, $since);
172         return Notice::getStreamByIds($ids);
173     }
174
175     function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0, $since=null)
176     {
177         // XXX: I'm not sure this is going to be any faster. It probably isn't.
178         $ids = Notice::stream(array($this, '_streamDirect'),
179                               array(),
180                               'profile:notice_ids:' . $this->id,
181                               $offset, $limit, $since_id, $max_id, $since);
182
183         return Notice::getStreamByIds($ids);
184     }
185
186     function _streamTaggedDirect($tag, $offset, $limit, $since_id, $max_id, $since)
187     {
188         // XXX It would be nice to do this without a join
189
190         $notice = new Notice();
191
192         $query =
193           "select id from notice join notice_tag on id=notice_id where tag='".
194           $notice->escape($tag) .
195           "' and profile_id=" . $notice->escape($this->id);
196
197         if ($since_id != 0) {
198             $query .= " and id > $since_id";
199         }
200
201         if ($max_id != 0) {
202             $query .= " and id < $max_id";
203         }
204
205         if (!is_null($since)) {
206             $query .= " and created > '" . date('Y-m-d H:i:s', $since) . "'";
207         }
208
209         $query .= ' order by id DESC';
210
211         if (!is_null($offset)) {
212             $query .= " LIMIT $limit OFFSET $offset";
213         }
214
215         $notice->query($query);
216
217         $ids = array();
218
219         while ($notice->fetch()) {
220             $ids[] = $notice->id;
221         }
222
223         return $ids;
224     }
225
226     function _streamDirect($offset, $limit, $since_id, $max_id, $since = null)
227     {
228         $notice = new Notice();
229
230         $notice->profile_id = $this->id;
231
232         $notice->selectAdd();
233         $notice->selectAdd('id');
234
235         if ($since_id != 0) {
236             $notice->whereAdd('id > ' . $since_id);
237         }
238
239         if ($max_id != 0) {
240             $notice->whereAdd('id <= ' . $max_id);
241         }
242
243         if (!is_null($since)) {
244             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
245         }
246
247         $notice->orderBy('id DESC');
248
249         if (!is_null($offset)) {
250             $notice->limit($offset, $limit);
251         }
252
253         $ids = array();
254
255         if ($notice->find()) {
256             while ($notice->fetch()) {
257                 $ids[] = $notice->id;
258             }
259         }
260
261         return $ids;
262     }
263
264     function isMember($group)
265     {
266         $mem = new Group_member();
267
268         $mem->group_id = $group->id;
269         $mem->profile_id = $this->id;
270
271         if ($mem->find()) {
272             return true;
273         } else {
274             return false;
275         }
276     }
277
278     function isAdmin($group)
279     {
280         $mem = new Group_member();
281
282         $mem->group_id = $group->id;
283         $mem->profile_id = $this->id;
284         $mem->is_admin = 1;
285
286         if ($mem->find()) {
287             return true;
288         } else {
289             return false;
290         }
291     }
292
293     function avatarUrl($size=AVATAR_PROFILE_SIZE)
294     {
295         $avatar = $this->getAvatar($size);
296         if ($avatar) {
297             return $avatar->displayUrl();
298         } else {
299             return Avatar::defaultImage($size);
300         }
301     }
302
303     function getSubscriptions($offset=0, $limit=null)
304     {
305         $qry =
306           'SELECT profile.* ' .
307           'FROM profile JOIN subscription ' .
308           'ON profile.id = subscription.subscribed ' .
309           'WHERE subscription.subscriber = %d ' .
310           'AND subscription.subscribed != subscription.subscriber ' .
311           'ORDER BY subscription.created DESC ';
312
313         if ($offset>0 && !is_null($limit)){
314             if (common_config('db','type') == 'pgsql') {
315                 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
316             } else {
317                 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
318             }
319         }
320
321         $profile = new Profile();
322
323         $profile->query(sprintf($qry, $this->id));
324
325         return $profile;
326     }
327
328     function getSubscribers($offset=0, $limit=null)
329     {
330         $qry =
331           'SELECT profile.* ' .
332           'FROM profile JOIN subscription ' .
333           'ON profile.id = subscription.subscriber ' .
334           'WHERE subscription.subscribed = %d ' .
335           'AND subscription.subscribed != subscription.subscriber ' .
336           'ORDER BY subscription.created DESC ';
337
338         if ($offset>0 && !is_null($limit)){
339             if ($offset) {
340                 if (common_config('db','type') == 'pgsql') {
341                     $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
342                 } else {
343                     $qry .= ' LIMIT ' . $offset . ', ' . $limit;
344                 }
345             }
346         }
347
348         $profile = new Profile();
349
350         $cnt = $profile->query(sprintf($qry, $this->id));
351
352         return $profile;
353     }
354
355     function getApplications($offset = 0, $limit = null)
356     {
357         $qry =
358           'SELECT a.* ' .
359           'FROM oauth_application_user u, oauth_application a ' .
360           'WHERE u.profile_id = %d ' .
361           'AND a.id = u.application_id ' .
362           'ORDER BY u.created DESC ';
363
364         if ($offset > 0) {
365             if (common_config('db','type') == 'pgsql') {
366                 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
367             } else {
368                 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
369             }
370         }
371
372         $application = new Oauth_application();
373
374         $cnt = $application->query(sprintf($qry, $this->id));
375
376         return $application;
377     }
378
379     function subscriptionCount()
380     {
381         $c = common_memcache();
382
383         if (!empty($c)) {
384             $cnt = $c->get(common_cache_key('profile:subscription_count:'.$this->id));
385             if (is_integer($cnt)) {
386                 return (int) $cnt;
387             }
388         }
389
390         $sub = new Subscription();
391         $sub->subscriber = $this->id;
392
393         $cnt = (int) $sub->count('distinct subscribed');
394
395         $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
396
397         if (!empty($c)) {
398             $c->set(common_cache_key('profile:subscription_count:'.$this->id), $cnt);
399         }
400
401         return $cnt;
402     }
403
404     function subscriberCount()
405     {
406         $c = common_memcache();
407         if (!empty($c)) {
408             $cnt = $c->get(common_cache_key('profile:subscriber_count:'.$this->id));
409             if (is_integer($cnt)) {
410                 return (int) $cnt;
411             }
412         }
413
414         $sub = new Subscription();
415         $sub->subscribed = $this->id;
416
417         $cnt = (int) $sub->count('distinct subscriber');
418
419         $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
420
421         if (!empty($c)) {
422             $c->set(common_cache_key('profile:subscriber_count:'.$this->id), $cnt);
423         }
424
425         return $cnt;
426     }
427
428     function faveCount()
429     {
430         $c = common_memcache();
431         if (!empty($c)) {
432             $cnt = $c->get(common_cache_key('profile:fave_count:'.$this->id));
433             if (is_integer($cnt)) {
434                 return (int) $cnt;
435             }
436         }
437
438         $faves = new Fave();
439         $faves->user_id = $this->id;
440         $cnt = (int) $faves->count('distinct notice_id');
441
442         if (!empty($c)) {
443             $c->set(common_cache_key('profile:fave_count:'.$this->id), $cnt);
444         }
445
446         return $cnt;
447     }
448
449     function noticeCount()
450     {
451         $c = common_memcache();
452
453         if (!empty($c)) {
454             $cnt = $c->get(common_cache_key('profile:notice_count:'.$this->id));
455             if (is_integer($cnt)) {
456                 return (int) $cnt;
457             }
458         }
459
460         $notices = new Notice();
461         $notices->profile_id = $this->id;
462         $cnt = (int) $notices->count('distinct id');
463
464         if (!empty($c)) {
465             $c->set(common_cache_key('profile:notice_count:'.$this->id), $cnt);
466         }
467
468         return $cnt;
469     }
470
471     function blowSubscriberCount()
472     {
473         $c = common_memcache();
474         if (!empty($c)) {
475             $c->delete(common_cache_key('profile:subscriber_count:'.$this->id));
476         }
477     }
478
479     function blowSubscriptionCount()
480     {
481         $c = common_memcache();
482         if (!empty($c)) {
483             $c->delete(common_cache_key('profile:subscription_count:'.$this->id));
484         }
485     }
486
487     function blowFaveCount()
488     {
489         $c = common_memcache();
490         if (!empty($c)) {
491             $c->delete(common_cache_key('profile:fave_count:'.$this->id));
492         }
493     }
494
495     function blowNoticeCount()
496     {
497         $c = common_memcache();
498         if (!empty($c)) {
499             $c->delete(common_cache_key('profile:notice_count:'.$this->id));
500         }
501     }
502
503     static function maxBio()
504     {
505         $biolimit = common_config('profile', 'biolimit');
506         // null => use global limit (distinct from 0!)
507         if (is_null($biolimit)) {
508             $biolimit = common_config('site', 'textlimit');
509         }
510         return $biolimit;
511     }
512
513     static function bioTooLong($bio)
514     {
515         $biolimit = self::maxBio();
516         return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
517     }
518
519     function delete()
520     {
521         $this->_deleteNotices();
522         $this->_deleteSubscriptions();
523         $this->_deleteMessages();
524         $this->_deleteTags();
525         $this->_deleteBlocks();
526
527         $related = array('Avatar',
528                          'Reply',
529                          'Group_member',
530                          );
531         Event::handle('ProfileDeleteRelated', array($this, &$related));
532
533         foreach ($related as $cls) {
534             $inst = new $cls();
535             $inst->profile_id = $this->id;
536             $inst->delete();
537         }
538
539         parent::delete();
540     }
541
542     function _deleteNotices()
543     {
544         $notice = new Notice();
545         $notice->profile_id = $this->id;
546
547         if ($notice->find()) {
548             while ($notice->fetch()) {
549                 $other = clone($notice);
550                 $other->delete();
551             }
552         }
553     }
554
555     function _deleteSubscriptions()
556     {
557         $sub = new Subscription();
558         $sub->subscriber = $this->id;
559         $sub->delete();
560
561         $subd = new Subscription();
562         $subd->subscribed = $this->id;
563         $subd->delete();
564     }
565
566     function _deleteMessages()
567     {
568         $msg = new Message();
569         $msg->from_profile = $this->id;
570         $msg->delete();
571
572         $msg = new Message();
573         $msg->to_profile = $this->id;
574         $msg->delete();
575     }
576
577     function _deleteTags()
578     {
579         $tag = new Profile_tag();
580         $tag->tagged = $this->id;
581         $tag->delete();
582     }
583
584     function _deleteBlocks()
585     {
586         $block = new Profile_block();
587         $block->blocked = $this->id;
588         $block->delete();
589
590         $block = new Group_block();
591         $block->blocked = $this->id;
592         $block->delete();
593     }
594
595     // XXX: identical to Notice::getLocation.
596
597     function getLocation()
598     {
599         $location = null;
600
601         if (!empty($this->location_id) && !empty($this->location_ns)) {
602             $location = Location::fromId($this->location_id, $this->location_ns);
603         }
604
605         if (is_null($location)) { // no ID, or Location::fromId() failed
606             if (!empty($this->lat) && !empty($this->lon)) {
607                 $location = Location::fromLatLon($this->lat, $this->lon);
608             }
609         }
610
611         if (is_null($location)) { // still haven't found it!
612             if (!empty($this->location)) {
613                 $location = Location::fromName($this->location);
614             }
615         }
616
617         return $location;
618     }
619
620     function hasRole($name)
621     {
622         $has_role = false;
623         if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
624             $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
625                                                 'role' => $name));
626             $has_role = !empty($role);
627             Event::handle('EndHasRole', array($this, $name, $has_role));
628         }
629         return $has_role;
630     }
631
632     function grantRole($name)
633     {
634         $role = new Profile_role();
635
636         $role->profile_id = $this->id;
637         $role->role       = $name;
638         $role->created    = common_sql_now();
639
640         $result = $role->insert();
641
642         if (!$result) {
643             common_log_db_error($role, 'INSERT', __FILE__);
644             return false;
645         }
646
647         return true;
648     }
649
650     function revokeRole($name)
651     {
652         $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
653                                             'role' => $name));
654
655         if (empty($role)) {
656             throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; does not exist.');
657         }
658
659         $result = $role->delete();
660
661         if (!$result) {
662             common_log_db_error($role, 'DELETE', __FILE__);
663             throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; database error.');
664         }
665
666         return true;
667     }
668
669     function isSandboxed()
670     {
671         return $this->hasRole(Profile_role::SANDBOXED);
672     }
673
674     function isSilenced()
675     {
676         return $this->hasRole(Profile_role::SILENCED);
677     }
678
679     function sandbox()
680     {
681         $this->grantRole(Profile_role::SANDBOXED);
682     }
683
684     function unsandbox()
685     {
686         $this->revokeRole(Profile_role::SANDBOXED);
687     }
688
689     function silence()
690     {
691         $this->grantRole(Profile_role::SILENCED);
692     }
693
694     function unsilence()
695     {
696         $this->revokeRole(Profile_role::SILENCED);
697     }
698
699     /**
700      * Does this user have the right to do X?
701      *
702      * With our role-based authorization, this is merely a lookup for whether the user
703      * has a particular role. The implementation currently uses a switch statement
704      * to determine if the user has the pre-defined role to exercise the right. Future
705      * implementations may allow per-site roles, and different mappings of roles to rights.
706      *
707      * @param $right string Name of the right, usually a constant in class Right
708      * @return boolean whether the user has the right in question
709      */
710
711     function hasRight($right)
712     {
713         $result = false;
714         if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
715             switch ($right)
716             {
717             case Right::DELETEOTHERSNOTICE:
718             case Right::SANDBOXUSER:
719             case Right::SILENCEUSER:
720             case Right::DELETEUSER:
721                 $result = $this->hasRole(Profile_role::MODERATOR);
722                 break;
723             case Right::CONFIGURESITE:
724                 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
725                 break;
726             case Right::NEWNOTICE:
727             case Right::NEWMESSAGE:
728             case Right::SUBSCRIBE:
729                 $result = !$this->isSilenced();
730                 break;
731             case Right::PUBLICNOTICE:
732             case Right::EMAILONREPLY:
733             case Right::EMAILONSUBSCRIBE:
734             case Right::EMAILONFAVE:
735                 $result = !$this->isSandboxed();
736                 break;
737             default:
738                 $result = false;
739                 break;
740             }
741         }
742         return $result;
743     }
744
745     function hasRepeated($notice_id)
746     {
747         // XXX: not really a pkey, but should work
748
749         $notice = Memcached_DataObject::pkeyGet('Notice',
750                                                 array('profile_id' => $this->id,
751                                                       'repeat_of' => $notice_id));
752
753         return !empty($notice);
754     }
755 }