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