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