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