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