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