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