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