]> git.mxchange.org Git - friendica.git/blob - mod/photos.php
Replace json_encode + exit by System::jsonExit in mod/item
[friendica.git] / mod / photos.php
1 <?php
2 /**
3  * @file mod/photos.php
4  */
5
6 use Friendica\App;
7 use Friendica\Content\Feature;
8 use Friendica\Content\Nav;
9 use Friendica\Content\Pager;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Core\ACL;
12 use Friendica\Core\Hook;
13 use Friendica\Core\Logger;
14 use Friendica\Core\Renderer;
15 use Friendica\Core\Session;
16 use Friendica\Core\System;
17 use Friendica\Database\DBA;
18 use Friendica\DI;
19 use Friendica\Model\Contact;
20 use Friendica\Model\Item;
21 use Friendica\Model\Photo;
22 use Friendica\Model\Profile;
23 use Friendica\Model\User;
24 use Friendica\Module\BaseProfile;
25 use Friendica\Network\Probe;
26 use Friendica\Object\Image;
27 use Friendica\Protocol\Activity;
28 use Friendica\Util\Crypto;
29 use Friendica\Util\DateTimeFormat;
30 use Friendica\Util\Images;
31 use Friendica\Util\Map;
32 use Friendica\Util\Security;
33 use Friendica\Util\Strings;
34 use Friendica\Util\Temporal;
35 use Friendica\Util\XML;
36
37 function photos_init(App $a) {
38
39         if (DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) {
40                 return;
41         }
42
43         Nav::setSelected('home');
44
45         if ($a->argc > 1) {
46                 $nick = $a->argv[1];
47                 $user = DBA::selectFirst('user', [], ['nickname' => $nick, 'blocked' => false]);
48
49                 if (!DBA::isResult($user)) {
50                         return;
51                 }
52
53                 $a->data['user'] = $user;
54                 $a->profile_uid = $user['uid'];
55                 $is_owner = (local_user() && (local_user() == $a->profile_uid));
56
57                 $profile = Profile::getByNickname($nick, $a->profile_uid);
58
59                 $account_type = Contact::getAccountType($profile);
60
61                 $tpl = Renderer::getMarkupTemplate("widget/vcard.tpl");
62
63                 $vcard_widget = Renderer::replaceMacros($tpl, [
64                         '$name' => $profile['name'],
65                         '$photo' => $profile['photo'],
66                         '$addr' => $profile['addr'] ?? '',
67                         '$account_type' => $account_type,
68                         '$pdesc' => $profile['pdesc'] ?? '',
69                 ]);
70
71                 $albums = Photo::getAlbums($a->data['user']['uid']);
72
73                 $albums_visible = ((intval($a->data['user']['hidewall']) && !Session::isAuthenticated()) ? false : true);
74
75                 // add various encodings to the array so we can just loop through and pick them out in a template
76                 $ret = ['success' => false];
77
78                 if ($albums) {
79                         $a->data['albums'] = $albums;
80
81                         if ($albums_visible) {
82                                 $ret['success'] = true;
83                         }
84
85                         $ret['albums'] = [];
86                         foreach ($albums as $k => $album) {
87                                 //hide profile photos to others
88                                 if (!$is_owner && !Session::getRemoteContactID($a->profile_uid) && ($album['album'] == DI::l10n()->t('Profile Photos')))
89                                         continue;
90                                 $entry = [
91                                         'text'      => $album['album'],
92                                         'total'     => $album['total'],
93                                         'url'       => 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album['album']),
94                                         'urlencode' => urlencode($album['album']),
95                                         'bin2hex'   => bin2hex($album['album'])
96                                 ];
97                                 $ret['albums'][] = $entry;
98                         }
99                 }
100
101                 if (local_user() && $a->data['user']['uid'] == local_user()) {
102                         $can_post = true;
103                 } else {
104                         $can_post = false;
105                 }
106
107                 if ($ret['success']) {
108                         $photo_albums_widget = Renderer::replaceMacros(Renderer::getMarkupTemplate('photo_albums.tpl'), [
109                                 '$nick'     => $a->data['user']['nickname'],
110                                 '$title'    => DI::l10n()->t('Photo Albums'),
111                                 '$recent'   => DI::l10n()->t('Recent Photos'),
112                                 '$albums'   => $ret['albums'],
113                                 '$upload'   => [DI::l10n()->t('Upload New Photos'), 'photos/' . $a->data['user']['nickname'] . '/upload'],
114                                 '$can_post' => $can_post
115                         ]);
116                 }
117
118                 if (empty(DI::page()['aside'])) {
119                         DI::page()['aside'] = '';
120                 }
121
122                 DI::page()['aside'] .= $vcard_widget;
123
124                 if (!empty($photo_albums_widget)) {
125                         DI::page()['aside'] .= $photo_albums_widget;
126                 }
127
128                 $tpl = Renderer::getMarkupTemplate("photos_head.tpl");
129
130                 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl,[
131                         '$ispublic' => DI::l10n()->t('everybody')
132                 ]);
133         }
134
135         return;
136 }
137
138 function photos_post(App $a)
139 {
140         Logger::log('mod-photos: photos_post: begin' , Logger::DEBUG);
141         Logger::log('mod_photos: REQUEST ' . print_r($_REQUEST, true), Logger::DATA);
142         Logger::log('mod_photos: FILES '   . print_r($_FILES, true), Logger::DATA);
143
144         $phototypes = Images::supportedTypes();
145
146         $can_post  = false;
147         $visitor   = 0;
148
149         $page_owner_uid = intval($a->data['user']['uid']);
150         $community_page = $a->data['user']['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
151
152         if (local_user() && (local_user() == $page_owner_uid)) {
153                 $can_post = true;
154         } elseif ($community_page && !empty(Session::getRemoteContactID($page_owner_uid))) {
155                 $contact_id = Session::getRemoteContactID($page_owner_uid);
156                 $can_post = true;
157                 $visitor = $contact_id;
158         }
159
160         if (!$can_post) {
161                 notice(DI::l10n()->t('Permission denied.') . EOL);
162                 exit();
163         }
164
165         $owner_record = User::getOwnerDataById($page_owner_uid);
166
167         if (!$owner_record) {
168                 notice(DI::l10n()->t('Contact information unavailable') . EOL);
169                 Logger::log('photos_post: unable to locate contact record for page owner. uid=' . $page_owner_uid);
170                 exit();
171         }
172
173         if ($a->argc > 3 && $a->argv[2] === 'album') {
174                 if (!Strings::isHex($a->argv[3])) {
175                         DI::baseUrl()->redirect('photos/' . $a->data['user']['nickname'] . '/album');
176                 }
177                 $album = hex2bin($a->argv[3]);
178
179                 if ($album === DI::l10n()->t('Profile Photos') || $album === 'Contact Photos' || $album === DI::l10n()->t('Contact Photos')) {
180                         DI::baseUrl()->redirect($_SESSION['photo_return']);
181                         return; // NOTREACHED
182                 }
183
184                 $r = q("SELECT `album` FROM `photo` WHERE `album` = '%s' AND `uid` = %d",
185                         DBA::escape($album),
186                         intval($page_owner_uid)
187                 );
188
189                 if (!DBA::isResult($r)) {
190                         notice(DI::l10n()->t('Album not found.') . EOL);
191                         DI::baseUrl()->redirect($_SESSION['photo_return']);
192                         return; // NOTREACHED
193                 }
194
195                 // Check if the user has responded to a delete confirmation query
196                 if (!empty($_REQUEST['canceled'])) {
197                         DI::baseUrl()->redirect($_SESSION['photo_return']);
198                 }
199
200                 // RENAME photo album
201                 $newalbum = Strings::escapeTags(trim($_POST['albumname']));
202                 if ($newalbum != $album) {
203                         q("UPDATE `photo` SET `album` = '%s' WHERE `album` = '%s' AND `uid` = %d",
204                                 DBA::escape($newalbum),
205                                 DBA::escape($album),
206                                 intval($page_owner_uid)
207                         );
208                         // Update the photo albums cache
209                         Photo::clearAlbumCache($page_owner_uid);
210
211                         DI::baseUrl()->redirect('photos/' . $a->user['nickname'] . '/album/' . bin2hex($newalbum));
212                         return; // NOTREACHED
213                 }
214
215                 /*
216                  * DELETE all photos filed in a given album
217                  */
218                 if (!empty($_POST['dropalbum'])) {
219                         $res = [];
220
221                         // get the list of photos we are about to delete
222                         if ($visitor) {
223                                 $r = q("SELECT distinct(`resource-id`) as `rid` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d AND `album` = '%s'",
224                                         intval($visitor),
225                                         intval($page_owner_uid),
226                                         DBA::escape($album)
227                                 );
228                         } else {
229                                 $r = q("SELECT distinct(`resource-id`) as `rid` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
230                                         intval(local_user()),
231                                         DBA::escape($album)
232                                 );
233                         }
234
235                         if (DBA::isResult($r)) {
236                                 foreach ($r as $rr) {
237                                         $res[] = $rr['rid'];
238                                 }
239
240                                 // remove the associated photos
241                                 Photo::delete(['resource-id' => $res, 'uid' => $page_owner_uid]);
242
243                                 // find and delete the corresponding item with all the comments and likes/dislikes
244                                 Item::deleteForUser(['resource-id' => $res, 'uid' => $page_owner_uid], $page_owner_uid);
245
246                                 // Update the photo albums cache
247                                 Photo::clearAlbumCache($page_owner_uid);
248                                 notice(DI::l10n()->t('Album successfully deleted'));
249                         } else {
250                                 notice(DI::l10n()->t('Album was empty.'));
251                         }
252                 }
253
254                 DI::baseUrl()->redirect('photos/' . $a->argv[1]);
255         }
256
257         if ($a->argc > 3 && $a->argv[2] === 'image') {
258                 // Check if the user has responded to a delete confirmation query for a single photo
259                 if (!empty($_POST['canceled'])) {
260                         DI::baseUrl()->redirect('photos/' . $a->argv[1] . '/image/' . $a->argv[3]);
261                 }
262
263                 if (!empty($_POST['delete'])) {
264                         // same as above but remove single photo
265                         if ($visitor) {
266                                 $condition = ['contact-id' => $visitor, 'uid' => $page_owner_uid, 'resource-id' => $a->argv[3]];
267
268                         } else {
269                                 $condition = ['uid' => local_user(), 'resource-id' => $a->argv[3]];
270                         }
271
272                         $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
273
274                         if (DBA::isResult($photo)) {
275                                 Photo::delete(['uid' => $page_owner_uid, 'resource-id' => $photo['resource-id']]);
276
277                                 Item::deleteForUser(['resource-id' => $photo['resource-id'], 'uid' => $page_owner_uid], $page_owner_uid);
278
279                                 // Update the photo albums cache
280                                 Photo::clearAlbumCache($page_owner_uid);
281                                 notice('Successfully deleted the photo.');
282                         } else {
283                                 notice('Failed to delete the photo.');
284                                 DI::baseUrl()->redirect('photos/' . $a->argv[1] . '/image/' . $a->argv[3]);
285                         }
286
287                         DI::baseUrl()->redirect('photos/' . $a->argv[1]);
288                         return; // NOTREACHED
289                 }
290         }
291
292         if ($a->argc > 2 && (!empty($_POST['desc']) || !empty($_POST['newtag']) || isset($_POST['albname']))) {
293                 $desc        = !empty($_POST['desc'])      ? Strings::escapeTags(trim($_POST['desc']))      : '';
294                 $rawtags     = !empty($_POST['newtag'])    ? Strings::escapeTags(trim($_POST['newtag']))    : '';
295                 $item_id     = !empty($_POST['item_id'])   ? intval($_POST['item_id'])                      : 0;
296                 $albname     = !empty($_POST['albname'])   ? Strings::escapeTags(trim($_POST['albname']))   : '';
297                 $origaname   = !empty($_POST['origaname']) ? Strings::escapeTags(trim($_POST['origaname'])) : '';
298
299                 $aclFormatter = DI::aclFormatter();
300
301                 $str_group_allow   = !empty($_POST['group_allow'])   ? $aclFormatter->toString($_POST['group_allow'])   : '';
302                 $str_contact_allow = !empty($_POST['contact_allow']) ? $aclFormatter->toString($_POST['contact_allow']) : '';
303                 $str_group_deny    = !empty($_POST['group_deny'])    ? $aclFormatter->toString($_POST['group_deny'])    : '';
304                 $str_contact_deny  = !empty($_POST['contact_deny'])  ? $aclFormatter->toString($_POST['contact_deny'])  : '';
305
306                 $resource_id = $a->argv[3];
307
308                 if (!strlen($albname)) {
309                         $albname = DateTimeFormat::localNow('Y');
310                 }
311
312                 if (!empty($_POST['rotate']) && (intval($_POST['rotate']) == 1 || intval($_POST['rotate']) == 2)) {
313                         Logger::log('rotate');
314
315                         $photo = Photo::getPhotoForUser($page_owner_uid, $resource_id);
316
317                         if (DBA::isResult($photo)) {
318                                 $image = Photo::getImageForPhoto($photo);
319
320                                 if ($image->isValid()) {
321                                         $rotate_deg = ((intval($_POST['rotate']) == 1) ? 270 : 90);
322                                         $image->rotate($rotate_deg);
323
324                                         $width  = $image->getWidth();
325                                         $height = $image->getHeight();
326
327                                         Photo::update(['height' => $height, 'width' => $width], ['resource-id' => $resource_id, 'uid' => $page_owner_uid, 'scale' => 0], $image);
328
329                                         if ($width > 640 || $height > 640) {
330                                                 $image->scaleDown(640);
331                                                 $width  = $image->getWidth();
332                                                 $height = $image->getHeight();
333
334                                                 Photo::update(['height' => $height, 'width' => $width], ['resource-id' => $resource_id, 'uid' => $page_owner_uid, 'scale' => 1], $image);
335                                         }
336
337                                         if ($width > 320 || $height > 320) {
338                                                 $image->scaleDown(320);
339                                                 $width  = $image->getWidth();
340                                                 $height = $image->getHeight();
341
342                                                 Photo::update(['height' => $height, 'width' => $width], ['resource-id' => $resource_id, 'uid' => $page_owner_uid, 'scale' => 2], $image);
343                                         }
344                                 }
345                         }
346                 }
347
348                 $photos_stmt = DBA::select('photo', [], ['resource-id' => $resource_id, 'uid' => $page_owner_uid], ['order' => ['scale' => true]]);
349
350                 $photos = DBA::toArray($photos_stmt);
351
352                 if (DBA::isResult($photos)) {
353                         $photo = $photos[0];
354                         $ext = $phototypes[$photo['type']];
355                         Photo::update(
356                                 ['desc' => $desc, 'album' => $albname, 'allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow, 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny],
357                                 ['resource-id' => $resource_id, 'uid' => $page_owner_uid]
358                         );
359
360                         // Update the photo albums cache if album name was changed
361                         if ($albname !== $origaname) {
362                                 Photo::clearAlbumCache($page_owner_uid);
363                         }
364                         /* Don't make the item visible if the only change was the album name */
365
366                         $visibility = 0;
367                         if ($photo['desc'] !== $desc || strlen($rawtags)) {
368                                 $visibility = 1;
369                         }
370                 }
371
372                 if (DBA::isResult($photos) && !$item_id) {
373                         // Create item container
374                         $title = '';
375                         $uri = Item::newURI($page_owner_uid);
376
377                         $arr = [];
378                         $arr['guid']          = System::createUUID();
379                         $arr['uid']           = $page_owner_uid;
380                         $arr['uri']           = $uri;
381                         $arr['parent-uri']    = $uri;
382                         $arr['post-type']     = Item::PT_IMAGE;
383                         $arr['wall']          = 1;
384                         $arr['resource-id']   = $photo['resource-id'];
385                         $arr['contact-id']    = $owner_record['id'];
386                         $arr['owner-name']    = $owner_record['name'];
387                         $arr['owner-link']    = $owner_record['url'];
388                         $arr['owner-avatar']  = $owner_record['thumb'];
389                         $arr['author-name']   = $owner_record['name'];
390                         $arr['author-link']   = $owner_record['url'];
391                         $arr['author-avatar'] = $owner_record['thumb'];
392                         $arr['title']         = $title;
393                         $arr['allow_cid']     = $photo['allow_cid'];
394                         $arr['allow_gid']     = $photo['allow_gid'];
395                         $arr['deny_cid']      = $photo['deny_cid'];
396                         $arr['deny_gid']      = $photo['deny_gid'];
397                         $arr['visible']       = $visibility;
398                         $arr['origin']        = 1;
399
400                         $arr['body']          = '[url=' . DI::baseUrl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $photo['resource-id'] . ']'
401                                                 . '[img]' . DI::baseUrl() . '/photo/' . $photo['resource-id'] . '-' . $photo['scale'] . '.'. $ext . '[/img]'
402                                                 . '[/url]';
403
404                         $item_id = Item::insert($arr);
405                 }
406
407                 if ($item_id) {
408                         $item = Item::selectFirst(['tag', 'inform'], ['id' => $item_id, 'uid' => $page_owner_uid]);
409
410                         if (DBA::isResult($item)) {
411                                 $old_tag    = $item['tag'];
412                                 $old_inform = $item['inform'];
413                         }
414                 }
415
416                 if (strlen($rawtags)) {
417                         $str_tags = '';
418                         $inform   = '';
419
420                         // if the new tag doesn't have a namespace specifier (@foo or #foo) give it a hashtag
421                         $x = substr($rawtags, 0, 1);
422                         if ($x !== '@' && $x !== '#') {
423                                 $rawtags = '#' . $rawtags;
424                         }
425
426                         $taginfo = [];
427                         $tags = BBCode::getTags($rawtags);
428
429                         if (count($tags)) {
430                                 foreach ($tags as $tag) {
431                                         if (strpos($tag, '@') === 0) {
432                                                 $profile = '';
433                                                 $contact = null;
434                                                 $name = substr($tag,1);
435
436                                                 if ((strpos($name, '@')) || (strpos($name, 'http://'))) {
437                                                         $newname = $name;
438                                                         $links = @Probe::lrdd($name);
439
440                                                         if (count($links)) {
441                                                                 foreach ($links as $link) {
442                                                                         if ($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page') {
443                                                                                 $profile = $link['@attributes']['href'];
444                                                                         }
445
446                                                                         if ($link['@attributes']['rel'] === 'salmon') {
447                                                                                 $salmon = '$url:' . str_replace(',', '%sc', $link['@attributes']['href']);
448
449                                                                                 if (strlen($inform)) {
450                                                                                         $inform .= ',';
451                                                                                 }
452
453                                                                                 $inform .= $salmon;
454                                                                         }
455                                                                 }
456                                                         }
457
458                                                         $taginfo[] = [$newname, $profile, $salmon];
459                                                 } else {
460                                                         $newname = $name;
461                                                         $tagcid = 0;
462
463                                                         if (strrpos($newname, '+')) {
464                                                                 $tagcid = intval(substr($newname, strrpos($newname, '+') + 1));
465                                                         }
466
467                                                         if ($tagcid) {
468                                                                 $contact = DBA::selectFirst('contact', [], ['id' => $tagcid, 'uid' => $page_owner_uid]);
469                                                         } else {
470                                                                 $newname = str_replace('_',' ',$name);
471
472                                                                 //select someone from this user's contacts by name
473                                                                 $contact = DBA::selectFirst('contact', [], ['name' => $newname, 'uid' => $page_owner_uid]);
474                                                                 if (!DBA::isResult($contact)) {
475                                                                         //select someone by attag or nick and the name passed in
476                                                                         $contact = DBA::selectFirst('contact', [],
477                                                                                 ['(`attag` = ? OR `nick` = ?) AND `uid` = ?', $name, $name, $page_owner_uid],
478                                                                                 ['order' => ['attag' => true]]
479                                                                         );
480                                                                 }
481                                                         }
482
483                                                         if (DBA::isResult($contact)) {
484                                                                 $newname = $contact['name'];
485                                                                 $profile = $contact['url'];
486
487                                                                 $notify = 'cid:' . $contact['id'];
488                                                                 if (strlen($inform)) {
489                                                                         $inform .= ',';
490                                                                 }
491                                                                 $inform .= $notify;
492                                                         }
493                                                 }
494
495                                                 if ($profile) {
496                                                         if (!empty($contact)) {
497                                                                 $taginfo[] = [$newname, $profile, $notify, $contact, '@[url=' . str_replace(',', '%2c', $profile) . ']' . $newname . '[/url]'];
498                                                         } else {
499                                                                 $taginfo[] = [$newname, $profile, $notify, null, $str_tags .= '@[url=' . $profile . ']' . $newname . '[/url]'];
500                                                         }
501
502                                                         if (strlen($str_tags)) {
503                                                                 $str_tags .= ',';
504                                                         }
505
506                                                         $profile = str_replace(',', '%2c', $profile);
507                                                         $str_tags .= '@[url=' . $profile . ']' . $newname . '[/url]';
508                                                 }
509                                         } elseif (strpos($tag, '#') === 0) {
510                                                 $tagname = substr($tag, 1);
511                                                 $str_tags .= '#[url=' . DI::baseUrl() . "/search?tag=" . $tagname . ']' . $tagname . '[/url],';
512                                         }
513                                 }
514                         }
515
516                         $newtag = $old_tag ?? '';
517                         if (strlen($newtag) && strlen($str_tags)) {
518                                 $newtag .= ',';
519                         }
520                         $newtag .= $str_tags;
521
522                         $newinform = $old_inform ?? '';
523                         if (strlen($newinform) && strlen($inform)) {
524                                 $newinform .= ',';
525                         }
526                         $newinform .= $inform;
527
528                         $fields = ['tag' => $newtag, 'inform' => $newinform, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
529                         $condition = ['id' => $item_id];
530                         Item::update($fields, $condition);
531
532                         $best = 0;
533                         foreach ($photos as $scales) {
534                                 if (intval($scales['scale']) == 2) {
535                                         $best = 2;
536                                         break;
537                                 }
538
539                                 if (intval($scales['scale']) == 4) {
540                                         $best = 4;
541                                         break;
542                                 }
543                         }
544
545                         if (count($taginfo)) {
546                                 foreach ($taginfo as $tagged) {
547                                         $uri = Item::newURI($page_owner_uid);
548
549                                         $arr = [];
550                                         $arr['guid']          = System::createUUID();
551                                         $arr['uid']           = $page_owner_uid;
552                                         $arr['uri']           = $uri;
553                                         $arr['parent-uri']    = $uri;
554                                         $arr['wall']          = 1;
555                                         $arr['contact-id']    = $owner_record['id'];
556                                         $arr['owner-name']    = $owner_record['name'];
557                                         $arr['owner-link']    = $owner_record['url'];
558                                         $arr['owner-avatar']  = $owner_record['thumb'];
559                                         $arr['author-name']   = $owner_record['name'];
560                                         $arr['author-link']   = $owner_record['url'];
561                                         $arr['author-avatar'] = $owner_record['thumb'];
562                                         $arr['title']         = '';
563                                         $arr['allow_cid']     = $photo['allow_cid'];
564                                         $arr['allow_gid']     = $photo['allow_gid'];
565                                         $arr['deny_cid']      = $photo['deny_cid'];
566                                         $arr['deny_gid']      = $photo['deny_gid'];
567                                         $arr['visible']       = 1;
568                                         $arr['verb']          = Activity::TAG;
569                                         $arr['gravity']       = GRAVITY_PARENT;
570                                         $arr['object-type']   = Activity\ObjectType::PERSON;
571                                         $arr['target-type']   = Activity\ObjectType::IMAGE;
572                                         $arr['tag']           = $tagged[4];
573                                         $arr['inform']        = $tagged[2];
574                                         $arr['origin']        = 1;
575                                         $arr['body']          = DI::l10n()->t('%1$s was tagged in %2$s by %3$s', '[url=' . $tagged[1] . ']' . $tagged[0] . '[/url]', '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo['resource-id'] . ']' . DI::l10n()->t('a photo') . '[/url]', '[url=' . $owner_record['url'] . ']' . $owner_record['name'] . '[/url]') ;
576                                         $arr['body'] .= "\n\n" . '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo['resource-id'] . ']' . '[img]' . DI::baseUrl() . "/photo/" . $photo['resource-id'] . '-' . $best . '.' . $ext . '[/img][/url]' . "\n" ;
577
578                                         $arr['object'] = '<object><type>' . Activity\ObjectType::PERSON . '</type><title>' . $tagged[0] . '</title><id>' . $tagged[1] . '/' . $tagged[0] . '</id>';
579                                         $arr['object'] .= '<link>' . XML::escape('<link rel="alternate" type="text/html" href="' . $tagged[1] . '" />' . "\n");
580                                         if ($tagged[3]) {
581                                                 $arr['object'] .= XML::escape('<link rel="photo" type="' . $photo['type'] . '" href="' . $tagged[3]['photo'] . '" />' . "\n");
582                                         }
583                                         $arr['object'] .= '</link></object>' . "\n";
584
585                                         $arr['target'] = '<target><type>' . Activity\ObjectType::IMAGE . '</type><title>' . $photo['desc'] . '</title><id>'
586                                                 . DI::baseUrl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo['resource-id'] . '</id>';
587                                         $arr['target'] .= '<link>' . XML::escape('<link rel="alternate" type="text/html" href="' . DI::baseUrl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo['resource-id'] . '" />' . "\n" . '<link rel="preview" type="' . $photo['type'] . '" href="' . DI::baseUrl() . "/photo/" . $photo['resource-id'] . '-' . $best . '.' . $ext . '" />') . '</link></target>';
588
589                                         Item::insert($arr);
590                                 }
591                         }
592                 }
593                 DI::baseUrl()->redirect($_SESSION['photo_return']);
594                 return; // NOTREACHED
595         }
596
597
598         // default post action - upload a photo
599         Hook::callAll('photo_post_init', $_POST);
600
601         // Determine the album to use
602         $album    = !empty($_REQUEST['album'])    ? Strings::escapeTags(trim($_REQUEST['album']))    : '';
603         $newalbum = !empty($_REQUEST['newalbum']) ? Strings::escapeTags(trim($_REQUEST['newalbum'])) : '';
604
605         Logger::log('mod/photos.php: photos_post(): album= ' . $album . ' newalbum= ' . $newalbum , Logger::DEBUG);
606
607         if (!strlen($album)) {
608                 if (strlen($newalbum)) {
609                         $album = $newalbum;
610                 } else {
611                         $album = DateTimeFormat::localNow('Y');
612                 }
613         }
614
615         /*
616          * We create a wall item for every photo, but we don't want to
617          * overwhelm the data stream with a hundred newly uploaded photos.
618          * So we will make the first photo uploaded to this album in the last several hours
619          * visible by default, the rest will become visible over time when and if
620          * they acquire comments, likes, dislikes, and/or tags
621          */
622
623         $r = Photo::selectToArray([], ['`album` = ? AND `uid` = ? AND `created` > UTC_TIMESTAMP() - INTERVAL 3 HOUR', $album, $page_owner_uid]);
624
625         if (!DBA::isResult($r) || ($album == DI::l10n()->t('Profile Photos'))) {
626                 $visible = 1;
627         } else {
628                 $visible = 0;
629         }
630
631         if (!empty($_REQUEST['not_visible']) && $_REQUEST['not_visible'] !== 'false') {
632                 $visible = 0;
633         }
634
635         $group_allow   = $_REQUEST['group_allow']   ?? [];
636         $contact_allow = $_REQUEST['contact_allow'] ?? [];
637         $group_deny    = $_REQUEST['group_deny']    ?? [];
638         $contact_deny  = $_REQUEST['contact_deny']  ?? [];
639
640         $aclFormatter = DI::aclFormatter();
641
642         $str_group_allow   = $aclFormatter->toString(is_array($group_allow)   ? $group_allow   : explode(',', $group_allow));
643         $str_contact_allow = $aclFormatter->toString(is_array($contact_allow) ? $contact_allow : explode(',', $contact_allow));
644         $str_group_deny    = $aclFormatter->toString(is_array($group_deny)    ? $group_deny    : explode(',', $group_deny));
645         $str_contact_deny  = $aclFormatter->toString(is_array($contact_deny)  ? $contact_deny  : explode(',', $contact_deny));
646
647         $ret = ['src' => '', 'filename' => '', 'filesize' => 0, 'type' => ''];
648
649         Hook::callAll('photo_post_file', $ret);
650
651         if (!empty($ret['src']) && !empty($ret['filesize'])) {
652                 $src      = $ret['src'];
653                 $filename = $ret['filename'];
654                 $filesize = $ret['filesize'];
655                 $type     = $ret['type'];
656                 $error    = UPLOAD_ERR_OK;
657         } elseif (!empty($_FILES['userfile'])) {
658                 $src      = $_FILES['userfile']['tmp_name'];
659                 $filename = basename($_FILES['userfile']['name']);
660                 $filesize = intval($_FILES['userfile']['size']);
661                 $type     = $_FILES['userfile']['type'];
662                 $error    = $_FILES['userfile']['error'];
663         } else {
664                 $error    = UPLOAD_ERR_NO_FILE;
665         }
666
667         if ($error !== UPLOAD_ERR_OK) {
668                 switch ($error) {
669                         case UPLOAD_ERR_INI_SIZE:
670                                 notice(DI::l10n()->t('Image exceeds size limit of %s', ini_get('upload_max_filesize')) . EOL);
671                                 break;
672                         case UPLOAD_ERR_FORM_SIZE:
673                                 notice(DI::l10n()->t('Image exceeds size limit of %s', Strings::formatBytes($_REQUEST['MAX_FILE_SIZE'] ?? 0)) . EOL);
674                                 break;
675                         case UPLOAD_ERR_PARTIAL:
676                                 notice(DI::l10n()->t('Image upload didn\'t complete, please try again') . EOL);
677                                 break;
678                         case UPLOAD_ERR_NO_FILE:
679                                 notice(DI::l10n()->t('Image file is missing') . EOL);
680                                 break;
681                         case UPLOAD_ERR_NO_TMP_DIR:
682                         case UPLOAD_ERR_CANT_WRITE:
683                         case UPLOAD_ERR_EXTENSION:
684                                 notice(DI::l10n()->t('Server can\'t accept new file upload at this time, please contact your administrator') . EOL);
685                                 break;
686                 }
687                 @unlink($src);
688                 $foo = 0;
689                 Hook::callAll('photo_post_end', $foo);
690                 return;
691         }
692
693         if ($type == "") {
694                 $type = Images::guessType($filename);
695         }
696
697         Logger::log('photos: upload: received file: ' . $filename . ' as ' . $src . ' ('. $type . ') ' . $filesize . ' bytes', Logger::DEBUG);
698
699         $maximagesize = DI::config()->get('system', 'maximagesize');
700
701         if ($maximagesize && ($filesize > $maximagesize)) {
702                 notice(DI::l10n()->t('Image exceeds size limit of %s', Strings::formatBytes($maximagesize)) . EOL);
703                 @unlink($src);
704                 $foo = 0;
705                 Hook::callAll('photo_post_end', $foo);
706                 return;
707         }
708
709         if (!$filesize) {
710                 notice(DI::l10n()->t('Image file is empty.') . EOL);
711                 @unlink($src);
712                 $foo = 0;
713                 Hook::callAll('photo_post_end', $foo);
714                 return;
715         }
716
717         Logger::log('mod/photos.php: photos_post(): loading the contents of ' . $src , Logger::DEBUG);
718
719         $imagedata = @file_get_contents($src);
720
721         $image = new Image($imagedata, $type);
722
723         if (!$image->isValid()) {
724                 Logger::log('mod/photos.php: photos_post(): unable to process image' , Logger::DEBUG);
725                 notice(DI::l10n()->t('Unable to process image.') . EOL);
726                 @unlink($src);
727                 $foo = 0;
728                 Hook::callAll('photo_post_end',$foo);
729                 return;
730         }
731
732         $exif = $image->orient($src);
733         @unlink($src);
734
735         $max_length = DI::config()->get('system', 'max_image_length');
736         if (!$max_length) {
737                 $max_length = MAX_IMAGE_LENGTH;
738         }
739         if ($max_length > 0) {
740                 $image->scaleDown($max_length);
741         }
742
743         $width  = $image->getWidth();
744         $height = $image->getHeight();
745
746         $smallest = 0;
747
748         $resource_id = Photo::newResource();
749
750         $r = Photo::store($image, $page_owner_uid, $visitor, $resource_id, $filename, $album, 0 , 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
751
752         if (!$r) {
753                 Logger::log('mod/photos.php: photos_post(): image store failed', Logger::DEBUG);
754                 notice(DI::l10n()->t('Image upload failed.') . EOL);
755                 return;
756         }
757
758         if ($width > 640 || $height > 640) {
759                 $image->scaleDown(640);
760                 Photo::store($image, $page_owner_uid, $visitor, $resource_id, $filename, $album, 1, 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
761                 $smallest = 1;
762         }
763
764         if ($width > 320 || $height > 320) {
765                 $image->scaleDown(320);
766                 Photo::store($image, $page_owner_uid, $visitor, $resource_id, $filename, $album, 2, 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
767                 $smallest = 2;
768         }
769
770         $uri = Item::newURI($page_owner_uid);
771
772         // Create item container
773         $lat = $lon = null;
774         if ($exif && $exif['GPS'] && Feature::isEnabled($page_owner_uid, 'photo_location')) {
775                 $lat = Photo::getGps($exif['GPS']['GPSLatitude'], $exif['GPS']['GPSLatitudeRef']);
776                 $lon = Photo::getGps($exif['GPS']['GPSLongitude'], $exif['GPS']['GPSLongitudeRef']);
777         }
778
779         $arr = [];
780         if ($lat && $lon) {
781                 $arr['coord'] = $lat . ' ' . $lon;
782         }
783
784         $arr['guid']          = System::createUUID();
785         $arr['uid']           = $page_owner_uid;
786         $arr['uri']           = $uri;
787         $arr['parent-uri']    = $uri;
788         $arr['type']          = 'photo';
789         $arr['wall']          = 1;
790         $arr['resource-id']   = $resource_id;
791         $arr['contact-id']    = $owner_record['id'];
792         $arr['owner-name']    = $owner_record['name'];
793         $arr['owner-link']    = $owner_record['url'];
794         $arr['owner-avatar']  = $owner_record['thumb'];
795         $arr['author-name']   = $owner_record['name'];
796         $arr['author-link']   = $owner_record['url'];
797         $arr['author-avatar'] = $owner_record['thumb'];
798         $arr['title']         = '';
799         $arr['allow_cid']     = $str_contact_allow;
800         $arr['allow_gid']     = $str_group_allow;
801         $arr['deny_cid']      = $str_contact_deny;
802         $arr['deny_gid']      = $str_group_deny;
803         $arr['visible']       = $visible;
804         $arr['origin']        = 1;
805
806         $arr['body']          = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nickname'] . '/image/' . $resource_id . ']'
807                                 . '[img]' . DI::baseUrl() . "/photo/{$resource_id}-{$smallest}.".$image->getExt() . '[/img]'
808                                 . '[/url]';
809
810         $item_id = Item::insert($arr);
811         // Update the photo albums cache
812         Photo::clearAlbumCache($page_owner_uid);
813
814         Hook::callAll('photo_post_end', $item_id);
815
816         // addon uploaders should call "exit()" within the photo_post_end hook
817         // if they do not wish to be redirected
818
819         DI::baseUrl()->redirect($_SESSION['photo_return']);
820         // NOTREACHED
821 }
822
823 function photos_content(App $a)
824 {
825         // URLs:
826         // photos/name
827         // photos/name/upload
828         // photos/name/upload/xxxxx (xxxxx is album name)
829         // photos/name/album/xxxxx
830         // photos/name/album/xxxxx/edit
831         // photos/name/album/xxxxx/drop
832         // photos/name/image/xxxxx
833         // photos/name/image/xxxxx/edit
834         // photos/name/image/xxxxx/drop
835
836         if (DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) {
837                 notice(DI::l10n()->t('Public access denied.') . EOL);
838                 return;
839         }
840
841         if (empty($a->data['user'])) {
842                 notice(DI::l10n()->t('No photos selected') . EOL);
843                 return;
844         }
845
846         $phototypes = Images::supportedTypes();
847
848         $_SESSION['photo_return'] = DI::args()->getCommand();
849
850         // Parse arguments
851         $datum = null;
852         if ($a->argc > 3) {
853                 $datatype = $a->argv[2];
854                 $datum = $a->argv[3];
855         } elseif (($a->argc > 2) && ($a->argv[2] === 'upload')) {
856                 $datatype = 'upload';
857         } else {
858                 $datatype = 'summary';
859         }
860
861         if ($a->argc > 4) {
862                 $cmd = $a->argv[4];
863         } else {
864                 $cmd = 'view';
865         }
866
867         // Setup permissions structures
868         $can_post       = false;
869         $visitor        = 0;
870         $contact        = null;
871         $remote_contact = false;
872         $contact_id     = 0;
873         $edit           = '';
874         $drop           = '';
875
876         $owner_uid = $a->data['user']['uid'];
877
878         $community_page = (($a->data['user']['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
879
880         if (local_user() && (local_user() == $owner_uid)) {
881                 $can_post = true;
882         } elseif ($community_page && !empty(Session::getRemoteContactID($owner_uid))) {
883                 $contact_id = Session::getRemoteContactID($owner_uid);
884                 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id, 'uid' => $owner_uid, 'blocked' => false, 'pending' => false]);
885
886                 if (DBA::isResult($contact)) {
887                         $can_post = true;
888                         $remote_contact = true;
889                         $visitor = $contact_id;
890                 }
891         }
892
893         // perhaps they're visiting - but not a community page, so they wouldn't have write access
894         if (!empty(Session::getRemoteContactID($owner_uid)) && !$visitor) {
895                 $contact_id = Session::getRemoteContactID($owner_uid);
896
897                 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id, 'uid' => $owner_uid, 'blocked' => false, 'pending' => false]);
898
899                 $remote_contact = DBA::isResult($contact);
900         }
901
902         if (!$remote_contact && local_user()) {
903                 $contact_id = $_SESSION['cid'];
904                 $contact = $a->contact;
905         }
906
907         if ($a->data['user']['hidewall'] && (local_user() != $owner_uid) && !$remote_contact) {
908                 notice(DI::l10n()->t('Access to this item is restricted.') . EOL);
909                 return;
910         }
911
912         $sql_extra = Security::getPermissionsSQLByUserId($owner_uid);
913
914         $o = "";
915
916         // tabs
917         $is_owner = (local_user() && (local_user() == $owner_uid));
918         $o .= BaseProfile::getTabsHTML($a, 'photos', $is_owner, $a->data['user']['nickname']);
919
920         // Display upload form
921         if ($datatype === 'upload') {
922                 if (!$can_post) {
923                         notice(DI::l10n()->t('Permission denied.'));
924                         return;
925                 }
926
927                 $selname = Strings::isHex($datum) ? hex2bin($datum) : '';
928
929                 $albumselect = '';
930
931                 $albumselect .= '<option value="" ' . (!$selname ? ' selected="selected" ' : '') . '>&lt;current year&gt;</option>';
932                 if (!empty($a->data['albums'])) {
933                         foreach ($a->data['albums'] as $album) {
934                                 if (($album['album'] === '') || ($album['album'] === 'Contact Photos') || ($album['album'] === DI::l10n()->t('Contact Photos'))) {
935                                         continue;
936                                 }
937                                 $selected = (($selname === $album['album']) ? ' selected="selected" ' : '');
938                                 $albumselect .= '<option value="' . $album['album'] . '"' . $selected . '>' . $album['album'] . '</option>';
939                         }
940                 }
941
942                 $uploader = '';
943
944                 $ret = ['post_url' => 'photos/' . $a->data['user']['nickname'],
945                                 'addon_text' => $uploader,
946                                 'default_upload' => true];
947
948                 Hook::callAll('photo_upload_form',$ret);
949
950                 $default_upload_box = Renderer::replaceMacros(Renderer::getMarkupTemplate('photos_default_uploader_box.tpl'), []);
951                 $default_upload_submit = Renderer::replaceMacros(Renderer::getMarkupTemplate('photos_default_uploader_submit.tpl'), [
952                         '$submit' => DI::l10n()->t('Submit'),
953                 ]);
954
955                 $usage_message = '';
956
957                 $tpl = Renderer::getMarkupTemplate('photos_upload.tpl');
958
959                 $aclselect_e = ($visitor ? '' : ACL::getFullSelectorHTML(DI::page(), $a->user));
960
961                 $o .= Renderer::replaceMacros($tpl,[
962                         '$pagename' => DI::l10n()->t('Upload Photos'),
963                         '$sessid' => session_id(),
964                         '$usage' => $usage_message,
965                         '$nickname' => $a->data['user']['nickname'],
966                         '$newalbum' => DI::l10n()->t('New album name: '),
967                         '$existalbumtext' => DI::l10n()->t('or select existing album:'),
968                         '$nosharetext' => DI::l10n()->t('Do not show a status post for this upload'),
969                         '$albumselect' => $albumselect,
970                         '$permissions' => DI::l10n()->t('Permissions'),
971                         '$aclselect' => $aclselect_e,
972                         '$lockstate' => is_array($a->user)
973                                         && (strlen($a->user['allow_cid'])
974                                                 || strlen($a->user['allow_gid'])
975                                                 || strlen($a->user['deny_cid'])
976                                                 || strlen($a->user['deny_gid'])
977                                         ) ? 'lock' : 'unlock',
978                         '$alt_uploader' => $ret['addon_text'],
979                         '$default_upload_box' => ($ret['default_upload'] ? $default_upload_box : ''),
980                         '$default_upload_submit' => ($ret['default_upload'] ? $default_upload_submit : ''),
981                         '$uploadurl' => $ret['post_url'],
982
983                         // ACL permissions box
984                         '$group_perms' => DI::l10n()->t('Show to Groups'),
985                         '$contact_perms' => DI::l10n()->t('Show to Contacts'),
986                         '$return_path' => DI::args()->getQueryString(),
987                 ]);
988
989                 return $o;
990         }
991
992         // Display a single photo album
993         if ($datatype === 'album') {
994                 // if $datum is not a valid hex, redirect to the default page
995                 if (!Strings::isHex($datum)) {
996                         DI::baseUrl()->redirect('photos/' . $a->data['user']['nickname']. '/album');
997                 }
998                 $album = hex2bin($datum);
999
1000                 $total = 0;
1001                 $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` = '%s'
1002                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id`",
1003                         intval($owner_uid),
1004                         DBA::escape($album)
1005                 );
1006                 if (DBA::isResult($r)) {
1007                         $total = count($r);
1008                 }
1009
1010                 $pager = new Pager(DI::args()->getQueryString(), 20);
1011
1012                 /// @TODO I have seen this many times, maybe generalize it script-wide and encapsulate it?
1013                 $order_field = $_GET['order'] ?? '';
1014                 if ($order_field === 'posted') {
1015                         $order = 'ASC';
1016                 } else {
1017                         $order = 'DESC';
1018                 }
1019
1020                 $r = q("SELECT `resource-id`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`filename`) AS `filename`,
1021                         ANY_VALUE(`type`) AS `type`, max(`scale`) AS `scale`, ANY_VALUE(`desc`) as `desc`,
1022                         ANY_VALUE(`created`) as `created`
1023                         FROM `photo` WHERE `uid` = %d AND `album` = '%s'
1024                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id` ORDER BY `created` $order LIMIT %d , %d",
1025                         intval($owner_uid),
1026                         DBA::escape($album),
1027                         $pager->getStart(),
1028                         $pager->getItemsPerPage()
1029                 );
1030
1031                 if ($cmd === 'drop') {
1032                         $drop_url = DI::args()->getQueryString();
1033
1034                         return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
1035                                 '$method' => 'post',
1036                                 '$message' => DI::l10n()->t('Do you really want to delete this photo album and all its photos?'),
1037                                 '$extra_inputs' => [],
1038                                 '$confirm' => DI::l10n()->t('Delete Album'),
1039                                 '$confirm_url' => $drop_url,
1040                                 '$confirm_name' => 'dropalbum',
1041                                 '$cancel' => DI::l10n()->t('Cancel'),
1042                         ]);
1043                 }
1044
1045                 // edit album name
1046                 if ($cmd === 'edit') {
1047                         if (($album !== DI::l10n()->t('Profile Photos')) && ($album !== 'Contact Photos') && ($album !== DI::l10n()->t('Contact Photos'))) {
1048                                 if ($can_post) {
1049                                         $edit_tpl = Renderer::getMarkupTemplate('album_edit.tpl');
1050
1051                                         $album_e = $album;
1052
1053                                         $o .= Renderer::replaceMacros($edit_tpl,[
1054                                                 '$nametext' => DI::l10n()->t('New album name: '),
1055                                                 '$nickname' => $a->data['user']['nickname'],
1056                                                 '$album' => $album_e,
1057                                                 '$hexalbum' => bin2hex($album),
1058                                                 '$submit' => DI::l10n()->t('Submit'),
1059                                                 '$dropsubmit' => DI::l10n()->t('Delete Album')
1060                                         ]);
1061                                 }
1062                         }
1063                 } else {
1064                         if (($album !== DI::l10n()->t('Profile Photos')) && ($album !== 'Contact Photos') && ($album !== DI::l10n()->t('Contact Photos')) && $can_post) {
1065                                 $edit = [DI::l10n()->t('Edit Album'), 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '/edit'];
1066                                 $drop = [DI::l10n()->t('Drop Album'), 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '/drop'];
1067                         }
1068                 }
1069
1070                 if ($order_field === 'posted') {
1071                         $order =  [DI::l10n()->t('Show Newest First'), 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album), 'oldest'];
1072                 } else {
1073                         $order = [DI::l10n()->t('Show Oldest First'), 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '?order=posted', 'newest'];
1074                 }
1075
1076                 $photos = [];
1077
1078                 if (DBA::isResult($r)) {
1079                         // "Twist" is only used for the duepunto theme with style "slackr"
1080                         $twist = false;
1081                         foreach ($r as $rr) {
1082                                 $twist = !$twist;
1083
1084                                 $ext = $phototypes[$rr['type']];
1085
1086                                 $imgalt_e = $rr['filename'];
1087                                 $desc_e = $rr['desc'];
1088
1089                                 $photos[] = [
1090                                         'id' => $rr['id'],
1091                                         'twist' => ' ' . ($twist ? 'rotleft' : 'rotright') . rand(2,4),
1092                                         'link' => 'photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id']
1093                                                 . ($order_field === 'posted' ? '?order=posted' : ''),
1094                                         'title' => DI::l10n()->t('View Photo'),
1095                                         'src' => 'photo/' . $rr['resource-id'] . '-' . $rr['scale'] . '.' .$ext,
1096                                         'alt' => $imgalt_e,
1097                                         'desc'=> $desc_e,
1098                                         'ext' => $ext,
1099                                         'hash'=> $rr['resource-id'],
1100                                 ];
1101                         }
1102                 }
1103
1104                 $tpl = Renderer::getMarkupTemplate('photo_album.tpl');
1105                 $o .= Renderer::replaceMacros($tpl, [
1106                         '$photos' => $photos,
1107                         '$album' => $album,
1108                         '$can_post' => $can_post,
1109                         '$upload' => [DI::l10n()->t('Upload New Photos'), 'photos/' . $a->data['user']['nickname'] . '/upload/' . bin2hex($album)],
1110                         '$order' => $order,
1111                         '$edit' => $edit,
1112                         '$drop' => $drop,
1113                         '$paginate' => $pager->renderFull($total),
1114                 ]);
1115
1116                 return $o;
1117
1118         }
1119
1120         // Display one photo
1121         if ($datatype === 'image') {
1122                 // fetch image, item containing image, then comments
1123                 $ph = q("SELECT * FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'
1124                         $sql_extra ORDER BY `scale` ASC ",
1125                         intval($owner_uid),
1126                         DBA::escape($datum)
1127                 );
1128
1129                 if (!DBA::isResult($ph)) {
1130                         if (DBA::exists('photo', ['resource-id' => $datum, 'uid' => $owner_uid])) {
1131                                 notice(DI::l10n()->t('Permission denied. Access to this item may be restricted.'));
1132                         } else {
1133                                 notice(DI::l10n()->t('Photo not available') . EOL);
1134                         }
1135                         return;
1136                 }
1137
1138                 if ($cmd === 'drop') {
1139                         $drop_url = DI::args()->getQueryString();
1140
1141                         return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
1142                                 '$method' => 'post',
1143                                 '$message' => DI::l10n()->t('Do you really want to delete this photo?'),
1144                                 '$extra_inputs' => [],
1145                                 '$confirm' => DI::l10n()->t('Delete Photo'),
1146                                 '$confirm_url' => $drop_url,
1147                                 '$confirm_name' => 'delete',
1148                                 '$cancel' => DI::l10n()->t('Cancel'),
1149                         ]);
1150                 }
1151
1152                 $prevlink = '';
1153                 $nextlink = '';
1154
1155                 /*
1156                  * @todo This query is totally bad, the whole functionality has to be changed
1157                  * The query leads to a really intense used index.
1158                  * By now we hide it if someone wants to.
1159                  */
1160                 if ($cmd === 'view' && !DI::config()->get('system', 'no_count', false)) {
1161                         $order_field = $_GET['order'] ?? '';
1162
1163                         if ($order_field === 'posted') {
1164                                 $order = 'ASC';
1165                         } else {
1166                                 $order = 'DESC';
1167                         }
1168
1169                         $prvnxt = q("SELECT `resource-id` FROM `photo` WHERE `album` = '%s' AND `uid` = %d AND `scale` = 0
1170                                 $sql_extra ORDER BY `created` $order ",
1171                                 DBA::escape($ph[0]['album']),
1172                                 intval($owner_uid)
1173                         );
1174
1175                         if (DBA::isResult($prvnxt)) {
1176                                 $prv = null;
1177                                 $nxt = null;
1178                                 foreach ($prvnxt as $z => $entry) {
1179                                         if ($entry['resource-id'] == $ph[0]['resource-id']) {
1180                                                 $prv = $z - 1;
1181                                                 $nxt = $z + 1;
1182                                                 if ($prv < 0) {
1183                                                         $prv = count($prvnxt) - 1;
1184                                                 }
1185                                                 if ($nxt >= count($prvnxt)) {
1186                                                         $nxt = 0;
1187                                                 }
1188                                                 break;
1189                                         }
1190                                 }
1191
1192                                 if (!is_null($prv)) {
1193                                         $prevlink = 'photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$prv]['resource-id'] . ($order_field === 'posted' ? '?order=posted' : '');
1194                                 }
1195                                 if (!is_null($nxt)) {
1196                                         $nextlink = 'photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$nxt]['resource-id'] . ($order_field === 'posted' ? '?order=posted' : '');
1197                                 }
1198
1199                                 $tpl = Renderer::getMarkupTemplate('photo_edit_head.tpl');
1200                                 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl,[
1201                                         '$prevlink' => $prevlink,
1202                                         '$nextlink' => $nextlink
1203                                 ]);
1204
1205                                 if ($prevlink) {
1206                                         $prevlink = [$prevlink, '<div class="icon prev"></div>'];
1207                                 }
1208
1209                                 if ($nextlink) {
1210                                         $nextlink = [$nextlink, '<div class="icon next"></div>'];
1211                                 }
1212                         }
1213                 }
1214
1215                 if (count($ph) == 1) {
1216                         $hires = $lores = $ph[0];
1217                 }
1218
1219                 if (count($ph) > 1) {
1220                         if ($ph[1]['scale'] == 2) {
1221                                 // original is 640 or less, we can display it directly
1222                                 $hires = $lores = $ph[0];
1223                         } else {
1224                                 $hires = $ph[0];
1225                                 $lores = $ph[1];
1226                         }
1227                 }
1228
1229                 $album_link = 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($ph[0]['album']);
1230
1231                 $tools = null;
1232
1233                 if ($can_post && ($ph[0]['uid'] == $owner_uid)) {
1234                         $tools = [];
1235                         if ($cmd === 'edit') {
1236                                 $tools['view'] = ['photos/' . $a->data['user']['nickname'] . '/image/' . $datum, DI::l10n()->t('View photo')];
1237                         } else {
1238                                 $tools['edit'] = ['photos/' . $a->data['user']['nickname'] . '/image/' . $datum . '/edit', DI::l10n()->t('Edit photo')];
1239                                 $tools['delete'] = ['photos/' . $a->data['user']['nickname'] . '/image/' . $datum . '/drop', DI::l10n()->t('Delete photo')];
1240                                 $tools['profile'] = ['settings/profile/photo/crop/' . $ph[0]['resource-id'], DI::l10n()->t('Use as profile photo')];
1241                         }
1242
1243                         if (
1244                                 $ph[0]['uid'] == local_user()
1245                                 && (strlen($ph[0]['allow_cid']) || strlen($ph[0]['allow_gid']) || strlen($ph[0]['deny_cid']) || strlen($ph[0]['deny_gid']))
1246                         ) {
1247                                 $tools['lock'] = DI::l10n()->t('Private Photo');
1248                         }
1249                 }
1250
1251                 $photo = [
1252                         'href' => 'photo/' . $hires['resource-id'] . '-' . $hires['scale'] . '.' . $phototypes[$hires['type']],
1253                         'title'=> DI::l10n()->t('View Full Size'),
1254                         'src'  => 'photo/' . $lores['resource-id'] . '-' . $lores['scale'] . '.' . $phototypes[$lores['type']] . '?_u=' . DateTimeFormat::utcNow('ymdhis'),
1255                         'height' => $hires['height'],
1256                         'width' => $hires['width'],
1257                         'album' => $hires['album'],
1258                         'filename' => $hires['filename'],
1259                 ];
1260
1261                 $map = null;
1262                 $link_item = [];
1263                 $total = 0;
1264
1265                 // Do we have an item for this photo?
1266
1267                 // FIXME! - replace following code to display the conversation with our normal
1268                 // conversation functions so that it works correctly and tracks changes
1269                 // in the evolving conversation code.
1270                 // The difference is that we won't be displaying the conversation head item
1271                 // as a "post" but displaying instead the photo it is linked to
1272
1273                 /// @todo Rewrite this query. To do so, $sql_extra must be changed
1274                 $linked_items = q("SELECT `id` FROM `item` WHERE `resource-id` = '%s' $sql_extra LIMIT 1",
1275                         DBA::escape($datum)
1276                 );
1277                 if (DBA::isResult($linked_items)) {
1278                         // This is a workaround to not being forced to rewrite the while $sql_extra handling
1279                         $link_item = Item::selectFirst([], ['id' => $linked_items[0]['id']]);
1280                 }
1281
1282                 if (!empty($link_item['parent']) && !empty($link_item['uid'])) {
1283                         $condition = ["`parent` = ? AND `parent` != `id`",  $link_item['parent']];
1284                         $total = DBA::count('item', $condition);
1285
1286                         $pager = new Pager(DI::args()->getQueryString());
1287
1288                         $params = ['order' => ['id'], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1289                         $result = Item::selectForUser($link_item['uid'], Item::ITEM_FIELDLIST, $condition, $params);
1290                         $items = Item::inArray($result);
1291
1292                         if (local_user() == $link_item['uid']) {
1293                                 Item::update(['unseen' => false], ['parent' => $link_item['parent']]);
1294                         }
1295                 }
1296
1297                 if (!empty($link_item['coord'])) {
1298                         $map = Map::byCoordinates($link_item['coord']);
1299                 }
1300
1301                 $tags = null;
1302
1303                 if (!empty($link_item['id']) && !empty($link_item['tag'])) {
1304                         $arr = explode(',', $link_item['tag']);
1305                         // parse tags and add links
1306                         $tag_arr = [];
1307                         foreach ($arr as $tag) {
1308                                 $tag_arr[] = [
1309                                         'name' => BBCode::convert($tag),
1310                                         'removeurl' => '/tagrm/' . $link_item['id'] . '/' . bin2hex($tag)
1311                                 ];
1312                         }
1313                         $tags = ['title' => DI::l10n()->t('Tags: '), 'tags' => $tag_arr];
1314                         if ($cmd === 'edit') {
1315                                 $tags['removeanyurl'] = 'tagrm/' . $link_item['id'];
1316                                 $tags['removetitle'] = DI::l10n()->t('[Select tags to remove]');
1317                         }
1318                 }
1319
1320
1321                 $edit = Null;
1322                 if ($cmd === 'edit' && $can_post) {
1323                         $edit_tpl = Renderer::getMarkupTemplate('photo_edit.tpl');
1324
1325                         $album_e = $ph[0]['album'];
1326                         $caption_e = $ph[0]['desc'];
1327                         $aclselect_e = ACL::getFullSelectorHTML(DI::page(), $a->user, false, ACL::getDefaultUserPermissions($ph[0]));
1328
1329                         $edit = Renderer::replaceMacros($edit_tpl, [
1330                                 '$id' => $ph[0]['id'],
1331                                 '$album' => ['albname', DI::l10n()->t('New album name'), $album_e,''],
1332                                 '$caption' => ['desc', DI::l10n()->t('Caption'), $caption_e, ''],
1333                                 '$tags' => ['newtag', DI::l10n()->t('Add a Tag'), "", DI::l10n()->t('Example: @bob, @Barbara_Jensen, @jim@example.com, #California, #camping')],
1334                                 '$rotate_none' => ['rotate', DI::l10n()->t('Do not rotate'),0,'', true],
1335                                 '$rotate_cw' => ['rotate', DI::l10n()->t("Rotate CW \x28right\x29"),1,''],
1336                                 '$rotate_ccw' => ['rotate', DI::l10n()->t("Rotate CCW \x28left\x29"),2,''],
1337
1338                                 '$nickname' => $a->data['user']['nickname'],
1339                                 '$resource_id' => $ph[0]['resource-id'],
1340                                 '$permissions' => DI::l10n()->t('Permissions'),
1341                                 '$aclselect' => $aclselect_e,
1342
1343                                 '$item_id' => $link_item['id'] ?? 0,
1344                                 '$submit' => DI::l10n()->t('Submit'),
1345                                 '$delete' => DI::l10n()->t('Delete Photo'),
1346
1347                                 // ACL permissions box
1348                                 '$group_perms' => DI::l10n()->t('Show to Groups'),
1349                                 '$contact_perms' => DI::l10n()->t('Show to Contacts'),
1350                                 '$return_path' => DI::args()->getQueryString(),
1351                         ]);
1352                 }
1353
1354                 $like = '';
1355                 $dislike = '';
1356                 $likebuttons = '';
1357                 $comments = '';
1358                 $paginate = '';
1359                 $responses = '';
1360
1361                 if (!empty($link_item['id']) && !empty($link_item['uri'])) {
1362                         $cmnt_tpl = Renderer::getMarkupTemplate('comment_item.tpl');
1363                         $tpl = Renderer::getMarkupTemplate('photo_item.tpl');
1364                         $return_path = DI::args()->getCommand();
1365
1366                         if ($cmd === 'view' && ($can_post || Security::canWriteToUserWall($owner_uid))) {
1367                                 $like_tpl = Renderer::getMarkupTemplate('like_noshare.tpl');
1368                                 $likebuttons = Renderer::replaceMacros($like_tpl, [
1369                                         '$id' => $link_item['id'],
1370                                         '$likethis' => DI::l10n()->t("I like this \x28toggle\x29"),
1371                                         '$nolike' => DI::l10n()->t("I don't like this \x28toggle\x29"),
1372                                         '$wait' => DI::l10n()->t('Please wait'),
1373                                         '$return_path' => DI::args()->getQueryString(),
1374                                 ]);
1375                         }
1376
1377                         if (!DBA::isResult($items)) {
1378                                 if (($can_post || Security::canWriteToUserWall($owner_uid))) {
1379                                         $comments .= Renderer::replaceMacros($cmnt_tpl, [
1380                                                 '$return_path' => '',
1381                                                 '$jsreload' => $return_path,
1382                                                 '$id' => $link_item['id'],
1383                                                 '$parent' => $link_item['id'],
1384                                                 '$profile_uid' =>  $owner_uid,
1385                                                 '$mylink' => $contact['url'],
1386                                                 '$mytitle' => DI::l10n()->t('This is you'),
1387                                                 '$myphoto' => $contact['thumb'],
1388                                                 '$comment' => DI::l10n()->t('Comment'),
1389                                                 '$submit' => DI::l10n()->t('Submit'),
1390                                                 '$preview' => DI::l10n()->t('Preview'),
1391                                                 '$sourceapp' => DI::l10n()->t($a->sourcename),
1392                                                 '$ww' => '',
1393                                                 '$rand_num' => Crypto::randomDigits(12)
1394                                         ]);
1395                                 }
1396                         }
1397
1398                         $conv_responses = [
1399                                 'like' => ['title' => DI::l10n()->t('Likes','title')],'dislike' => ['title' => DI::l10n()->t('Dislikes','title')],
1400                                 'attendyes' => ['title' => DI::l10n()->t('Attending','title')], 'attendno' => ['title' => DI::l10n()->t('Not attending','title')], 'attendmaybe' => ['title' => DI::l10n()->t('Might attend','title')]
1401                         ];
1402
1403                         // display comments
1404                         if (DBA::isResult($items)) {
1405                                 foreach ($items as $item) {
1406                                         builtin_activity_puller($item, $conv_responses);
1407                                 }
1408
1409                                 if (!empty($conv_responses['like'][$link_item['uri']])) {
1410                                         $like = format_like($conv_responses['like'][$link_item['uri']], $conv_responses['like'][$link_item['uri'] . '-l'], 'like', $link_item['id']);
1411                                 }
1412
1413                                 if (!empty($conv_responses['dislike'][$link_item['uri']])) {
1414                                         $dislike = format_like($conv_responses['dislike'][$link_item['uri']], $conv_responses['dislike'][$link_item['uri'] . '-l'], 'dislike', $link_item['id']);
1415                                 }
1416
1417                                 if (($can_post || Security::canWriteToUserWall($owner_uid))) {
1418                                         $comments .= Renderer::replaceMacros($cmnt_tpl,[
1419                                                 '$return_path' => '',
1420                                                 '$jsreload' => $return_path,
1421                                                 '$id' => $link_item['id'],
1422                                                 '$parent' => $link_item['id'],
1423                                                 '$profile_uid' =>  $owner_uid,
1424                                                 '$mylink' => $contact['url'],
1425                                                 '$mytitle' => DI::l10n()->t('This is you'),
1426                                                 '$myphoto' => $contact['thumb'],
1427                                                 '$comment' => DI::l10n()->t('Comment'),
1428                                                 '$submit' => DI::l10n()->t('Submit'),
1429                                                 '$preview' => DI::l10n()->t('Preview'),
1430                                                 '$sourceapp' => DI::l10n()->t($a->sourcename),
1431                                                 '$ww' => '',
1432                                                 '$rand_num' => Crypto::randomDigits(12)
1433                                         ]);
1434                                 }
1435
1436                                 foreach ($items as $item) {
1437                                         $comment = '';
1438                                         $template = $tpl;
1439                                         $sparkle = '';
1440
1441                                         $activity = DI::activity();
1442
1443                                         if (($activity->match($item['verb'], Activity::LIKE) ||
1444                                              $activity->match($item['verb'], Activity::DISLIKE)) &&
1445                                             ($item['id'] != $item['parent'])) {
1446                                                 continue;
1447                                         }
1448
1449                                         $profile_url = Contact::magicLinkbyId($item['author-id']);
1450                                         if (strpos($profile_url, 'redir/') === 0) {
1451                                                 $sparkle = ' sparkle';
1452                                         } else {
1453                                                 $sparkle = '';
1454                                         }
1455
1456                                         $dropping = (($item['contact-id'] == $contact_id) || ($item['uid'] == local_user()));
1457                                         $drop = [
1458                                                 'dropping' => $dropping,
1459                                                 'pagedrop' => false,
1460                                                 'select' => DI::l10n()->t('Select'),
1461                                                 'delete' => DI::l10n()->t('Delete'),
1462                                         ];
1463
1464                                         $title_e = $item['title'];
1465                                         $body_e = BBCode::convert($item['body']);
1466
1467                                         $comments .= Renderer::replaceMacros($template,[
1468                                                 '$id' => $item['id'],
1469                                                 '$profile_url' => $profile_url,
1470                                                 '$name' => $item['author-name'],
1471                                                 '$thumb' => $item['author-avatar'],
1472                                                 '$sparkle' => $sparkle,
1473                                                 '$title' => $title_e,
1474                                                 '$body' => $body_e,
1475                                                 '$ago' => Temporal::getRelativeDate($item['created']),
1476                                                 '$indent' => (($item['parent'] != $item['id']) ? ' comment' : ''),
1477                                                 '$drop' => $drop,
1478                                                 '$comment' => $comment
1479                                         ]);
1480
1481                                         if (($can_post || Security::canWriteToUserWall($owner_uid))) {
1482                                                 $comments .= Renderer::replaceMacros($cmnt_tpl, [
1483                                                         '$return_path' => '',
1484                                                         '$jsreload' => $return_path,
1485                                                         '$id' => $item['id'],
1486                                                         '$parent' => $item['parent'],
1487                                                         '$profile_uid' =>  $owner_uid,
1488                                                         '$mylink' => $contact['url'],
1489                                                         '$mytitle' => DI::l10n()->t('This is you'),
1490                                                         '$myphoto' => $contact['thumb'],
1491                                                         '$comment' => DI::l10n()->t('Comment'),
1492                                                         '$submit' => DI::l10n()->t('Submit'),
1493                                                         '$preview' => DI::l10n()->t('Preview'),
1494                                                         '$sourceapp' => DI::l10n()->t($a->sourcename),
1495                                                         '$ww' => '',
1496                                                         '$rand_num' => Crypto::randomDigits(12)
1497                                                 ]);
1498                                         }
1499                                 }
1500                         }
1501                         $response_verbs = ['like'];
1502                         $response_verbs[] = 'dislike';
1503                         $responses = get_responses($conv_responses, $response_verbs, $link_item);
1504
1505                         $paginate = $pager->renderFull($total);
1506                 }
1507
1508                 $photo_tpl = Renderer::getMarkupTemplate('photo_view.tpl');
1509                 $o .= Renderer::replaceMacros($photo_tpl, [
1510                         '$id' => $ph[0]['id'],
1511                         '$album' => [$album_link, $ph[0]['album']],
1512                         '$tools' => $tools,
1513                         '$photo' => $photo,
1514                         '$prevlink' => $prevlink,
1515                         '$nextlink' => $nextlink,
1516                         '$desc' => $ph[0]['desc'],
1517                         '$tags' => $tags,
1518                         '$edit' => $edit,
1519                         '$map' => $map,
1520                         '$map_text' => DI::l10n()->t('Map'),
1521                         '$likebuttons' => $likebuttons,
1522                         '$like' => $like,
1523                         '$dislike' => $dislike,
1524                         'responses' => $responses,
1525                         '$comments' => $comments,
1526                         '$paginate' => $paginate,
1527                 ]);
1528
1529                 DI::page()['htmlhead'] .= "\n" . '<meta name="twitter:card" content="summary_large_image" />' . "\n";
1530                 DI::page()['htmlhead'] .= '<meta name="twitter:title" content="' . $photo["album"] . '" />' . "\n";
1531                 DI::page()['htmlhead'] .= '<meta name="twitter:image" content="' . DI::baseUrl() . "/" . $photo["href"] . '" />' . "\n";
1532                 DI::page()['htmlhead'] .= '<meta name="twitter:image:width" content="' . $photo["width"] . '" />' . "\n";
1533                 DI::page()['htmlhead'] .= '<meta name="twitter:image:height" content="' . $photo["height"] . '" />' . "\n";
1534
1535                 return $o;
1536         }
1537
1538         // Default - show recent photos with upload link (if applicable)
1539         //$o = '';
1540         $total = 0;
1541         $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s'
1542                 $sql_extra GROUP BY `resource-id`",
1543                 intval($a->data['user']['uid']),
1544                 DBA::escape('Contact Photos'),
1545                 DBA::escape(DI::l10n()->t('Contact Photos'))
1546         );
1547         if (DBA::isResult($r)) {
1548                 $total = count($r);
1549         }
1550
1551         $pager = new Pager(DI::args()->getQueryString(), 20);
1552
1553         $r = q("SELECT `resource-id`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`filename`) AS `filename`,
1554                 ANY_VALUE(`type`) AS `type`, ANY_VALUE(`album`) AS `album`, max(`scale`) AS `scale`,
1555                 ANY_VALUE(`created`) AS `created` FROM `photo`
1556                 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s'
1557                 $sql_extra GROUP BY `resource-id` ORDER BY `created` DESC LIMIT %d , %d",
1558                 intval($a->data['user']['uid']),
1559                 DBA::escape('Contact Photos'),
1560                 DBA::escape(DI::l10n()->t('Contact Photos')),
1561                 $pager->getStart(),
1562                 $pager->getItemsPerPage()
1563         );
1564
1565         $photos = [];
1566         if (DBA::isResult($r)) {
1567                 // "Twist" is only used for the duepunto theme with style "slackr"
1568                 $twist = false;
1569                 foreach ($r as $rr) {
1570                         //hide profile photos to others
1571                         if (!$is_owner && !Session::getRemoteContactID($owner_uid) && ($rr['album'] == DI::l10n()->t('Profile Photos'))) {
1572                                 continue;
1573                         }
1574
1575                         $twist = !$twist;
1576                         $ext = $phototypes[$rr['type']];
1577
1578                         $alt_e = $rr['filename'];
1579                         $name_e = $rr['album'];
1580
1581                         $photos[] = [
1582                                 'id'    => $rr['id'],
1583                                 'twist' => ' ' . ($twist ? 'rotleft' : 'rotright') . rand(2,4),
1584                                 'link'  => 'photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id'],
1585                                 'title' => DI::l10n()->t('View Photo'),
1586                                 'src'   => 'photo/' . $rr['resource-id'] . '-' . ((($rr['scale']) == 6) ? 4 : $rr['scale']) . '.' . $ext,
1587                                 'alt'   => $alt_e,
1588                                 'album' => [
1589                                         'link' => 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($rr['album']),
1590                                         'name' => $name_e,
1591                                         'alt'  => DI::l10n()->t('View Album'),
1592                                 ],
1593
1594                         ];
1595                 }
1596         }
1597
1598         $tpl = Renderer::getMarkupTemplate('photos_recent.tpl');
1599         $o .= Renderer::replaceMacros($tpl, [
1600                 '$title' => DI::l10n()->t('Recent Photos'),
1601                 '$can_post' => $can_post,
1602                 '$upload' => [DI::l10n()->t('Upload New Photos'), 'photos/'.$a->data['user']['nickname'].'/upload'],
1603                 '$photos' => $photos,
1604                 '$paginate' => $pager->renderFull($total),
1605         ]);
1606
1607         return $o;
1608 }