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