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