]> git.mxchange.org Git - friendica.git/blob - mod/photos.php
Merge pull request #4399 from MrPetovan/task/3878-move-include-bbcode-to-src
[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\Core\Addon;
10 use Friendica\Core\Config;
11 use Friendica\Core\L10n;
12 use Friendica\Core\System;
13 use Friendica\Core\Worker;
14 use Friendica\Database\DBM;
15 use Friendica\Model\Contact;
16 use Friendica\Model\Group;
17 use Friendica\Model\Item;
18 use Friendica\Model\Photo;
19 use Friendica\Model\Profile;
20 use Friendica\Model\Term;
21 use Friendica\Network\Probe;
22 use Friendica\Object\Image;
23 use Friendica\Protocol\DFRN;
24 use Friendica\Util\DateTimeFormat;
25 use Friendica\Util\Map;
26 use Friendica\Util\Temporal;
27
28 require_once 'include/items.php';
29 require_once 'include/acl_selectors.php';
30 require_once 'include/bbcode.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_new_resource();
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($channel_id, '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/bbcode.php';
938         require_once 'include/security.php';
939         require_once 'include/conversation.php';
940
941         if (!x($a->data,'user')) {
942                 notice(L10n::t('No photos selected') . EOL );
943                 return;
944         }
945
946         $phototypes = Image::supportedTypes();
947
948         $_SESSION['photo_return'] = $a->cmd;
949
950         // Parse arguments
951         $datum = null;
952         if ($a->argc > 3) {
953                 $datatype = $a->argv[2];
954                 $datum = $a->argv[3];
955         } elseif (($a->argc > 2) && ($a->argv[2] === 'upload')) {
956                 $datatype = 'upload';
957         } else {
958                 $datatype = 'summary';
959         }
960
961         if ($a->argc > 4) {
962                 $cmd = $a->argv[4];
963         } else {
964                 $cmd = 'view';
965         }
966
967         // Setup permissions structures
968         $can_post       = false;
969         $visitor        = 0;
970         $contact        = null;
971         $remote_contact = false;
972         $contact_id     = 0;
973
974         $owner_uid = $a->data['user']['uid'];
975
976         $community_page = (($a->data['user']['page-flags'] == PAGE_COMMUNITY) ? true : false);
977
978         if (local_user() && (local_user() == $owner_uid)) {
979                 $can_post = true;
980         } else {
981                 if ($community_page && remote_user()) {
982                         if (is_array($_SESSION['remote'])) {
983                                 foreach ($_SESSION['remote'] as $v) {
984                                         if ($v['uid'] == $owner_uid) {
985                                                 $contact_id = $v['cid'];
986                                                 break;
987                                         }
988                                 }
989                         }
990                         if ($contact_id) {
991
992                                 $r = q("SELECT `uid` FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1",
993                                         intval($contact_id),
994                                         intval($owner_uid)
995                                 );
996                                 if (DBM::is_result($r)) {
997                                         $can_post = true;
998                                         $contact = $r[0];
999                                         $remote_contact = true;
1000                                         $visitor = $contact_id;
1001                                 }
1002                         }
1003                 }
1004         }
1005
1006         $groups = [];
1007
1008         // perhaps they're visiting - but not a community page, so they wouldn't have write access
1009         if (remote_user() && !$visitor) {
1010                 $contact_id = 0;
1011                 if (is_array($_SESSION['remote'])) {
1012                         foreach ($_SESSION['remote'] as $v) {
1013                                 if ($v['uid'] == $owner_uid) {
1014                                         $contact_id = $v['cid'];
1015                                         break;
1016                                 }
1017                         }
1018                 }
1019                 if ($contact_id) {
1020                         $groups = Group::getIdsByContactId($contact_id);
1021                         $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1",
1022                                 intval($contact_id),
1023                                 intval($owner_uid)
1024                         );
1025                         if (DBM::is_result($r)) {
1026                                 $contact = $r[0];
1027                                 $remote_contact = true;
1028                         }
1029                 }
1030         }
1031
1032         if (!$remote_contact && local_user()) {
1033                 $contact_id = $_SESSION['cid'];
1034                 $contact = $a->contact;
1035         }
1036
1037         if ($a->data['user']['hidewall'] && (local_user() != $owner_uid) && !$remote_contact) {
1038                 notice(L10n::t('Access to this item is restricted.') . EOL);
1039                 return;
1040         }
1041
1042         $sql_extra = permissions_sql($owner_uid, $remote_contact, $groups);
1043
1044         $o = "";
1045
1046         // tabs
1047         $is_owner = (local_user() && (local_user() == $owner_uid));
1048         $o .= Profile::getTabs($a, $is_owner, $a->data['user']['nickname']);
1049
1050         // Display upload form
1051         if ($datatype === 'upload') {
1052                 if (!$can_post) {
1053                         notice(L10n::t('Permission denied.'));
1054                         return;
1055                 }
1056
1057                 $selname = $datum ? hex2bin($datum) : '';
1058
1059                 $albumselect = '';
1060
1061                 $albumselect .= '<option value="" ' . (!$selname ? ' selected="selected" ' : '') . '>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option>';
1062                 if (count($a->data['albums'])) {
1063                         foreach ($a->data['albums'] as $album) {
1064                                 if (($album['album'] === '') || ($album['album'] === 'Contact Photos') || ($album['album'] === L10n::t('Contact Photos'))) {
1065                                         continue;
1066                                 }
1067                                 $selected = (($selname === $album['album']) ? ' selected="selected" ' : '');
1068                                 $albumselect .= '<option value="' . $album['album'] . '"' . $selected . '>' . $album['album'] . '</option>';
1069                         }
1070                 }
1071
1072                 $uploader = '';
1073
1074                 $ret = ['post_url' => 'photos/' . $a->data['user']['nickname'],
1075                                 'addon_text' => $uploader,
1076                                 'default_upload' => true];
1077
1078                 Addon::callHooks('photo_upload_form',$ret);
1079
1080                 $default_upload_box = replace_macros(get_markup_template('photos_default_uploader_box.tpl'), []);
1081                 $default_upload_submit = replace_macros(get_markup_template('photos_default_uploader_submit.tpl'), [
1082                         '$submit' => L10n::t('Submit'),
1083                 ]);
1084
1085                 $usage_message = '';
1086
1087                 $tpl = get_markup_template('photos_upload.tpl');
1088
1089                 $aclselect_e = ($visitor ? '' : populate_acl($a->user));
1090
1091                 $o .= replace_macros($tpl,[
1092                         '$pagename' => L10n::t('Upload Photos'),
1093                         '$sessid' => session_id(),
1094                         '$usage' => $usage_message,
1095                         '$nickname' => $a->data['user']['nickname'],
1096                         '$newalbum' => L10n::t('New album name: '),
1097                         '$existalbumtext' => L10n::t('or existing album name: '),
1098                         '$nosharetext' => L10n::t('Do not show a status post for this upload'),
1099                         '$albumselect' => $albumselect,
1100                         '$permissions' => L10n::t('Permissions'),
1101                         '$aclselect' => $aclselect_e,
1102                         '$alt_uploader' => $ret['addon_text'],
1103                         '$default_upload_box' => ($ret['default_upload'] ? $default_upload_box : ''),
1104                         '$default_upload_submit' => ($ret['default_upload'] ? $default_upload_submit : ''),
1105                         '$uploadurl' => $ret['post_url'],
1106
1107                         // ACL permissions box
1108                         '$group_perms' => L10n::t('Show to Groups'),
1109                         '$contact_perms' => L10n::t('Show to Contacts'),
1110                         '$return_path' => $a->query_string,
1111                 ]);
1112
1113                 return $o;
1114         }
1115
1116         // Display a single photo album
1117         if ($datatype === 'album') {
1118                 $album = hex2bin($datum);
1119
1120                 $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` = '%s'
1121                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id`",
1122                         intval($owner_uid),
1123                         dbesc($album)
1124                 );
1125                 if (DBM::is_result($r)) {
1126                         $a->set_pager_total(count($r));
1127                         $a->set_pager_itemspage(20);
1128                 }
1129
1130                 /// @TODO I have seen this many times, maybe generalize it script-wide and encapsulate it?
1131                 $order_field = defaults($_GET, 'order', '');
1132                 if ($order_field === 'posted') {
1133                         $order = 'ASC';
1134                 } else {
1135                         $order = 'DESC';
1136                 }
1137
1138                 $r = q("SELECT `resource-id`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`filename`) AS `filename`,
1139                         ANY_VALUE(`type`) AS `type`, max(`scale`) AS `scale`, ANY_VALUE(`desc`) as `desc`,
1140                         ANY_VALUE(`created`) as `created`
1141                         FROM `photo` WHERE `uid` = %d AND `album` = '%s'
1142                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id` ORDER BY `created` $order LIMIT %d , %d",
1143                         intval($owner_uid),
1144                         dbesc($album),
1145                         intval($a->pager['start']),
1146                         intval($a->pager['itemspage'])
1147                 );
1148
1149                 // edit album name
1150                 if ($cmd === 'edit') {
1151                         if (($album !== L10n::t('Profile Photos')) && ($album !== 'Contact Photos') && ($album !== L10n::t('Contact Photos'))) {
1152                                 if ($can_post) {
1153                                         $edit_tpl = get_markup_template('album_edit.tpl');
1154
1155                                         $album_e = $album;
1156
1157                                         $o .= replace_macros($edit_tpl,[
1158                                                 '$nametext' => L10n::t('New album name: '),
1159                                                 '$nickname' => $a->data['user']['nickname'],
1160                                                 '$album' => $album_e,
1161                                                 '$hexalbum' => bin2hex($album),
1162                                                 '$submit' => L10n::t('Submit'),
1163                                                 '$dropsubmit' => L10n::t('Delete Album')
1164                                         ]);
1165                                 }
1166                         }
1167                 } else {
1168                         if (($album !== L10n::t('Profile Photos')) && ($album !== 'Contact Photos') && ($album !== L10n::t('Contact Photos')) && $can_post) {
1169                                 $edit = [L10n::t('Edit Album'), 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '/edit'];
1170                         }
1171                 }
1172
1173                 if ($order_field === 'posted') {
1174                         $order =  [L10n::t('Show Newest First'), 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album)];
1175                 } else {
1176                         $order = [L10n::t('Show Oldest First'), 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '?f=&order=posted'];
1177                 }
1178
1179                 $photos = [];
1180
1181                 if (DBM::is_result($r)) {
1182                         // "Twist" is only used for the duepunto theme with style "slackr"
1183                         $twist = false;
1184                         foreach ($r as $rr) {
1185                                 $twist = !$twist;
1186
1187                                 $ext = $phototypes[$rr['type']];
1188
1189                                 $imgalt_e = $rr['filename'];
1190                                 $desc_e = $rr['desc'];
1191
1192                                 $photos[] = [
1193                                         'id' => $rr['id'],
1194                                         'twist' => ' ' . ($twist ? 'rotleft' : 'rotright') . rand(2,4),
1195                                         'link' => 'photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id']
1196                                                 . ($order_field === 'posted' ? '?f=&order=posted' : ''),
1197                                         'title' => L10n::t('View Photo'),
1198                                         'src' => 'photo/' . $rr['resource-id'] . '-' . $rr['scale'] . '.' .$ext,
1199                                         'alt' => $imgalt_e,
1200                                         'desc'=> $desc_e,
1201                                         'ext' => $ext,
1202                                         'hash'=> $rr['resource-id'],
1203                                 ];
1204                         }
1205                 }
1206
1207                 $tpl = get_markup_template('photo_album.tpl');
1208                 $o .= replace_macros($tpl, [
1209                                 '$photos' => $photos,
1210                                 '$album' => $album,
1211                                 '$can_post' => $can_post,
1212                                 '$upload' => [L10n::t('Upload New Photos'), 'photos/' . $a->data['user']['nickname'] . '/upload/' . bin2hex($album)],
1213                                 '$order' => $order,
1214                                 '$edit' => $edit,
1215                                 '$paginate' => paginate($a),
1216                         ]);
1217
1218                 return $o;
1219
1220         }
1221
1222         // Display one photo
1223         if ($datatype === 'image') {
1224                 // fetch image, item containing image, then comments
1225                 $ph = q("SELECT * FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'
1226                         $sql_extra ORDER BY `scale` ASC ",
1227                         intval($owner_uid),
1228                         dbesc($datum)
1229                 );
1230
1231                 if (!DBM::is_result($ph)) {
1232                         $ph = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'
1233                                 LIMIT 1",
1234                                 intval($owner_uid),
1235                                 dbesc($datum)
1236                         );
1237                         if (DBM::is_result($ph)) {
1238                                 notice(L10n::t('Permission denied. Access to this item may be restricted.'));
1239                         } else {
1240                                 notice(L10n::t('Photo not available') . EOL );
1241                         }
1242                         return;
1243                 }
1244
1245                 $prevlink = '';
1246                 $nextlink = '';
1247
1248                 /// @todo This query is totally bad, the whole functionality has to be changed
1249                 // The query leads to a really intense used index.
1250                 // By now we hide it if someone wants to.
1251                 if (!Config::get('system', 'no_count', false)) {
1252                         $order_field = defaults($_GET, 'order', '');
1253                         if ($order_field === 'posted') {
1254                                 $order = 'ASC';
1255                         } else {
1256                                 $order = 'DESC';
1257                         }
1258
1259                         $prvnxt = q("SELECT `resource-id` FROM `photo` WHERE `album` = '%s' AND `uid` = %d AND `scale` = 0
1260                                 $sql_extra ORDER BY `created` $order ",
1261                                 dbesc($ph[0]['album']),
1262                                 intval($owner_uid)
1263                         );
1264
1265                         if (DBM::is_result($prvnxt)) {
1266                                 foreach ($prvnxt as $z => $entry) {
1267                                         if ($entry['resource-id'] == $ph[0]['resource-id']) {
1268                                                 $prv = $z - 1;
1269                                                 $nxt = $z + 1;
1270                                                 if ($prv < 0) {
1271                                                         $prv = count($prvnxt) - 1;
1272                                                 }
1273                                                 if ($nxt >= count($prvnxt)) {
1274                                                         $nxt = 0;
1275                                                 }
1276                                                 break;
1277                                         }
1278                                 }
1279                                 $edit_suffix = ((($cmd === 'edit') && $can_post) ? '/edit' : '');
1280                                 $prevlink = 'photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$prv]['resource-id'] . $edit_suffix . ($order_field === 'posted' ? '?f=&order=posted' : '');
1281                                 $nextlink = 'photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$nxt]['resource-id'] . $edit_suffix . ($order_field === 'posted' ? '?f=&order=posted' : '');
1282                         }
1283                 }
1284
1285                 if (count($ph) == 1)
1286                         $hires = $lores = $ph[0];
1287                 if (count($ph) > 1) {
1288                         if ($ph[1]['scale'] == 2) {
1289                                 // original is 640 or less, we can display it directly
1290                                 $hires = $lores = $ph[0];
1291                         } else {
1292                                 $hires = $ph[0];
1293                                 $lores = $ph[1];
1294                         }
1295                 }
1296
1297                 $album_link = 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($ph[0]['album']);
1298                 $tools = null;
1299                 $lock = null;
1300
1301                 if ($can_post && ($ph[0]['uid'] == $owner_uid)) {
1302                         $tools = [
1303                                 'edit'  => ['photos/' . $a->data['user']['nickname'] . '/image/' . $datum . (($cmd === 'edit') ? '' : '/edit'), (($cmd === 'edit') ? L10n::t('View photo') : L10n::t('Edit photo'))],
1304                                 'profile'=>['profile_photo/use/'.$ph[0]['resource-id'], L10n::t('Use as profile photo')],
1305                         ];
1306
1307                         // lock
1308                         $lock = ( ( ($ph[0]['uid'] == local_user()) && (strlen($ph[0]['allow_cid']) || strlen($ph[0]['allow_gid'])
1309                                         || strlen($ph[0]['deny_cid']) || strlen($ph[0]['deny_gid'])) )
1310                                         ? L10n::t('Private Message')
1311                                         : Null);
1312
1313
1314                 }
1315
1316                 if ( $cmd === 'edit') {
1317                         $tpl = get_markup_template('photo_edit_head.tpl');
1318                         $a->page['htmlhead'] .= replace_macros($tpl,[
1319                                 '$prevlink' => $prevlink,
1320                                 '$nextlink' => $nextlink
1321                         ]);
1322                 }
1323
1324                 if ($prevlink)
1325                         $prevlink = [$prevlink, '<div class="icon prev"></div>'] ;
1326
1327                 $photo = [
1328                         'href' => 'photo/' . $hires['resource-id'] . '-' . $hires['scale'] . '.' . $phototypes[$hires['type']],
1329                         'title'=> L10n::t('View Full Size'),
1330                         'src'  => 'photo/' . $lores['resource-id'] . '-' . $lores['scale'] . '.' . $phototypes[$lores['type']] . '?f=&_u=' . DateTimeFormat::utcNow('ymdhis'),
1331                         'height' => $hires['height'],
1332                         'width' => $hires['width'],
1333                         'album' => $hires['album'],
1334                         'filename' => $hires['filename'],
1335                 ];
1336
1337                 if ($nextlink) {
1338                         $nextlink = [$nextlink, '<div class="icon next"></div>'];
1339                 }
1340
1341
1342                 // Do we have an item for this photo?
1343
1344                 // FIXME! - replace following code to display the conversation with our normal
1345                 // conversation functions so that it works correctly and tracks changes
1346                 // in the evolving conversation code.
1347                 // The difference is that we won't be displaying the conversation head item
1348                 // as a "post" but displaying instead the photo it is linked to
1349
1350                 $linked_items = q("SELECT * FROM `item` WHERE `resource-id` = '%s' $sql_extra LIMIT 1",
1351                         dbesc($datum)
1352                 );
1353
1354                 $map = null;
1355                 $link_item = [];
1356
1357                 if (DBM::is_result($linked_items)) {
1358                         $link_item = $linked_items[0];
1359
1360                         $r = q("SELECT COUNT(*) AS `total`
1361                                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1362                                 WHERE `parent-uri` = '%s' AND `uri` != '%s' AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1363                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1364                                 AND `item`.`uid` = %d
1365                                 $sql_extra ",
1366                                 dbesc($link_item['uri']),
1367                                 dbesc($link_item['uri']),
1368                                 intval($link_item['uid'])
1369
1370                         );
1371
1372                         if (DBM::is_result($r)) {
1373                                 $a->set_pager_total($r[0]['total']);
1374                         }
1375
1376
1377                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
1378                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`network`,
1379                                 `contact`.`rel`, `contact`.`thumb`, `contact`.`self`,
1380                                 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1381                                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1382                                 WHERE `parent-uri` = '%s' AND `uri` != '%s' AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1383                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1384                                 AND `item`.`uid` = %d
1385                                 $sql_extra
1386                                 ORDER BY `parent` DESC, `id` ASC LIMIT %d ,%d ",
1387                                 dbesc($link_item['uri']),
1388                                 dbesc($link_item['uri']),
1389                                 intval($link_item['uid']),
1390                                 intval($a->pager['start']),
1391                                 intval($a->pager['itemspage'])
1392
1393                         );
1394
1395                         if (local_user() && (local_user() == $link_item['uid'])) {
1396                                 Item::update(['unseen' => false], ['parent' => $link_item['parent']]);
1397                         }
1398
1399                         if ($link_item['coord']) {
1400                                 $map = Map::byCoordinates($link_item['coord']);
1401                         }
1402                 }
1403
1404                 $tags = null;
1405
1406                 if (count($linked_items) && strlen($link_item['tag'])) {
1407                         $arr = explode(',', $link_item['tag']);
1408                         // parse tags and add links
1409                         $tag_str = '';
1410                         foreach ($arr as $t) {
1411                                 if (strlen($tag_str)) {
1412                                         $tag_str .= ', ';
1413                                 }
1414                                 $tag_str .= bbcode($t);
1415                         }
1416                         $tags = [L10n::t('Tags: '), $tag_str];
1417                         if ($cmd === 'edit') {
1418                                 $tags[] = 'tagrm/' . $link_item['id'];
1419                                 $tags[] = L10n::t('[Remove any tag]');
1420                         }
1421                 }
1422
1423
1424                 $edit = Null;
1425                 if ($cmd === 'edit' && $can_post) {
1426                         $edit_tpl = get_markup_template('photo_edit.tpl');
1427
1428                         $album_e = $ph[0]['album'];
1429                         $caption_e = $ph[0]['desc'];
1430                         $aclselect_e = populate_acl($ph[0]);
1431
1432                         $edit = replace_macros($edit_tpl, [
1433                                 '$id' => $ph[0]['id'],
1434                                 '$album' => ['albname', L10n::t('New album name'), $album_e,''],
1435                                 '$caption' => ['desc', L10n::t('Caption'), $caption_e, ''],
1436                                 '$tags' => ['newtag', L10n::t('Add a Tag'), "", L10n::t('Example: @bob, @Barbara_Jensen, @jim@example.com, #California, #camping')],
1437                                 '$rotate_none' => ['rotate', L10n::t('Do not rotate'),0,'', true],
1438                                 '$rotate_cw' => ['rotate', L10n::t("Rotate CW \x28right\x29"),1,''],
1439                                 '$rotate_ccw' => ['rotate', L10n::t("Rotate CCW \x28left\x29"),2,''],
1440
1441                                 '$nickname' => $a->data['user']['nickname'],
1442                                 '$resource_id' => $ph[0]['resource-id'],
1443                                 '$permissions' => L10n::t('Permissions'),
1444                                 '$aclselect' => $aclselect_e,
1445
1446                                 '$item_id' => defaults($link_item, 'id', 0),
1447                                 '$submit' => L10n::t('Submit'),
1448                                 '$delete' => L10n::t('Delete Photo'),
1449
1450                                 // ACL permissions box
1451                                 '$group_perms' => L10n::t('Show to Groups'),
1452                                 '$contact_perms' => L10n::t('Show to Contacts'),
1453                                 '$return_path' => $a->query_string,
1454                         ]);
1455                 }
1456
1457                 $like = '';
1458                 $dislike = '';
1459                 $likebuttons = '';
1460                 $comments = '';
1461                 $paginate = '';
1462                 $responses = '';
1463
1464                 if (count($linked_items)) {
1465                         $cmnt_tpl = get_markup_template('comment_item.tpl');
1466                         $tpl = get_markup_template('photo_item.tpl');
1467                         $return_url = $a->cmd;
1468
1469                         if ($can_post || can_write_wall($owner_uid)) {
1470                                 $like_tpl = get_markup_template('like_noshare.tpl');
1471                                 $likebuttons = replace_macros($like_tpl, [
1472                                         '$id' => $link_item['id'],
1473                                         '$likethis' => L10n::t("I like this \x28toggle\x29"),
1474                                         '$nolike' => (Feature::isEnabled(local_user(), 'dislike') ? L10n::t("I don't like this \x28toggle\x29") : ''),
1475                                         '$wait' => L10n::t('Please wait'),
1476                                         '$return_path' => $a->query_string,
1477                                 ]);
1478                         }
1479
1480                         if (!DBM::is_result($r)) {
1481                                 if (($can_post || can_write_wall($owner_uid))) {
1482                                         $comments .= replace_macros($cmnt_tpl, [
1483                                                 '$return_path' => '',
1484                                                 '$jsreload' => $return_url,
1485                                                 '$type' => 'wall-comment',
1486                                                 '$id' => $link_item['id'],
1487                                                 '$parent' => $link_item['id'],
1488                                                 '$profile_uid' =>  $owner_uid,
1489                                                 '$mylink' => $contact['url'],
1490                                                 '$mytitle' => L10n::t('This is you'),
1491                                                 '$myphoto' => $contact['thumb'],
1492                                                 '$comment' => L10n::t('Comment'),
1493                                                 '$submit' => L10n::t('Submit'),
1494                                                 '$preview' => L10n::t('Preview'),
1495                                                 '$sourceapp' => L10n::t($a->sourcename),
1496                                                 '$ww' => '',
1497                                                 '$rand_num' => random_digits(12)
1498                                         ]);
1499                                 }
1500                         }
1501
1502                         $conv_responses = [
1503                                 'like' => ['title' => L10n::t('Likes','title')],'dislike' => ['title' => L10n::t('Dislikes','title')],
1504                                 'attendyes' => ['title' => L10n::t('Attending','title')], 'attendno' => ['title' => L10n::t('Not attending','title')], 'attendmaybe' => ['title' => L10n::t('Might attend','title')]
1505                         ];
1506
1507                         // display comments
1508                         if (DBM::is_result($r)) {
1509                                 foreach ($r as $item) {
1510                                         builtin_activity_puller($item, $conv_responses);
1511                                 }
1512
1513                                 if (x($conv_responses['like'], $link_item['uri'])) {
1514                                         $like = format_like($conv_responses['like'][$link_item['uri']], $conv_responses['like'][$link_item['uri'] . '-l'], 'like', $link_item['id']);
1515                                 }
1516                                 if (x($conv_responses['dislike'], $link_item['uri'])) {
1517                                         $dislike = format_like($conv_responses['dislike'][$link_item['uri']], $conv_responses['dislike'][$link_item['uri'] . '-l'], 'dislike', $link_item['id']);
1518                                 }
1519
1520                                 if (($can_post || can_write_wall($owner_uid))) {
1521                                         $comments .= replace_macros($cmnt_tpl,[
1522                                                 '$return_path' => '',
1523                                                 '$jsreload' => $return_url,
1524                                                 '$type' => 'wall-comment',
1525                                                 '$id' => $link_item['id'],
1526                                                 '$parent' => $link_item['id'],
1527                                                 '$profile_uid' =>  $owner_uid,
1528                                                 '$mylink' => $contact['url'],
1529                                                 '$mytitle' => L10n::t('This is you'),
1530                                                 '$myphoto' => $contact['thumb'],
1531                                                 '$comment' => L10n::t('Comment'),
1532                                                 '$submit' => L10n::t('Submit'),
1533                                                 '$preview' => L10n::t('Preview'),
1534                                                 '$sourceapp' => L10n::t($a->sourcename),
1535                                                 '$ww' => '',
1536                                                 '$rand_num' => random_digits(12)
1537                                         ]);
1538                                 }
1539
1540                                 foreach ($r as $item) {
1541                                         $comment = '';
1542                                         $template = $tpl;
1543                                         $sparkle = '';
1544
1545                                         if ((activity_match($item['verb'], ACTIVITY_LIKE) || activity_match($item['verb'], ACTIVITY_DISLIKE)) && ($item['id'] != $item['parent'])) {
1546                                                 continue;
1547                                         }
1548
1549                                         $redirect_url = 'redir/' . $item['cid'];
1550
1551                                         if (local_user() && ($item['contact-uid'] == local_user())
1552                                                 && ($item['network'] == NETWORK_DFRN) && !$item['self']) {
1553                                                 $profile_url = $redirect_url;
1554                                                 $sparkle = ' sparkle';
1555                                         } else {
1556                                                 $profile_url = $item['url'];
1557                                                 $sparkle = '';
1558                                         }
1559
1560                                         $diff_author = (($item['url'] !== $item['author-link']) ? true : false);
1561
1562                                         $profile_name   = ((strlen($item['author-name'])   && $diff_author) ? $item['author-name']   : $item['name']);
1563                                         $profile_avatar = ((strlen($item['author-avatar']) && $diff_author) ? $item['author-avatar'] : $item['thumb']);
1564
1565                                         $profile_link = $profile_url;
1566
1567                                         $dropping = (($item['contact-id'] == $contact_id) || ($item['uid'] == local_user()));
1568                                         $drop = [
1569                                                 'dropping' => $dropping,
1570                                                 'pagedrop' => false,
1571                                                 'select' => L10n::t('Select'),
1572                                                 'delete' => L10n::t('Delete'),
1573                                         ];
1574
1575                                         $name_e = $profile_name;
1576                                         $title_e = $item['title'];
1577                                         $body_e = bbcode($item['body']);
1578
1579                                         $comments .= replace_macros($template,[
1580                                                 '$id' => $item['item_id'],
1581                                                 '$profile_url' => $profile_link,
1582                                                 '$name' => $name_e,
1583                                                 '$thumb' => $profile_avatar,
1584                                                 '$sparkle' => $sparkle,
1585                                                 '$title' => $title_e,
1586                                                 '$body' => $body_e,
1587                                                 '$ago' => Temporal::getRelativeDate($item['created']),
1588                                                 '$indent' => (($item['parent'] != $item['item_id']) ? ' comment' : ''),
1589                                                 '$drop' => $drop,
1590                                                 '$comment' => $comment
1591                                         ]);
1592
1593                                         if (($can_post || can_write_wall($owner_uid))) {
1594                                                 $comments .= replace_macros($cmnt_tpl, [
1595                                                         '$return_path' => '',
1596                                                         '$jsreload' => $return_url,
1597                                                         '$type' => 'wall-comment',
1598                                                         '$id' => $item['item_id'],
1599                                                         '$parent' => $item['parent'],
1600                                                         '$profile_uid' =>  $owner_uid,
1601                                                         '$mylink' => $contact['url'],
1602                                                         '$mytitle' => L10n::t('This is you'),
1603                                                         '$myphoto' => $contact['thumb'],
1604                                                         '$comment' => L10n::t('Comment'),
1605                                                         '$submit' => L10n::t('Submit'),
1606                                                         '$preview' => L10n::t('Preview'),
1607                                                         '$sourceapp' => L10n::t($a->sourcename),
1608                                                         '$ww' => '',
1609                                                         '$rand_num' => random_digits(12)
1610                                                 ]);
1611                                         }
1612                                 }
1613                         }
1614                         $response_verbs = ['like'];
1615                         if (Feature::isEnabled($owner_uid, 'dislike')) {
1616                                 $response_verbs[] = 'dislike';
1617                         }
1618                         $responses = get_responses($conv_responses, $response_verbs, '', $link_item);
1619
1620                         $paginate = paginate($a);
1621                 }
1622
1623                 $photo_tpl = get_markup_template('photo_view.tpl');
1624                 $o .= replace_macros($photo_tpl, [
1625                         '$id' => $ph[0]['id'],
1626                         '$album' => [$album_link, $ph[0]['album']],
1627                         '$tools' => $tools,
1628                         '$lock' => $lock,
1629                         '$photo' => $photo,
1630                         '$prevlink' => $prevlink,
1631                         '$nextlink' => $nextlink,
1632                         '$desc' => $ph[0]['desc'],
1633                         '$tags' => $tags,
1634                         '$edit' => $edit,
1635                         '$map' => $map,
1636                         '$map_text' => L10n::t('Map'),
1637                         '$likebuttons' => $likebuttons,
1638                         '$like' => $like,
1639                         '$dislike' => $dislike,
1640                         'responses' => $responses,
1641                         '$comments' => $comments,
1642                         '$paginate' => $paginate,
1643                 ]);
1644
1645                 $a->page['htmlhead'] .= "\n" . '<meta name="twitter:card" content="photo" />' . "\n";
1646                 $a->page['htmlhead'] .= '<meta name="twitter:title" content="' . $photo["album"] . '" />' . "\n";
1647                 $a->page['htmlhead'] .= '<meta name="twitter:image" content="' . $photo["href"] . '" />' . "\n";
1648                 $a->page['htmlhead'] .= '<meta name="twitter:image:width" content="' . $photo["width"] . '" />' . "\n";
1649                 $a->page['htmlhead'] .= '<meta name="twitter:image:height" content="' . $photo["height"] . '" />' . "\n";
1650
1651                 return $o;
1652         }
1653
1654         // Default - show recent photos with upload link (if applicable)
1655         //$o = '';
1656
1657         $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s'
1658                 $sql_extra GROUP BY `resource-id`",
1659                 intval($a->data['user']['uid']),
1660                 dbesc('Contact Photos'),
1661                 dbesc(L10n::t('Contact Photos'))
1662         );
1663         if (DBM::is_result($r)) {
1664                 $a->set_pager_total(count($r));
1665                 $a->set_pager_itemspage(20);
1666         }
1667
1668         $r = q("SELECT `resource-id`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`filename`) AS `filename`,
1669                 ANY_VALUE(`type`) AS `type`, ANY_VALUE(`album`) AS `album`, max(`scale`) AS `scale`,
1670                 ANY_VALUE(`created`) AS `created` FROM `photo`
1671                 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s'
1672                 $sql_extra GROUP BY `resource-id` ORDER BY `created` DESC LIMIT %d , %d",
1673                 intval($a->data['user']['uid']),
1674                 dbesc('Contact Photos'),
1675                 dbesc(L10n::t('Contact Photos')),
1676                 intval($a->pager['start']),
1677                 intval($a->pager['itemspage'])
1678         );
1679
1680         $photos = [];
1681         if (DBM::is_result($r)) {
1682                 // "Twist" is only used for the duepunto theme with style "slackr"
1683                 $twist = false;
1684                 foreach ($r as $rr) {
1685                         //hide profile photos to others
1686                         if (!$is_owner && !remote_user() && ($rr['album'] == L10n::t('Profile Photos')))
1687                                 continue;
1688
1689                         $twist = !$twist;
1690
1691                         $ext = $phototypes[$rr['type']];
1692
1693                         $alt_e = $rr['filename'];
1694                         $name_e = $rr['album'];
1695
1696                         $photos[] = [
1697                                 'id'            => $rr['id'],
1698                                 'twist'         => ' ' . ($twist ? 'rotleft' : 'rotright') . rand(2,4),
1699                                 'link'          => 'photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id'],
1700                                 'title'         => L10n::t('View Photo'),
1701                                 'src'           => 'photo/' . $rr['resource-id'] . '-' . ((($rr['scale']) == 6) ? 4 : $rr['scale']) . '.' . $ext,
1702                                 'alt'           => $alt_e,
1703                                 'album' => [
1704                                         'link'  => 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($rr['album']),
1705                                         'name'  => $name_e,
1706                                         'alt'   => L10n::t('View Album'),
1707                                 ],
1708
1709                         ];
1710                 }
1711         }
1712
1713         $tpl = get_markup_template('photos_recent.tpl');
1714         $o .= replace_macros($tpl, [
1715                 '$title' => L10n::t('Recent Photos'),
1716                 '$can_post' => $can_post,
1717                 '$upload' => [L10n::t('Upload New Photos'), 'photos/'.$a->data['user']['nickname'].'/upload'],
1718                 '$photos' => $photos,
1719                 '$paginate' => paginate($a),
1720         ]);
1721
1722         return $o;
1723 }