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