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