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