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