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