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