]> git.mxchange.org Git - friendica.git/blob - mod/photos.php
Merge pull request #10900 from annando/notify
[friendica.git] / mod / photos.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, 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                 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                 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 = Strings::escapeTags(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'])      ? Strings::escapeTags(trim($_POST['desc']))      : '';
295                 $rawtags     = !empty($_POST['newtag'])    ? Strings::escapeTags(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']) ? Strings::escapeTags(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` > UTC_TIMESTAMP() - INTERVAL 3 HOUR', $album, $page_owner_uid]);
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) {
707                 $max_length = MAX_IMAGE_LENGTH;
708         }
709         if ($max_length > 0) {
710                 $image->scaleDown($max_length);
711         }
712
713         $width  = $image->getWidth();
714         $height = $image->getHeight();
715
716         $smallest = 0;
717
718         $resource_id = Photo::newResource();
719
720         $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);
721
722         if (!$r) {
723                 Logger::info('image store failed');
724                 notice(DI::l10n()->t('Image upload failed.'));
725                 return;
726         }
727
728         if ($width > 640 || $height > 640) {
729                 $image->scaleDown(640);
730                 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);
731                 $smallest = 1;
732         }
733
734         if ($width > 320 || $height > 320) {
735                 $image->scaleDown(320);
736                 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);
737                 $smallest = 2;
738         }
739
740         $uri = Item::newURI($page_owner_uid);
741
742         // Create item container
743         $lat = $lon = null;
744         if (!empty($exif['GPS']) && Feature::isEnabled($page_owner_uid, 'photo_location')) {
745                 $lat = Photo::getGps($exif['GPS']['GPSLatitude'], $exif['GPS']['GPSLatitudeRef']);
746                 $lon = Photo::getGps($exif['GPS']['GPSLongitude'], $exif['GPS']['GPSLongitudeRef']);
747         }
748
749         $arr = [];
750         if ($lat && $lon) {
751                 $arr['coord'] = $lat . ' ' . $lon;
752         }
753
754         $arr['guid']          = System::createUUID();
755         $arr['uid']           = $page_owner_uid;
756         $arr['uri']           = $uri;
757         $arr['post-type']     = Item::PT_IMAGE;
758         $arr['wall']          = 1;
759         $arr['resource-id']   = $resource_id;
760         $arr['contact-id']    = $owner_record['id'];
761         $arr['owner-name']    = $owner_record['name'];
762         $arr['owner-link']    = $owner_record['url'];
763         $arr['owner-avatar']  = $owner_record['thumb'];
764         $arr['author-name']   = $owner_record['name'];
765         $arr['author-link']   = $owner_record['url'];
766         $arr['author-avatar'] = $owner_record['thumb'];
767         $arr['title']         = '';
768         $arr['allow_cid']     = $str_contact_allow;
769         $arr['allow_gid']     = $str_group_allow;
770         $arr['deny_cid']      = $str_contact_deny;
771         $arr['deny_gid']      = $str_group_deny;
772         $arr['visible']       = $visible;
773         $arr['origin']        = 1;
774
775         $arr['body']          = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nickname'] . '/image/' . $resource_id . ']'
776                                 . '[img]' . DI::baseUrl() . "/photo/{$resource_id}-{$smallest}.".$image->getExt() . '[/img]'
777                                 . '[/url]';
778
779         $item_id = Item::insert($arr);
780         // Update the photo albums cache
781         Photo::clearAlbumCache($page_owner_uid);
782
783         Hook::callAll('photo_post_end', $item_id);
784
785         // addon uploaders should call "exit()" within the photo_post_end hook
786         // if they do not wish to be redirected
787
788         DI::baseUrl()->redirect($_SESSION['photo_return']);
789         // NOTREACHED
790 }
791
792 function photos_content(App $a)
793 {
794         // URLs:
795         // photos/name
796         // photos/name/upload
797         // photos/name/upload/xxxxx (xxxxx is album name)
798         // photos/name/album/xxxxx
799         // photos/name/album/xxxxx/edit
800         // photos/name/album/xxxxx/drop
801         // photos/name/image/xxxxx
802         // photos/name/image/xxxxx/edit
803         // photos/name/image/xxxxx/drop
804
805         $user = User::getByNickname(DI::args()->getArgv()[1]);
806         if (!DBA::isResult($user)) {
807                 throw new HTTPException\NotFoundException(DI::l10n()->t('User not found.'));
808         }
809
810         if (DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) {
811                 notice(DI::l10n()->t('Public access denied.'));
812                 return;
813         }
814
815         if (empty($user)) {
816                 notice(DI::l10n()->t('No photos selected'));
817                 return;
818         }
819
820         $profile = Profile::getByUID($user['uid']);
821
822         $phototypes = Images::supportedTypes();
823
824         $_SESSION['photo_return'] = DI::args()->getCommand();
825
826         // Parse arguments
827         $datum = null;
828         if (DI::args()->getArgc() > 3) {
829                 $datatype = DI::args()->getArgv()[2];
830                 $datum = DI::args()->getArgv()[3];
831         } elseif ((DI::args()->getArgc() > 2) && (DI::args()->getArgv()[2] === 'upload')) {
832                 $datatype = 'upload';
833         } else {
834                 $datatype = 'summary';
835         }
836
837         if (DI::args()->getArgc() > 4) {
838                 $cmd = DI::args()->getArgv()[4];
839         } else {
840                 $cmd = 'view';
841         }
842
843         // Setup permissions structures
844         $can_post       = false;
845         $visitor        = 0;
846         $contact        = null;
847         $remote_contact = false;
848         $contact_id     = 0;
849         $edit           = '';
850         $drop           = '';
851
852         $owner_uid = $user['uid'];
853
854         $community_page = (($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
855
856         if (local_user() && (local_user() == $owner_uid)) {
857                 $can_post = true;
858         } elseif ($community_page && !empty(Session::getRemoteContactID($owner_uid))) {
859                 $contact_id = Session::getRemoteContactID($owner_uid);
860                 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id, 'uid' => $owner_uid, 'blocked' => false, 'pending' => false]);
861
862                 if (DBA::isResult($contact)) {
863                         $can_post = true;
864                         $remote_contact = true;
865                         $visitor = $contact_id;
866                 }
867         }
868
869         // perhaps they're visiting - but not a community page, so they wouldn't have write access
870         if (!empty(Session::getRemoteContactID($owner_uid)) && !$visitor) {
871                 $contact_id = Session::getRemoteContactID($owner_uid);
872
873                 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id, 'uid' => $owner_uid, 'blocked' => false, 'pending' => false]);
874
875                 $remote_contact = DBA::isResult($contact);
876         }
877
878         if (!$remote_contact && local_user()) {
879                 $contact_id = $_SESSION['cid'];
880
881                 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id, 'uid' => $owner_uid, 'blocked' => false, 'pending' => false]);
882         }
883
884         if ($user['hidewall'] && (local_user() != $owner_uid) && !$remote_contact) {
885                 notice(DI::l10n()->t('Access to this item is restricted.'));
886                 return;
887         }
888
889         $sql_extra = Security::getPermissionsSQLByUserId($owner_uid);
890
891         $o = "";
892
893         // tabs
894         $is_owner = (local_user() && (local_user() == $owner_uid));
895         $o .= BaseProfile::getTabsHTML($a, 'photos', $is_owner, $user['nickname'], $profile['hide-friends']);
896
897         // Display upload form
898         if ($datatype === 'upload') {
899                 if (!$can_post) {
900                         notice(DI::l10n()->t('Permission denied.'));
901                         return;
902                 }
903
904                 $selname = Strings::isHex($datum) ? hex2bin($datum) : '';
905
906                 $albumselect = '';
907
908                 $albumselect .= '<option value="" ' . (!$selname ? ' selected="selected" ' : '') . '>&lt;current year&gt;</option>';
909                 $albums = Photo::getAlbums($owner_uid);
910                 if (!empty($albums)) {
911                         foreach ($albums as $album) {
912                                 if ($album['album'] === '') {
913                                         continue;
914                                 }
915                                 $selected = (($selname === $album['album']) ? ' selected="selected" ' : '');
916                                 $albumselect .= '<option value="' . $album['album'] . '"' . $selected . '>' . $album['album'] . '</option>';
917                         }
918                 }
919
920                 $uploader = '';
921
922                 $ret = ['post_url' => 'photos/' . $user['nickname'],
923                                 'addon_text' => $uploader,
924                                 'default_upload' => true];
925
926                 Hook::callAll('photo_upload_form',$ret);
927
928                 $default_upload_box = Renderer::replaceMacros(Renderer::getMarkupTemplate('photos_default_uploader_box.tpl'), []);
929                 $default_upload_submit = Renderer::replaceMacros(Renderer::getMarkupTemplate('photos_default_uploader_submit.tpl'), [
930                         '$submit' => DI::l10n()->t('Submit'),
931                 ]);
932
933                 $usage_message = '';
934
935                 $tpl = Renderer::getMarkupTemplate('photos_upload.tpl');
936
937                 $aclselect_e = ($visitor ? '' : ACL::getFullSelectorHTML(DI::page(), $a->getLoggedInUserId()));
938
939                 $o .= Renderer::replaceMacros($tpl,[
940                         '$pagename' => DI::l10n()->t('Upload Photos'),
941                         '$sessid' => session_id(),
942                         '$usage' => $usage_message,
943                         '$nickname' => $user['nickname'],
944                         '$newalbum' => DI::l10n()->t('New album name: '),
945                         '$existalbumtext' => DI::l10n()->t('or select existing album:'),
946                         '$nosharetext' => DI::l10n()->t('Do not show a status post for this upload'),
947                         '$albumselect' => $albumselect,
948                         '$permissions' => DI::l10n()->t('Permissions'),
949                         '$aclselect' => $aclselect_e,
950                         '$lockstate' => ACL::getLockstateForUserId($a->getLoggedInUserId()) ? 'lock' : 'unlock',
951                         '$alt_uploader' => $ret['addon_text'],
952                         '$default_upload_box' => ($ret['default_upload'] ? $default_upload_box : ''),
953                         '$default_upload_submit' => ($ret['default_upload'] ? $default_upload_submit : ''),
954                         '$uploadurl' => $ret['post_url'],
955
956                         // ACL permissions box
957                         '$return_path' => DI::args()->getQueryString(),
958                 ]);
959
960                 return $o;
961         }
962
963         // Display a single photo album
964         if ($datatype === 'album') {
965                 // if $datum is not a valid hex, redirect to the default page
966                 if (!Strings::isHex($datum)) {
967                         DI::baseUrl()->redirect('photos/' . $user['nickname']. '/album');
968                 }
969                 $album = hex2bin($datum);
970
971                 if ($can_post && !Photo::exists(['uid' => $owner_uid, 'album' => $album, 'photo-type' => Photo::DEFAULT])) {
972                         $can_post = false;
973                 }
974
975                 $total = 0;
976                 $r = DBA::toArray(DBA::p("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = ? AND `album` = ?
977                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id`",
978                         $owner_uid,
979                         $album
980                 ));
981                 if (DBA::isResult($r)) {
982                         $total = count($r);
983                 }
984
985                 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), 20);
986
987                 /// @TODO I have seen this many times, maybe generalize it script-wide and encapsulate it?
988                 $order_field = $_GET['order'] ?? '';
989                 if ($order_field === 'posted') {
990                         $order = 'ASC';
991                 } else {
992                         $order = 'DESC';
993                 }
994
995                 $r = DBA::toArray(DBA::p("SELECT `resource-id`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`filename`) AS `filename`,
996                         ANY_VALUE(`type`) AS `type`, max(`scale`) AS `scale`, ANY_VALUE(`desc`) as `desc`,
997                         ANY_VALUE(`created`) as `created`
998                         FROM `photo` WHERE `uid` = ? AND `album` = ?
999                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id` ORDER BY `created` $order LIMIT ? , ?",
1000                         intval($owner_uid),
1001                         DBA::escape($album),
1002                         $pager->getStart(),
1003                         $pager->getItemsPerPage()
1004                 ));
1005
1006                 if ($cmd === 'drop') {
1007                         $drop_url = DI::args()->getQueryString();
1008
1009                         return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
1010                                 '$l10n'           => [
1011                                         'message' => DI::l10n()->t('Do you really want to delete this photo album and all its photos?'),
1012                                         'confirm' => DI::l10n()->t('Delete Album'),
1013                                         'cancel'  => DI::l10n()->t('Cancel'),
1014                                 ],
1015                                 '$method'        => 'post',
1016                                 '$confirm_url'   => $drop_url,
1017                                 '$confirm_name'  => 'dropalbum',
1018                                 '$confirm_value' => 'dropalbum',
1019                         ]);
1020                 }
1021
1022                 // edit album name
1023                 if ($cmd === 'edit') {
1024                         if ($can_post) {
1025                                 $edit_tpl = Renderer::getMarkupTemplate('album_edit.tpl');
1026
1027                                 $album_e = $album;
1028
1029                                 $o .= Renderer::replaceMacros($edit_tpl,[
1030                                         '$nametext' => DI::l10n()->t('New album name: '),
1031                                         '$nickname' => $user['nickname'],
1032                                         '$album' => $album_e,
1033                                         '$hexalbum' => bin2hex($album),
1034                                         '$submit' => DI::l10n()->t('Submit'),
1035                                         '$dropsubmit' => DI::l10n()->t('Delete Album')
1036                                 ]);
1037                         }
1038                 } elseif ($can_post) {
1039                         $edit = [DI::l10n()->t('Edit Album'), 'photos/' . $user['nickname'] . '/album/' . bin2hex($album) . '/edit'];
1040                         $drop = [DI::l10n()->t('Drop Album'), 'photos/' . $user['nickname'] . '/album/' . bin2hex($album) . '/drop'];
1041                 }
1042
1043                 if ($order_field === 'posted') {
1044                         $order =  [DI::l10n()->t('Show Newest First'), 'photos/' . $user['nickname'] . '/album/' . bin2hex($album), 'oldest'];
1045                 } else {
1046                         $order = [DI::l10n()->t('Show Oldest First'), 'photos/' . $user['nickname'] . '/album/' . bin2hex($album) . '?order=posted', 'newest'];
1047                 }
1048
1049                 $photos = [];
1050
1051                 if (DBA::isResult($r)) {
1052                         // "Twist" is only used for the duepunto theme with style "slackr"
1053                         $twist = false;
1054                         foreach ($r as $rr) {
1055                                 $twist = !$twist;
1056
1057                                 $ext = $phototypes[$rr['type']];
1058
1059                                 $imgalt_e = $rr['filename'];
1060                                 $desc_e = $rr['desc'];
1061
1062                                 $photos[] = [
1063                                         'id' => $rr['id'],
1064                                         'twist' => ' ' . ($twist ? 'rotleft' : 'rotright') . rand(2,4),
1065                                         'link' => 'photos/' . $user['nickname'] . '/image/' . $rr['resource-id']
1066                                                 . ($order_field === 'posted' ? '?order=posted' : ''),
1067                                         'title' => DI::l10n()->t('View Photo'),
1068                                         'src' => 'photo/' . $rr['resource-id'] . '-' . $rr['scale'] . '.' .$ext,
1069                                         'alt' => $imgalt_e,
1070                                         'desc'=> $desc_e,
1071                                         'ext' => $ext,
1072                                         'hash'=> $rr['resource-id'],
1073                                 ];
1074                         }
1075                 }
1076
1077                 $tpl = Renderer::getMarkupTemplate('photo_album.tpl');
1078                 $o .= Renderer::replaceMacros($tpl, [
1079                         '$photos' => $photos,
1080                         '$album' => $album,
1081                         '$can_post' => $can_post,
1082                         '$upload' => [DI::l10n()->t('Upload New Photos'), 'photos/' . $user['nickname'] . '/upload/' . bin2hex($album)],
1083                         '$order' => $order,
1084                         '$edit' => $edit,
1085                         '$drop' => $drop,
1086                         '$paginate' => $pager->renderFull($total),
1087                 ]);
1088
1089                 return $o;
1090
1091         }
1092
1093         // Display one photo
1094         if ($datatype === 'image') {
1095                 // fetch image, item containing image, then comments
1096                 $ph = Photo::selectToArray([], ["`uid` = ? AND `resource-id` = ? " . $sql_extra, $owner_uid, $datum], ['order' => ['scale' => true]]);
1097
1098                 if (!DBA::isResult($ph)) {
1099                         if (DBA::exists('photo', ['resource-id' => $datum, 'uid' => $owner_uid])) {
1100                                 notice(DI::l10n()->t('Permission denied. Access to this item may be restricted.'));
1101                         } else {
1102                                 notice(DI::l10n()->t('Photo not available'));
1103                         }
1104                         return;
1105                 }
1106
1107                 if ($cmd === 'drop') {
1108                         $drop_url = DI::args()->getQueryString();
1109
1110                         return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
1111                                 '$l10n'           => [
1112                                         'message' => DI::l10n()->t('Do you really want to delete this photo?'),
1113                                         'confirm' => DI::l10n()->t('Delete Photo'),
1114                                         'cancel'  => DI::l10n()->t('Cancel'),
1115                                 ],
1116                                 '$method'        => 'post',
1117                                 '$confirm_url'   => $drop_url,
1118                                 '$confirm_name'  => 'delete',
1119                                 '$confirm_value' => 'delete',
1120                         ]);
1121                 }
1122
1123                 $prevlink = '';
1124                 $nextlink = '';
1125
1126                 /*
1127                  * @todo This query is totally bad, the whole functionality has to be changed
1128                  * The query leads to a really intense used index.
1129                  * By now we hide it if someone wants to.
1130                  */
1131                 if ($cmd === 'view' && !DI::config()->get('system', 'no_count', false)) {
1132                         $order_field = $_GET['order'] ?? '';
1133
1134                         if ($order_field === 'posted') {
1135                                 $order = 'ASC';
1136                         } else {
1137                                 $order = 'DESC';
1138                         }
1139
1140                         $prvnxt = Photo::selectToArray(['resource-id'], ["`album` = ? AND `uid` = ? AND `scale` = ?" . $sql_extra, $ph[0]['album'], $owner_uid, 0]);
1141
1142                         if (DBA::isResult($prvnxt)) {
1143                                 $prv = null;
1144                                 $nxt = null;
1145                                 foreach ($prvnxt as $z => $entry) {
1146                                         if ($entry['resource-id'] == $ph[0]['resource-id']) {
1147                                                 $prv = $z - 1;
1148                                                 $nxt = $z + 1;
1149                                                 if ($prv < 0) {
1150                                                         $prv = count($prvnxt) - 1;
1151                                                 }
1152                                                 if ($nxt >= count($prvnxt)) {
1153                                                         $nxt = 0;
1154                                                 }
1155                                                 break;
1156                                         }
1157                                 }
1158
1159                                 if (!is_null($prv)) {
1160                                         $prevlink = 'photos/' . $user['nickname'] . '/image/' . $prvnxt[$prv]['resource-id'] . ($order_field === 'posted' ? '?order=posted' : '');
1161                                 }
1162                                 if (!is_null($nxt)) {
1163                                         $nextlink = 'photos/' . $user['nickname'] . '/image/' . $prvnxt[$nxt]['resource-id'] . ($order_field === 'posted' ? '?order=posted' : '');
1164                                 }
1165
1166                                 $tpl = Renderer::getMarkupTemplate('photo_edit_head.tpl');
1167                                 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl,[
1168                                         '$prevlink' => $prevlink,
1169                                         '$nextlink' => $nextlink
1170                                 ]);
1171
1172                                 if ($prevlink) {
1173                                         $prevlink = [$prevlink, '<div class="icon prev"></div>'];
1174                                 }
1175
1176                                 if ($nextlink) {
1177                                         $nextlink = [$nextlink, '<div class="icon next"></div>'];
1178                                 }
1179                         }
1180                 }
1181
1182                 if (count($ph) == 1) {
1183                         $hires = $lores = $ph[0];
1184                 }
1185
1186                 if (count($ph) > 1) {
1187                         if ($ph[1]['scale'] == 2) {
1188                                 // original is 640 or less, we can display it directly
1189                                 $hires = $lores = $ph[0];
1190                         } else {
1191                                 $hires = $ph[0];
1192                                 $lores = $ph[1];
1193                         }
1194                 }
1195
1196                 $album_link = 'photos/' . $user['nickname'] . '/album/' . bin2hex($ph[0]['album']);
1197
1198                 $tools = null;
1199
1200                 if ($can_post && ($ph[0]['uid'] == $owner_uid)) {
1201                         $tools = [];
1202                         if ($cmd === 'edit') {
1203                                 $tools['view'] = ['photos/' . $user['nickname'] . '/image/' . $datum, DI::l10n()->t('View photo')];
1204                         } else {
1205                                 $tools['edit'] = ['photos/' . $user['nickname'] . '/image/' . $datum . '/edit', DI::l10n()->t('Edit photo')];
1206                                 $tools['delete'] = ['photos/' . $user['nickname'] . '/image/' . $datum . '/drop', DI::l10n()->t('Delete photo')];
1207                                 $tools['profile'] = ['settings/profile/photo/crop/' . $ph[0]['resource-id'], DI::l10n()->t('Use as profile photo')];
1208                         }
1209
1210                         if (
1211                                 $ph[0]['uid'] == local_user()
1212                                 && (strlen($ph[0]['allow_cid']) || strlen($ph[0]['allow_gid']) || strlen($ph[0]['deny_cid']) || strlen($ph[0]['deny_gid']))
1213                         ) {
1214                                 $tools['lock'] = DI::l10n()->t('Private Photo');
1215                         }
1216                 }
1217
1218                 $photo = [
1219                         'href' => 'photo/' . $hires['resource-id'] . '-' . $hires['scale'] . '.' . $phototypes[$hires['type']],
1220                         'title'=> DI::l10n()->t('View Full Size'),
1221                         'src'  => 'photo/' . $lores['resource-id'] . '-' . $lores['scale'] . '.' . $phototypes[$lores['type']] . '?_u=' . DateTimeFormat::utcNow('ymdhis'),
1222                         'height' => $hires['height'],
1223                         'width' => $hires['width'],
1224                         'album' => $hires['album'],
1225                         'filename' => $hires['filename'],
1226                 ];
1227
1228                 $map = null;
1229                 $link_item = [];
1230                 $total = 0;
1231
1232                 // Do we have an item for this photo?
1233
1234                 // FIXME! - replace following code to display the conversation with our normal
1235                 // conversation functions so that it works correctly and tracks changes
1236                 // in the evolving conversation code.
1237                 // The difference is that we won't be displaying the conversation head item
1238                 // as a "post" but displaying instead the photo it is linked to
1239
1240                 $link_item = Post::selectFirst([], ["`resource-id` = ?" . $sql_extra, $datum]);
1241
1242                 if (!empty($link_item['parent']) && !empty($link_item['uid'])) {
1243                         $condition = ["`parent` = ? AND `gravity` = ?",  $link_item['parent'], GRAVITY_COMMENT];
1244                         $total = Post::count($condition);
1245
1246                         $pager = new Pager(DI::l10n(), DI::args()->getQueryString());
1247
1248                         $params = ['order' => ['id'], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1249                         $items = Post::toArray(Post::selectForUser($link_item['uid'], Item::ITEM_FIELDLIST, $condition, $params));
1250
1251                         if (local_user() == $link_item['uid']) {
1252                                 Item::update(['unseen' => false], ['parent' => $link_item['parent']]);
1253                         }
1254                 }
1255
1256                 if (!empty($link_item['coord'])) {
1257                         $map = Map::byCoordinates($link_item['coord']);
1258                 }
1259
1260                 $tags = null;
1261
1262                 if (!empty($link_item['id'])) {
1263                         $tag_text = Tag::getCSVByURIId($link_item['uri-id']);
1264                         $arr = explode(',', $tag_text);
1265                         // parse tags and add links
1266                         $tag_arr = [];
1267                         foreach ($arr as $tag) {
1268                                 $tag_arr[] = [
1269                                         'name' => BBCode::convert($tag),
1270                                         'removeurl' => '/tagrm/' . $link_item['id'] . '/' . bin2hex($tag)
1271                                 ];
1272                         }
1273                         $tags = ['title' => DI::l10n()->t('Tags: '), 'tags' => $tag_arr];
1274                         if ($cmd === 'edit') {
1275                                 $tags['removeanyurl'] = 'tagrm/' . $link_item['id'];
1276                                 $tags['removetitle'] = DI::l10n()->t('[Select tags to remove]');
1277                         }
1278                 }
1279
1280
1281                 $edit = Null;
1282                 if ($cmd === 'edit' && $can_post) {
1283                         $edit_tpl = Renderer::getMarkupTemplate('photo_edit.tpl');
1284
1285                         $album_e = $ph[0]['album'];
1286                         $caption_e = $ph[0]['desc'];
1287                         $aclselect_e = ACL::getFullSelectorHTML(DI::page(), $a->getLoggedInUserId(), false, ACL::getDefaultUserPermissions($ph[0]));
1288
1289                         $edit = Renderer::replaceMacros($edit_tpl, [
1290                                 '$id' => $ph[0]['id'],
1291                                 '$album' => ['albname', DI::l10n()->t('New album name'), $album_e,''],
1292                                 '$caption' => ['desc', DI::l10n()->t('Caption'), $caption_e, ''],
1293                                 '$tags' => ['newtag', DI::l10n()->t('Add a Tag'), "", DI::l10n()->t('Example: @bob, @Barbara_Jensen, @jim@example.com, #California, #camping')],
1294                                 '$rotate_none' => ['rotate', DI::l10n()->t('Do not rotate'),0,'', true],
1295                                 '$rotate_cw' => ['rotate', DI::l10n()->t("Rotate CW \x28right\x29"),1,''],
1296                                 '$rotate_ccw' => ['rotate', DI::l10n()->t("Rotate CCW \x28left\x29"),2,''],
1297
1298                                 '$nickname' => $user['nickname'],
1299                                 '$resource_id' => $ph[0]['resource-id'],
1300                                 '$permissions' => DI::l10n()->t('Permissions'),
1301                                 '$aclselect' => $aclselect_e,
1302
1303                                 '$item_id' => $link_item['id'] ?? 0,
1304                                 '$submit' => DI::l10n()->t('Submit'),
1305                                 '$delete' => DI::l10n()->t('Delete Photo'),
1306
1307                                 // ACL permissions box
1308                                 '$return_path' => DI::args()->getQueryString(),
1309                         ]);
1310                 }
1311
1312                 $like = '';
1313                 $dislike = '';
1314                 $likebuttons = '';
1315                 $comments = '';
1316                 $paginate = '';
1317
1318                 if (!empty($link_item['id']) && !empty($link_item['uri'])) {
1319                         $cmnt_tpl = Renderer::getMarkupTemplate('comment_item.tpl');
1320                         $tpl = Renderer::getMarkupTemplate('photo_item.tpl');
1321                         $return_path = DI::args()->getCommand();
1322
1323                         if (!DBA::isResult($items)) {
1324                                 if (($can_post || Security::canWriteToUserWall($owner_uid))) {
1325                                         /*
1326                                          * Hmmm, code depending on the presence of a particular addon?
1327                                          * This should be better if done by a hook
1328                                          */
1329                                         $qcomment = null;
1330                                         if (Addon::isEnabled('qcomment')) {
1331                                                 $words = DI::pConfig()->get(local_user(), 'qcomment', 'words');
1332                                                 $qcomment = $words ? explode("\n", $words) : [];
1333                                         }
1334
1335                                         $comments .= Renderer::replaceMacros($cmnt_tpl, [
1336                                                 '$return_path' => '',
1337                                                 '$jsreload' => $return_path,
1338                                                 '$id' => $link_item['id'],
1339                                                 '$parent' => $link_item['id'],
1340                                                 '$profile_uid' =>  $owner_uid,
1341                                                 '$mylink' => $contact['url'],
1342                                                 '$mytitle' => DI::l10n()->t('This is you'),
1343                                                 '$myphoto' => $contact['thumb'],
1344                                                 '$comment' => DI::l10n()->t('Comment'),
1345                                                 '$submit' => DI::l10n()->t('Submit'),
1346                                                 '$preview' => DI::l10n()->t('Preview'),
1347                                                 '$loading' => DI::l10n()->t('Loading...'),
1348                                                 '$qcomment' => $qcomment,
1349                                                 '$rand_num' => Crypto::randomDigits(12)
1350                                         ]);
1351                                 }
1352                         }
1353
1354                         $conv_responses = [
1355                                 'like'        => [],
1356                                 'dislike'     => [],
1357                                 'attendyes'   => [],
1358                                 'attendno'    => [],
1359                                 'attendmaybe' => []
1360                         ];
1361
1362                         if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
1363                                 unset($conv_responses['dislike']);
1364                         }
1365
1366                         // display comments
1367                         if (DBA::isResult($items)) {
1368                                 foreach ($items as $item) {
1369                                         DI::conversation()->builtinActivityPuller($item, $conv_responses);
1370                                 }
1371
1372                                 if (!empty($conv_responses['like'][$link_item['uri']])) {
1373                                         $like = DI::conversation()->formatActivity($conv_responses['like'][$link_item['uri']]['links'], 'like', $link_item['id']);
1374                                 }
1375
1376                                 if (!empty($conv_responses['dislike'][$link_item['uri']])) {
1377                                         $dislike = DI::conversation()->formatActivity($conv_responses['dislike'][$link_item['uri']]['links'], 'dislike', $link_item['id']);
1378                                 }
1379
1380                                 if (($can_post || Security::canWriteToUserWall($owner_uid))) {
1381                                         /*
1382                                          * Hmmm, code depending on the presence of a particular addon?
1383                                          * This should be better if done by a hook
1384                                          */
1385                                         $qcomment = null;
1386                                         if (Addon::isEnabled('qcomment')) {
1387                                                 $words = DI::pConfig()->get(local_user(), 'qcomment', 'words');
1388                                                 $qcomment = $words ? explode("\n", $words) : [];
1389                                         }
1390
1391                                         $comments .= Renderer::replaceMacros($cmnt_tpl,[
1392                                                 '$return_path' => '',
1393                                                 '$jsreload' => $return_path,
1394                                                 '$id' => $link_item['id'],
1395                                                 '$parent' => $link_item['id'],
1396                                                 '$profile_uid' =>  $owner_uid,
1397                                                 '$mylink' => $contact['url'],
1398                                                 '$mytitle' => DI::l10n()->t('This is you'),
1399                                                 '$myphoto' => $contact['thumb'],
1400                                                 '$comment' => DI::l10n()->t('Comment'),
1401                                                 '$submit' => DI::l10n()->t('Submit'),
1402                                                 '$preview' => DI::l10n()->t('Preview'),
1403                                                 '$qcomment' => $qcomment,
1404                                                 '$rand_num' => Crypto::randomDigits(12)
1405                                         ]);
1406                                 }
1407
1408                                 foreach ($items as $item) {
1409                                         $comment = '';
1410                                         $template = $tpl;
1411
1412                                         $activity = DI::activity();
1413
1414                                         if (($activity->match($item['verb'], Activity::LIKE) ||
1415                                              $activity->match($item['verb'], Activity::DISLIKE)) &&
1416                                             ($item['gravity'] != GRAVITY_PARENT)) {
1417                                                 continue;
1418                                         }
1419
1420                                         $author = ['uid' => 0, 'id' => $item['author-id'],
1421                                                 'network' => $item['author-network'], 'url' => $item['author-link']];
1422                                         $profile_url = Contact::magicLinkByContact($author);
1423                                         if (strpos($profile_url, 'redir/') === 0) {
1424                                                 $sparkle = ' sparkle';
1425                                         } else {
1426                                                 $sparkle = '';
1427                                         }
1428
1429                                         $dropping = (($item['contact-id'] == $contact_id) || ($item['uid'] == local_user()));
1430                                         $drop = [
1431                                                 'dropping' => $dropping,
1432                                                 'pagedrop' => false,
1433                                                 'select' => DI::l10n()->t('Select'),
1434                                                 'delete' => DI::l10n()->t('Delete'),
1435                                         ];
1436
1437                                         $title_e = $item['title'];
1438                                         $body_e = BBCode::convert($item['body']);
1439
1440                                         $comments .= Renderer::replaceMacros($template,[
1441                                                 '$id' => $item['id'],
1442                                                 '$profile_url' => $profile_url,
1443                                                 '$name' => $item['author-name'],
1444                                                 '$thumb' => $item['author-avatar'],
1445                                                 '$sparkle' => $sparkle,
1446                                                 '$title' => $title_e,
1447                                                 '$body' => $body_e,
1448                                                 '$ago' => Temporal::getRelativeDate($item['created']),
1449                                                 '$indent' => (($item['parent'] != $item['id']) ? ' comment' : ''),
1450                                                 '$drop' => $drop,
1451                                                 '$comment' => $comment
1452                                         ]);
1453
1454                                         if (($can_post || Security::canWriteToUserWall($owner_uid))) {
1455                                                 /*
1456                                                  * Hmmm, code depending on the presence of a particular addon?
1457                                                  * This should be better if done by a hook
1458                                                  */
1459                                                 $qcomment = null;
1460                                                 if (Addon::isEnabled('qcomment')) {
1461                                                         $words = DI::pConfig()->get(local_user(), 'qcomment', 'words');
1462                                                         $qcomment = $words ? explode("\n", $words) : [];
1463                                                 }
1464
1465                                                 $comments .= Renderer::replaceMacros($cmnt_tpl, [
1466                                                         '$return_path' => '',
1467                                                         '$jsreload' => $return_path,
1468                                                         '$id' => $item['id'],
1469                                                         '$parent' => $item['parent'],
1470                                                         '$profile_uid' =>  $owner_uid,
1471                                                         '$mylink' => $contact['url'],
1472                                                         '$mytitle' => DI::l10n()->t('This is you'),
1473                                                         '$myphoto' => $contact['thumb'],
1474                                                         '$comment' => DI::l10n()->t('Comment'),
1475                                                         '$submit' => DI::l10n()->t('Submit'),
1476                                                         '$preview' => DI::l10n()->t('Preview'),
1477                                                         '$qcomment' => $qcomment,
1478                                                         '$rand_num' => Crypto::randomDigits(12)
1479                                                 ]);
1480                                         }
1481                                 }
1482                         }
1483
1484                         $responses = [];
1485                         foreach ($conv_responses as $verb => $activity) {
1486                                 if (isset($activity[$link_item['uri']])) {
1487                                         $responses[$verb] = $activity[$link_item['uri']];
1488                                 }
1489                         }
1490
1491                         if ($cmd === 'view' && ($can_post || Security::canWriteToUserWall($owner_uid))) {
1492                                 $like_tpl = Renderer::getMarkupTemplate('like_noshare.tpl');
1493                                 $likebuttons = Renderer::replaceMacros($like_tpl, [
1494                                         '$id' => $link_item['id'],
1495                                         '$like' => DI::l10n()->t('Like'),
1496                                         '$like_title' => DI::l10n()->t('I like this (toggle)'),
1497                                         '$dislike' => DI::l10n()->t('Dislike'),
1498                                         '$wait' => DI::l10n()->t('Please wait'),
1499                                         '$dislike_title' => DI::l10n()->t('I don\'t like this (toggle)'),
1500                                         '$hide_dislike' => DI::pConfig()->get(local_user(), 'system', 'hide_dislike'),
1501                                         '$responses' => $responses,
1502                                         '$return_path' => DI::args()->getQueryString(),
1503                                 ]);
1504                         }
1505
1506                         $paginate = $pager->renderFull($total);
1507                 }
1508
1509                 $photo_tpl = Renderer::getMarkupTemplate('photo_view.tpl');
1510                 $o .= Renderer::replaceMacros($photo_tpl, [
1511                         '$id' => $ph[0]['id'],
1512                         '$album' => [$album_link, $ph[0]['album']],
1513                         '$tools' => $tools,
1514                         '$photo' => $photo,
1515                         '$prevlink' => $prevlink,
1516                         '$nextlink' => $nextlink,
1517                         '$desc' => $ph[0]['desc'],
1518                         '$tags' => $tags,
1519                         '$edit' => $edit,
1520                         '$map' => $map,
1521                         '$map_text' => DI::l10n()->t('Map'),
1522                         '$likebuttons' => $likebuttons,
1523                         '$like' => $like,
1524                         '$dislike' => $dislike,
1525                         '$comments' => $comments,
1526                         '$paginate' => $paginate,
1527                 ]);
1528
1529                 DI::page()['htmlhead'] .= "\n" . '<meta name="twitter:card" content="summary_large_image" />' . "\n";
1530                 DI::page()['htmlhead'] .= '<meta name="twitter:title" content="' . $photo["album"] . '" />' . "\n";
1531                 DI::page()['htmlhead'] .= '<meta name="twitter:image" content="' . DI::baseUrl() . "/" . $photo["href"] . '" />' . "\n";
1532                 DI::page()['htmlhead'] .= '<meta name="twitter:image:width" content="' . $photo["width"] . '" />' . "\n";
1533                 DI::page()['htmlhead'] .= '<meta name="twitter:image:height" content="' . $photo["height"] . '" />' . "\n";
1534
1535                 return $o;
1536         }
1537
1538         // Default - show recent photos with upload link (if applicable)
1539         //$o = '';
1540         $total = 0;
1541         $r = DBA::toArray(DBA::p("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = ? AND `photo-type` = ?
1542                 $sql_extra GROUP BY `resource-id`",
1543                 $user['uid'],
1544                 Photo::DEFAULT,
1545         ));
1546         if (DBA::isResult($r)) {
1547                 $total = count($r);
1548         }
1549
1550         $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), 20);
1551
1552         $r = DBA::toArray(DBA::p("SELECT `resource-id`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`filename`) AS `filename`,
1553                 ANY_VALUE(`type`) AS `type`, ANY_VALUE(`album`) AS `album`, max(`scale`) AS `scale`,
1554                 ANY_VALUE(`created`) AS `created` FROM `photo`
1555                 WHERE `uid` = ? AND `photo-type` = ?
1556                 $sql_extra GROUP BY `resource-id` ORDER BY `created` DESC LIMIT ? , ?",
1557                 $user['uid'],
1558                 Photo::DEFAULT,
1559                 $pager->getStart(),
1560                 $pager->getItemsPerPage()
1561         ));
1562
1563         $photos = [];
1564         if (DBA::isResult($r)) {
1565                 // "Twist" is only used for the duepunto theme with style "slackr"
1566                 $twist = false;
1567                 foreach ($r as $rr) {
1568                         $twist = !$twist;
1569                         $ext = $phototypes[$rr['type']];
1570
1571                         $alt_e = $rr['filename'];
1572                         $name_e = $rr['album'];
1573
1574                         $photos[] = [
1575                                 'id'    => $rr['id'],
1576                                 'twist' => ' ' . ($twist ? 'rotleft' : 'rotright') . rand(2,4),
1577                                 'link'  => 'photos/' . $user['nickname'] . '/image/' . $rr['resource-id'],
1578                                 'title' => DI::l10n()->t('View Photo'),
1579                                 'src'   => 'photo/' . $rr['resource-id'] . '-' . ((($rr['scale']) == 6) ? 4 : $rr['scale']) . '.' . $ext,
1580                                 'alt'   => $alt_e,
1581                                 'album' => [
1582                                         'link' => 'photos/' . $user['nickname'] . '/album/' . bin2hex($rr['album']),
1583                                         'name' => $name_e,
1584                                         'alt'  => DI::l10n()->t('View Album'),
1585                                 ],
1586
1587                         ];
1588                 }
1589         }
1590
1591         $tpl = Renderer::getMarkupTemplate('photos_recent.tpl');
1592         $o .= Renderer::replaceMacros($tpl, [
1593                 '$title' => DI::l10n()->t('Recent Photos'),
1594                 '$can_post' => $can_post,
1595                 '$upload' => [DI::l10n()->t('Upload New Photos'), 'photos/' . $user['nickname'] . '/upload'],
1596                 '$photos' => $photos,
1597                 '$paginate' => $pager->renderFull($total),
1598         ]);
1599
1600         return $o;
1601 }