]> git.mxchange.org Git - friendica.git/blob - mod/photos.php
Merge pull request #12267 from MarekBenjamin/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                 // Get the relevant size limits for uploads. Abbreviated var names: MaxImageSize -> mis; upload_max_filesize -> umf
918                 $mis_bytes = Strings::getBytesFromShorthand(DI::config()->get('system', 'maximagesize'));
919                 $umf_bytes = Strings::getBytesFromShorthand(ini_get('upload_max_filesize'));
920
921                 // Per Friendica definition a value of '0' means unlimited:
922                 If ($mis_bytes == 0) {
923                         $mis_bytes = INF;
924                 }
925
926                 // When PHP is configured with upload_max_filesize less than maximagesize provide this lower limit.
927                 $maximagesize_bytes = (is_numeric($mis_bytes) && ($mis_bytes < $umf_bytes) ? $mis_bytes : $umf_bytes);
928
929                 // @todo We may be want to use appropriate binary prefixed dynamicly
930                 $usage_message = DI::l10n()->t('The maximum accepted image size is %s', Strings::formatBytes($maximagesize_bytes));
931
932                 $tpl = Renderer::getMarkupTemplate('photos_upload.tpl');
933
934                 $aclselect_e = ($visitor ? '' : ACL::getFullSelectorHTML(DI::page(), $a->getLoggedInUserId()));
935
936                 $o .= Renderer::replaceMacros($tpl,[
937                         '$pagename' => DI::l10n()->t('Upload Photos'),
938                         '$sessid' => session_id(),
939                         '$usage' => $usage_message,
940                         '$nickname' => $user['nickname'],
941                         '$newalbum' => DI::l10n()->t('New album name: '),
942                         '$existalbumtext' => DI::l10n()->t('or select existing album:'),
943                         '$nosharetext' => DI::l10n()->t('Do not show a status post for this upload'),
944                         '$albumselect' => $albumselect,
945                         '$permissions' => DI::l10n()->t('Permissions'),
946                         '$aclselect' => $aclselect_e,
947                         '$lockstate' => ACL::getLockstateForUserId($a->getLoggedInUserId()) ? 'lock' : 'unlock',
948                         '$alt_uploader' => $ret['addon_text'],
949                         '$default_upload_box' => ($ret['default_upload'] ? $default_upload_box : ''),
950                         '$default_upload_submit' => ($ret['default_upload'] ? $default_upload_submit : ''),
951                         '$uploadurl' => $ret['post_url'],
952
953                         // ACL permissions box
954                         '$return_path' => DI::args()->getQueryString(),
955                 ]);
956
957                 return $o;
958         }
959
960         // Display a single photo album
961         if ($datatype === 'album') {
962                 // if $datum is not a valid hex, redirect to the default page
963                 if (is_null($datum) || !Strings::isHex($datum)) {
964                         DI::baseUrl()->redirect('photos/' . $user['nickname']. '/album');
965                 }
966                 $album = hex2bin($datum);
967
968                 if ($can_post && !Photo::exists(['uid' => $owner_uid, 'album' => $album, 'photo-type' => Photo::DEFAULT])) {
969                         $can_post = false;
970                 }
971
972                 $total = 0;
973                 $r = DBA::toArray(DBA::p("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = ? AND `album` = ?
974                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id`",
975                         $owner_uid,
976                         $album
977                 ));
978                 if (DBA::isResult($r)) {
979                         $total = count($r);
980                 }
981
982                 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), 20);
983
984                 /// @TODO I have seen this many times, maybe generalize it script-wide and encapsulate it?
985                 $order_field = $_GET['order'] ?? '';
986                 if ($order_field === 'created') {
987                         $order = 'ASC';
988                 } else {
989                         $order = 'DESC';
990                 }
991
992                 $r = DBA::toArray(DBA::p("SELECT `resource-id`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`filename`) AS `filename`,
993                         ANY_VALUE(`type`) AS `type`, max(`scale`) AS `scale`, ANY_VALUE(`desc`) as `desc`,
994                         ANY_VALUE(`created`) as `created`
995                         FROM `photo` WHERE `uid` = ? AND `album` = ?
996                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id` ORDER BY `created` $order LIMIT ? , ?",
997                         intval($owner_uid),
998                         DBA::escape($album),
999                         $pager->getStart(),
1000                         $pager->getItemsPerPage()
1001                 ));
1002
1003                 if ($cmd === 'drop') {
1004                         $drop_url = DI::args()->getQueryString();
1005
1006                         return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
1007                                 '$l10n'           => [
1008                                         'message' => DI::l10n()->t('Do you really want to delete this photo album and all its photos?'),
1009                                         'confirm' => DI::l10n()->t('Delete Album'),
1010                                         'cancel'  => DI::l10n()->t('Cancel'),
1011                                 ],
1012                                 '$method'        => 'post',
1013                                 '$confirm_url'   => $drop_url,
1014                                 '$confirm_name'  => 'dropalbum',
1015                                 '$confirm_value' => 'dropalbum',
1016                         ]);
1017                 }
1018
1019                 // edit album name
1020                 if ($cmd === 'edit') {
1021                         if ($can_post) {
1022                                 $edit_tpl = Renderer::getMarkupTemplate('album_edit.tpl');
1023
1024                                 $album_e = $album;
1025
1026                                 $o .= Renderer::replaceMacros($edit_tpl,[
1027                                         '$nametext' => DI::l10n()->t('New album name: '),
1028                                         '$nickname' => $user['nickname'],
1029                                         '$album' => $album_e,
1030                                         '$hexalbum' => bin2hex($album),
1031                                         '$submit' => DI::l10n()->t('Submit'),
1032                                         '$dropsubmit' => DI::l10n()->t('Delete Album')
1033                                 ]);
1034                         }
1035                 } elseif ($can_post) {
1036                         $edit = [DI::l10n()->t('Edit Album'), 'photos/' . $user['nickname'] . '/album/' . bin2hex($album) . '/edit'];
1037                         $drop = [DI::l10n()->t('Drop Album'), 'photos/' . $user['nickname'] . '/album/' . bin2hex($album) . '/drop'];
1038                 }
1039
1040                 if ($order_field === 'created') {
1041                         $order =  [DI::l10n()->t('Show Newest First'), 'photos/' . $user['nickname'] . '/album/' . bin2hex($album), 'oldest'];
1042                 } else {
1043                         $order = [DI::l10n()->t('Show Oldest First'), 'photos/' . $user['nickname'] . '/album/' . bin2hex($album) . '?order=created', 'newest'];
1044                 }
1045
1046                 $photos = [];
1047
1048                 if (DBA::isResult($r)) {
1049                         // "Twist" is only used for the duepunto theme with style "slackr"
1050                         $twist = false;
1051                         foreach ($r as $rr) {
1052                                 $twist = !$twist;
1053
1054                                 $ext = $phototypes[$rr['type']];
1055
1056                                 $imgalt_e = $rr['filename'];
1057                                 $desc_e = $rr['desc'];
1058
1059                                 $photos[] = [
1060                                         'id' => $rr['id'],
1061                                         'twist' => ' ' . ($twist ? 'rotleft' : 'rotright') . rand(2,4),
1062                                         'link' => 'photos/' . $user['nickname'] . '/image/' . $rr['resource-id']
1063                                                 . ($order_field === 'created' ? '?order=created' : ''),
1064                                         'title' => DI::l10n()->t('View Photo'),
1065                                         'src' => 'photo/' . $rr['resource-id'] . '-' . $rr['scale'] . '.' .$ext,
1066                                         'alt' => $imgalt_e,
1067                                         'desc'=> $desc_e,
1068                                         'ext' => $ext,
1069                                         'hash'=> $rr['resource-id'],
1070                                 ];
1071                         }
1072                 }
1073
1074                 $tpl = Renderer::getMarkupTemplate('photo_album.tpl');
1075                 $o .= Renderer::replaceMacros($tpl, [
1076                         '$photos' => $photos,
1077                         '$album' => $album,
1078                         '$can_post' => $can_post,
1079                         '$upload' => [DI::l10n()->t('Upload New Photos'), 'photos/' . $user['nickname'] . '/upload/' . bin2hex($album)],
1080                         '$order' => $order,
1081                         '$edit' => $edit,
1082                         '$drop' => $drop,
1083                         '$paginate' => $pager->renderFull($total),
1084                 ]);
1085
1086                 return $o;
1087
1088         }
1089
1090         // Display one photo
1091         if ($datatype === 'image') {
1092                 // fetch image, item containing image, then comments
1093                 $ph = Photo::selectToArray([], ["`uid` = ? AND `resource-id` = ? " . $sql_extra, $owner_uid, $datum], ['order' => ['scale']]);
1094
1095                 if (!DBA::isResult($ph)) {
1096                         if (DBA::exists('photo', ['resource-id' => $datum, 'uid' => $owner_uid])) {
1097                                 DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied. Access to this item may be restricted.'));
1098                         } else {
1099                                 DI::sysmsg()->addNotice(DI::l10n()->t('Photo not available'));
1100                         }
1101                         return;
1102                 }
1103
1104                 if ($cmd === 'drop') {
1105                         $drop_url = DI::args()->getQueryString();
1106
1107                         return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
1108                                 '$l10n'           => [
1109                                         'message' => DI::l10n()->t('Do you really want to delete this photo?'),
1110                                         'confirm' => DI::l10n()->t('Delete Photo'),
1111                                         'cancel'  => DI::l10n()->t('Cancel'),
1112                                 ],
1113                                 '$method'        => 'post',
1114                                 '$confirm_url'   => $drop_url,
1115                                 '$confirm_name'  => 'delete',
1116                                 '$confirm_value' => 'delete',
1117                         ]);
1118                 }
1119
1120                 $prevlink = '';
1121                 $nextlink = '';
1122
1123                 /*
1124                  * @todo This query is totally bad, the whole functionality has to be changed
1125                  * The query leads to a really intense used index.
1126                  * By now we hide it if someone wants to.
1127                  */
1128                 if ($cmd === 'view' && !DI::config()->get('system', 'no_count', false)) {
1129                         $order_field = $_GET['order'] ?? '';
1130
1131                         if ($order_field === 'created') {
1132                                 $params = ['order' => [$order_field]];
1133                         } elseif (!empty($order_field)) {
1134                                 $params = ['order' => [$order_field => true]];
1135                         } else {
1136                                 $params = [];
1137                         }
1138
1139                         $prvnxt = Photo::selectToArray(['resource-id'], ["`album` = ? AND `uid` = ? AND `scale` = ?" . $sql_extra, $ph[0]['album'], $owner_uid, 0], $params);
1140
1141                         if (DBA::isResult($prvnxt)) {
1142                                 $prv = null;
1143                                 $nxt = null;
1144                                 foreach ($prvnxt as $z => $entry) {
1145                                         if ($entry['resource-id'] == $ph[0]['resource-id']) {
1146                                                 $prv = $z - 1;
1147                                                 $nxt = $z + 1;
1148                                                 if ($prv < 0) {
1149                                                         $prv = count($prvnxt) - 1;
1150                                                 }
1151                                                 if ($nxt >= count($prvnxt)) {
1152                                                         $nxt = 0;
1153                                                 }
1154                                                 break;
1155                                         }
1156                                 }
1157
1158                                 if (!is_null($prv)) {
1159                                         $prevlink = 'photos/' . $user['nickname'] . '/image/' . $prvnxt[$prv]['resource-id'] . ($order_field === 'created' ? '?order=created' : '');
1160                                 }
1161                                 if (!is_null($nxt)) {
1162                                         $nextlink = 'photos/' . $user['nickname'] . '/image/' . $prvnxt[$nxt]['resource-id'] . ($order_field === 'created' ? '?order=created' : '');
1163                                 }
1164
1165                                 $tpl = Renderer::getMarkupTemplate('photo_edit_head.tpl');
1166                                 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl,[
1167                                         '$prevlink' => $prevlink,
1168                                         '$nextlink' => $nextlink
1169                                 ]);
1170
1171                                 if ($prevlink) {
1172                                         $prevlink = [$prevlink, '<div class="icon prev"></div>'];
1173                                 }
1174
1175                                 if ($nextlink) {
1176                                         $nextlink = [$nextlink, '<div class="icon next"></div>'];
1177                                 }
1178                         }
1179                 }
1180
1181                 if (count($ph) == 1) {
1182                         $hires = $lores = $ph[0];
1183                 }
1184
1185                 if (count($ph) > 1) {
1186                         if ($ph[1]['scale'] == 2) {
1187                                 // original is 640 or less, we can display it directly
1188                                 $hires = $lores = $ph[0];
1189                         } else {
1190                                 $hires = $ph[0];
1191                                 $lores = $ph[1];
1192                         }
1193                 }
1194
1195                 $album_link = 'photos/' . $user['nickname'] . '/album/' . bin2hex($ph[0]['album']);
1196
1197                 $tools = null;
1198
1199                 if ($can_post && ($ph[0]['uid'] == $owner_uid)) {
1200                         $tools = [];
1201                         if ($cmd === 'edit') {
1202                                 $tools['view'] = ['photos/' . $user['nickname'] . '/image/' . $datum, DI::l10n()->t('View photo')];
1203                         } else {
1204                                 $tools['edit'] = ['photos/' . $user['nickname'] . '/image/' . $datum . '/edit', DI::l10n()->t('Edit photo')];
1205                                 $tools['delete'] = ['photos/' . $user['nickname'] . '/image/' . $datum . '/drop', DI::l10n()->t('Delete photo')];
1206                                 $tools['profile'] = ['settings/profile/photo/crop/' . $ph[0]['resource-id'], DI::l10n()->t('Use as profile photo')];
1207                         }
1208
1209                         if (
1210                                 $ph[0]['uid'] == DI::userSession()->getLocalUserId()
1211                                 && (strlen($ph[0]['allow_cid']) || strlen($ph[0]['allow_gid']) || strlen($ph[0]['deny_cid']) || strlen($ph[0]['deny_gid']))
1212                         ) {
1213                                 $tools['lock'] = DI::l10n()->t('Private Photo');
1214                         }
1215                 }
1216
1217                 $photo = [
1218                         'href' => 'photo/' . $hires['resource-id'] . '-' . $hires['scale'] . '.' . $phototypes[$hires['type']],
1219                         'title'=> DI::l10n()->t('View Full Size'),
1220                         'src'  => 'photo/' . $lores['resource-id'] . '-' . $lores['scale'] . '.' . $phototypes[$lores['type']] . '?_u=' . DateTimeFormat::utcNow('ymdhis'),
1221                         'height' => $hires['height'],
1222                         'width' => $hires['width'],
1223                         'album' => $hires['album'],
1224                         'filename' => $hires['filename'],
1225                 ];
1226
1227                 $map = null;
1228                 $link_item = [];
1229                 $total = 0;
1230
1231                 // Do we have an item for this photo?
1232
1233                 // FIXME! - replace following code to display the conversation with our normal
1234                 // conversation functions so that it works correctly and tracks changes
1235                 // in the evolving conversation code.
1236                 // The difference is that we won't be displaying the conversation head item
1237                 // as a "post" but displaying instead the photo it is linked to
1238
1239                 $link_item = Post::selectFirst([], ["`resource-id` = ?" . $sql_extra, $datum]);
1240
1241                 if (!empty($link_item['parent']) && !empty($link_item['uid'])) {
1242                         $condition = ["`parent` = ? AND `gravity` = ?",  $link_item['parent'], Item::GRAVITY_COMMENT];
1243                         $total = Post::count($condition);
1244
1245                         $pager = new Pager(DI::l10n(), DI::args()->getQueryString());
1246
1247                         $params = ['order' => ['id'], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1248                         $items = Post::toArray(Post::selectForUser($link_item['uid'], Item::ITEM_FIELDLIST, $condition, $params));
1249
1250                         if (DI::userSession()->getLocalUserId() == $link_item['uid']) {
1251                                 Item::update(['unseen' => false], ['parent' => $link_item['parent']]);
1252                         }
1253                 }
1254
1255                 if (!empty($link_item['coord'])) {
1256                         $map = Map::byCoordinates($link_item['coord']);
1257                 }
1258
1259                 $tags = null;
1260
1261                 if (!empty($link_item['id'])) {
1262                         // parse tags and add links
1263                         $tag_arr = [];
1264                         foreach (explode(',', Tag::getCSVByURIId($link_item['uri-id'])) as $tag_name) {
1265                                 if ($tag_name) {
1266                                         $tag_arr[] = [
1267                                                 'name'      => BBCode::toPlaintext($tag_name),
1268                                                 'removeurl' => 'post/' . $link_item['id'] . '/tag/remove/' . bin2hex($tag_name) . '?return=' . urlencode(DI::args()->getCommand()),
1269                                         ];
1270                                 }
1271                         }
1272                         $tags = ['title' => DI::l10n()->t('Tags: '), 'tags' => $tag_arr];
1273                         if ($cmd === 'edit') {
1274                                 $tags['removeanyurl'] = 'post/' . $link_item['id'] . '/tag/remove?return=' . urlencode(DI::args()->getCommand());
1275                                 $tags['removetitle'] = DI::l10n()->t('[Select tags to remove]');
1276                         }
1277                 }
1278
1279
1280                 $edit = Null;
1281                 if ($cmd === 'edit' && $can_post) {
1282                         $edit_tpl = Renderer::getMarkupTemplate('photo_edit.tpl');
1283
1284                         $album_e = $ph[0]['album'];
1285                         $caption_e = $ph[0]['desc'];
1286                         $aclselect_e = ACL::getFullSelectorHTML(DI::page(), $a->getLoggedInUserId(), false, ACL::getDefaultUserPermissions($ph[0]));
1287
1288                         $edit = Renderer::replaceMacros($edit_tpl, [
1289                                 '$id' => $ph[0]['id'],
1290                                 '$album' => ['albname', DI::l10n()->t('New album name'), $album_e,''],
1291                                 '$caption' => ['desc', DI::l10n()->t('Caption'), $caption_e, ''],
1292                                 '$tags' => ['newtag', DI::l10n()->t('Add a Tag'), "", DI::l10n()->t('Example: @bob, @Barbara_Jensen, @jim@example.com, #California, #camping')],
1293                                 '$rotate_none' => ['rotate', DI::l10n()->t('Do not rotate'),0,'', true],
1294                                 '$rotate_cw' => ['rotate', DI::l10n()->t("Rotate CW \x28right\x29"),1,''],
1295                                 '$rotate_ccw' => ['rotate', DI::l10n()->t("Rotate CCW \x28left\x29"),2,''],
1296
1297                                 '$nickname' => $user['nickname'],
1298                                 '$resource_id' => $ph[0]['resource-id'],
1299                                 '$permissions' => DI::l10n()->t('Permissions'),
1300                                 '$aclselect' => $aclselect_e,
1301
1302                                 '$item_id' => $link_item['id'] ?? 0,
1303                                 '$submit' => DI::l10n()->t('Submit'),
1304                                 '$delete' => DI::l10n()->t('Delete Photo'),
1305
1306                                 // ACL permissions box
1307                                 '$return_path' => DI::args()->getQueryString(),
1308                         ]);
1309                 }
1310
1311                 $like = '';
1312                 $dislike = '';
1313                 $likebuttons = '';
1314                 $comments = '';
1315                 $paginate = '';
1316
1317                 if (!empty($link_item['id']) && !empty($link_item['uri'])) {
1318                         $cmnt_tpl = Renderer::getMarkupTemplate('comment_item.tpl');
1319                         $tpl = Renderer::getMarkupTemplate('photo_item.tpl');
1320                         $return_path = DI::args()->getCommand();
1321
1322                         if (!DBA::isResult($items)) {
1323                                 if (($can_post || Security::canWriteToUserWall($owner_uid))) {
1324                                         /*
1325                                          * Hmmm, code depending on the presence of a particular addon?
1326                                          * This should be better if done by a hook
1327                                          */
1328                                         $qcomment = null;
1329                                         if (Addon::isEnabled('qcomment')) {
1330                                                 $words = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'qcomment', 'words');
1331                                                 $qcomment = $words ? explode("\n", $words) : [];
1332                                         }
1333
1334                                         $comments .= Renderer::replaceMacros($cmnt_tpl, [
1335                                                 '$return_path' => '',
1336                                                 '$jsreload' => $return_path,
1337                                                 '$id' => $link_item['id'],
1338                                                 '$parent' => $link_item['id'],
1339                                                 '$profile_uid' =>  $owner_uid,
1340                                                 '$mylink' => $contact['url'],
1341                                                 '$mytitle' => DI::l10n()->t('This is you'),
1342                                                 '$myphoto' => $contact['thumb'],
1343                                                 '$comment' => DI::l10n()->t('Comment'),
1344                                                 '$submit' => DI::l10n()->t('Submit'),
1345                                                 '$preview' => DI::l10n()->t('Preview'),
1346                                                 '$loading' => DI::l10n()->t('Loading...'),
1347                                                 '$qcomment' => $qcomment,
1348                                                 '$rand_num' => Crypto::randomDigits(12)
1349                                         ]);
1350                                 }
1351                         }
1352
1353                         $conv_responses = [
1354                                 'like'        => [],
1355                                 'dislike'     => [],
1356                                 'attendyes'   => [],
1357                                 'attendno'    => [],
1358                                 'attendmaybe' => []
1359                         ];
1360
1361                         if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'hide_dislike')) {
1362                                 unset($conv_responses['dislike']);
1363                         }
1364
1365                         // display comments
1366                         if (DBA::isResult($items)) {
1367                                 foreach ($items as $item) {
1368                                         DI::conversation()->builtinActivityPuller($item, $conv_responses);
1369                                 }
1370
1371                                 if (!empty($conv_responses['like'][$link_item['uri']])) {
1372                                         $like = DI::conversation()->formatActivity($conv_responses['like'][$link_item['uri']]['links'], 'like', $link_item['id']);
1373                                 }
1374
1375                                 if (!empty($conv_responses['dislike'][$link_item['uri']])) {
1376                                         $dislike = DI::conversation()->formatActivity($conv_responses['dislike'][$link_item['uri']]['links'], 'dislike', $link_item['id']);
1377                                 }
1378
1379                                 if (($can_post || Security::canWriteToUserWall($owner_uid))) {
1380                                         /*
1381                                          * Hmmm, code depending on the presence of a particular addon?
1382                                          * This should be better if done by a hook
1383                                          */
1384                                         $qcomment = null;
1385                                         if (Addon::isEnabled('qcomment')) {
1386                                                 $words = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'qcomment', 'words');
1387                                                 $qcomment = $words ? explode("\n", $words) : [];
1388                                         }
1389
1390                                         $comments .= Renderer::replaceMacros($cmnt_tpl,[
1391                                                 '$return_path' => '',
1392                                                 '$jsreload' => $return_path,
1393                                                 '$id' => $link_item['id'],
1394                                                 '$parent' => $link_item['id'],
1395                                                 '$profile_uid' =>  $owner_uid,
1396                                                 '$mylink' => $contact['url'],
1397                                                 '$mytitle' => DI::l10n()->t('This is you'),
1398                                                 '$myphoto' => $contact['thumb'],
1399                                                 '$comment' => DI::l10n()->t('Comment'),
1400                                                 '$submit' => DI::l10n()->t('Submit'),
1401                                                 '$preview' => DI::l10n()->t('Preview'),
1402                                                 '$qcomment' => $qcomment,
1403                                                 '$rand_num' => Crypto::randomDigits(12)
1404                                         ]);
1405                                 }
1406
1407                                 foreach ($items as $item) {
1408                                         $comment = '';
1409                                         $template = $tpl;
1410
1411                                         $activity = DI::activity();
1412
1413                                         if (($activity->match($item['verb'], Activity::LIKE) ||
1414                                              $activity->match($item['verb'], Activity::DISLIKE)) &&
1415                                             ($item['gravity'] != Item::GRAVITY_PARENT)) {
1416                                                 continue;
1417                                         }
1418
1419                                         $author = ['uid' => 0, 'id' => $item['author-id'],
1420                                                 'network' => $item['author-network'], 'url' => $item['author-link']];
1421                                         $profile_url = Contact::magicLinkByContact($author);
1422                                         if (strpos($profile_url, 'contact/redir/') === 0) {
1423                                                 $sparkle = ' sparkle';
1424                                         } else {
1425                                                 $sparkle = '';
1426                                         }
1427
1428                                         $dropping = (($item['contact-id'] == $contact_id) || ($item['uid'] == DI::userSession()->getLocalUserId()));
1429                                         $drop = [
1430                                                 'dropping' => $dropping,
1431                                                 'pagedrop' => false,
1432                                                 'select'   => DI::l10n()->t('Select'),
1433                                                 'delete'   => DI::l10n()->t('Delete'),
1434                                         ];
1435
1436                                         $title_e = $item['title'];
1437                                         $body_e = BBCode::convertForUriId($item['uri-id'], $item['body']);
1438
1439                                         $comments .= Renderer::replaceMacros($template,[
1440                                                 '$id'          => $item['id'],
1441                                                 '$profile_url' => $profile_url,
1442                                                 '$name'        => $item['author-name'],
1443                                                 '$thumb'       => $item['author-avatar'],
1444                                                 '$sparkle'     => $sparkle,
1445                                                 '$title'       => $title_e,
1446                                                 '$body'        => $body_e,
1447                                                 '$ago'         => Temporal::getRelativeDate($item['created']),
1448                                                 '$indent'      => (($item['parent'] != $item['id']) ? ' comment' : ''),
1449                                                 '$drop'        => $drop,
1450                                                 '$comment'     => $comment
1451                                         ]);
1452
1453                                         if (($can_post || Security::canWriteToUserWall($owner_uid))) {
1454                                                 /*
1455                                                  * Hmmm, code depending on the presence of a particular addon?
1456                                                  * This should be better if done by a hook
1457                                                  */
1458                                                 $qcomment = null;
1459                                                 if (Addon::isEnabled('qcomment')) {
1460                                                         $words = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'qcomment', 'words');
1461                                                         $qcomment = $words ? explode("\n", $words) : [];
1462                                                 }
1463
1464                                                 $comments .= Renderer::replaceMacros($cmnt_tpl, [
1465                                                         '$return_path' => '',
1466                                                         '$jsreload' => $return_path,
1467                                                         '$id' => $item['id'],
1468                                                         '$parent' => $item['parent'],
1469                                                         '$profile_uid' =>  $owner_uid,
1470                                                         '$mylink' => $contact['url'],
1471                                                         '$mytitle' => DI::l10n()->t('This is you'),
1472                                                         '$myphoto' => $contact['thumb'],
1473                                                         '$comment' => DI::l10n()->t('Comment'),
1474                                                         '$submit' => DI::l10n()->t('Submit'),
1475                                                         '$preview' => DI::l10n()->t('Preview'),
1476                                                         '$qcomment' => $qcomment,
1477                                                         '$rand_num' => Crypto::randomDigits(12)
1478                                                 ]);
1479                                         }
1480                                 }
1481                         }
1482
1483                         $responses = [];
1484                         foreach ($conv_responses as $verb => $activity) {
1485                                 if (isset($activity[$link_item['uri']])) {
1486                                         $responses[$verb] = $activity[$link_item['uri']];
1487                                 }
1488                         }
1489
1490                         if ($cmd === 'view' && ($can_post || Security::canWriteToUserWall($owner_uid))) {
1491                                 $like_tpl = Renderer::getMarkupTemplate('like_noshare.tpl');
1492                                 $likebuttons = Renderer::replaceMacros($like_tpl, [
1493                                         '$id' => $link_item['id'],
1494                                         '$like' => DI::l10n()->t('Like'),
1495                                         '$like_title' => DI::l10n()->t('I like this (toggle)'),
1496                                         '$dislike' => DI::l10n()->t('Dislike'),
1497                                         '$wait' => DI::l10n()->t('Please wait'),
1498                                         '$dislike_title' => DI::l10n()->t('I don\'t like this (toggle)'),
1499                                         '$hide_dislike' => DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'hide_dislike'),
1500                                         '$responses' => $responses,
1501                                         '$return_path' => DI::args()->getQueryString(),
1502                                 ]);
1503                         }
1504
1505                         $paginate = $pager->renderFull($total);
1506                 }
1507
1508                 $photo_tpl = Renderer::getMarkupTemplate('photo_view.tpl');
1509                 $o .= Renderer::replaceMacros($photo_tpl, [
1510                         '$id' => $ph[0]['id'],
1511                         '$album' => [$album_link, $ph[0]['album']],
1512                         '$tools' => $tools,
1513                         '$photo' => $photo,
1514                         '$prevlink' => $prevlink,
1515                         '$nextlink' => $nextlink,
1516                         '$desc' => $ph[0]['desc'],
1517                         '$tags' => $tags,
1518                         '$edit' => $edit,
1519                         '$map' => $map,
1520                         '$map_text' => DI::l10n()->t('Map'),
1521                         '$likebuttons' => $likebuttons,
1522                         '$like' => $like,
1523                         '$dislike' => $dislike,
1524                         '$comments' => $comments,
1525                         '$paginate' => $paginate,
1526                 ]);
1527
1528                 DI::page()['htmlhead'] .= "\n" . '<meta name="twitter:card" content="summary_large_image" />' . "\n";
1529                 DI::page()['htmlhead'] .= '<meta name="twitter:title" content="' . $photo["album"] . '" />' . "\n";
1530                 DI::page()['htmlhead'] .= '<meta name="twitter:image" content="' . DI::baseUrl() . "/" . $photo["href"] . '" />' . "\n";
1531                 DI::page()['htmlhead'] .= '<meta name="twitter:image:width" content="' . $photo["width"] . '" />' . "\n";
1532                 DI::page()['htmlhead'] .= '<meta name="twitter:image:height" content="' . $photo["height"] . '" />' . "\n";
1533
1534                 return $o;
1535         }
1536 }