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