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