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