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