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