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