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