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