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