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