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