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