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