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