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