]> git.mxchange.org Git - friendica.git/blob - mod/photos.php
Reduce the amount of "UpdateContact" worker calls
[friendica.git] / mod / photos.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 use Friendica\App;
23 use Friendica\Content\Nav;
24 use Friendica\Content\Pager;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Widget;
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\System;
33 use Friendica\Database\DBA;
34 use Friendica\DI;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Item;
37 use Friendica\Model\Photo;
38 use Friendica\Model\Post;
39 use Friendica\Model\Profile;
40 use Friendica\Model\Tag;
41 use Friendica\Model\User;
42 use Friendica\Module\BaseProfile;
43 use Friendica\Network\HTTPException;
44 use Friendica\Network\Probe;
45 use Friendica\Protocol\Activity;
46 use Friendica\Security\Security;
47 use Friendica\Util\Crypto;
48 use Friendica\Util\DateTimeFormat;
49 use Friendica\Util\Images;
50 use Friendica\Util\Map;
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') && !DI::userSession()->isAuthenticated()) {
58                 return;
59         }
60
61         Nav::setSelected('home');
62
63         if (DI::args()->getArgc() > 1) {
64                 $owner = User::getOwnerDataByNick(DI::args()->getArgv()[1]);
65                 if (!isset($owner['account_removed']) || $owner['account_removed']) {
66                         throw new HTTPException\NotFoundException(DI::l10n()->t('User not found.'));
67                 }
68
69                 $is_owner = (DI::userSession()->getLocalUserId() && (DI::userSession()->getLocalUserId() == $owner['uid']));
70
71                 $albums = Photo::getAlbums($owner['uid']);
72
73                 $albums_visible = ((intval($owner['hidewall']) && !DI::userSession()->isAuthenticated()) ? false : true);
74
75                 // add various encodings to the array so we can just loop through and pick them out in a template
76                 $ret = ['success' => false];
77
78                 if ($albums) {
79                         if ($albums_visible) {
80                                 $ret['success'] = true;
81                         }
82
83                         $ret['albums'] = [];
84                         foreach ($albums as $k => $album) {
85                                 $entry = [
86                                         'text'      => $album['album'],
87                                         'total'     => $album['total'],
88                                         'url'       => 'photos/' . $owner['nickname'] . '/album/' . bin2hex($album['album']),
89                                         'urlencode' => urlencode($album['album']),
90                                         'bin2hex'   => bin2hex($album['album'])
91                                 ];
92                                 $ret['albums'][] = $entry;
93                         }
94                 }
95
96                 if (DI::userSession()->getLocalUserId() && $owner['uid'] == DI::userSession()->getLocalUserId()) {
97                         $can_post = true;
98                 } else {
99                         $can_post = false;
100                 }
101
102                 if ($ret['success']) {
103                         $photo_albums_widget = Renderer::replaceMacros(Renderer::getMarkupTemplate('photo_albums.tpl'), [
104                                 '$nick'     => $owner['nickname'],
105                                 '$title'    => DI::l10n()->t('Photo Albums'),
106                                 '$recent'   => DI::l10n()->t('Recent Photos'),
107                                 '$albums'   => $ret['albums'],
108                                 '$upload'   => [DI::l10n()->t('Upload New Photos'), 'photos/' . $owner['nickname'] . '/upload'],
109                                 '$can_post' => $can_post
110                         ]);
111                 }
112
113                 if (empty(DI::page()['aside'])) {
114                         DI::page()['aside'] = '';
115                 }
116
117                 DI::page()['aside'] .= Widget\VCard::getHTML($owner);
118
119                 if (!empty($photo_albums_widget)) {
120                         DI::page()['aside'] .= $photo_albums_widget;
121                 }
122
123                 $tpl = Renderer::getMarkupTemplate("photos_head.tpl");
124
125                 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl,[
126                         '$ispublic' => DI::l10n()->t('everybody')
127                 ]);
128         }
129
130         return;
131 }
132
133 function photos_post(App $a)
134 {
135         $user = User::getByNickname(DI::args()->getArgv()[1]);
136         if (!DBA::isResult($user)) {
137                 throw new HTTPException\NotFoundException(DI::l10n()->t('User not found.'));
138         }
139
140         $phototypes = Images::supportedTypes();
141
142         $can_post  = false;
143         $visitor   = 0;
144
145         $page_owner_uid = intval($user['uid']);
146         $community_page = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
147
148         if (DI::userSession()->getLocalUserId() && (DI::userSession()->getLocalUserId() == $page_owner_uid)) {
149                 $can_post = true;
150         } elseif ($community_page && !empty(DI::userSession()->getRemoteContactID($page_owner_uid))) {
151                 $contact_id = DI::userSession()->getRemoteContactID($page_owner_uid);
152                 $can_post = true;
153                 $visitor = $contact_id;
154         }
155
156         if (!$can_post) {
157                 DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
158                 System::exit();
159         }
160
161         $owner_record = User::getOwnerDataById($page_owner_uid);
162
163         if (!$owner_record) {
164                 DI::sysmsg()->addNotice(DI::l10n()->t('Contact information unavailable'));
165                 DI::logger()->info('photos_post: unable to locate contact record for page owner. uid=' . $page_owner_uid);
166                 System::exit();
167         }
168
169         $aclFormatter = DI::aclFormatter();
170         $str_contact_allow = isset($_REQUEST['contact_allow']) ? $aclFormatter->toString($_REQUEST['contact_allow']) : $owner_record['allow_cid'] ?? '';
171         $str_group_allow   = isset($_REQUEST['group_allow'])   ? $aclFormatter->toString($_REQUEST['group_allow'])   : $owner_record['allow_gid'] ?? '';
172         $str_contact_deny  = isset($_REQUEST['contact_deny'])  ? $aclFormatter->toString($_REQUEST['contact_deny'])  : $owner_record['deny_cid']  ?? '';
173         $str_group_deny    = isset($_REQUEST['group_deny'])    ? $aclFormatter->toString($_REQUEST['group_deny'])    : $owner_record['deny_gid']  ?? '';
174
175         $visibility = $_REQUEST['visibility'] ?? '';
176         if ($visibility === 'public') {
177                 // The ACL selector introduced in version 2019.12 sends ACL input data even when the Public visibility is selected
178                 $str_contact_allow = $str_group_allow = $str_contact_deny = $str_group_deny = '';
179         } else if ($visibility === 'custom') {
180                 // Since we know from the visibility parameter the item should be private, we have to prevent the empty ACL
181                 // case that would make it public. So we always append the author's contact id to the allowed contacts.
182                 // See https://github.com/friendica/friendica/issues/9672
183                 $str_contact_allow .= $aclFormatter->toString(Contact::getPublicIdByUserId($page_owner_uid));
184         }
185
186         if (DI::args()->getArgc() > 3 && DI::args()->getArgv()[2] === 'album') {
187                 if (!Strings::isHex(DI::args()->getArgv()[3] ?? '')) {
188                         DI::baseUrl()->redirect('photos/' . $user['nickname'] . '/album');
189                 }
190                 $album = hex2bin(DI::args()->getArgv()[3]);
191
192                 if (!DBA::exists('photo', ['album' => $album, 'uid' => $page_owner_uid, 'photo-type' => Photo::DEFAULT])) {
193                         DI::sysmsg()->addNotice(DI::l10n()->t('Album not found.'));
194                         DI::baseUrl()->redirect('photos/' . $user['nickname'] . '/album');
195                         return; // NOTREACHED
196                 }
197
198                 // Check if the user has responded to a delete confirmation query
199                 if (!empty($_REQUEST['canceled'])) {
200                         DI::baseUrl()->redirect('photos/' . $user['nickname'] . '/album/' . DI::args()->getArgv()[3]);
201                 }
202
203                 // RENAME photo album
204                 $newalbum = trim($_POST['albumname'] ?? '');
205                 if ($newalbum != $album) {
206                         Photo::update(['album' => $newalbum], ['album' => $album, 'uid' => $page_owner_uid]);
207                         // Update the photo albums cache
208                         Photo::clearAlbumCache($page_owner_uid);
209
210                         DI::baseUrl()->redirect('photos/' . $a->getLoggedInUserNickname() . '/album/' . bin2hex($newalbum));
211                         return; // NOTREACHED
212                 }
213
214                 /*
215                  * DELETE all photos filed in a given album
216                  */
217                 if (!empty($_POST['dropalbum'])) {
218                         $res = [];
219
220                         // get the list of photos we are about to delete
221                         if ($visitor) {
222                                 $r = DBA::toArray(DBA::p("SELECT distinct(`resource-id`) as `rid` FROM `photo` WHERE `contact-id` = ? AND `uid` = ? AND `album` = ?",
223                                         $visitor,
224                                         $page_owner_uid,
225                                         $album
226                                 ));
227                         } else {
228                                 $r = DBA::toArray(DBA::p("SELECT distinct(`resource-id`) as `rid` FROM `photo` WHERE `uid` = ? AND `album` = ?",
229                                         DI::userSession()->getLocalUserId(),
230                                         $album
231                                 ));
232                         }
233
234                         if (DBA::isResult($r)) {
235                                 foreach ($r as $rr) {
236                                         $res[] = $rr['rid'];
237                                 }
238
239                                 // remove the associated photos
240                                 Photo::delete(['resource-id' => $res, 'uid' => $page_owner_uid]);
241
242                                 // find and delete the corresponding item with all the comments and likes/dislikes
243                                 Item::deleteForUser(['resource-id' => $res, 'uid' => $page_owner_uid], $page_owner_uid);
244
245                                 // Update the photo albums cache
246                                 Photo::clearAlbumCache($page_owner_uid);
247                                 DI::sysmsg()->addNotice(DI::l10n()->t('Album successfully deleted'));
248                         } else {
249                                 DI::sysmsg()->addNotice(DI::l10n()->t('Album was empty.'));
250                         }
251                 }
252
253                 DI::baseUrl()->redirect('photos/' . $user['nickname'] . '/album');
254         }
255
256         if (DI::args()->getArgc() > 3 && DI::args()->getArgv()[2] === 'image') {
257                 // Check if the user has responded to a delete confirmation query for a single photo
258                 if (!empty($_POST['canceled'])) {
259                         DI::baseUrl()->redirect('photos/' . DI::args()->getArgv()[1] . '/image/' . DI::args()->getArgv()[3]);
260                 }
261
262                 if (!empty($_POST['delete'])) {
263                         // same as above but remove single photo
264                         if ($visitor) {
265                                 $condition = ['contact-id' => $visitor, 'uid' => $page_owner_uid, 'resource-id' => DI::args()->getArgv()[3]];
266
267                         } else {
268                                 $condition = ['uid' => DI::userSession()->getLocalUserId(), 'resource-id' => DI::args()->getArgv()[3]];
269                         }
270
271                         $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
272
273                         if (DBA::isResult($photo)) {
274                                 Photo::delete(['uid' => $page_owner_uid, 'resource-id' => $photo['resource-id']]);
275
276                                 Item::deleteForUser(['resource-id' => $photo['resource-id'], 'uid' => $page_owner_uid], $page_owner_uid);
277
278                                 // Update the photo albums cache
279                                 Photo::clearAlbumCache($page_owner_uid);
280                         } else {
281                                 DI::sysmsg()->addNotice(DI::l10n()->t('Failed to delete the photo.'));
282                                 DI::baseUrl()->redirect('photos/' . DI::args()->getArgv()[1] . '/image/' . DI::args()->getArgv()[3]);
283                         }
284
285                         DI::baseUrl()->redirect('profile/' . DI::args()->getArgv()[1] . '/photos');
286                 }
287         }
288
289         if (DI::args()->getArgc() > 2 && (!empty($_POST['desc']) || !empty($_POST['newtag']) || isset($_POST['albname']))) {
290                 $desc      = !empty($_POST['desc'])      ? trim($_POST['desc'])      : '';
291                 $rawtags   = !empty($_POST['newtag'])    ? trim($_POST['newtag'])    : '';
292                 $item_id   = !empty($_POST['item_id'])   ? intval($_POST['item_id']) : 0;
293                 $albname   = !empty($_POST['albname'])   ? trim($_POST['albname'])   : '';
294                 $origaname = !empty($_POST['origaname']) ? trim($_POST['origaname']) : '';
295
296                 $resource_id = DI::args()->getArgv()[3];
297
298                 if (!strlen($albname)) {
299                         $albname = DateTimeFormat::localNow('Y');
300                 }
301
302                 if (!empty($_POST['rotate']) && (intval($_POST['rotate']) == 1 || intval($_POST['rotate']) == 2)) {
303                         Logger::debug('rotate');
304
305                         $photo = Photo::getPhotoForUser($page_owner_uid, $resource_id);
306
307                         if (DBA::isResult($photo)) {
308                                 $image = Photo::getImageForPhoto($photo);
309
310                                 if ($image->isValid()) {
311                                         $rotate_deg = ((intval($_POST['rotate']) == 1) ? 270 : 90);
312                                         $image->rotate($rotate_deg);
313
314                                         $width  = $image->getWidth();
315                                         $height = $image->getHeight();
316
317                                         Photo::update(['height' => $height, 'width' => $width], ['resource-id' => $resource_id, 'uid' => $page_owner_uid, 'scale' => 0], $image);
318
319                                         if ($width > 640 || $height > 640) {
320                                                 $image->scaleDown(640);
321                                                 $width  = $image->getWidth();
322                                                 $height = $image->getHeight();
323
324                                                 Photo::update(['height' => $height, 'width' => $width], ['resource-id' => $resource_id, 'uid' => $page_owner_uid, 'scale' => 1], $image);
325                                         }
326
327                                         if ($width > 320 || $height > 320) {
328                                                 $image->scaleDown(320);
329                                                 $width  = $image->getWidth();
330                                                 $height = $image->getHeight();
331
332                                                 Photo::update(['height' => $height, 'width' => $width], ['resource-id' => $resource_id, 'uid' => $page_owner_uid, 'scale' => 2], $image);
333                                         }
334                                 }
335                         }
336                 }
337
338                 $photos_stmt = DBA::select('photo', [], ['resource-id' => $resource_id, 'uid' => $page_owner_uid], ['order' => ['scale' => true]]);
339
340                 $photos = DBA::toArray($photos_stmt);
341
342                 if (DBA::isResult($photos)) {
343                         $photo = $photos[0];
344                         $ext = $phototypes[$photo['type']];
345                         Photo::update(
346                                 ['desc' => $desc, 'album' => $albname, 'allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow, 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny],
347                                 ['resource-id' => $resource_id, 'uid' => $page_owner_uid]
348                         );
349
350                         // Update the photo albums cache if album name was changed
351                         if ($albname !== $origaname) {
352                                 Photo::clearAlbumCache($page_owner_uid);
353                         }
354                 }
355
356                 if (DBA::isResult($photos) && !$item_id) {
357                         // Create item container
358                         $title = '';
359                         $uri = Item::newURI();
360
361                         $arr = [];
362                         $arr['guid']          = System::createUUID();
363                         $arr['uid']           = $page_owner_uid;
364                         $arr['uri']           = $uri;
365                         $arr['post-type']     = Item::PT_IMAGE;
366                         $arr['wall']          = 1;
367                         $arr['resource-id']   = $photo['resource-id'];
368                         $arr['contact-id']    = $owner_record['id'];
369                         $arr['owner-name']    = $owner_record['name'];
370                         $arr['owner-link']    = $owner_record['url'];
371                         $arr['owner-avatar']  = $owner_record['thumb'];
372                         $arr['author-name']   = $owner_record['name'];
373                         $arr['author-link']   = $owner_record['url'];
374                         $arr['author-avatar'] = $owner_record['thumb'];
375                         $arr['title']         = $title;
376                         $arr['allow_cid']     = $photo['allow_cid'];
377                         $arr['allow_gid']     = $photo['allow_gid'];
378                         $arr['deny_cid']      = $photo['deny_cid'];
379                         $arr['deny_gid']      = $photo['deny_gid'];
380                         $arr['visible']       = 0;
381                         $arr['origin']        = 1;
382
383                         $arr['body']          = '[url=' . DI::baseUrl() . '/photos/' . $user['nickname'] . '/image/' . $photo['resource-id'] . ']'
384                                                 . '[img]' . DI::baseUrl() . '/photo/' . $photo['resource-id'] . '-' . $photo['scale'] . '.'. $ext . '[/img]'
385                                                 . '[/url]';
386
387                         $item_id = Item::insert($arr);
388                 }
389
390                 if ($item_id) {
391                         $item = Post::selectFirst(['inform', 'uri-id'], ['id' => $item_id, 'uid' => $page_owner_uid]);
392
393                         if (DBA::isResult($item)) {
394                                 $old_inform = $item['inform'];
395                         }
396                 }
397
398                 if (strlen($rawtags)) {
399                         $inform   = '';
400
401                         // if the new tag doesn't have a namespace specifier (@foo or #foo) give it a hashtag
402                         $x = substr($rawtags, 0, 1);
403                         if ($x !== '@' && $x !== '#') {
404                                 $rawtags = '#' . $rawtags;
405                         }
406
407                         $taginfo = [];
408                         $tags = BBCode::getTags($rawtags);
409
410                         if (count($tags)) {
411                                 foreach ($tags as $tag) {
412                                         if (strpos($tag, '@') === 0) {
413                                                 $profile = '';
414                                                 $contact = null;
415                                                 $name = substr($tag,1);
416
417                                                 if ((strpos($name, '@')) || (strpos($name, 'http://'))) {
418                                                         $newname = $name;
419                                                         $links = @Probe::lrdd($name);
420
421                                                         if (count($links)) {
422                                                                 foreach ($links as $link) {
423                                                                         if ($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page') {
424                                                                                 $profile = $link['@attributes']['href'];
425                                                                         }
426
427                                                                         if ($link['@attributes']['rel'] === 'salmon') {
428                                                                                 $salmon = '$url:' . str_replace(',', '%sc', $link['@attributes']['href']);
429
430                                                                                 if (strlen($inform)) {
431                                                                                         $inform .= ',';
432                                                                                 }
433
434                                                                                 $inform .= $salmon;
435                                                                         }
436                                                                 }
437                                                         }
438
439                                                         $taginfo[] = [$newname, $profile, $salmon];
440                                                 } else {
441                                                         $newname = $name;
442                                                         $tagcid = 0;
443
444                                                         if (strrpos($newname, '+')) {
445                                                                 $tagcid = intval(substr($newname, strrpos($newname, '+') + 1));
446                                                         }
447
448                                                         if ($tagcid) {
449                                                                 $contact = DBA::selectFirst('contact', [], ['id' => $tagcid, 'uid' => $page_owner_uid]);
450                                                         } else {
451                                                                 $newname = str_replace('_',' ',$name);
452
453                                                                 //select someone from this user's contacts by name
454                                                                 $contact = DBA::selectFirst('contact', [], ['name' => $newname, 'uid' => $page_owner_uid]);
455                                                                 if (!DBA::isResult($contact)) {
456                                                                         //select someone by attag or nick and the name passed in
457                                                                         $contact = DBA::selectFirst('contact', [],
458                                                                                 ['(`attag` = ? OR `nick` = ?) AND `uid` = ?', $name, $name, $page_owner_uid],
459                                                                                 ['order' => ['attag' => true]]
460                                                                         );
461                                                                 }
462                                                         }
463
464                                                         if (DBA::isResult($contact)) {
465                                                                 $newname = $contact['name'];
466                                                                 $profile = $contact['url'];
467
468                                                                 $notify = 'cid:' . $contact['id'];
469                                                                 if (strlen($inform)) {
470                                                                         $inform .= ',';
471                                                                 }
472                                                                 $inform .= $notify;
473                                                         }
474                                                 }
475
476                                                 if ($profile) {
477                                                         if (!empty($contact)) {
478                                                                 $taginfo[] = [$newname, $profile, $notify, $contact];
479                                                         } else {
480                                                                 $taginfo[] = [$newname, $profile, $notify, null];
481                                                         }
482
483                                                         $profile = str_replace(',', '%2c', $profile);
484
485                                                         if (!empty($item['uri-id'])) {
486                                                                 Tag::store($item['uri-id'], Tag::MENTION, $newname, $profile);
487                                                         }
488                                                 }
489                                         } elseif (strpos($tag, '#') === 0) {
490                                                 $tagname = substr($tag, 1);
491                                                 if (!empty($item['uri-id'])) {
492                                                         Tag::store($item['uri-id'], Tag::HASHTAG, $tagname);
493                                                 }
494                                         }
495                                 }
496                         }
497
498                         $newinform = $old_inform ?? '';
499                         if (strlen($newinform) && strlen($inform)) {
500                                 $newinform .= ',';
501                         }
502                         $newinform .= $inform;
503
504                         $fields = ['inform' => $newinform, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
505                         $condition = ['id' => $item_id];
506                         Item::update($fields, $condition);
507
508                         $best = 0;
509                         foreach ($photos as $scales) {
510                                 if (intval($scales['scale']) == 2) {
511                                         $best = 2;
512                                         break;
513                                 }
514
515                                 if (intval($scales['scale']) == 4) {
516                                         $best = 4;
517                                         break;
518                                 }
519                         }
520
521                         if (count($taginfo)) {
522                                 foreach ($taginfo as $tagged) {
523                                         $uri = Item::newURI();
524
525                                         $arr = [
526                                                 'guid'          => System::createUUID(),
527                                                 'uid'           => $page_owner_uid,
528                                                 'uri'           => $uri,
529                                                 'wall'          => 1,
530                                                 'contact-id'    => $owner_record['id'],
531                                                 'owner-name'    => $owner_record['name'],
532                                                 'owner-link'    => $owner_record['url'],
533                                                 'owner-avatar'  => $owner_record['thumb'],
534                                                 'author-name'   => $owner_record['name'],
535                                                 'author-link'   => $owner_record['url'],
536                                                 'author-avatar' => $owner_record['thumb'],
537                                                 'title'         => '',
538                                                 'allow_cid'     => $photo['allow_cid'],
539                                                 'allow_gid'     => $photo['allow_gid'],
540                                                 'deny_cid'      => $photo['deny_cid'],
541                                                 'deny_gid'      => $photo['deny_gid'],
542                                                 'visible'       => 0,
543                                                 'verb'          => Activity::TAG,
544                                                 'gravity'       => Item::GRAVITY_PARENT,
545                                                 'object-type'   => Activity\ObjectType::PERSON,
546                                                 'target-type'   => Activity\ObjectType::IMAGE,
547                                                 'inform'        => $tagged[2],
548                                                 'origin'        => 1,
549                                                 '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]') . "\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",
550                                                 'object'        => '<object><type>' . Activity\ObjectType::PERSON . '</type><title>' . $tagged[0] . '</title><id>' . $tagged[1] . '/' . $tagged[0] . '</id><link>' . XML::escape('<link rel="alternate" type="text/html" href="' . $tagged[1] . '" />' . "\n"),
551                                                 'target'        => '<target><type>' . Activity\ObjectType::IMAGE . '</type><title>' . $photo['desc'] . '</title><id>' . DI::baseUrl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo['resource-id'] . '</id><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>',
552                                         ];
553
554                                         if ($tagged[3]) {
555                                                 $arr['object'] .= XML::escape('<link rel="photo" type="' . $photo['type'] . '" href="' . $tagged[3]['photo'] . '" />' . "\n");
556                                         }
557                                         $arr['object'] .= '</link></object>' . "\n";
558
559                                         Item::insert($arr);
560                                 }
561                         }
562                 }
563                 DI::baseUrl()->redirect($_SESSION['photo_return']);
564                 return; // NOTREACHED
565         }
566 }
567
568 function photos_content(App $a)
569 {
570         // URLs:
571         // photos/name/upload
572         // photos/name/upload/xxxxx (xxxxx is album name)
573         // photos/name/album/xxxxx
574         // photos/name/album/xxxxx/edit
575         // photos/name/album/xxxxx/drop
576         // photos/name/image/xxxxx
577         // photos/name/image/xxxxx/edit
578         // photos/name/image/xxxxx/drop
579
580         $user = User::getByNickname(DI::args()->getArgv()[1] ?? '');
581         if (!DBA::isResult($user)) {
582                 throw new HTTPException\NotFoundException(DI::l10n()->t('User not found.'));
583         }
584
585         if (DI::config()->get('system', 'block_public') && !DI::userSession()->isAuthenticated()) {
586                 DI::sysmsg()->addNotice(DI::l10n()->t('Public access denied.'));
587                 return;
588         }
589
590         if (empty($user)) {
591                 DI::sysmsg()->addNotice(DI::l10n()->t('No photos selected'));
592                 return;
593         }
594
595         $profile = Profile::getByUID($user['uid']);
596
597         $phototypes = Images::supportedTypes();
598
599         $_SESSION['photo_return'] = DI::args()->getCommand();
600
601         // Parse arguments
602         $datum = null;
603         if (DI::args()->getArgc() > 3) {
604                 $datatype = DI::args()->getArgv()[2];
605                 $datum = DI::args()->getArgv()[3];
606         } elseif ((DI::args()->getArgc() > 2) && (DI::args()->getArgv()[2] === 'upload')) {
607                 $datatype = 'upload';
608         } else {
609                 $datatype = 'summary';
610         }
611
612         if (DI::args()->getArgc() > 4) {
613                 $cmd = DI::args()->getArgv()[4];
614         } else {
615                 $cmd = 'view';
616         }
617
618         // Setup permissions structures
619         $can_post       = false;
620         $visitor        = 0;
621         $contact        = null;
622         $remote_contact = false;
623         $contact_id     = 0;
624         $edit           = '';
625         $drop           = '';
626
627         $owner_uid = $user['uid'];
628
629         $community_page = (($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
630
631         if (DI::userSession()->getLocalUserId() && (DI::userSession()->getLocalUserId() == $owner_uid)) {
632                 $can_post = true;
633         } elseif ($community_page && !empty(DI::userSession()->getRemoteContactID($owner_uid))) {
634                 $contact_id = DI::userSession()->getRemoteContactID($owner_uid);
635                 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id, 'uid' => $owner_uid, 'blocked' => false, 'pending' => false]);
636
637                 if (DBA::isResult($contact)) {
638                         $can_post = true;
639                         $remote_contact = true;
640                         $visitor = $contact_id;
641                 }
642         }
643
644         // perhaps they're visiting - but not a community page, so they wouldn't have write access
645         if (!empty(DI::userSession()->getRemoteContactID($owner_uid)) && !$visitor) {
646                 $contact_id = DI::userSession()->getRemoteContactID($owner_uid);
647
648                 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id, 'uid' => $owner_uid, 'blocked' => false, 'pending' => false]);
649
650                 $remote_contact = DBA::isResult($contact);
651         }
652
653         if (!$remote_contact && DI::userSession()->getLocalUserId()) {
654                 $contact_id = $_SESSION['cid'];
655
656                 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id, 'uid' => $owner_uid, 'blocked' => false, 'pending' => false]);
657         }
658
659         if ($user['hidewall'] && !DI::userSession()->isAuthenticated()) {
660                 DI::baseUrl()->redirect('profile/' . $user['nickname'] . '/restricted');
661         }
662
663         $sql_extra = Security::getPermissionsSQLByUserId($owner_uid);
664
665         $o = "";
666
667         // tabs
668         $is_owner = (DI::userSession()->getLocalUserId() && (DI::userSession()->getLocalUserId() == $owner_uid));
669         $o .= BaseProfile::getTabsHTML('photos', $is_owner, $user['nickname'], $profile['hide-friends']);
670
671         // Display upload form
672         if ($datatype === 'upload') {
673                 if (!$can_post) {
674                         DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
675                         return;
676                 }
677
678                 // This prevents the photo upload form to return to itself without a hint the picture has been correctly uploaded.
679                 DI::session()->remove('photo_return');
680
681                 $selname = (!is_null($datum) && Strings::isHex($datum)) ? hex2bin($datum) : '';
682
683                 $albumselect = '';
684
685                 $albumselect .= '<option value="" ' . (!$selname ? ' selected="selected" ' : '') . '>&lt;current year&gt;</option>';
686                 $albums = Photo::getAlbums($owner_uid);
687                 if (!empty($albums)) {
688                         foreach ($albums as $album) {
689                                 if ($album['album'] === '') {
690                                         continue;
691                                 }
692                                 $selected = (($selname === $album['album']) ? ' selected="selected" ' : '');
693                                 $albumselect .= '<option value="' . $album['album'] . '"' . $selected . '>' . $album['album'] . '</option>';
694                         }
695                 }
696
697                 $uploader = '';
698
699                 $ret = ['post_url' => 'profile/' . $user['nickname'] . '/photos',
700                                 'addon_text' => $uploader,
701                                 'default_upload' => true];
702
703                 Hook::callAll('photo_upload_form',$ret);
704
705                 $default_upload_box = Renderer::replaceMacros(Renderer::getMarkupTemplate('photos_default_uploader_box.tpl'), []);
706                 $default_upload_submit = Renderer::replaceMacros(Renderer::getMarkupTemplate('photos_default_uploader_submit.tpl'), [
707                         '$submit' => DI::l10n()->t('Submit'),
708                 ]);
709
710                 // Get the relevant size limits for uploads. Abbreviated var names: MaxImageSize -> mis; upload_max_filesize -> umf
711                 $mis_bytes = Strings::getBytesFromShorthand(DI::config()->get('system', 'maximagesize'));
712                 $umf_bytes = Strings::getBytesFromShorthand(ini_get('upload_max_filesize'));
713
714                 // Per Friendica definition a value of '0' means unlimited:
715                 If ($mis_bytes == 0) {
716                         $mis_bytes = INF;
717                 }
718
719                 // When PHP is configured with upload_max_filesize less than maximagesize provide this lower limit.
720                 $maximagesize_bytes = (is_numeric($mis_bytes) && ($mis_bytes < $umf_bytes) ? $mis_bytes : $umf_bytes);
721
722                 // @todo We may be want to use appropriate binary prefixed dynamicly
723                 $usage_message = DI::l10n()->t('The maximum accepted image size is %s', Strings::formatBytes($maximagesize_bytes));
724
725                 $tpl = Renderer::getMarkupTemplate('photos_upload.tpl');
726
727                 $aclselect_e = ($visitor ? '' : ACL::getFullSelectorHTML(DI::page(), $a->getLoggedInUserId()));
728
729                 $o .= Renderer::replaceMacros($tpl,[
730                         '$pagename' => DI::l10n()->t('Upload Photos'),
731                         '$sessid' => session_id(),
732                         '$usage' => $usage_message,
733                         '$nickname' => $user['nickname'],
734                         '$newalbum' => DI::l10n()->t('New album name: '),
735                         '$existalbumtext' => DI::l10n()->t('or select existing album:'),
736                         '$nosharetext' => DI::l10n()->t('Do not show a status post for this upload'),
737                         '$albumselect' => $albumselect,
738                         '$permissions' => DI::l10n()->t('Permissions'),
739                         '$aclselect' => $aclselect_e,
740                         '$lockstate' => ACL::getLockstateForUserId($a->getLoggedInUserId()) ? 'lock' : 'unlock',
741                         '$alt_uploader' => $ret['addon_text'],
742                         '$default_upload_box' => ($ret['default_upload'] ? $default_upload_box : ''),
743                         '$default_upload_submit' => ($ret['default_upload'] ? $default_upload_submit : ''),
744                         '$uploadurl' => $ret['post_url'],
745
746                         // ACL permissions box
747                         '$return_path' => DI::args()->getQueryString(),
748                 ]);
749
750                 return $o;
751         }
752
753         // Display a single photo album
754         if ($datatype === 'album') {
755                 // if $datum is not a valid hex, redirect to the default page
756                 if (is_null($datum) || !Strings::isHex($datum)) {
757                         DI::baseUrl()->redirect('photos/' . $user['nickname']. '/album');
758                 }
759                 $album = hex2bin($datum);
760
761                 if ($can_post && !Photo::exists(['uid' => $owner_uid, 'album' => $album, 'photo-type' => Photo::DEFAULT])) {
762                         $can_post = false;
763                 }
764
765                 $total = 0;
766                 $r = DBA::toArray(DBA::p("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = ? AND `album` = ?
767                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id`",
768                         $owner_uid,
769                         $album
770                 ));
771                 if (DBA::isResult($r)) {
772                         $total = count($r);
773                 }
774
775                 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), 20);
776
777                 /// @TODO I have seen this many times, maybe generalize it script-wide and encapsulate it?
778                 $order_field = $_GET['order'] ?? '';
779                 if ($order_field === 'created') {
780                         $order = 'ASC';
781                 } else {
782                         $order = 'DESC';
783                 }
784
785                 $r = DBA::toArray(DBA::p("SELECT `resource-id`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`filename`) AS `filename`,
786                         ANY_VALUE(`type`) AS `type`, max(`scale`) AS `scale`, ANY_VALUE(`desc`) as `desc`,
787                         ANY_VALUE(`created`) as `created`
788                         FROM `photo` WHERE `uid` = ? AND `album` = ?
789                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id` ORDER BY `created` $order LIMIT ? , ?",
790                         intval($owner_uid),
791                         DBA::escape($album),
792                         $pager->getStart(),
793                         $pager->getItemsPerPage()
794                 ));
795
796                 if ($cmd === 'drop') {
797                         $drop_url = DI::args()->getQueryString();
798
799                         return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
800                                 '$l10n'           => [
801                                         'message' => DI::l10n()->t('Do you really want to delete this photo album and all its photos?'),
802                                         'confirm' => DI::l10n()->t('Delete Album'),
803                                         'cancel'  => DI::l10n()->t('Cancel'),
804                                 ],
805                                 '$method'        => 'post',
806                                 '$confirm_url'   => $drop_url,
807                                 '$confirm_name'  => 'dropalbum',
808                                 '$confirm_value' => 'dropalbum',
809                         ]);
810                 }
811
812                 // edit album name
813                 if ($cmd === 'edit') {
814                         if ($can_post) {
815                                 $edit_tpl = Renderer::getMarkupTemplate('album_edit.tpl');
816
817                                 $album_e = $album;
818
819                                 $o .= Renderer::replaceMacros($edit_tpl,[
820                                         '$nametext' => DI::l10n()->t('New album name: '),
821                                         '$nickname' => $user['nickname'],
822                                         '$album' => $album_e,
823                                         '$hexalbum' => bin2hex($album),
824                                         '$submit' => DI::l10n()->t('Submit'),
825                                         '$dropsubmit' => DI::l10n()->t('Delete Album')
826                                 ]);
827                         }
828                 } elseif ($can_post) {
829                         $edit = [DI::l10n()->t('Edit Album'), 'photos/' . $user['nickname'] . '/album/' . bin2hex($album) . '/edit'];
830                         $drop = [DI::l10n()->t('Drop Album'), 'photos/' . $user['nickname'] . '/album/' . bin2hex($album) . '/drop'];
831                 }
832
833                 if ($order_field === 'created') {
834                         $order =  [DI::l10n()->t('Show Newest First'), 'photos/' . $user['nickname'] . '/album/' . bin2hex($album), 'oldest'];
835                 } else {
836                         $order = [DI::l10n()->t('Show Oldest First'), 'photos/' . $user['nickname'] . '/album/' . bin2hex($album) . '?order=created', 'newest'];
837                 }
838
839                 $photos = [];
840
841                 if (DBA::isResult($r)) {
842                         // "Twist" is only used for the duepunto theme with style "slackr"
843                         $twist = false;
844                         foreach ($r as $rr) {
845                                 $twist = !$twist;
846
847                                 $ext = $phototypes[$rr['type']];
848
849                                 $imgalt_e = $rr['filename'];
850                                 $desc_e = $rr['desc'];
851
852                                 $photos[] = [
853                                         'id' => $rr['id'],
854                                         'twist' => ' ' . ($twist ? 'rotleft' : 'rotright') . rand(2,4),
855                                         'link' => 'photos/' . $user['nickname'] . '/image/' . $rr['resource-id']
856                                                 . ($order_field === 'created' ? '?order=created' : ''),
857                                         'title' => DI::l10n()->t('View Photo'),
858                                         'src' => 'photo/' . $rr['resource-id'] . '-' . $rr['scale'] . '.' .$ext,
859                                         'alt' => $imgalt_e,
860                                         'desc'=> $desc_e,
861                                         'ext' => $ext,
862                                         'hash'=> $rr['resource-id'],
863                                 ];
864                         }
865                 }
866
867                 $tpl = Renderer::getMarkupTemplate('photo_album.tpl');
868                 $o .= Renderer::replaceMacros($tpl, [
869                         '$photos' => $photos,
870                         '$album' => $album,
871                         '$can_post' => $can_post,
872                         '$upload' => [DI::l10n()->t('Upload New Photos'), 'photos/' . $user['nickname'] . '/upload/' . bin2hex($album)],
873                         '$order' => $order,
874                         '$edit' => $edit,
875                         '$drop' => $drop,
876                         '$paginate' => $pager->renderFull($total),
877                 ]);
878
879                 return $o;
880
881         }
882
883         // Display one photo
884         if ($datatype === 'image') {
885                 // fetch image, item containing image, then comments
886                 $ph = Photo::selectToArray([], ["`uid` = ? AND `resource-id` = ? " . $sql_extra, $owner_uid, $datum], ['order' => ['scale']]);
887
888                 if (!DBA::isResult($ph)) {
889                         if (DBA::exists('photo', ['resource-id' => $datum, 'uid' => $owner_uid])) {
890                                 DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied. Access to this item may be restricted.'));
891                         } else {
892                                 DI::sysmsg()->addNotice(DI::l10n()->t('Photo not available'));
893                         }
894                         return;
895                 }
896
897                 if ($cmd === 'drop') {
898                         $drop_url = DI::args()->getQueryString();
899
900                         return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
901                                 '$l10n'           => [
902                                         'message' => DI::l10n()->t('Do you really want to delete this photo?'),
903                                         'confirm' => DI::l10n()->t('Delete Photo'),
904                                         'cancel'  => DI::l10n()->t('Cancel'),
905                                 ],
906                                 '$method'        => 'post',
907                                 '$confirm_url'   => $drop_url,
908                                 '$confirm_name'  => 'delete',
909                                 '$confirm_value' => 'delete',
910                         ]);
911                 }
912
913                 $prevlink = '';
914                 $nextlink = '';
915
916                 /*
917                  * @todo This query is totally bad, the whole functionality has to be changed
918                  * The query leads to a really intense used index.
919                  * By now we hide it if someone wants to.
920                  */
921                 if ($cmd === 'view' && !DI::config()->get('system', 'no_count', false)) {
922                         $order_field = $_GET['order'] ?? '';
923
924                         if ($order_field === 'created') {
925                                 $params = ['order' => [$order_field]];
926                         } elseif (!empty($order_field)) {
927                                 $params = ['order' => [$order_field => true]];
928                         } else {
929                                 $params = [];
930                         }
931
932                         $prvnxt = Photo::selectToArray(['resource-id'], ["`album` = ? AND `uid` = ? AND `scale` = ?" . $sql_extra, $ph[0]['album'], $owner_uid, 0], $params);
933
934                         if (DBA::isResult($prvnxt)) {
935                                 $prv = null;
936                                 $nxt = null;
937                                 foreach ($prvnxt as $z => $entry) {
938                                         if ($entry['resource-id'] == $ph[0]['resource-id']) {
939                                                 $prv = $z - 1;
940                                                 $nxt = $z + 1;
941                                                 if ($prv < 0) {
942                                                         $prv = count($prvnxt) - 1;
943                                                 }
944                                                 if ($nxt >= count($prvnxt)) {
945                                                         $nxt = 0;
946                                                 }
947                                                 break;
948                                         }
949                                 }
950
951                                 if (!is_null($prv)) {
952                                         $prevlink = 'photos/' . $user['nickname'] . '/image/' . $prvnxt[$prv]['resource-id'] . ($order_field === 'created' ? '?order=created' : '');
953                                 }
954                                 if (!is_null($nxt)) {
955                                         $nextlink = 'photos/' . $user['nickname'] . '/image/' . $prvnxt[$nxt]['resource-id'] . ($order_field === 'created' ? '?order=created' : '');
956                                 }
957
958                                 $tpl = Renderer::getMarkupTemplate('photo_edit_head.tpl');
959                                 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl,[
960                                         '$prevlink' => $prevlink,
961                                         '$nextlink' => $nextlink
962                                 ]);
963
964                                 if ($prevlink) {
965                                         $prevlink = [$prevlink, '<div class="icon prev"></div>'];
966                                 }
967
968                                 if ($nextlink) {
969                                         $nextlink = [$nextlink, '<div class="icon next"></div>'];
970                                 }
971                         }
972                 }
973
974                 if (count($ph) == 1) {
975                         $hires = $lores = $ph[0];
976                 }
977
978                 if (count($ph) > 1) {
979                         if ($ph[1]['scale'] == 2) {
980                                 // original is 640 or less, we can display it directly
981                                 $hires = $lores = $ph[0];
982                         } else {
983                                 $hires = $ph[0];
984                                 $lores = $ph[1];
985                         }
986                 }
987
988                 $album_link = 'photos/' . $user['nickname'] . '/album/' . bin2hex($ph[0]['album']);
989
990                 $tools = null;
991
992                 if ($can_post && ($ph[0]['uid'] == $owner_uid)) {
993                         $tools = [];
994                         if ($cmd === 'edit') {
995                                 $tools['view'] = ['photos/' . $user['nickname'] . '/image/' . $datum, DI::l10n()->t('View photo')];
996                         } else {
997                                 $tools['edit'] = ['photos/' . $user['nickname'] . '/image/' . $datum . '/edit', DI::l10n()->t('Edit photo')];
998                                 $tools['delete'] = ['photos/' . $user['nickname'] . '/image/' . $datum . '/drop', DI::l10n()->t('Delete photo')];
999                                 $tools['profile'] = ['settings/profile/photo/crop/' . $ph[0]['resource-id'], DI::l10n()->t('Use as profile photo')];
1000                         }
1001
1002                         if (
1003                                 $ph[0]['uid'] == DI::userSession()->getLocalUserId()
1004                                 && (strlen($ph[0]['allow_cid']) || strlen($ph[0]['allow_gid']) || strlen($ph[0]['deny_cid']) || strlen($ph[0]['deny_gid']))
1005                         ) {
1006                                 $tools['lock'] = DI::l10n()->t('Private Photo');
1007                         }
1008                 }
1009
1010                 $photo = [
1011                         'href' => 'photo/' . $hires['resource-id'] . '-' . $hires['scale'] . '.' . $phototypes[$hires['type']],
1012                         'title'=> DI::l10n()->t('View Full Size'),
1013                         'src'  => 'photo/' . $lores['resource-id'] . '-' . $lores['scale'] . '.' . $phototypes[$lores['type']] . '?_u=' . DateTimeFormat::utcNow('ymdhis'),
1014                         'height' => $hires['height'],
1015                         'width' => $hires['width'],
1016                         'album' => $hires['album'],
1017                         'filename' => $hires['filename'],
1018                 ];
1019
1020                 $map = null;
1021                 $link_item = [];
1022                 $total = 0;
1023
1024                 // Do we have an item for this photo?
1025
1026                 // FIXME! - replace following code to display the conversation with our normal
1027                 // conversation functions so that it works correctly and tracks changes
1028                 // in the evolving conversation code.
1029                 // The difference is that we won't be displaying the conversation head item
1030                 // as a "post" but displaying instead the photo it is linked to
1031
1032                 $link_item = Post::selectFirst([], ["`resource-id` = ?" . $sql_extra, $datum]);
1033
1034                 if (!empty($link_item['parent']) && !empty($link_item['uid'])) {
1035                         $condition = ["`parent` = ? AND `gravity` = ?",  $link_item['parent'], Item::GRAVITY_COMMENT];
1036                         $total = Post::count($condition);
1037
1038                         $pager = new Pager(DI::l10n(), DI::args()->getQueryString());
1039
1040                         $params = ['order' => ['id'], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1041                         $items = Post::toArray(Post::selectForUser($link_item['uid'], Item::ITEM_FIELDLIST, $condition, $params));
1042
1043                         if (DI::userSession()->getLocalUserId() == $link_item['uid']) {
1044                                 Item::update(['unseen' => false], ['parent' => $link_item['parent']]);
1045                         }
1046                 }
1047
1048                 if (!empty($link_item['coord'])) {
1049                         $map = Map::byCoordinates($link_item['coord']);
1050                 }
1051
1052                 $tags = null;
1053
1054                 if (!empty($link_item['id'])) {
1055                         // parse tags and add links
1056                         $tag_arr = [];
1057                         foreach (explode(',', Tag::getCSVByURIId($link_item['uri-id'])) as $tag_name) {
1058                                 if ($tag_name) {
1059                                         $tag_arr[] = [
1060                                                 'name'      => BBCode::toPlaintext($tag_name),
1061                                                 'removeurl' => 'post/' . $link_item['id'] . '/tag/remove/' . bin2hex($tag_name) . '?return=' . urlencode(DI::args()->getCommand()),
1062                                         ];
1063                                 }
1064                         }
1065                         $tags = ['title' => DI::l10n()->t('Tags: '), 'tags' => $tag_arr];
1066                         if ($cmd === 'edit') {
1067                                 $tags['removeanyurl'] = 'post/' . $link_item['id'] . '/tag/remove?return=' . urlencode(DI::args()->getCommand());
1068                                 $tags['removetitle'] = DI::l10n()->t('[Select tags to remove]');
1069                         }
1070                 }
1071
1072
1073                 $edit = Null;
1074                 if ($cmd === 'edit' && $can_post) {
1075                         $edit_tpl = Renderer::getMarkupTemplate('photo_edit.tpl');
1076
1077                         $album_e = $ph[0]['album'];
1078                         $caption_e = $ph[0]['desc'];
1079                         $aclselect_e = ACL::getFullSelectorHTML(DI::page(), $a->getLoggedInUserId(), false, ACL::getDefaultUserPermissions($ph[0]));
1080
1081                         $edit = Renderer::replaceMacros($edit_tpl, [
1082                                 '$id' => $ph[0]['id'],
1083                                 '$album' => ['albname', DI::l10n()->t('New album name'), $album_e,''],
1084                                 '$caption' => ['desc', DI::l10n()->t('Caption'), $caption_e, ''],
1085                                 '$tags' => ['newtag', DI::l10n()->t('Add a Tag'), "", DI::l10n()->t('Example: @bob, @Barbara_Jensen, @jim@example.com, #California, #camping')],
1086                                 '$rotate_none' => ['rotate', DI::l10n()->t('Do not rotate'),0,'', true],
1087                                 '$rotate_cw' => ['rotate', DI::l10n()->t("Rotate CW \x28right\x29"),1,''],
1088                                 '$rotate_ccw' => ['rotate', DI::l10n()->t("Rotate CCW \x28left\x29"),2,''],
1089
1090                                 '$nickname' => $user['nickname'],
1091                                 '$resource_id' => $ph[0]['resource-id'],
1092                                 '$permissions' => DI::l10n()->t('Permissions'),
1093                                 '$aclselect' => $aclselect_e,
1094
1095                                 '$item_id' => $link_item['id'] ?? 0,
1096                                 '$submit' => DI::l10n()->t('Submit'),
1097                                 '$delete' => DI::l10n()->t('Delete Photo'),
1098
1099                                 // ACL permissions box
1100                                 '$return_path' => DI::args()->getQueryString(),
1101                         ]);
1102                 }
1103
1104                 $like = '';
1105                 $dislike = '';
1106                 $likebuttons = '';
1107                 $comments = '';
1108                 $paginate = '';
1109
1110                 if (!empty($link_item['id']) && !empty($link_item['uri'])) {
1111                         $cmnt_tpl = Renderer::getMarkupTemplate('comment_item.tpl');
1112                         $tpl = Renderer::getMarkupTemplate('photo_item.tpl');
1113                         $return_path = DI::args()->getCommand();
1114
1115                         if (!DBA::isResult($items)) {
1116                                 if (($can_post || Security::canWriteToUserWall($owner_uid))) {
1117                                         /*
1118                                          * Hmmm, code depending on the presence of a particular addon?
1119                                          * This should be better if done by a hook
1120                                          */
1121                                         $qcomment = null;
1122                                         if (Addon::isEnabled('qcomment')) {
1123                                                 $words = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'qcomment', 'words');
1124                                                 $qcomment = $words ? explode("\n", $words) : [];
1125                                         }
1126
1127                                         $comments .= Renderer::replaceMacros($cmnt_tpl, [
1128                                                 '$return_path' => '',
1129                                                 '$jsreload' => $return_path,
1130                                                 '$id' => $link_item['id'],
1131                                                 '$parent' => $link_item['id'],
1132                                                 '$profile_uid' =>  $owner_uid,
1133                                                 '$mylink' => $contact['url'],
1134                                                 '$mytitle' => DI::l10n()->t('This is you'),
1135                                                 '$myphoto' => $contact['thumb'],
1136                                                 '$comment' => DI::l10n()->t('Comment'),
1137                                                 '$submit' => DI::l10n()->t('Submit'),
1138                                                 '$preview' => DI::l10n()->t('Preview'),
1139                                                 '$loading' => DI::l10n()->t('Loading...'),
1140                                                 '$qcomment' => $qcomment,
1141                                                 '$rand_num' => Crypto::randomDigits(12)
1142                                         ]);
1143                                 }
1144                         }
1145
1146                         $conv_responses = [
1147                                 'like'        => [],
1148                                 'dislike'     => [],
1149                                 'attendyes'   => [],
1150                                 'attendno'    => [],
1151                                 'attendmaybe' => []
1152                         ];
1153
1154                         if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'hide_dislike')) {
1155                                 unset($conv_responses['dislike']);
1156                         }
1157
1158                         // display comments
1159                         if (DBA::isResult($items)) {
1160                                 foreach ($items as $item) {
1161                                         DI::conversation()->builtinActivityPuller($item, $conv_responses);
1162                                 }
1163
1164                                 if (!empty($conv_responses['like'][$link_item['uri']])) {
1165                                         $like = DI::conversation()->formatActivity($conv_responses['like'][$link_item['uri']]['links'], 'like', $link_item['id']);
1166                                 }
1167
1168                                 if (!empty($conv_responses['dislike'][$link_item['uri']])) {
1169                                         $dislike = DI::conversation()->formatActivity($conv_responses['dislike'][$link_item['uri']]['links'], 'dislike', $link_item['id']);
1170                                 }
1171
1172                                 if (($can_post || Security::canWriteToUserWall($owner_uid))) {
1173                                         /*
1174                                          * Hmmm, code depending on the presence of a particular addon?
1175                                          * This should be better if done by a hook
1176                                          */
1177                                         $qcomment = null;
1178                                         if (Addon::isEnabled('qcomment')) {
1179                                                 $words = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'qcomment', 'words');
1180                                                 $qcomment = $words ? explode("\n", $words) : [];
1181                                         }
1182
1183                                         $comments .= Renderer::replaceMacros($cmnt_tpl,[
1184                                                 '$return_path' => '',
1185                                                 '$jsreload' => $return_path,
1186                                                 '$id' => $link_item['id'],
1187                                                 '$parent' => $link_item['id'],
1188                                                 '$profile_uid' =>  $owner_uid,
1189                                                 '$mylink' => $contact['url'],
1190                                                 '$mytitle' => DI::l10n()->t('This is you'),
1191                                                 '$myphoto' => $contact['thumb'],
1192                                                 '$comment' => DI::l10n()->t('Comment'),
1193                                                 '$submit' => DI::l10n()->t('Submit'),
1194                                                 '$preview' => DI::l10n()->t('Preview'),
1195                                                 '$qcomment' => $qcomment,
1196                                                 '$rand_num' => Crypto::randomDigits(12)
1197                                         ]);
1198                                 }
1199
1200                                 foreach ($items as $item) {
1201                                         $comment = '';
1202                                         $template = $tpl;
1203
1204                                         $activity = DI::activity();
1205
1206                                         if (($activity->match($item['verb'], Activity::LIKE) ||
1207                                              $activity->match($item['verb'], Activity::DISLIKE)) &&
1208                                             ($item['gravity'] != Item::GRAVITY_PARENT)) {
1209                                                 continue;
1210                                         }
1211
1212                                         $author = ['uid' => 0, 'id' => $item['author-id'],
1213                                                 'network' => $item['author-network'], 'url' => $item['author-link']];
1214                                         $profile_url = Contact::magicLinkByContact($author);
1215                                         if (strpos($profile_url, 'contact/redir/') === 0) {
1216                                                 $sparkle = ' sparkle';
1217                                         } else {
1218                                                 $sparkle = '';
1219                                         }
1220
1221                                         $dropping = (($item['contact-id'] == $contact_id) || ($item['uid'] == DI::userSession()->getLocalUserId()));
1222                                         $drop = [
1223                                                 'dropping' => $dropping,
1224                                                 'pagedrop' => false,
1225                                                 'select'   => DI::l10n()->t('Select'),
1226                                                 'delete'   => DI::l10n()->t('Delete'),
1227                                         ];
1228
1229                                         $title_e = $item['title'];
1230                                         $body_e = BBCode::convertForUriId($item['uri-id'], $item['body']);
1231
1232                                         $comments .= Renderer::replaceMacros($template,[
1233                                                 '$id'          => $item['id'],
1234                                                 '$profile_url' => $profile_url,
1235                                                 '$name'        => $item['author-name'],
1236                                                 '$thumb'       => $item['author-avatar'],
1237                                                 '$sparkle'     => $sparkle,
1238                                                 '$title'       => $title_e,
1239                                                 '$body'        => $body_e,
1240                                                 '$ago'         => Temporal::getRelativeDate($item['created']),
1241                                                 '$indent'      => (($item['parent'] != $item['id']) ? ' comment' : ''),
1242                                                 '$drop'        => $drop,
1243                                                 '$comment'     => $comment
1244                                         ]);
1245
1246                                         if (($can_post || Security::canWriteToUserWall($owner_uid))) {
1247                                                 /*
1248                                                  * Hmmm, code depending on the presence of a particular addon?
1249                                                  * This should be better if done by a hook
1250                                                  */
1251                                                 $qcomment = null;
1252                                                 if (Addon::isEnabled('qcomment')) {
1253                                                         $words = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'qcomment', 'words');
1254                                                         $qcomment = $words ? explode("\n", $words) : [];
1255                                                 }
1256
1257                                                 $comments .= Renderer::replaceMacros($cmnt_tpl, [
1258                                                         '$return_path' => '',
1259                                                         '$jsreload' => $return_path,
1260                                                         '$id' => $item['id'],
1261                                                         '$parent' => $item['parent'],
1262                                                         '$profile_uid' =>  $owner_uid,
1263                                                         '$mylink' => $contact['url'],
1264                                                         '$mytitle' => DI::l10n()->t('This is you'),
1265                                                         '$myphoto' => $contact['thumb'],
1266                                                         '$comment' => DI::l10n()->t('Comment'),
1267                                                         '$submit' => DI::l10n()->t('Submit'),
1268                                                         '$preview' => DI::l10n()->t('Preview'),
1269                                                         '$qcomment' => $qcomment,
1270                                                         '$rand_num' => Crypto::randomDigits(12)
1271                                                 ]);
1272                                         }
1273                                 }
1274                         }
1275
1276                         $responses = [];
1277                         foreach ($conv_responses as $verb => $activity) {
1278                                 if (isset($activity[$link_item['uri']])) {
1279                                         $responses[$verb] = $activity[$link_item['uri']];
1280                                 }
1281                         }
1282
1283                         if ($cmd === 'view' && ($can_post || Security::canWriteToUserWall($owner_uid))) {
1284                                 $like_tpl = Renderer::getMarkupTemplate('like_noshare.tpl');
1285                                 $likebuttons = Renderer::replaceMacros($like_tpl, [
1286                                         '$id' => $link_item['id'],
1287                                         '$like' => DI::l10n()->t('Like'),
1288                                         '$like_title' => DI::l10n()->t('I like this (toggle)'),
1289                                         '$dislike' => DI::l10n()->t('Dislike'),
1290                                         '$wait' => DI::l10n()->t('Please wait'),
1291                                         '$dislike_title' => DI::l10n()->t('I don\'t like this (toggle)'),
1292                                         '$hide_dislike' => DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'hide_dislike'),
1293                                         '$responses' => $responses,
1294                                         '$return_path' => DI::args()->getQueryString(),
1295                                 ]);
1296                         }
1297
1298                         $paginate = $pager->renderFull($total);
1299                 }
1300
1301                 $photo_tpl = Renderer::getMarkupTemplate('photo_view.tpl');
1302                 $o .= Renderer::replaceMacros($photo_tpl, [
1303                         '$id' => $ph[0]['id'],
1304                         '$album' => [$album_link, $ph[0]['album']],
1305                         '$tools' => $tools,
1306                         '$photo' => $photo,
1307                         '$prevlink' => $prevlink,
1308                         '$nextlink' => $nextlink,
1309                         '$desc' => $ph[0]['desc'],
1310                         '$tags' => $tags,
1311                         '$edit' => $edit,
1312                         '$map' => $map,
1313                         '$map_text' => DI::l10n()->t('Map'),
1314                         '$likebuttons' => $likebuttons,
1315                         '$like' => $like,
1316                         '$dislike' => $dislike,
1317                         '$comments' => $comments,
1318                         '$paginate' => $paginate,
1319                 ]);
1320
1321                 DI::page()['htmlhead'] .= "\n" . '<meta name="twitter:card" content="summary_large_image" />' . "\n";
1322                 DI::page()['htmlhead'] .= '<meta name="twitter:title" content="' . $photo["album"] . '" />' . "\n";
1323                 DI::page()['htmlhead'] .= '<meta name="twitter:image" content="' . DI::baseUrl() . "/" . $photo["href"] . '" />' . "\n";
1324                 DI::page()['htmlhead'] .= '<meta name="twitter:image:width" content="' . $photo["width"] . '" />' . "\n";
1325                 DI::page()['htmlhead'] .= '<meta name="twitter:image:height" content="' . $photo["height"] . '" />' . "\n";
1326
1327                 return $o;
1328         }
1329 }