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