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