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