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