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