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