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