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