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