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