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