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