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