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