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