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