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