]> git.mxchange.org Git - friendica.git/blob - src/Module/Settings/Profile/Index.php
old boot.php functions replaced in src/module (3)
[friendica.git] / src / Module / Settings / Profile / Index.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Module\Settings\Profile;
23
24 use Friendica\Core\ACL;
25 use Friendica\Core\Hook;
26 use Friendica\Core\Protocol;
27 use Friendica\Core\Renderer;
28 use Friendica\Core\Session;
29 use Friendica\Core\Theme;
30 use Friendica\Database\DBA;
31 use Friendica\DI;
32 use Friendica\Model\Contact;
33 use Friendica\Model\Profile;
34 use Friendica\Profile\ProfileField\Collection\ProfileFields;
35 use Friendica\Profile\ProfileField\Entity\ProfileField;
36 use Friendica\Model\User;
37 use Friendica\Module\BaseSettings;
38 use Friendica\Module\Security\Login;
39 use Friendica\Network\HTTPException;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Temporal;
42
43 class Index extends BaseSettings
44 {
45         protected function post(array $request = [])
46         {
47                 if (!Session::getLocalUser()) {
48                         return;
49                 }
50
51                 $profile = Profile::getByUID(Session::getLocalUser());
52                 if (!DBA::isResult($profile)) {
53                         return;
54                 }
55
56                 self::checkFormSecurityTokenRedirectOnError('/settings/profile', 'settings_profile');
57
58                 Hook::callAll('profile_post', $_POST);
59
60                 $dob = trim($_POST['dob'] ?? '');
61
62                 if ($dob && !in_array($dob, ['0000-00-00', DBA::NULL_DATE])) {
63                         $y = substr($dob, 0, 4);
64                         if ((!ctype_digit($y)) || ($y < 1900)) {
65                                 $ignore_year = true;
66                         } else {
67                                 $ignore_year = false;
68                         }
69
70                         if (strpos($dob, '0000-') === 0 || strpos($dob, '0001-') === 0) {
71                                 $ignore_year = true;
72                                 $dob = substr($dob, 5);
73                         }
74
75                         if ($ignore_year) {
76                                 $dob = '0000-' . DateTimeFormat::utc('1900-' . $dob, 'm-d');
77                         } else {
78                                 $dob = DateTimeFormat::utc($dob, 'Y-m-d');
79                         }
80                 }
81
82                 $name = trim($_POST['name'] ?? '');
83                 if (!strlen($name)) {
84                         DI::sysmsg()->addNotice(DI::l10n()->t('Profile Name is required.'));
85                         return;
86                 }
87
88                 $about = trim($_POST['about']);
89                 $address = trim($_POST['address']);
90                 $locality = trim($_POST['locality']);
91                 $region = trim($_POST['region']);
92                 $postal_code = trim($_POST['postal_code']);
93                 $country_name = trim($_POST['country_name']);
94                 $pub_keywords = self::cleanKeywords(trim($_POST['pub_keywords']));
95                 $prv_keywords = self::cleanKeywords(trim($_POST['prv_keywords']));
96                 $xmpp = trim($_POST['xmpp']);
97                 $matrix = trim($_POST['matrix']);
98                 $homepage = trim($_POST['homepage']);
99                 if ((strpos($homepage, 'http') !== 0) && (strlen($homepage))) {
100                         // neither http nor https in URL, add them
101                         $homepage = 'http://' . $homepage;
102                 }
103
104                 $profileFieldsNew = self::getProfileFieldsFromInput(
105                         Session::getLocalUser(),
106                         $_REQUEST['profile_field'],
107                         $_REQUEST['profile_field_order']
108                 );
109
110                 DI::profileField()->saveCollectionForUser(Session::getLocalUser(), $profileFieldsNew);
111
112                 $result = Profile::update(
113                         [
114                                 'name'         => $name,
115                                 'about'        => $about,
116                                 'dob'          => $dob,
117                                 'address'      => $address,
118                                 'locality'     => $locality,
119                                 'region'       => $region,
120                                 'postal-code'  => $postal_code,
121                                 'country-name' => $country_name,
122                                 'xmpp'         => $xmpp,
123                                 'matrix'       => $matrix,
124                                 'homepage'     => $homepage,
125                                 'pub_keywords' => $pub_keywords,
126                                 'prv_keywords' => $prv_keywords,
127                         ],
128                         Session::getLocalUser()
129                 );
130
131                 if (!$result) {
132                         DI::sysmsg()->addNotice(DI::l10n()->t('Profile couldn\'t be updated.'));
133                         return;
134                 }
135
136                 DI::baseUrl()->redirect('settings/profile');
137         }
138
139         protected function content(array $request = []): string
140         {
141                 if (!Session::getLocalUser()) {
142                         DI::sysmsg()->addNotice(DI::l10n()->t('You must be logged in to use this module'));
143                         return Login::form();
144                 }
145
146                 parent::content();
147
148                 $o = '';
149
150                 $profile = User::getOwnerDataById(Session::getLocalUser());
151                 if (!DBA::isResult($profile)) {
152                         throw new HTTPException\NotFoundException();
153                 }
154
155                 $a = DI::app();
156
157                 DI::page()->registerFooterScript('view/asset/es-jquery-sortable/source/js/jquery-sortable-min.js');
158                 DI::page()->registerFooterScript(Theme::getPathForFile('js/module/settings/profile/index.js'));
159
160                 $custom_fields = [];
161
162                 $profileFields = DI::profileField()->selectByUserId(Session::getLocalUser());
163                 foreach ($profileFields as $profileField) {
164                         /** @var ProfileField $profileField */
165                         $defaultPermissions = $profileField->permissionSet->withAllowedContacts(
166                                 Contact::pruneUnavailable($profileField->permissionSet->allow_cid)
167                         );
168
169                         $custom_fields[] = [
170                                 'id' => $profileField->id,
171                                 'legend' => $profileField->label,
172                                 'fields' => [
173                                         'label' => ['profile_field[' . $profileField->id . '][label]', DI::l10n()->t('Label:'), $profileField->label],
174                                         'value' => ['profile_field[' . $profileField->id . '][value]', DI::l10n()->t('Value:'), $profileField->value],
175                                         'acl' => ACL::getFullSelectorHTML(
176                                                 DI::page(),
177                                                 $a->getLoggedInUserId(),
178                                                 false,
179                                                 $defaultPermissions->toArray(),
180                                                 ['network' => Protocol::DFRN],
181                                                 'profile_field[' . $profileField->id . ']'
182                                         ),
183                                 ],
184                                 'permissions' => DI::l10n()->t('Field Permissions'),
185                                 'permdesc' => DI::l10n()->t("(click to open/close)"),
186                         ];
187                 };
188
189                 $custom_fields[] = [
190                         'id' => 'new',
191                         'legend' => DI::l10n()->t('Add a new profile field'),
192                         'fields' => [
193                                 'label' => ['profile_field[new][label]', DI::l10n()->t('Label:')],
194                                 'value' => ['profile_field[new][value]', DI::l10n()->t('Value:')],
195                                 'acl' => ACL::getFullSelectorHTML(
196                                         DI::page(),
197                                         $a->getLoggedInUserId(),
198                                         false,
199                                         ['allow_cid' => []],
200                                         ['network' => Protocol::DFRN],
201                                         'profile_field[new]'
202                                 ),
203                         ],
204                         'permissions' => DI::l10n()->t('Field Permissions'),
205                         'permdesc' => DI::l10n()->t("(click to open/close)"),
206                 ];
207
208                 DI::page()['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('settings/profile/index_head.tpl'), [
209                         '$baseurl' => DI::baseUrl()->get(true),
210                 ]);
211
212                 $personal_account = ($profile['account-type'] != User::ACCOUNT_TYPE_COMMUNITY);
213
214                 $tpl = Renderer::getMarkupTemplate('settings/profile/index.tpl');
215                 $o .= Renderer::replaceMacros($tpl, [
216                         '$personal_account' => $personal_account,
217
218                         '$form_security_token' => self::getFormSecurityToken('settings_profile'),
219                         '$form_security_token_photo' => self::getFormSecurityToken('settings_profile_photo'),
220
221                         '$profile_action' => DI::l10n()->t('Profile Actions'),
222                         '$banner' => DI::l10n()->t('Edit Profile Details'),
223                         '$submit' => DI::l10n()->t('Submit'),
224                         '$profpic' => DI::l10n()->t('Change Profile Photo'),
225                         '$profpiclink' => '/photos/' . $profile['nickname'],
226                         '$viewprof' => DI::l10n()->t('View Profile'),
227
228                         '$lbl_personal_section' => DI::l10n()->t('Personal'),
229                         '$lbl_picture_section' => DI::l10n()->t('Profile picture'),
230                         '$lbl_location_section' => DI::l10n()->t('Location'),
231                         '$lbl_miscellaneous_section' => DI::l10n()->t('Miscellaneous'),
232                         '$lbl_custom_fields_section' => DI::l10n()->t('Custom Profile Fields'),
233
234                         '$lbl_profile_photo' => DI::l10n()->t('Upload Profile Photo'),
235
236                         '$baseurl' => DI::baseUrl()->get(true),
237                         '$nickname' => $profile['nickname'],
238                         '$name' => ['name', DI::l10n()->t('Display name:'), $profile['name']],
239                         '$about' => ['about', DI::l10n()->t('Description:'), $profile['about']],
240                         '$dob' => Temporal::getDateofBirthField($profile['dob'], $profile['timezone']),
241                         '$address' => ['address', DI::l10n()->t('Street Address:'), $profile['address']],
242                         '$locality' => ['locality', DI::l10n()->t('Locality/City:'), $profile['locality']],
243                         '$region' => ['region', DI::l10n()->t('Region/State:'), $profile['region']],
244                         '$postal_code' => ['postal_code', DI::l10n()->t('Postal/Zip Code:'), $profile['postal-code']],
245                         '$country_name' => ['country_name', DI::l10n()->t('Country:'), $profile['country-name']],
246                         '$age' => ((intval($profile['dob'])) ? '(' . DI::l10n()->t('Age: ') . DI::l10n()->tt('%d year old', '%d years old', Temporal::getAgeByTimezone($profile['dob'], $profile['timezone'])) . ')' : ''),
247                         '$xmpp' => ['xmpp', DI::l10n()->t('XMPP (Jabber) address:'), $profile['xmpp'], DI::l10n()->t('The XMPP address will be published so that people can follow you there.')],
248                         '$matrix' => ['matrix', DI::l10n()->t('Matrix (Element) address:'), $profile['matrix'], DI::l10n()->t('The Matrix address will be published so that people can follow you there.')],
249                         '$homepage' => ['homepage', DI::l10n()->t('Homepage URL:'), $profile['homepage']],
250                         '$pub_keywords' => ['pub_keywords', DI::l10n()->t('Public Keywords:'), $profile['pub_keywords'], DI::l10n()->t('(Used for suggesting potential friends, can be seen by others)')],
251                         '$prv_keywords' => ['prv_keywords', DI::l10n()->t('Private Keywords:'), $profile['prv_keywords'], DI::l10n()->t('(Used for searching profiles, never shown to others)')],
252                         '$custom_fields_description' => DI::l10n()->t("<p>Custom fields appear on <a href=\"%s\">your profile page</a>.</p>
253                                 <p>You can use BBCodes in the field values.</p>
254                                 <p>Reorder by dragging the field title.</p>
255                                 <p>Empty the label field to remove a custom field.</p>
256                                 <p>Non-public fields can only be seen by the selected Friendica contacts or the Friendica contacts in the selected groups.</p>",
257                                 'profile/' . $profile['nickname']
258                         ),
259                         '$custom_fields' => $custom_fields,
260                 ]);
261
262                 $arr = ['profile' => $profile, 'entry' => $o];
263                 Hook::callAll('profile_edit', $arr);
264
265                 return $o;
266         }
267
268         private static function getProfileFieldsFromInput(int $uid, array $profileFieldInputs, array $profileFieldOrder): ProfileFields
269         {
270                 $profileFields = new ProfileFields();
271
272                 // Returns an associative array of id => order values
273                 $profileFieldOrder = array_flip($profileFieldOrder);
274
275                 // Creation of the new field
276                 if (!empty($profileFieldInputs['new']['label'])) {
277                         $permissionSet = DI::permissionSet()->selectOrCreate(DI::permissionSetFactory()->createFromString(
278                                 $uid,
279                                 DI::aclFormatter()->toString($profileFieldInputs['new']['contact_allow'] ?? ''),
280                                 DI::aclFormatter()->toString($profileFieldInputs['new']['group_allow'] ?? ''),
281                                 DI::aclFormatter()->toString($profileFieldInputs['new']['contact_deny'] ?? ''),
282                                 DI::aclFormatter()->toString($profileFieldInputs['new']['group_deny'] ?? '')
283                         ));
284
285                         $profileFields->append(DI::profileFieldFactory()->createFromValues(
286                                 $uid,
287                                 $profileFieldOrder['new'],
288                                 $profileFieldInputs['new']['label'],
289                                 $profileFieldInputs['new']['value'],
290                                 $permissionSet
291                         ));
292                 }
293
294                 unset($profileFieldInputs['new']);
295                 unset($profileFieldOrder['new']);
296
297                 foreach ($profileFieldInputs as $id => $profileFieldInput) {
298                         $permissionSet = DI::permissionSet()->selectOrCreate(DI::permissionSetFactory()->createFromString(
299                                 $uid,
300                                 DI::aclFormatter()->toString($profileFieldInput['contact_allow'] ?? ''),
301                                 DI::aclFormatter()->toString($profileFieldInput['group_allow'] ?? ''),
302                                 DI::aclFormatter()->toString($profileFieldInput['contact_deny'] ?? ''),
303                                 DI::aclFormatter()->toString($profileFieldInput['group_deny'] ?? '')
304                         ));
305
306                         $profileFields->append(DI::profileFieldFactory()->createFromValues(
307                                 $uid,
308                                 $profileFieldOrder[$id],
309                                 $profileFieldInput['label'],
310                                 $profileFieldInput['value'],
311                                 $permissionSet
312                         ));
313                 }
314
315                 return $profileFields;
316         }
317
318         private static function cleanKeywords($keywords)
319         {
320                 $keywords = str_replace(',', ' ', $keywords);
321                 $keywords = explode(' ', $keywords);
322
323                 $cleaned = [];
324                 foreach ($keywords as $keyword) {
325                         $keyword = trim(strtolower($keyword));
326                         $keyword = trim($keyword, '#');
327                         if ($keyword != '') {
328                                 $cleaned[] = $keyword;
329                         }
330                 }
331
332                 $keywords = implode(', ', $cleaned);
333
334                 return $keywords;
335         }
336 }