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