]> git.mxchange.org Git - friendica.git/blob - mod/photos.php
Don't make photo item visible
[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 (empty($owner) || $owner['account_removed']) {
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                 }
359
360                 if (DBA::isResult($photos) && !$item_id) {
361                         // Create item container
362                         $title = '';
363                         $uri = Item::newURI($page_owner_uid);
364
365                         $arr = [];
366                         $arr['guid']          = System::createUUID();
367                         $arr['uid']           = $page_owner_uid;
368                         $arr['uri']           = $uri;
369                         $arr['post-type']     = Item::PT_IMAGE;
370                         $arr['wall']          = 1;
371                         $arr['resource-id']   = $photo['resource-id'];
372                         $arr['contact-id']    = $owner_record['id'];
373                         $arr['owner-name']    = $owner_record['name'];
374                         $arr['owner-link']    = $owner_record['url'];
375                         $arr['owner-avatar']  = $owner_record['thumb'];
376                         $arr['author-name']   = $owner_record['name'];
377                         $arr['author-link']   = $owner_record['url'];
378                         $arr['author-avatar'] = $owner_record['thumb'];
379                         $arr['title']         = $title;
380                         $arr['allow_cid']     = $photo['allow_cid'];
381                         $arr['allow_gid']     = $photo['allow_gid'];
382                         $arr['deny_cid']      = $photo['deny_cid'];
383                         $arr['deny_gid']      = $photo['deny_gid'];
384                         $arr['visible']       = 0;
385                         $arr['origin']        = 1;
386
387                         $arr['body']          = '[url=' . DI::baseUrl() . '/photos/' . $user['nickname'] . '/image/' . $photo['resource-id'] . ']'
388                                                 . '[img]' . DI::baseUrl() . '/photo/' . $photo['resource-id'] . '-' . $photo['scale'] . '.'. $ext . '[/img]'
389                                                 . '[/url]';
390
391                         $item_id = Item::insert($arr);
392                 }
393
394                 if ($item_id) {
395                         $item = Post::selectFirst(['inform', 'uri-id'], ['id' => $item_id, 'uid' => $page_owner_uid]);
396
397                         if (DBA::isResult($item)) {
398                                 $old_inform = $item['inform'];
399                         }
400                 }
401
402                 if (strlen($rawtags)) {
403                         $inform   = '';
404
405                         // if the new tag doesn't have a namespace specifier (@foo or #foo) give it a hashtag
406                         $x = substr($rawtags, 0, 1);
407                         if ($x !== '@' && $x !== '#') {
408                                 $rawtags = '#' . $rawtags;
409                         }
410
411                         $taginfo = [];
412                         $tags = BBCode::getTags($rawtags);
413
414                         if (count($tags)) {
415                                 foreach ($tags as $tag) {
416                                         if (strpos($tag, '@') === 0) {
417                                                 $profile = '';
418                                                 $contact = null;
419                                                 $name = substr($tag,1);
420
421                                                 if ((strpos($name, '@')) || (strpos($name, 'http://'))) {
422                                                         $newname = $name;
423                                                         $links = @Probe::lrdd($name);
424
425                                                         if (count($links)) {
426                                                                 foreach ($links as $link) {
427                                                                         if ($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page') {
428                                                                                 $profile = $link['@attributes']['href'];
429                                                                         }
430
431                                                                         if ($link['@attributes']['rel'] === 'salmon') {
432                                                                                 $salmon = '$url:' . str_replace(',', '%sc', $link['@attributes']['href']);
433
434                                                                                 if (strlen($inform)) {
435                                                                                         $inform .= ',';
436                                                                                 }
437
438                                                                                 $inform .= $salmon;
439                                                                         }
440                                                                 }
441                                                         }
442
443                                                         $taginfo[] = [$newname, $profile, $salmon];
444                                                 } else {
445                                                         $newname = $name;
446                                                         $tagcid = 0;
447
448                                                         if (strrpos($newname, '+')) {
449                                                                 $tagcid = intval(substr($newname, strrpos($newname, '+') + 1));
450                                                         }
451
452                                                         if ($tagcid) {
453                                                                 $contact = DBA::selectFirst('contact', [], ['id' => $tagcid, 'uid' => $page_owner_uid]);
454                                                         } else {
455                                                                 $newname = str_replace('_',' ',$name);
456
457                                                                 //select someone from this user's contacts by name
458                                                                 $contact = DBA::selectFirst('contact', [], ['name' => $newname, 'uid' => $page_owner_uid]);
459                                                                 if (!DBA::isResult($contact)) {
460                                                                         //select someone by attag or nick and the name passed in
461                                                                         $contact = DBA::selectFirst('contact', [],
462                                                                                 ['(`attag` = ? OR `nick` = ?) AND `uid` = ?', $name, $name, $page_owner_uid],
463                                                                                 ['order' => ['attag' => true]]
464                                                                         );
465                                                                 }
466                                                         }
467
468                                                         if (DBA::isResult($contact)) {
469                                                                 $newname = $contact['name'];
470                                                                 $profile = $contact['url'];
471
472                                                                 $notify = 'cid:' . $contact['id'];
473                                                                 if (strlen($inform)) {
474                                                                         $inform .= ',';
475                                                                 }
476                                                                 $inform .= $notify;
477                                                         }
478                                                 }
479
480                                                 if ($profile) {
481                                                         if (!empty($contact)) {
482                                                                 $taginfo[] = [$newname, $profile, $notify, $contact];
483                                                         } else {
484                                                                 $taginfo[] = [$newname, $profile, $notify, null];
485                                                         }
486
487                                                         $profile = str_replace(',', '%2c', $profile);
488
489                                                         if (!empty($item['uri-id'])) {
490                                                                 Tag::store($item['uri-id'], Tag::MENTION, $newname, $profile);
491                                                         }
492                                                 }
493                                         } elseif (strpos($tag, '#') === 0) {
494                                                 $tagname = substr($tag, 1);
495                                                 if (!empty($item['uri-id'])) {
496                                                         Tag::store($item['uri-id'], Tag::HASHTAG, $tagname);
497                                                 }
498                                         }
499                                 }
500                         }
501
502                         $newinform = $old_inform ?? '';
503                         if (strlen($newinform) && strlen($inform)) {
504                                 $newinform .= ',';
505                         }
506                         $newinform .= $inform;
507
508                         $fields = ['inform' => $newinform, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
509                         $condition = ['id' => $item_id];
510                         Item::update($fields, $condition);
511
512                         $best = 0;
513                         foreach ($photos as $scales) {
514                                 if (intval($scales['scale']) == 2) {
515                                         $best = 2;
516                                         break;
517                                 }
518
519                                 if (intval($scales['scale']) == 4) {
520                                         $best = 4;
521                                         break;
522                                 }
523                         }
524
525                         if (count($taginfo)) {
526                                 foreach ($taginfo as $tagged) {
527                                         $uri = Item::newURI($page_owner_uid);
528
529                                         $arr = [];
530                                         $arr['guid']          = System::createUUID();
531                                         $arr['uid']           = $page_owner_uid;
532                                         $arr['uri']           = $uri;
533                                         $arr['wall']          = 1;
534                                         $arr['contact-id']    = $owner_record['id'];
535                                         $arr['owner-name']    = $owner_record['name'];
536                                         $arr['owner-link']    = $owner_record['url'];
537                                         $arr['owner-avatar']  = $owner_record['thumb'];
538                                         $arr['author-name']   = $owner_record['name'];
539                                         $arr['author-link']   = $owner_record['url'];
540                                         $arr['author-avatar'] = $owner_record['thumb'];
541                                         $arr['title']         = '';
542                                         $arr['allow_cid']     = $photo['allow_cid'];
543                                         $arr['allow_gid']     = $photo['allow_gid'];
544                                         $arr['deny_cid']      = $photo['deny_cid'];
545                                         $arr['deny_gid']      = $photo['deny_gid'];
546                                         $arr['visible']       = 0;
547                                         $arr['verb']          = Activity::TAG;
548                                         $arr['gravity']       = GRAVITY_PARENT;
549                                         $arr['object-type']   = Activity\ObjectType::PERSON;
550                                         $arr['target-type']   = Activity\ObjectType::IMAGE;
551                                         $arr['inform']        = $tagged[2];
552                                         $arr['origin']        = 1;
553                                         $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]') ;
554                                         $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" ;
555
556                                         $arr['object'] = '<object><type>' . Activity\ObjectType::PERSON . '</type><title>' . $tagged[0] . '</title><id>' . $tagged[1] . '/' . $tagged[0] . '</id>';
557                                         $arr['object'] .= '<link>' . XML::escape('<link rel="alternate" type="text/html" href="' . $tagged[1] . '" />' . "\n");
558                                         if ($tagged[3]) {
559                                                 $arr['object'] .= XML::escape('<link rel="photo" type="' . $photo['type'] . '" href="' . $tagged[3]['photo'] . '" />' . "\n");
560                                         }
561                                         $arr['object'] .= '</link></object>' . "\n";
562
563                                         $arr['target'] = '<target><type>' . Activity\ObjectType::IMAGE . '</type><title>' . $photo['desc'] . '</title><id>'
564                                                 . DI::baseUrl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo['resource-id'] . '</id>';
565                                         $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>';
566
567                                         Item::insert($arr);
568                                 }
569                         }
570                 }
571                 DI::baseUrl()->redirect($_SESSION['photo_return']);
572                 return; // NOTREACHED
573         }
574
575
576         // default post action - upload a photo
577         Hook::callAll('photo_post_init', $_POST);
578
579         // Determine the album to use
580         $album    = trim($_REQUEST['album'] ?? '');
581         $newalbum = trim($_REQUEST['newalbum'] ?? '');
582
583         Logger::info('album= ' . $album . ' newalbum= ' . $newalbum);
584
585         if (!strlen($album)) {
586                 if (strlen($newalbum)) {
587                         $album = $newalbum;
588                 } else {
589                         $album = DateTimeFormat::localNow('Y');
590                 }
591         }
592
593         $ret = ['src' => '', 'filename' => '', 'filesize' => 0, 'type' => ''];
594
595         Hook::callAll('photo_post_file', $ret);
596
597         if (!empty($ret['src']) && !empty($ret['filesize'])) {
598                 $src      = $ret['src'];
599                 $filename = $ret['filename'];
600                 $filesize = $ret['filesize'];
601                 $type     = $ret['type'];
602                 $error    = UPLOAD_ERR_OK;
603         } elseif (!empty($_FILES['userfile'])) {
604                 $src      = $_FILES['userfile']['tmp_name'];
605                 $filename = basename($_FILES['userfile']['name']);
606                 $filesize = intval($_FILES['userfile']['size']);
607                 $type     = $_FILES['userfile']['type'];
608                 $error    = $_FILES['userfile']['error'];
609         } else {
610                 $error    = UPLOAD_ERR_NO_FILE;
611         }
612
613         if ($error !== UPLOAD_ERR_OK) {
614                 switch ($error) {
615                         case UPLOAD_ERR_INI_SIZE:
616                                 notice(DI::l10n()->t('Image exceeds size limit of %s', ini_get('upload_max_filesize')));
617                                 break;
618                         case UPLOAD_ERR_FORM_SIZE:
619                                 notice(DI::l10n()->t('Image exceeds size limit of %s', Strings::formatBytes($_REQUEST['MAX_FILE_SIZE'] ?? 0)));
620                                 break;
621                         case UPLOAD_ERR_PARTIAL:
622                                 notice(DI::l10n()->t('Image upload didn\'t complete, please try again'));
623                                 break;
624                         case UPLOAD_ERR_NO_FILE:
625                                 notice(DI::l10n()->t('Image file is missing'));
626                                 break;
627                         case UPLOAD_ERR_NO_TMP_DIR:
628                         case UPLOAD_ERR_CANT_WRITE:
629                         case UPLOAD_ERR_EXTENSION:
630                                 notice(DI::l10n()->t('Server can\'t accept new file upload at this time, please contact your administrator'));
631                                 break;
632                 }
633                 @unlink($src);
634                 $foo = 0;
635                 Hook::callAll('photo_post_end', $foo);
636                 return;
637         }
638
639         $type = Images::getMimeTypeBySource($src, $filename, $type);
640
641         Logger::info('photos: upload: received file: ' . $filename . ' as ' . $src . ' ('. $type . ') ' . $filesize . ' bytes');
642
643         $maximagesize = DI::config()->get('system', 'maximagesize');
644
645         if ($maximagesize && ($filesize > $maximagesize)) {
646                 notice(DI::l10n()->t('Image exceeds size limit of %s', Strings::formatBytes($maximagesize)));
647                 @unlink($src);
648                 $foo = 0;
649                 Hook::callAll('photo_post_end', $foo);
650                 return;
651         }
652
653         if (!$filesize) {
654                 notice(DI::l10n()->t('Image file is empty.'));
655                 @unlink($src);
656                 $foo = 0;
657                 Hook::callAll('photo_post_end', $foo);
658                 return;
659         }
660
661         Logger::info('loading the contents of ' . $src);
662
663         $imagedata = @file_get_contents($src);
664
665         $image = new Image($imagedata, $type);
666
667         if (!$image->isValid()) {
668                 Logger::info('unable to process image');
669                 notice(DI::l10n()->t('Unable to process image.'));
670                 @unlink($src);
671                 $foo = 0;
672                 Hook::callAll('photo_post_end',$foo);
673                 return;
674         }
675
676         $exif = $image->orient($src);
677         @unlink($src);
678
679         $max_length = DI::config()->get('system', 'max_image_length');
680         if ($max_length > 0) {
681                 $image->scaleDown($max_length);
682         }
683
684         $width  = $image->getWidth();
685         $height = $image->getHeight();
686
687         $smallest = 0;
688
689         $resource_id = Photo::newResource();
690
691         $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);
692
693         if (!$r) {
694                 Logger::info('image store failed');
695                 notice(DI::l10n()->t('Image upload failed.'));
696                 return;
697         }
698
699         if ($width > 640 || $height > 640) {
700                 $image->scaleDown(640);
701                 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);
702                 $smallest = 1;
703         }
704
705         if ($width > 320 || $height > 320) {
706                 $image->scaleDown(320);
707                 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);
708                 $smallest = 2;
709         }
710
711         $uri = Item::newURI($page_owner_uid);
712
713         // Create item container
714         $lat = $lon = null;
715         if (!empty($exif['GPS']) && Feature::isEnabled($page_owner_uid, 'photo_location')) {
716                 $lat = Photo::getGps($exif['GPS']['GPSLatitude'], $exif['GPS']['GPSLatitudeRef']);
717                 $lon = Photo::getGps($exif['GPS']['GPSLongitude'], $exif['GPS']['GPSLongitudeRef']);
718         }
719
720         $arr = [];
721         if ($lat && $lon) {
722                 $arr['coord'] = $lat . ' ' . $lon;
723         }
724
725         $arr['guid']          = System::createUUID();
726         $arr['uid']           = $page_owner_uid;
727         $arr['uri']           = $uri;
728         $arr['post-type']     = Item::PT_IMAGE;
729         $arr['wall']          = 1;
730         $arr['resource-id']   = $resource_id;
731         $arr['contact-id']    = $owner_record['id'];
732         $arr['owner-name']    = $owner_record['name'];
733         $arr['owner-link']    = $owner_record['url'];
734         $arr['owner-avatar']  = $owner_record['thumb'];
735         $arr['author-name']   = $owner_record['name'];
736         $arr['author-link']   = $owner_record['url'];
737         $arr['author-avatar'] = $owner_record['thumb'];
738         $arr['title']         = '';
739         $arr['allow_cid']     = $str_contact_allow;
740         $arr['allow_gid']     = $str_group_allow;
741         $arr['deny_cid']      = $str_contact_deny;
742         $arr['deny_gid']      = $str_group_deny;
743         $arr['visible']       = 0;
744         $arr['origin']        = 1;
745
746         $arr['body']          = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nickname'] . '/image/' . $resource_id . ']'
747                                 . '[img]' . DI::baseUrl() . "/photo/{$resource_id}-{$smallest}.".$image->getExt() . '[/img]'
748                                 . '[/url]';
749
750         $item_id = Item::insert($arr);
751         // Update the photo albums cache
752         Photo::clearAlbumCache($page_owner_uid);
753
754         Hook::callAll('photo_post_end', $item_id);
755
756         // addon uploaders should call "exit()" within the photo_post_end hook
757         // if they do not wish to be redirected
758
759         DI::baseUrl()->redirect($_SESSION['photo_return']);
760         // NOTREACHED
761 }
762
763 function photos_content(App $a)
764 {
765         // URLs:
766         // photos/name
767         // photos/name/upload
768         // photos/name/upload/xxxxx (xxxxx is album name)
769         // photos/name/album/xxxxx
770         // photos/name/album/xxxxx/edit
771         // photos/name/album/xxxxx/drop
772         // photos/name/image/xxxxx
773         // photos/name/image/xxxxx/edit
774         // photos/name/image/xxxxx/drop
775
776         $user = User::getByNickname(DI::args()->getArgv()[1]);
777         if (!DBA::isResult($user)) {
778                 throw new HTTPException\NotFoundException(DI::l10n()->t('User not found.'));
779         }
780
781         if (DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) {
782                 notice(DI::l10n()->t('Public access denied.'));
783                 return;
784         }
785
786         if (empty($user)) {
787                 notice(DI::l10n()->t('No photos selected'));
788                 return;
789         }
790
791         $profile = Profile::getByUID($user['uid']);
792
793         $phototypes = Images::supportedTypes();
794
795         $_SESSION['photo_return'] = DI::args()->getCommand();
796
797         // Parse arguments
798         $datum = null;
799         if (DI::args()->getArgc() > 3) {
800                 $datatype = DI::args()->getArgv()[2];
801                 $datum = DI::args()->getArgv()[3];
802         } elseif ((DI::args()->getArgc() > 2) && (DI::args()->getArgv()[2] === 'upload')) {
803                 $datatype = 'upload';
804         } else {
805                 $datatype = 'summary';
806         }
807
808         if (DI::args()->getArgc() > 4) {
809                 $cmd = DI::args()->getArgv()[4];
810         } else {
811                 $cmd = 'view';
812         }
813
814         // Setup permissions structures
815         $can_post       = false;
816         $visitor        = 0;
817         $contact        = null;
818         $remote_contact = false;
819         $contact_id     = 0;
820         $edit           = '';
821         $drop           = '';
822
823         $owner_uid = $user['uid'];
824
825         $community_page = (($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
826
827         if (local_user() && (local_user() == $owner_uid)) {
828                 $can_post = true;
829         } elseif ($community_page && !empty(Session::getRemoteContactID($owner_uid))) {
830                 $contact_id = Session::getRemoteContactID($owner_uid);
831                 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id, 'uid' => $owner_uid, 'blocked' => false, 'pending' => false]);
832
833                 if (DBA::isResult($contact)) {
834                         $can_post = true;
835                         $remote_contact = true;
836                         $visitor = $contact_id;
837                 }
838         }
839
840         // perhaps they're visiting - but not a community page, so they wouldn't have write access
841         if (!empty(Session::getRemoteContactID($owner_uid)) && !$visitor) {
842                 $contact_id = Session::getRemoteContactID($owner_uid);
843
844                 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id, 'uid' => $owner_uid, 'blocked' => false, 'pending' => false]);
845
846                 $remote_contact = DBA::isResult($contact);
847         }
848
849         if (!$remote_contact && local_user()) {
850                 $contact_id = $_SESSION['cid'];
851
852                 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id, 'uid' => $owner_uid, 'blocked' => false, 'pending' => false]);
853         }
854
855         if ($user['hidewall'] && (local_user() != $owner_uid) && !$remote_contact) {
856                 notice(DI::l10n()->t('Access to this item is restricted.'));
857                 return;
858         }
859
860         $sql_extra = Security::getPermissionsSQLByUserId($owner_uid);
861
862         $o = "";
863
864         // tabs
865         $is_owner = (local_user() && (local_user() == $owner_uid));
866         $o .= BaseProfile::getTabsHTML($a, 'photos', $is_owner, $user['nickname'], $profile['hide-friends']);
867
868         // Display upload form
869         if ($datatype === 'upload') {
870                 if (!$can_post) {
871                         notice(DI::l10n()->t('Permission denied.'));
872                         return;
873                 }
874
875                 $selname = Strings::isHex($datum) ? hex2bin($datum) : '';
876
877                 $albumselect = '';
878
879                 $albumselect .= '<option value="" ' . (!$selname ? ' selected="selected" ' : '') . '>&lt;current year&gt;</option>';
880                 $albums = Photo::getAlbums($owner_uid);
881                 if (!empty($albums)) {
882                         foreach ($albums as $album) {
883                                 if ($album['album'] === '') {
884                                         continue;
885                                 }
886                                 $selected = (($selname === $album['album']) ? ' selected="selected" ' : '');
887                                 $albumselect .= '<option value="' . $album['album'] . '"' . $selected . '>' . $album['album'] . '</option>';
888                         }
889                 }
890
891                 $uploader = '';
892
893                 $ret = ['post_url' => 'photos/' . $user['nickname'],
894                                 'addon_text' => $uploader,
895                                 'default_upload' => true];
896
897                 Hook::callAll('photo_upload_form',$ret);
898
899                 $default_upload_box = Renderer::replaceMacros(Renderer::getMarkupTemplate('photos_default_uploader_box.tpl'), []);
900                 $default_upload_submit = Renderer::replaceMacros(Renderer::getMarkupTemplate('photos_default_uploader_submit.tpl'), [
901                         '$submit' => DI::l10n()->t('Submit'),
902                 ]);
903
904                 $usage_message = '';
905
906                 $tpl = Renderer::getMarkupTemplate('photos_upload.tpl');
907
908                 $aclselect_e = ($visitor ? '' : ACL::getFullSelectorHTML(DI::page(), $a->getLoggedInUserId()));
909
910                 $o .= Renderer::replaceMacros($tpl,[
911                         '$pagename' => DI::l10n()->t('Upload Photos'),
912                         '$sessid' => session_id(),
913                         '$usage' => $usage_message,
914                         '$nickname' => $user['nickname'],
915                         '$newalbum' => DI::l10n()->t('New album name: '),
916                         '$existalbumtext' => DI::l10n()->t('or select existing album:'),
917                         '$nosharetext' => DI::l10n()->t('Do not show a status post for this upload'),
918                         '$albumselect' => $albumselect,
919                         '$permissions' => DI::l10n()->t('Permissions'),
920                         '$aclselect' => $aclselect_e,
921                         '$lockstate' => ACL::getLockstateForUserId($a->getLoggedInUserId()) ? 'lock' : 'unlock',
922                         '$alt_uploader' => $ret['addon_text'],
923                         '$default_upload_box' => ($ret['default_upload'] ? $default_upload_box : ''),
924                         '$default_upload_submit' => ($ret['default_upload'] ? $default_upload_submit : ''),
925                         '$uploadurl' => $ret['post_url'],
926
927                         // ACL permissions box
928                         '$return_path' => DI::args()->getQueryString(),
929                 ]);
930
931                 return $o;
932         }
933
934         // Display a single photo album
935         if ($datatype === 'album') {
936                 // if $datum is not a valid hex, redirect to the default page
937                 if (!Strings::isHex($datum)) {
938                         DI::baseUrl()->redirect('photos/' . $user['nickname']. '/album');
939                 }
940                 $album = hex2bin($datum);
941
942                 if ($can_post && !Photo::exists(['uid' => $owner_uid, 'album' => $album, 'photo-type' => Photo::DEFAULT])) {
943                         $can_post = false;
944                 }
945
946                 $total = 0;
947                 $r = DBA::toArray(DBA::p("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = ? AND `album` = ?
948                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id`",
949                         $owner_uid,
950                         $album
951                 ));
952                 if (DBA::isResult($r)) {
953                         $total = count($r);
954                 }
955
956                 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), 20);
957
958                 /// @TODO I have seen this many times, maybe generalize it script-wide and encapsulate it?
959                 $order_field = $_GET['order'] ?? '';
960                 if ($order_field === 'posted') {
961                         $order = 'ASC';
962                 } else {
963                         $order = 'DESC';
964                 }
965
966                 $r = DBA::toArray(DBA::p("SELECT `resource-id`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`filename`) AS `filename`,
967                         ANY_VALUE(`type`) AS `type`, max(`scale`) AS `scale`, ANY_VALUE(`desc`) as `desc`,
968                         ANY_VALUE(`created`) as `created`
969                         FROM `photo` WHERE `uid` = ? AND `album` = ?
970                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id` ORDER BY `created` $order LIMIT ? , ?",
971                         intval($owner_uid),
972                         DBA::escape($album),
973                         $pager->getStart(),
974                         $pager->getItemsPerPage()
975                 ));
976
977                 if ($cmd === 'drop') {
978                         $drop_url = DI::args()->getQueryString();
979
980                         return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
981                                 '$l10n'           => [
982                                         'message' => DI::l10n()->t('Do you really want to delete this photo album and all its photos?'),
983                                         'confirm' => DI::l10n()->t('Delete Album'),
984                                         'cancel'  => DI::l10n()->t('Cancel'),
985                                 ],
986                                 '$method'        => 'post',
987                                 '$confirm_url'   => $drop_url,
988                                 '$confirm_name'  => 'dropalbum',
989                                 '$confirm_value' => 'dropalbum',
990                         ]);
991                 }
992
993                 // edit album name
994                 if ($cmd === 'edit') {
995                         if ($can_post) {
996                                 $edit_tpl = Renderer::getMarkupTemplate('album_edit.tpl');
997
998                                 $album_e = $album;
999
1000                                 $o .= Renderer::replaceMacros($edit_tpl,[
1001                                         '$nametext' => DI::l10n()->t('New album name: '),
1002                                         '$nickname' => $user['nickname'],
1003                                         '$album' => $album_e,
1004                                         '$hexalbum' => bin2hex($album),
1005                                         '$submit' => DI::l10n()->t('Submit'),
1006                                         '$dropsubmit' => DI::l10n()->t('Delete Album')
1007                                 ]);
1008                         }
1009                 } elseif ($can_post) {
1010                         $edit = [DI::l10n()->t('Edit Album'), 'photos/' . $user['nickname'] . '/album/' . bin2hex($album) . '/edit'];
1011                         $drop = [DI::l10n()->t('Drop Album'), 'photos/' . $user['nickname'] . '/album/' . bin2hex($album) . '/drop'];
1012                 }
1013
1014                 if ($order_field === 'posted') {
1015                         $order =  [DI::l10n()->t('Show Newest First'), 'photos/' . $user['nickname'] . '/album/' . bin2hex($album), 'oldest'];
1016                 } else {
1017                         $order = [DI::l10n()->t('Show Oldest First'), 'photos/' . $user['nickname'] . '/album/' . bin2hex($album) . '?order=posted', 'newest'];
1018                 }
1019
1020                 $photos = [];
1021
1022                 if (DBA::isResult($r)) {
1023                         // "Twist" is only used for the duepunto theme with style "slackr"
1024                         $twist = false;
1025                         foreach ($r as $rr) {
1026                                 $twist = !$twist;
1027
1028                                 $ext = $phototypes[$rr['type']];
1029
1030                                 $imgalt_e = $rr['filename'];
1031                                 $desc_e = $rr['desc'];
1032
1033                                 $photos[] = [
1034                                         'id' => $rr['id'],
1035                                         'twist' => ' ' . ($twist ? 'rotleft' : 'rotright') . rand(2,4),
1036                                         'link' => 'photos/' . $user['nickname'] . '/image/' . $rr['resource-id']
1037                                                 . ($order_field === 'posted' ? '?order=posted' : ''),
1038                                         'title' => DI::l10n()->t('View Photo'),
1039                                         'src' => 'photo/' . $rr['resource-id'] . '-' . $rr['scale'] . '.' .$ext,
1040                                         'alt' => $imgalt_e,
1041                                         'desc'=> $desc_e,
1042                                         'ext' => $ext,
1043                                         'hash'=> $rr['resource-id'],
1044                                 ];
1045                         }
1046                 }
1047
1048                 $tpl = Renderer::getMarkupTemplate('photo_album.tpl');
1049                 $o .= Renderer::replaceMacros($tpl, [
1050                         '$photos' => $photos,
1051                         '$album' => $album,
1052                         '$can_post' => $can_post,
1053                         '$upload' => [DI::l10n()->t('Upload New Photos'), 'photos/' . $user['nickname'] . '/upload/' . bin2hex($album)],
1054                         '$order' => $order,
1055                         '$edit' => $edit,
1056                         '$drop' => $drop,
1057                         '$paginate' => $pager->renderFull($total),
1058                 ]);
1059
1060                 return $o;
1061
1062         }
1063
1064         // Display one photo
1065         if ($datatype === 'image') {
1066                 // fetch image, item containing image, then comments
1067                 $ph = Photo::selectToArray([], ["`uid` = ? AND `resource-id` = ? " . $sql_extra, $owner_uid, $datum], ['order' => ['scale']]);
1068
1069                 if (!DBA::isResult($ph)) {
1070                         if (DBA::exists('photo', ['resource-id' => $datum, 'uid' => $owner_uid])) {
1071                                 notice(DI::l10n()->t('Permission denied. Access to this item may be restricted.'));
1072                         } else {
1073                                 notice(DI::l10n()->t('Photo not available'));
1074                         }
1075                         return;
1076                 }
1077
1078                 if ($cmd === 'drop') {
1079                         $drop_url = DI::args()->getQueryString();
1080
1081                         return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
1082                                 '$l10n'           => [
1083                                         'message' => DI::l10n()->t('Do you really want to delete this photo?'),
1084                                         'confirm' => DI::l10n()->t('Delete Photo'),
1085                                         'cancel'  => DI::l10n()->t('Cancel'),
1086                                 ],
1087                                 '$method'        => 'post',
1088                                 '$confirm_url'   => $drop_url,
1089                                 '$confirm_name'  => 'delete',
1090                                 '$confirm_value' => 'delete',
1091                         ]);
1092                 }
1093
1094                 $prevlink = '';
1095                 $nextlink = '';
1096
1097                 /*
1098                  * @todo This query is totally bad, the whole functionality has to be changed
1099                  * The query leads to a really intense used index.
1100                  * By now we hide it if someone wants to.
1101                  */
1102                 if ($cmd === 'view' && !DI::config()->get('system', 'no_count', false)) {
1103                         $order_field = $_GET['order'] ?? '';
1104
1105                         if ($order_field === 'posted') {
1106                                 $params = ['order' => [$order_field]];
1107                         } elseif (!empty($order_field)) {
1108                                 $params = ['order' => [$order_field => true]];
1109                         } else {
1110                                 $params = [];
1111                         }
1112
1113                         $prvnxt = Photo::selectToArray(['resource-id'], ["`album` = ? AND `uid` = ? AND `scale` = ?" . $sql_extra, $ph[0]['album'], $owner_uid, 0], $params);
1114
1115                         if (DBA::isResult($prvnxt)) {
1116                                 $prv = null;
1117                                 $nxt = null;
1118                                 foreach ($prvnxt as $z => $entry) {
1119                                         if ($entry['resource-id'] == $ph[0]['resource-id']) {
1120                                                 $prv = $z - 1;
1121                                                 $nxt = $z + 1;
1122                                                 if ($prv < 0) {
1123                                                         $prv = count($prvnxt) - 1;
1124                                                 }
1125                                                 if ($nxt >= count($prvnxt)) {
1126                                                         $nxt = 0;
1127                                                 }
1128                                                 break;
1129                                         }
1130                                 }
1131
1132                                 if (!is_null($prv)) {
1133                                         $prevlink = 'photos/' . $user['nickname'] . '/image/' . $prvnxt[$prv]['resource-id'] . ($order_field === 'posted' ? '?order=posted' : '');
1134                                 }
1135                                 if (!is_null($nxt)) {
1136                                         $nextlink = 'photos/' . $user['nickname'] . '/image/' . $prvnxt[$nxt]['resource-id'] . ($order_field === 'posted' ? '?order=posted' : '');
1137                                 }
1138
1139                                 $tpl = Renderer::getMarkupTemplate('photo_edit_head.tpl');
1140                                 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl,[
1141                                         '$prevlink' => $prevlink,
1142                                         '$nextlink' => $nextlink
1143                                 ]);
1144
1145                                 if ($prevlink) {
1146                                         $prevlink = [$prevlink, '<div class="icon prev"></div>'];
1147                                 }
1148
1149                                 if ($nextlink) {
1150                                         $nextlink = [$nextlink, '<div class="icon next"></div>'];
1151                                 }
1152                         }
1153                 }
1154
1155                 if (count($ph) == 1) {
1156                         $hires = $lores = $ph[0];
1157                 }
1158
1159                 if (count($ph) > 1) {
1160                         if ($ph[1]['scale'] == 2) {
1161                                 // original is 640 or less, we can display it directly
1162                                 $hires = $lores = $ph[0];
1163                         } else {
1164                                 $hires = $ph[0];
1165                                 $lores = $ph[1];
1166                         }
1167                 }
1168
1169                 $album_link = 'photos/' . $user['nickname'] . '/album/' . bin2hex($ph[0]['album']);
1170
1171                 $tools = null;
1172
1173                 if ($can_post && ($ph[0]['uid'] == $owner_uid)) {
1174                         $tools = [];
1175                         if ($cmd === 'edit') {
1176                                 $tools['view'] = ['photos/' . $user['nickname'] . '/image/' . $datum, DI::l10n()->t('View photo')];
1177                         } else {
1178                                 $tools['edit'] = ['photos/' . $user['nickname'] . '/image/' . $datum . '/edit', DI::l10n()->t('Edit photo')];
1179                                 $tools['delete'] = ['photos/' . $user['nickname'] . '/image/' . $datum . '/drop', DI::l10n()->t('Delete photo')];
1180                                 $tools['profile'] = ['settings/profile/photo/crop/' . $ph[0]['resource-id'], DI::l10n()->t('Use as profile photo')];
1181                         }
1182
1183                         if (
1184                                 $ph[0]['uid'] == local_user()
1185                                 && (strlen($ph[0]['allow_cid']) || strlen($ph[0]['allow_gid']) || strlen($ph[0]['deny_cid']) || strlen($ph[0]['deny_gid']))
1186                         ) {
1187                                 $tools['lock'] = DI::l10n()->t('Private Photo');
1188                         }
1189                 }
1190
1191                 $photo = [
1192                         'href' => 'photo/' . $hires['resource-id'] . '-' . $hires['scale'] . '.' . $phototypes[$hires['type']],
1193                         'title'=> DI::l10n()->t('View Full Size'),
1194                         'src'  => 'photo/' . $lores['resource-id'] . '-' . $lores['scale'] . '.' . $phototypes[$lores['type']] . '?_u=' . DateTimeFormat::utcNow('ymdhis'),
1195                         'height' => $hires['height'],
1196                         'width' => $hires['width'],
1197                         'album' => $hires['album'],
1198                         'filename' => $hires['filename'],
1199                 ];
1200
1201                 $map = null;
1202                 $link_item = [];
1203                 $total = 0;
1204
1205                 // Do we have an item for this photo?
1206
1207                 // FIXME! - replace following code to display the conversation with our normal
1208                 // conversation functions so that it works correctly and tracks changes
1209                 // in the evolving conversation code.
1210                 // The difference is that we won't be displaying the conversation head item
1211                 // as a "post" but displaying instead the photo it is linked to
1212
1213                 $link_item = Post::selectFirst([], ["`resource-id` = ?" . $sql_extra, $datum]);
1214
1215                 if (!empty($link_item['parent']) && !empty($link_item['uid'])) {
1216                         $condition = ["`parent` = ? AND `gravity` = ?",  $link_item['parent'], GRAVITY_COMMENT];
1217                         $total = Post::count($condition);
1218
1219                         $pager = new Pager(DI::l10n(), DI::args()->getQueryString());
1220
1221                         $params = ['order' => ['id'], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1222                         $items = Post::toArray(Post::selectForUser($link_item['uid'], Item::ITEM_FIELDLIST, $condition, $params));
1223
1224                         if (local_user() == $link_item['uid']) {
1225                                 Item::update(['unseen' => false], ['parent' => $link_item['parent']]);
1226                         }
1227                 }
1228
1229                 if (!empty($link_item['coord'])) {
1230                         $map = Map::byCoordinates($link_item['coord']);
1231                 }
1232
1233                 $tags = null;
1234
1235                 if (!empty($link_item['id'])) {
1236                         // parse tags and add links
1237                         $tag_arr = [];
1238                         foreach (Tag::getByURIId($link_item['uri-id']) as $tag) {
1239                                 $tag_arr[] = [
1240                                         'name' => $tag['name'],
1241                                         'removeurl' => '/tagrm/' . $link_item['id'] . '/' . bin2hex($tag['name'])
1242                                 ];
1243                         }
1244                         $tags = ['title' => DI::l10n()->t('Tags: '), 'tags' => $tag_arr];
1245                         if ($cmd === 'edit') {
1246                                 $tags['removeanyurl'] = 'tagrm/' . $link_item['id'];
1247                                 $tags['removetitle'] = DI::l10n()->t('[Select tags to remove]');
1248                         }
1249                 }
1250
1251
1252                 $edit = Null;
1253                 if ($cmd === 'edit' && $can_post) {
1254                         $edit_tpl = Renderer::getMarkupTemplate('photo_edit.tpl');
1255
1256                         $album_e = $ph[0]['album'];
1257                         $caption_e = $ph[0]['desc'];
1258                         $aclselect_e = ACL::getFullSelectorHTML(DI::page(), $a->getLoggedInUserId(), false, ACL::getDefaultUserPermissions($ph[0]));
1259
1260                         $edit = Renderer::replaceMacros($edit_tpl, [
1261                                 '$id' => $ph[0]['id'],
1262                                 '$album' => ['albname', DI::l10n()->t('New album name'), $album_e,''],
1263                                 '$caption' => ['desc', DI::l10n()->t('Caption'), $caption_e, ''],
1264                                 '$tags' => ['newtag', DI::l10n()->t('Add a Tag'), "", DI::l10n()->t('Example: @bob, @Barbara_Jensen, @jim@example.com, #California, #camping')],
1265                                 '$rotate_none' => ['rotate', DI::l10n()->t('Do not rotate'),0,'', true],
1266                                 '$rotate_cw' => ['rotate', DI::l10n()->t("Rotate CW \x28right\x29"),1,''],
1267                                 '$rotate_ccw' => ['rotate', DI::l10n()->t("Rotate CCW \x28left\x29"),2,''],
1268
1269                                 '$nickname' => $user['nickname'],
1270                                 '$resource_id' => $ph[0]['resource-id'],
1271                                 '$permissions' => DI::l10n()->t('Permissions'),
1272                                 '$aclselect' => $aclselect_e,
1273
1274                                 '$item_id' => $link_item['id'] ?? 0,
1275                                 '$submit' => DI::l10n()->t('Submit'),
1276                                 '$delete' => DI::l10n()->t('Delete Photo'),
1277
1278                                 // ACL permissions box
1279                                 '$return_path' => DI::args()->getQueryString(),
1280                         ]);
1281                 }
1282
1283                 $like = '';
1284                 $dislike = '';
1285                 $likebuttons = '';
1286                 $comments = '';
1287                 $paginate = '';
1288
1289                 if (!empty($link_item['id']) && !empty($link_item['uri'])) {
1290                         $cmnt_tpl = Renderer::getMarkupTemplate('comment_item.tpl');
1291                         $tpl = Renderer::getMarkupTemplate('photo_item.tpl');
1292                         $return_path = DI::args()->getCommand();
1293
1294                         if (!DBA::isResult($items)) {
1295                                 if (($can_post || Security::canWriteToUserWall($owner_uid))) {
1296                                         /*
1297                                          * Hmmm, code depending on the presence of a particular addon?
1298                                          * This should be better if done by a hook
1299                                          */
1300                                         $qcomment = null;
1301                                         if (Addon::isEnabled('qcomment')) {
1302                                                 $words = DI::pConfig()->get(local_user(), 'qcomment', 'words');
1303                                                 $qcomment = $words ? explode("\n", $words) : [];
1304                                         }
1305
1306                                         $comments .= Renderer::replaceMacros($cmnt_tpl, [
1307                                                 '$return_path' => '',
1308                                                 '$jsreload' => $return_path,
1309                                                 '$id' => $link_item['id'],
1310                                                 '$parent' => $link_item['id'],
1311                                                 '$profile_uid' =>  $owner_uid,
1312                                                 '$mylink' => $contact['url'],
1313                                                 '$mytitle' => DI::l10n()->t('This is you'),
1314                                                 '$myphoto' => $contact['thumb'],
1315                                                 '$comment' => DI::l10n()->t('Comment'),
1316                                                 '$submit' => DI::l10n()->t('Submit'),
1317                                                 '$preview' => DI::l10n()->t('Preview'),
1318                                                 '$loading' => DI::l10n()->t('Loading...'),
1319                                                 '$qcomment' => $qcomment,
1320                                                 '$rand_num' => Crypto::randomDigits(12)
1321                                         ]);
1322                                 }
1323                         }
1324
1325                         $conv_responses = [
1326                                 'like'        => [],
1327                                 'dislike'     => [],
1328                                 'attendyes'   => [],
1329                                 'attendno'    => [],
1330                                 'attendmaybe' => []
1331                         ];
1332
1333                         if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
1334                                 unset($conv_responses['dislike']);
1335                         }
1336
1337                         // display comments
1338                         if (DBA::isResult($items)) {
1339                                 foreach ($items as $item) {
1340                                         DI::conversation()->builtinActivityPuller($item, $conv_responses);
1341                                 }
1342
1343                                 if (!empty($conv_responses['like'][$link_item['uri']])) {
1344                                         $like = DI::conversation()->formatActivity($conv_responses['like'][$link_item['uri']]['links'], 'like', $link_item['id']);
1345                                 }
1346
1347                                 if (!empty($conv_responses['dislike'][$link_item['uri']])) {
1348                                         $dislike = DI::conversation()->formatActivity($conv_responses['dislike'][$link_item['uri']]['links'], 'dislike', $link_item['id']);
1349                                 }
1350
1351                                 if (($can_post || Security::canWriteToUserWall($owner_uid))) {
1352                                         /*
1353                                          * Hmmm, code depending on the presence of a particular addon?
1354                                          * This should be better if done by a hook
1355                                          */
1356                                         $qcomment = null;
1357                                         if (Addon::isEnabled('qcomment')) {
1358                                                 $words = DI::pConfig()->get(local_user(), 'qcomment', 'words');
1359                                                 $qcomment = $words ? explode("\n", $words) : [];
1360                                         }
1361
1362                                         $comments .= Renderer::replaceMacros($cmnt_tpl,[
1363                                                 '$return_path' => '',
1364                                                 '$jsreload' => $return_path,
1365                                                 '$id' => $link_item['id'],
1366                                                 '$parent' => $link_item['id'],
1367                                                 '$profile_uid' =>  $owner_uid,
1368                                                 '$mylink' => $contact['url'],
1369                                                 '$mytitle' => DI::l10n()->t('This is you'),
1370                                                 '$myphoto' => $contact['thumb'],
1371                                                 '$comment' => DI::l10n()->t('Comment'),
1372                                                 '$submit' => DI::l10n()->t('Submit'),
1373                                                 '$preview' => DI::l10n()->t('Preview'),
1374                                                 '$qcomment' => $qcomment,
1375                                                 '$rand_num' => Crypto::randomDigits(12)
1376                                         ]);
1377                                 }
1378
1379                                 foreach ($items as $item) {
1380                                         $comment = '';
1381                                         $template = $tpl;
1382
1383                                         $activity = DI::activity();
1384
1385                                         if (($activity->match($item['verb'], Activity::LIKE) ||
1386                                              $activity->match($item['verb'], Activity::DISLIKE)) &&
1387                                             ($item['gravity'] != GRAVITY_PARENT)) {
1388                                                 continue;
1389                                         }
1390
1391                                         $author = ['uid' => 0, 'id' => $item['author-id'],
1392                                                 'network' => $item['author-network'], 'url' => $item['author-link']];
1393                                         $profile_url = Contact::magicLinkByContact($author);
1394                                         if (strpos($profile_url, 'redir/') === 0) {
1395                                                 $sparkle = ' sparkle';
1396                                         } else {
1397                                                 $sparkle = '';
1398                                         }
1399
1400                                         $dropping = (($item['contact-id'] == $contact_id) || ($item['uid'] == local_user()));
1401                                         $drop = [
1402                                                 'dropping' => $dropping,
1403                                                 'pagedrop' => false,
1404                                                 'select' => DI::l10n()->t('Select'),
1405                                                 'delete' => DI::l10n()->t('Delete'),
1406                                         ];
1407
1408                                         $title_e = $item['title'];
1409                                         $body_e = BBCode::convertForUriId($item['uri-id'], $item['body']);
1410
1411                                         $comments .= Renderer::replaceMacros($template,[
1412                                                 '$id' => $item['id'],
1413                                                 '$profile_url' => $profile_url,
1414                                                 '$name' => $item['author-name'],
1415                                                 '$thumb' => $item['author-avatar'],
1416                                                 '$sparkle' => $sparkle,
1417                                                 '$title' => $title_e,
1418                                                 '$body' => $body_e,
1419                                                 '$ago' => Temporal::getRelativeDate($item['created']),
1420                                                 '$indent' => (($item['parent'] != $item['id']) ? ' comment' : ''),
1421                                                 '$drop' => $drop,
1422                                                 '$comment' => $comment
1423                                         ]);
1424
1425                                         if (($can_post || Security::canWriteToUserWall($owner_uid))) {
1426                                                 /*
1427                                                  * Hmmm, code depending on the presence of a particular addon?
1428                                                  * This should be better if done by a hook
1429                                                  */
1430                                                 $qcomment = null;
1431                                                 if (Addon::isEnabled('qcomment')) {
1432                                                         $words = DI::pConfig()->get(local_user(), 'qcomment', 'words');
1433                                                         $qcomment = $words ? explode("\n", $words) : [];
1434                                                 }
1435
1436                                                 $comments .= Renderer::replaceMacros($cmnt_tpl, [
1437                                                         '$return_path' => '',
1438                                                         '$jsreload' => $return_path,
1439                                                         '$id' => $item['id'],
1440                                                         '$parent' => $item['parent'],
1441                                                         '$profile_uid' =>  $owner_uid,
1442                                                         '$mylink' => $contact['url'],
1443                                                         '$mytitle' => DI::l10n()->t('This is you'),
1444                                                         '$myphoto' => $contact['thumb'],
1445                                                         '$comment' => DI::l10n()->t('Comment'),
1446                                                         '$submit' => DI::l10n()->t('Submit'),
1447                                                         '$preview' => DI::l10n()->t('Preview'),
1448                                                         '$qcomment' => $qcomment,
1449                                                         '$rand_num' => Crypto::randomDigits(12)
1450                                                 ]);
1451                                         }
1452                                 }
1453                         }
1454
1455                         $responses = [];
1456                         foreach ($conv_responses as $verb => $activity) {
1457                                 if (isset($activity[$link_item['uri']])) {
1458                                         $responses[$verb] = $activity[$link_item['uri']];
1459                                 }
1460                         }
1461
1462                         if ($cmd === 'view' && ($can_post || Security::canWriteToUserWall($owner_uid))) {
1463                                 $like_tpl = Renderer::getMarkupTemplate('like_noshare.tpl');
1464                                 $likebuttons = Renderer::replaceMacros($like_tpl, [
1465                                         '$id' => $link_item['id'],
1466                                         '$like' => DI::l10n()->t('Like'),
1467                                         '$like_title' => DI::l10n()->t('I like this (toggle)'),
1468                                         '$dislike' => DI::l10n()->t('Dislike'),
1469                                         '$wait' => DI::l10n()->t('Please wait'),
1470                                         '$dislike_title' => DI::l10n()->t('I don\'t like this (toggle)'),
1471                                         '$hide_dislike' => DI::pConfig()->get(local_user(), 'system', 'hide_dislike'),
1472                                         '$responses' => $responses,
1473                                         '$return_path' => DI::args()->getQueryString(),
1474                                 ]);
1475                         }
1476
1477                         $paginate = $pager->renderFull($total);
1478                 }
1479
1480                 $photo_tpl = Renderer::getMarkupTemplate('photo_view.tpl');
1481                 $o .= Renderer::replaceMacros($photo_tpl, [
1482                         '$id' => $ph[0]['id'],
1483                         '$album' => [$album_link, $ph[0]['album']],
1484                         '$tools' => $tools,
1485                         '$photo' => $photo,
1486                         '$prevlink' => $prevlink,
1487                         '$nextlink' => $nextlink,
1488                         '$desc' => $ph[0]['desc'],
1489                         '$tags' => $tags,
1490                         '$edit' => $edit,
1491                         '$map' => $map,
1492                         '$map_text' => DI::l10n()->t('Map'),
1493                         '$likebuttons' => $likebuttons,
1494                         '$like' => $like,
1495                         '$dislike' => $dislike,
1496                         '$comments' => $comments,
1497                         '$paginate' => $paginate,
1498                 ]);
1499
1500                 DI::page()['htmlhead'] .= "\n" . '<meta name="twitter:card" content="summary_large_image" />' . "\n";
1501                 DI::page()['htmlhead'] .= '<meta name="twitter:title" content="' . $photo["album"] . '" />' . "\n";
1502                 DI::page()['htmlhead'] .= '<meta name="twitter:image" content="' . DI::baseUrl() . "/" . $photo["href"] . '" />' . "\n";
1503                 DI::page()['htmlhead'] .= '<meta name="twitter:image:width" content="' . $photo["width"] . '" />' . "\n";
1504                 DI::page()['htmlhead'] .= '<meta name="twitter:image:height" content="' . $photo["height"] . '" />' . "\n";
1505
1506                 return $o;
1507         }
1508
1509         // Default - show recent photos with upload link (if applicable)
1510         //$o = '';
1511         $total = 0;
1512         $r = DBA::toArray(DBA::p("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = ? AND `photo-type` = ?
1513                 $sql_extra GROUP BY `resource-id`",
1514                 $user['uid'],
1515                 Photo::DEFAULT,
1516         ));
1517         if (DBA::isResult($r)) {
1518                 $total = count($r);
1519         }
1520
1521         $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), 20);
1522
1523         $r = DBA::toArray(DBA::p("SELECT `resource-id`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`filename`) AS `filename`,
1524                 ANY_VALUE(`type`) AS `type`, ANY_VALUE(`album`) AS `album`, max(`scale`) AS `scale`,
1525                 ANY_VALUE(`created`) AS `created` FROM `photo`
1526                 WHERE `uid` = ? AND `photo-type` = ?
1527                 $sql_extra GROUP BY `resource-id` ORDER BY `created` DESC LIMIT ? , ?",
1528                 $user['uid'],
1529                 Photo::DEFAULT,
1530                 $pager->getStart(),
1531                 $pager->getItemsPerPage()
1532         ));
1533
1534         $photos = [];
1535         if (DBA::isResult($r)) {
1536                 // "Twist" is only used for the duepunto theme with style "slackr"
1537                 $twist = false;
1538                 foreach ($r as $rr) {
1539                         $twist = !$twist;
1540                         $ext = $phototypes[$rr['type']];
1541
1542                         $alt_e = $rr['filename'];
1543                         $name_e = $rr['album'];
1544
1545                         $photos[] = [
1546                                 'id'    => $rr['id'],
1547                                 'twist' => ' ' . ($twist ? 'rotleft' : 'rotright') . rand(2,4),
1548                                 'link'  => 'photos/' . $user['nickname'] . '/image/' . $rr['resource-id'],
1549                                 'title' => DI::l10n()->t('View Photo'),
1550                                 'src'   => 'photo/' . $rr['resource-id'] . '-' . ((($rr['scale']) == 6) ? 4 : $rr['scale']) . '.' . $ext,
1551                                 'alt'   => $alt_e,
1552                                 'album' => [
1553                                         'link' => 'photos/' . $user['nickname'] . '/album/' . bin2hex($rr['album']),
1554                                         'name' => $name_e,
1555                                         'alt'  => DI::l10n()->t('View Album'),
1556                                 ],
1557
1558                         ];
1559                 }
1560         }
1561
1562         $tpl = Renderer::getMarkupTemplate('photos_recent.tpl');
1563         $o .= Renderer::replaceMacros($tpl, [
1564                 '$title' => DI::l10n()->t('Recent Photos'),
1565                 '$can_post' => $can_post,
1566                 '$upload' => [DI::l10n()->t('Upload New Photos'), 'photos/' . $user['nickname'] . '/upload'],
1567                 '$photos' => $photos,
1568                 '$paginate' => $pager->renderFull($total),
1569         ]);
1570
1571         return $o;
1572 }