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