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