]> git.mxchange.org Git - friendica.git/blob - mod/photos.php
efeab8fa3c3ab87b164b9f4aa08e4a0debe00b4c
[friendica.git] / mod / photos.php
1 <?php
2 require_once('include/Photo.php');
3 require_once('include/items.php');
4 require_once('include/acl_selectors.php');
5 require_once('include/bbcode.php');
6 require_once('include/security.php');
7
8
9 function photos_init(&$a) {
10
11
12         if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
13                 return;
14         }
15         $o = '';
16
17         if($a->argc > 1) {
18                 $nick = $a->argv[1];
19                 $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' AND `blocked` = 0 LIMIT 1",
20                         dbesc($nick)
21                 );
22
23                 if(! count($r))
24                         return;
25
26                 $a->data['user'] = $r[0];
27
28                 $sql_extra = permissions_sql($a->data['user']['uid']);
29
30                 $albums = q("SELECT distinct(`album`) AS `album` FROM `photo` WHERE `uid` = %d $sql_extra ",
31                         intval($a->data['user']['uid'])
32                 );
33
34                 if(count($albums)) {
35                         $a->data['albums'] = $albums;
36
37                         $o .= '<div class="vcard">';
38                         $o .= '<div class="fn">' . $a->data['user']['username'] . '</div>';
39                         $o .= '<div id="profile-photo-wrapper"><img class="photo" style="width: 175px; height: 175px;" src="' . $a->get_baseurl() . '/photo/profile/' . $a->data['user']['uid'] . '.jpg" alt="' . $a->data['user']['username'] . '" /></div>';
40                         $o .= '</div>';
41                         
42                         if(! intval($a->data['user']['hidewall'])) {
43                                 $o .= '<div id="side-bar-photos-albums" class="widget">';
44                                 $o .= '<h3>' . '<a href="' . $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '">' . t('Photo Albums') . '</a></h3>';
45                                         
46                                 $o .= '<ul>';
47                                 foreach($albums as $album) {
48
49                                         // don't show contact photos. We once translated this name, but then you could still access it under
50                                         // a different language setting. Now we store the name in English and check in English (and translated for legacy albums).
51
52                                         if((! strlen($album['album'])) || ($album['album'] === 'Contact Photos') || ($album['album'] === t('Contact Photos')))
53                                                 continue;
54                                         $o .= '<li>' . '<a href="photos/' . $a->argv[1] . '/album/' . bin2hex($album['album']) . '" >' . $album['album'] . '</a></li>'; 
55                                 }
56                                 $o .= '</ul>';
57                         }
58                         if(local_user() && $a->data['user']['uid'] == local_user()) {
59                                 $o .= '<div id="photo-albums-upload-link"><a href="' . $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/upload" >' .t('Upload New Photos') . '</a></div>';
60                         }
61
62                         $o .= '</div>';
63                 }
64
65                 if(! x($a->page,'aside'))
66                         $a->page['aside'] = '';
67                 $a->page['aside'] .= $o;
68
69
70                 $a->page['htmlhead'] .= "<script> var ispublic = '" . t('everybody') . "';" ;
71
72                 $a->page['htmlhead'] .= <<< EOT
73
74                 $(document).ready(function() {
75
76                         $('#contact_allow, #contact_deny, #group_allow, #group_deny').change(function() {
77                                 var selstr;
78                                 $('#contact_allow option:selected, #contact_deny option:selected, #group_allow option:selected, #group_deny option:selected').each( function() {
79                                         selstr = $(this).text();
80                                         $('#jot-perms-icon').removeClass('unlock').addClass('lock');
81                                         $('#jot-public').hide();
82                                 });
83                                 if(selstr == null) { 
84                                         $('#jot-perms-icon').removeClass('lock').addClass('unlock');
85                                         $('#jot-public').show();
86                                 }
87
88                         }).trigger('change');
89
90                 });
91
92                 </script>
93 EOT;
94         }
95
96         return;
97 }
98
99
100
101 function photos_post(&$a) {
102
103         logger('mod-photos: photos_post: begin' , LOGGER_DEBUG);
104
105
106         logger('mod_photos: REQUEST ' . print_r($_REQUEST,true), LOGGER_DATA);
107         logger('mod_photos: FILES '   . print_r($_FILES,true), LOGGER_DATA);
108
109         $phototypes = Photo::supportedTypes();
110
111         $can_post  = false;
112         $visitor   = 0;
113
114         $page_owner_uid = $a->data['user']['uid'];
115         $community_page = (($a->data['user']['page-flags'] == PAGE_COMMUNITY) ? true : false);
116
117         if((local_user()) && (local_user() == $page_owner_uid))
118                 $can_post = true;
119         else {
120                 if($community_page && remote_user()) {
121                         $r = q("SELECT `uid` FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1",
122                                 intval(remote_user()),
123                                 intval($page_owner_uid)
124                         );
125                         if(count($r)) {
126                                 $can_post = true;
127                                 $visitor = remote_user();
128                         }
129                 }
130         }
131
132         if(! $can_post) {
133                 notice( t('Permission denied.') . EOL );
134                 killme();
135         }
136
137         $r = q("SELECT `contact`.*, `user`.`nickname` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` 
138                 WHERE `user`.`uid` = %d AND `self` = 1 LIMIT 1",
139                 intval($page_owner_uid)
140         );
141
142         if(! count($r)) {
143                 notice( t('Contact information unavailable') . EOL);
144                 logger('photos_post: unable to locate contact record for page owner. uid=' . $page_owner_uid);
145                 killme();
146         }
147
148         $owner_record = $r[0];  
149
150
151         if(($a->argc > 3) && ($a->argv[2] === 'album')) {
152                 $album = hex2bin($a->argv[3]);
153
154                 if($album === t('Profile Photos') || $album === 'Contact Photos' || $album === t('Contact Photos')) {
155                         goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
156                         return; // NOTREACHED
157                 }
158
159                 $r = q("SELECT count(*) FROM `photo` WHERE `album` = '%s' AND `uid` = %d",
160                         dbesc($album),
161                         intval($page_owner_uid)
162                 );
163                 if(! count($r)) {
164                         notice( t('Album not found.') . EOL);
165                         goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
166                         return; // NOTREACHED
167                 }
168
169                 $newalbum = notags(trim($_POST['albumname']));
170                 if($newalbum != $album) {
171                         q("UPDATE `photo` SET `album` = '%s' WHERE `album` = '%s' AND `uid` = %d",
172                                 dbesc($newalbum),
173                                 dbesc($album),
174                                 intval($page_owner_uid)
175                         );
176                         $newurl = str_replace(bin2hex($album),bin2hex($newalbum),$_SESSION['photo_return']);
177                         goaway($a->get_baseurl() . '/' . $newurl);
178                         return; // NOTREACHED
179                 }
180
181
182                 if($_POST['dropalbum'] == t('Delete Album')) {
183
184                         $res = array();
185
186                         // get the list of photos we are about to delete
187
188                         if($visitor) {
189                                 $r = q("SELECT distinct(`resource-id`) as `rid` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d AND `album` = '%s'",
190                                         intval($visitor),
191                                         intval($page_owner_uid),
192                                         dbesc($album)
193                                 );
194                         }
195                         else {
196                                 $r = q("SELECT distinct(`resource-id`) as `rid` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
197                                         intval(local_user()),
198                                         dbesc($album)
199                                 );
200                         }
201                         if(count($r)) {
202                                 foreach($r as $rr) {
203                                         $res[] = "'" . dbesc($rr['rid']) . "'" ;
204                                 }
205                         }
206                         else {
207                                 goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
208                                 return; // NOTREACHED
209                         }
210
211                         $str_res = implode(',', $res);
212
213                         // remove the associated photos
214
215                         q("DELETE FROM `photo` WHERE `resource-id` IN ( $str_res ) AND `uid` = %d",
216                                 intval($page_owner_uid)
217                         );
218
219                         // find and delete the corresponding item with all the comments and likes/dislikes
220
221                         $r = q("SELECT `parent-uri` FROM `item` WHERE `resource-id` IN ( $str_res ) AND `uid` = %d",
222                                 intval($page_owner_uid)
223                         );
224                         if(count($r)) {
225                                 foreach($r as $rr) {
226                                         q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
227                                                 dbesc(datetime_convert()),
228                                                 dbesc($rr['parent-uri']),
229                                                 intval($page_owner_uid)
230                                         );
231
232                                         $drop_id = intval($rr['id']);
233
234                                         // send the notification upstream/downstream as the case may be
235
236                                         if($rr['visible'])
237                                                 proc_run('php',"include/notifier.php","drop","$drop_id");
238                                 }
239                         }
240                 }
241                 goaway($a->get_baseurl() . '/photos/' . $a->data['user']['nickname']);
242                 return; // NOTREACHED
243         }
244
245         if(($a->argc > 2) && (x($_POST,'delete')) && ($_POST['delete'] == t('Delete Photo'))) {
246
247                 // same as above but remove single photo
248
249                 if($visitor) {
250                         $r = q("SELECT `id`, `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d AND `resource-id` = '%s' LIMIT 1",
251                                 intval($visitor),
252                                 intval($page_owner_uid),
253                                 dbesc($a->argv[2])
254                         );
255                 }
256                 else {
257                         $r = q("SELECT `id`, `resource-id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' LIMIT 1",
258                                 intval(local_user()),
259                                 dbesc($a->argv[2])
260                         );
261                 }
262                 if(count($r)) {
263                         q("DELETE FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
264                                 intval($page_owner_uid),
265                                 dbesc($r[0]['resource-id'])
266                         );
267                         $i = q("SELECT * FROM `item` WHERE `resource-id` = '%s' AND `uid` = %d LIMIT 1",
268                                 dbesc($r[0]['resource-id']),
269                                 intval($page_owner_uid)
270                         );
271                         if(count($i)) {
272                                 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
273                                         dbesc(datetime_convert()),
274                                         dbesc(datetime_convert()),
275                                         dbesc($i[0]['uri']),
276                                         intval($page_owner_uid)
277                                 );
278
279                                 $url = $a->get_baseurl();
280                                 $drop_id = intval($i[0]['id']);
281
282                                 if($i[0]['visible'])
283                                         proc_run('php',"include/notifier.php","drop","$drop_id");
284                         }
285                 }
286
287                 goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
288                 return; // NOTREACHED
289         }
290
291         if(($a->argc > 2) && ((x($_POST,'desc') !== false) || (x($_POST,'newtag') !== false)) || (x($_POST,'albname') !== false)) {
292
293
294                 $desc        = ((x($_POST,'desc'))    ? notags(trim($_POST['desc']))    : '');
295                 $rawtags     = ((x($_POST,'newtag'))  ? notags(trim($_POST['newtag']))  : '');
296                 $item_id     = ((x($_POST,'item_id')) ? intval($_POST['item_id'])       : 0);
297                 $albname     = ((x($_POST,'albname')) ? notags(trim($_POST['albname'])) : '');
298                 $str_group_allow   = perms2str($_POST['group_allow']);
299                 $str_contact_allow = perms2str($_POST['contact_allow']);
300                 $str_group_deny    = perms2str($_POST['group_deny']);
301                 $str_contact_deny  = perms2str($_POST['contact_deny']);
302
303                 $resource_id = $a->argv[2];
304
305                 if(! strlen($albname))
306                         $albname = datetime_convert('UTC',date_default_timezone_get(),'now', 'Y');
307
308
309                 if((x($_POST,'rotate') !== false) && (intval($_POST['rotate']) == 1)) {
310                         logger('rotate');
311
312                         $r = q("select * from photo where `resource-id` = '%s' and uid = %d and scale = 0 limit 1",
313                                 dbesc($resource_id),
314                                 intval($page_owner_uid)
315                         );
316                         if(count($r)) {
317                                 $ph = new Photo($r[0]['data'], $r[0]['type']);
318                                 if($ph->is_valid()) {
319                                         $ph->rotate(270);
320
321                                         $width  = $ph->getWidth();
322                                         $height = $ph->getHeight();
323
324                                         $x = q("update photo set data = '%s', height = %d, width = %d where `resource-id` = '%s' and uid = %d and scale = 0 limit 1",
325                                                 dbesc($ph->imageString()),
326                                                 intval($height),
327                                                 intval($width),
328                                 dbesc($resource_id),
329                                 intval($page_owner_uid)
330                                         );
331
332                                         if($width > 640 || $height > 640) {
333                                                 $ph->scaleImage(640);
334                                                 $width  = $ph->getWidth();
335                                                 $height = $ph->getHeight();
336                 
337                                                 $x = q("update photo set data = '%s', height = %d, width = %d where `resource-id` = '%s' and uid = %d and scale = 1 limit 1",
338                                                         dbesc($ph->imageString()),
339                                                         intval($height),
340                                                         intval($width),
341                                 dbesc($resource_id),
342                                 intval($page_owner_uid)
343                                                 );
344                                         }
345
346                                         if($width > 320 || $height > 320) {
347                                                 $ph->scaleImage(320);
348                                                 $width  = $ph->getWidth();
349                                                 $height = $ph->getHeight();
350
351                                                 $x = q("update photo set data = '%s', height = %d, width = %d where `resource-id` = '%s' and uid = %d and scale = 2 limit 1",
352                                                         dbesc($ph->imageString()),
353                                                         intval($height),
354                                                         intval($width),
355                                 dbesc($resource_id),
356                                 intval($page_owner_uid)
357                                                 );
358                                         }       
359                                 }
360                         }
361                 }
362
363                 $p = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ORDER BY `scale` DESC",
364                         dbesc($resource_id),
365                         intval($page_owner_uid)
366                 );
367                 if(count($p)) {
368                         $ext = $phototypes[$p[0]['type']];
369                         $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",
370                                 dbesc($desc),
371                                 dbesc($albname),
372                                 dbesc($str_contact_allow),
373                                 dbesc($str_group_allow),
374                                 dbesc($str_contact_deny),
375                                 dbesc($str_group_deny),
376                                 dbesc($resource_id),
377                                 intval($page_owner_uid)
378                         );
379                 }
380
381                 /* Don't make the item visible if the only change was the album name */
382
383                 $visibility = 0;
384                 if($p[0]['desc'] !== $desc || strlen($rawtags))
385                         $visibility = 1;
386                 
387                 if(! $item_id) {
388
389                         // Create item container
390
391                         $title = '';
392                         $uri = item_new_uri($a->get_hostname(),$page_owner_uid);
393                         
394                         $arr = array();
395
396                         $arr['uid']           = $page_owner_uid;
397                         $arr['uri']           = $uri;
398                         $arr['parent-uri']    = $uri; 
399                         $arr['type']          = 'photo';
400                         $arr['wall']          = 1;
401                         $arr['resource-id']   = $p[0]['resource-id'];
402                         $arr['contact-id']    = $owner_record['id'];
403                         $arr['owner-name']    = $owner_record['name'];
404                         $arr['owner-link']    = $owner_record['url'];
405                         $arr['owner-avatar']  = $owner_record['thumb'];
406                         $arr['author-name']   = $owner_record['name'];
407                         $arr['author-link']   = $owner_record['url'];
408                         $arr['author-avatar'] = $owner_record['thumb'];
409                         $arr['title']         = $title;
410                         $arr['allow_cid']     = $p[0]['allow_cid'];
411                         $arr['allow_gid']     = $p[0]['allow_gid'];
412                         $arr['deny_cid']      = $p[0]['deny_cid'];
413                         $arr['deny_gid']      = $p[0]['deny_gid'];
414                         $arr['last-child']    = 1;
415                         $arr['visible']       = $visibility;
416                         $arr['origin']        = 1;
417                         
418                         $arr['body']          = '[url=' . $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $p[0]['resource-id'] . ']' 
419                                                 . '[img]' . $a->get_baseurl() . '/photo/' . $p[0]['resource-id'] . '-' . $p[0]['scale'] . '.'. $ext . '[/img]' 
420                                                 . '[/url]';
421                 
422                         $item_id = item_store($arr);
423
424                 }
425
426                 if($item_id) {
427                         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
428                                 intval($item_id),
429                                 intval($page_owner_uid)
430                         );
431                 }
432                 if(count($r)) {
433                         $old_tag    = $r[0]['tag'];
434                         $old_inform = $r[0]['inform'];
435                 }
436
437                 if(strlen($rawtags)) {
438
439                         $str_tags = '';
440                         $inform   = '';
441
442                         // if the new tag doesn't have a namespace specifier (@foo or #foo) give it a hashtag
443
444                         $x = substr($rawtags,0,1);
445                         if($x !== '@' && $x !== '#')
446                                 $rawtags = '#' . $rawtags;
447
448                         $taginfo = array();
449                         $tags = get_tags($rawtags);
450
451                         if(count($tags)) {
452                                 foreach($tags as $tag) {
453                                         if(isset($profile))
454                                                 unset($profile);
455                                         if(strpos($tag,'@') === 0) {
456                                                 $name = substr($tag,1);
457                                                 if((strpos($name,'@')) || (strpos($name,'http://'))) {
458                                                         $newname = $name;
459                                                         $links = @lrdd($name);
460                                                         if(count($links)) {
461                                                                 foreach($links as $link) {
462                                                                         if($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page')
463                                                         $profile = $link['@attributes']['href'];
464                                                                         if($link['@attributes']['rel'] === 'salmon') {
465                                                                                 $salmon = '$url:' . str_replace(',','%sc',$link['@attributes']['href']);
466                                                                                 if(strlen($inform))
467                                                                                         $inform .= ',';
468                                                         $inform .= $salmon;
469                                                                         }
470                                                                 }
471                                                         }
472                                                         $taginfo[] = array($newname,$profile,$salmon);
473                                                 }
474                                                 else {
475                                                         $newname = $name;
476                                                         $alias = '';
477                                                         $tagcid = 0;
478                                                         if(strrpos($newname,'+'))
479                                                                 $tagcid = intval(substr($newname,strrpos($newname,'+') + 1));
480
481                                                         if($tagcid) {
482                                                                 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
483                                                                         intval($tagcid),
484                                                                         intval($profile_uid)
485                                                                 );
486                                                         }
487                                                         elseif(strstr($name,'_') || strstr($name,' ')) {
488                                                                 $newname = str_replace('_',' ',$name);
489                                                                 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
490                                                                         dbesc($newname),
491                                                                         intval($page_owner_uid)
492                                                                 );
493                                                         }
494                                                         else {
495                                                                 $r = q("SELECT * FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
496                                                                         dbesc($name),
497                                                                         dbesc($name),
498                                                                         intval($page_owner_uid)
499                                                                 );
500                                                         }
501                                                         if(count($r)) {
502                                                                 $newname = $r[0]['name'];
503                                                                 $profile = $r[0]['url'];
504                                                                 $notify = 'cid:' . $r[0]['id'];
505                                                                 if(strlen($inform))
506                                                                         $inform .= ',';
507                                                                 $inform .= $notify;
508                                                         }
509                                                 }
510                                                 if($profile) {
511                                                         if(substr($notify,0,4) === 'cid:')
512                                                                 $taginfo[] = array($newname,$profile,$notify,$r[0],'@[url=' . str_replace(',','%2c',$profile) . ']' . $newname  . '[/url]');
513                                                         else
514                                                                 $taginfo[] = array($newname,$profile,$notify,null,$str_tags .= '@[url=' . $profile . ']' . $newname     . '[/url]');
515                                                         if(strlen($str_tags))
516                                                                 $str_tags .= ',';
517                                                         $profile = str_replace(',','%2c',$profile);
518                                                         $str_tags .= '@[url=' . $profile . ']' . $newname       . '[/url]';
519                                                 }
520                                         }
521                                 }
522                         }
523
524                         $newtag = $old_tag;
525                         if(strlen($newtag) && strlen($str_tags)) 
526                                 $newtag .= ',';
527                         $newtag .= $str_tags;
528
529                         $newinform = $old_inform;
530                         if(strlen($newinform) && strlen($inform))
531                                 $newinform .= ',';
532                         $newinform .= $inform;
533
534                         $r = q("UPDATE `item` SET `tag` = '%s', `inform` = '%s', `edited` = '%s', `changed` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
535                                 dbesc($newtag),
536                                 dbesc($newinform),
537                                 dbesc(datetime_convert()),
538                                 dbesc(datetime_convert()),
539                                 intval($item_id),
540                                 intval($page_owner_uid)
541                         );
542
543                         $best = 0;
544                         foreach($p as $scales) {
545                                 if(intval($scales['scale']) == 2) {
546                                         $best = 2;
547                                         break;
548                                 }
549                                 if(intval($scales['scale']) == 4) {
550                                         $best = 4;
551                                         break;
552                                 }
553                         }
554
555                         if(count($taginfo)) {
556                                 foreach($taginfo as $tagged) {
557                 
558                                         $uri = item_new_uri($a->get_hostname(),$page_owner_uid);
559
560                                         $arr = array();
561
562                                         $arr['uid']           = $page_owner_uid;
563                                         $arr['uri']           = $uri;
564                                         $arr['parent-uri']    = $uri;
565                                         $arr['type']          = 'activity';
566                                         $arr['wall']          = 1;
567                                         $arr['contact-id']    = $owner_record['id'];
568                                         $arr['owner-name']    = $owner_record['name'];
569                                         $arr['owner-link']    = $owner_record['url'];
570                                         $arr['owner-avatar']  = $owner_record['thumb'];
571                                         $arr['author-name']   = $owner_record['name'];
572                                         $arr['author-link']   = $owner_record['url'];
573                                         $arr['author-avatar'] = $owner_record['thumb'];
574                                         $arr['title']         = '';
575                                         $arr['allow_cid']     = $p[0]['allow_cid'];
576                                         $arr['allow_gid']     = $p[0]['allow_gid'];
577                                         $arr['deny_cid']      = $p[0]['deny_cid'];
578                                         $arr['deny_gid']      = $p[0]['deny_gid'];
579                                         $arr['last-child']    = 1;
580                                         $arr['visible']       = 1;
581                                         $arr['verb']          = ACTIVITY_TAG;
582                                         $arr['object-type']   = ACTIVITY_OBJ_PERSON;
583                                         $arr['target-type']   = ACTIVITY_OBJ_PHOTO;
584                                         $arr['tag']           = $tagged[4];
585                                         $arr['inform']        = $tagged[2];
586                                         $arr['origin']        = 1;
587                                         $arr['body']          = '[url=' . $tagged[1] . ']' . $tagged[0] . '[/url]' . ' ' . t('was tagged in a') . ' ' . '[url=' . $a->get_baseurl() . '/photos/' . $owner_record['nickname'] . '/image/' . $p[0]['resource-id'] . ']' . t('photo') . '[/url]' . ' ' . t('by') . ' ' . '[url=' . $owner_record['url'] . ']' . $owner_record['name'] . '[/url]' ;
588                                         $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" ;
589
590                                         $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $tagged[0] . '</title><id>' . $tagged[1] . '/' . $tagged[0] . '</id>';
591                                         $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $tagged[1] . '" />' . "\n");
592                                         if($tagged[3])
593                                                 $arr['object'] .= xmlify('<link rel="photo" type="'.$p[0]['type'].'" href="' . $tagged[3]['photo'] . '" />' . "\n");
594                                         $arr['object'] .= '</link></object>' . "\n";
595
596                                         $arr['target'] = '<target><type>' . ACTIVITY_OBJ_PHOTO . '</type><title>' . $p[0]['desc'] . '</title><id>'
597                                                 . $a->get_baseurl() . '/photos/' . $owner_record['nickname'] . '/image/' . $p[0]['resource-id'] . '</id>';
598                                         $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>';
599
600                                         $item_id = item_store($arr);
601                                         if($item_id) {
602                                                 q("UPDATE `item` SET `plink` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
603                                                         dbesc($a->get_baseurl() . '/display/' . $owner_record['nickname'] . '/' . $item_id),
604                                                         intval($page_owner_uid),
605                                                         intval($item_id)
606                                                 );
607
608                                                 proc_run('php',"include/notifier.php","tag","$item_id");
609                                         }
610                                 }
611
612                         }
613
614                 }
615                 goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
616                 return; // NOTREACHED
617         }
618
619
620         /**
621          * default post action - upload a photo
622          */
623
624         call_hooks('photo_post_init', $_POST);
625
626         /**
627          * Determine the album to use
628          */
629
630         $album    = notags(trim($_REQUEST['album']));
631         $newalbum = notags(trim($_REQUEST['newalbum']));
632
633         logger('mod/photos.php: photos_post(): album= ' . $album . ' newalbum= ' . $newalbum , LOGGER_DEBUG);
634
635         if(! strlen($album)) {
636                 if(strlen($newalbum))
637                         $album = $newalbum;
638                 else
639                         $album = datetime_convert('UTC',date_default_timezone_get(),'now', 'Y');
640         }
641
642         /**
643          *
644          * We create a wall item for every photo, but we don't want to
645          * overwhelm the data stream with a hundred newly uploaded photos.
646          * So we will make the first photo uploaded to this album in the last several hours
647          * visible by default, the rest will become visible over time when and if
648          * they acquire comments, likes, dislikes, and/or tags 
649          *
650          */
651
652         $r = q("SELECT * FROM `photo` WHERE `album` = '%s' AND `uid` = %d AND `created` > UTC_TIMESTAMP() - INTERVAL 3 HOUR ",
653                 dbesc($album),
654                 intval($page_owner_uid)
655         );
656         if((! count($r)) || ($album == t('Profile Photos')))
657                 $visible = 1;
658         else
659                 $visible = 0;
660         
661         if(intval($_REQUEST['not_visible']) || $_REQUEST['not_visible'] === 'true')
662                 $visible = 0;
663
664         $str_group_allow   = perms2str(((is_array($_REQUEST['group_allow']))   ? $_REQUEST['group_allow']   : explode(',',$_REQUEST['group_allow'])));
665         $str_contact_allow = perms2str(((is_array($_REQUEST['contact_allow'])) ? $_REQUEST['contact_allow'] : explode(',',$_REQUEST['contact_allow'])));
666         $str_group_deny    = perms2str(((is_array($_REQUEST['group_deny']))    ? $_REQUEST['group_deny']    : explode(',',$_REQUEST['group_deny'])));
667         $str_contact_deny  = perms2str(((is_array($_REQUEST['contact_deny']))  ? $_REQUEST['contact_deny']  : explode(',',$_REQUEST['contact_deny'])));
668
669         $ret = array('src' => '', 'filename' => '', 'filesize' => 0, 'type' => '');
670
671         call_hooks('photo_post_file',$ret);
672
673         if(x($ret,'src') && x($ret,'filesize')) {
674                 $src      = $ret['src'];
675                 $filename = $ret['filename'];
676                 $filesize = $ret['filesize'];
677                 $type     = $ret['type'];
678         }
679         else {
680                 $src        = $_FILES['userfile']['tmp_name'];
681                 $filename   = basename($_FILES['userfile']['name']);
682                 $filesize   = intval($_FILES['userfile']['size']);
683                 $type       = $_FILES['userfile']['type'];
684         }
685         if ($type=="") $type=guess_image_type($filename);
686
687         logger('photos: upload: received file: ' . $filename . ' as ' . $src . ' ('. $type . ') ' . $filesize . ' bytes', LOGGER_DEBUG);
688
689         $maximagesize = get_config('system','maximagesize');
690
691         if(($maximagesize) && ($filesize > $maximagesize)) {
692                 notice( t('Image exceeds size limit of ') . $maximagesize . EOL);
693                 @unlink($src);
694                 $foo = 0;
695                 call_hooks('photo_post_end',$foo);
696                 return;
697         }
698
699         if(! $filesize) {
700                 notice( t('Image file is empty.') . EOL);
701                 @unlink($src);
702                 $foo = 0;
703                 call_hooks('photo_post_end',$foo);
704                 return;
705         }
706
707         logger('mod/photos.php: photos_post(): loading the contents of ' . $src , LOGGER_DEBUG);
708
709         $imagedata = @file_get_contents($src);
710         $ph = new Photo($imagedata, $type);
711
712         if(! $ph->is_valid()) {
713                 logger('mod/photos.php: photos_post(): unable to process image' , LOGGER_DEBUG);
714                 notice( t('Unable to process image.') . EOL );
715                 @unlink($src);
716                 $foo = 0;
717                 call_hooks('photo_post_end',$foo);
718                 killme();
719         }
720
721         @unlink($src);
722
723         $width  = $ph->getWidth();
724         $height = $ph->getHeight();
725
726         $smallest = 0;
727
728         $photo_hash = photo_new_resource();
729
730         $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);
731
732         if(! $r) {
733                 logger('mod/photos.php: photos_post(): image store failed' , LOGGER_DEBUG);
734                 notice( t('Image upload failed.') . EOL );
735                 killme();
736         }
737
738         if($width > 640 || $height > 640) {
739                 $ph->scaleImage(640);
740                 $ph->store($page_owner_uid, $visitor, $photo_hash, $filename, $album, 1, 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
741                 $smallest = 1;
742         }
743
744         if($width > 320 || $height > 320) {
745                 $ph->scaleImage(320);
746                 $ph->store($page_owner_uid, $visitor, $photo_hash, $filename, $album, 2, 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
747                 $smallest = 2;
748         }
749         
750         $basename = basename($filename);
751         $uri = item_new_uri($a->get_hostname(), $page_owner_uid);
752
753         // Create item container
754
755         $arr = array();
756
757         $arr['uid']           = $page_owner_uid;
758         $arr['uri']           = $uri;
759         $arr['parent-uri']    = $uri;
760         $arr['type']          = 'photo';
761         $arr['wall']          = 1;
762         $arr['resource-id']   = $photo_hash;
763         $arr['contact-id']    = $owner_record['id'];
764         $arr['owner-name']    = $owner_record['name'];
765         $arr['owner-link']    = $owner_record['url'];
766         $arr['owner-avatar']  = $owner_record['thumb'];
767         $arr['author-name']   = $owner_record['name'];
768         $arr['author-link']   = $owner_record['url'];
769         $arr['author-avatar'] = $owner_record['thumb'];
770         $arr['title']         = '';
771         $arr['allow_cid']     = $str_contact_allow;
772         $arr['allow_gid']     = $str_group_allow;
773         $arr['deny_cid']      = $str_contact_deny;
774         $arr['deny_gid']      = $str_group_deny;
775         $arr['last-child']    = 1;
776         $arr['visible']       = $visible;
777         $arr['origin']        = 1;
778
779         $arr['body']          = '[url=' . $a->get_baseurl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo_hash . ']' 
780                                 . '[img]' . $a->get_baseurl() . "/photo/{$photo_hash}-{$smallest}.".$ph->getExt() . '[/img]' 
781                                 . '[/url]';
782
783         $item_id = item_store($arr);
784
785         if($item_id) {
786                 q("UPDATE `item` SET `plink` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
787                         dbesc($a->get_baseurl() . '/display/' . $owner_record['nickname'] . '/' . $item_id),
788                         intval($page_owner_uid),
789                         intval($item_id)
790                 );
791         }
792         
793         if($visible) 
794                 proc_run('php', "include/notifier.php", 'wall-new', $item_id);
795
796         call_hooks('photo_post_end',intval($item_id));
797
798         // addon uploaders should call "killme()" [e.g. exit] within the photo_post_end hook
799         // if they do not wish to be redirected
800
801         goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
802         // NOTREACHED
803 }
804
805
806
807 function photos_content(&$a) {
808
809         // URLs:
810         // photos/name
811         // photos/name/upload
812         // photos/name/upload/xxxxx (xxxxx is album name)
813         // photos/name/album/xxxxx
814         // photos/name/album/xxxxx/edit
815         // photos/name/image/xxxxx
816         // photos/name/image/xxxxx/edit
817
818
819         if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
820                 notice( t('Public access denied.') . EOL);
821                 return;
822         }
823         
824         
825         require_once('include/bbcode.php');
826         require_once('include/security.php');
827         require_once('include/conversation.php');
828
829         if(! x($a->data,'user')) {
830                 notice( t('No photos selected') . EOL );
831                 return;
832         }
833
834         $phototypes = Photo::supportedTypes();
835
836         $_SESSION['photo_return'] = $a->cmd;
837
838         //
839         // Parse arguments 
840         //
841
842         if($a->argc > 3) {
843                 $datatype = $a->argv[2];
844                 $datum = $a->argv[3];
845         }
846         elseif(($a->argc > 2) && ($a->argv[2] === 'upload'))
847                 $datatype = 'upload';
848         else
849                 $datatype = 'summary';
850
851         if($a->argc > 4)
852                 $cmd = $a->argv[4];
853         else
854                 $cmd = 'view';
855
856         //
857         // Setup permissions structures
858         //
859
860         $can_post       = false;
861         $visitor        = 0;
862         $contact        = null;
863         $remote_contact = false;
864
865         $owner_uid = $a->data['user']['uid'];
866
867         $community_page = (($a->data['user']['page-flags'] == PAGE_COMMUNITY) ? true : false);
868
869         if((local_user()) && (local_user() == $owner_uid))
870                 $can_post = true;
871         else {
872                 if($community_page && remote_user()) {
873                         $r = q("SELECT `uid` FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1",
874                                 intval(remote_user()),
875                                 intval($owner_uid)
876                         );
877                         if(count($r)) {
878                                 $can_post = true;
879                                 $contact  = $r[0];
880                                 $remote_contact = true;
881                                 $visitor = remote_user();
882                         }
883                 }
884         }
885
886         // perhaps they're visiting - but not a community page, so they wouldn't have write access
887
888         if(remote_user() && (! $visitor)) {
889                 $contact_id = $_SESSION['visitor_id'];
890                 $groups = init_groups_visitor($contact_id);
891                 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1",
892                         intval(remote_user()),
893                         intval($owner_uid)
894                 );
895                 if(count($r)) {
896                         $contact = $r[0];
897                         $remote_contact = true;
898                 }
899         }
900
901         if(! $remote_contact) {
902                 if(local_user()) {
903                         $contact_id = $_SESSION['cid'];
904                         $contact = $a->contact;
905                 }
906         }
907
908         if($a->data['user']['hidewall'] && (local_user() != $owner_uid) && (! $remote_contact)) {
909                 notice( t('Access to this item is restricted.') . EOL);
910                 return;
911         }
912
913         $sql_extra = permissions_sql($owner_uid,$remote_contact,$groups);
914
915         $o = "";
916
917         // tabs
918         $_is_owner = (local_user() && (local_user() == $owner_uid));
919         $o .= profile_tabs($a,$_is_owner, $a->data['user']['nickname']);        
920
921         //
922         // dispatch request
923         //
924
925
926         if($datatype === 'upload') {
927                 if(! ($can_post)) {
928                         notice( t('Permission denied.'));
929                         return;
930                 }
931
932
933                 $selname = (($datum) ? hex2bin($datum) : '');
934
935
936                 $albumselect = '<select id="photos-upload-album-select" name="album" size="4">';
937
938                 
939                 $albumselect .= '<option value="" ' . ((! $selname) ? ' selected="selected" ' : '') . '>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option>';
940                 if(count($a->data['albums'])) {
941                         foreach($a->data['albums'] as $album) {
942                                 if(($album['album'] === '') || ($album['album'] === 'Contact Photos') || ($album['album'] === t('Contact Photos')))
943                                         continue;
944                                 $selected = (($selname === $album['album']) ? ' selected="selected" ' : '');
945                                 $albumselect .= '<option value="' . $album['album'] . '"' . $selected . '>' . $album['album'] . '</option>';
946                         }
947                 }
948
949                 $celeb = ((($a->user['page-flags'] == PAGE_SOAPBOX) || ($a->user['page-flags'] == PAGE_COMMUNITY)) ? true : false);
950
951                 $albumselect .= '</select>';
952
953                 $uploader = '';
954
955                 $ret = array('post_url' => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'],
956                                 'addon_text' => $uploader,
957                                 'default_upload' => true);
958
959
960                 call_hooks('photo_upload_form',$ret);
961
962                 $default_upload = '<input type="file" name="userfile" />        <div class="photos-upload-submit-wrapper" >
963                 <input type="submit" name="submit" value="' . t('Submit') . '" id="photos-upload-submit" /> </div>';
964
965
966  
967
968                 $tpl = get_markup_template('photos_upload.tpl');
969                 $o .= replace_macros($tpl,array(
970                         '$pagename' => t('Upload Photos'),
971                         '$sessid' => session_id(),
972                         '$nickname' => $a->data['user']['nickname'],
973                         '$newalbum' => t('New album name: '),
974                         '$existalbumtext' => t('or existing album name: '),
975                         '$nosharetext' => t('Do not show a status post for this upload'),
976                         '$albumselect' => template_escape($albumselect),
977                         '$permissions' => t('Permissions'),
978                         '$aclselect' => (($visitor) ? '' : template_escape(populate_acl($a->user, $celeb))),
979                         '$uploader' => $ret['addon_text'],
980                         '$default' => (($ret['default_upload']) ? $default_upload : ''),
981                         '$uploadurl' => $ret['post_url']
982
983                 ));
984
985                 return $o; 
986         }
987
988         if($datatype === 'album') {
989
990                 $album = hex2bin($datum);
991
992                 $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` = '%s' 
993                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id`",
994                         intval($owner_uid),
995                         dbesc($album)
996                 );
997                 if(count($r)) {
998                         $a->set_pager_total(count($r));
999                         $a->set_pager_itemspage(20);
1000                 }
1001
1002                 $r = q("SELECT `resource-id`, `id`, `filename`, type, max(`scale`) AS `scale`, `desc` FROM `photo` WHERE `uid` = %d AND `album` = '%s' 
1003                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id` ORDER BY `created` DESC LIMIT %d , %d",
1004                         intval($owner_uid),
1005                         dbesc($album),
1006                         intval($a->pager['start']),
1007                         intval($a->pager['itemspage'])
1008                 );
1009
1010                 $o .= '<h3>' . $album . '</h3>';
1011                 
1012                 if($cmd === 'edit') {           
1013                         if(($album !== t('Profile Photos')) && ($album !== 'Contact Photos') && ($album !== t('Contact Photos'))) {
1014                                 if($can_post) {
1015                                         $edit_tpl = get_markup_template('album_edit.tpl');
1016                                         $o .= replace_macros($edit_tpl,array(
1017                                                 '$nametext' => t('New album name: '),
1018                                                 '$nickname' => $a->data['user']['nickname'],
1019                                                 '$album' => template_escape($album),
1020                                                 '$hexalbum' => bin2hex($album),
1021                                                 '$submit' => t('Submit'),
1022                                                 '$dropsubmit' => t('Delete Album')
1023                                         ));
1024                                 }
1025                         }
1026                 }
1027                 else {
1028                         if(($album !== t('Profile Photos')) && ($album !== 'Contact Photos') && ($album !== t('Contact Photos'))) {
1029                                 if($can_post) {
1030                                         $o .= '<div id="album-edit-link"><a href="'. $a->get_baseurl() . '/photos/' 
1031                                                 . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '/edit' . '">' 
1032                                                 . t('Edit Album') . '</a></div>';
1033                                 }
1034                         }
1035                 }
1036
1037                 if($can_post) {
1038                         $o .= '<div class="photos-upload-link" ><a href="' . $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/upload/' . bin2hex($album) . '" >' . t('Upload New Photos') . '</a></div>';
1039                 }
1040
1041                 $tpl = get_markup_template('photo_album.tpl');
1042                 if(count($r))
1043                         $twist = 'rotright';
1044                         foreach($r as $rr) {
1045                                 if($twist == 'rotright')
1046                                         $twist = 'rotleft';
1047                                 else
1048                                         $twist = 'rotright';
1049                                 
1050                                 $ext = $phototypes[$rr['type']];
1051
1052                                 $o .= replace_macros($tpl,array(
1053                                         '$id' => $rr['id'],
1054                                         '$twist' => ' ' . $twist . rand(2,4),
1055                                         '$photolink' => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id'],
1056                                         '$phototitle' => t('View Photo'),
1057                                         '$imgsrc' => $a->get_baseurl() . '/photo/' . $rr['resource-id'] . '-' . $rr['scale'] . '.' .$ext,
1058                                         '$imgalt' => template_escape($rr['filename']),
1059                                         '$desc'=> template_escape($rr['desc'])
1060                                 ));
1061
1062                 }
1063                 $o .= '<div id="photo-album-end"></div>';
1064                 $o .= paginate($a);
1065
1066                 return $o;
1067
1068         }       
1069
1070
1071         if($datatype === 'image') {
1072
1073
1074
1075                 //$o = '';
1076                 // fetch image, item containing image, then comments
1077
1078                 $ph = q("SELECT * FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' 
1079                         $sql_extra ORDER BY `scale` ASC ",
1080                         intval($owner_uid),
1081                         dbesc($datum)
1082                 );
1083
1084                 if(! count($ph)) {
1085                         $ph = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' 
1086                                 LIMIT 1",
1087                                 intval($owner_uid),
1088                                 dbesc($datum)
1089                         );
1090                         if(count($ph)) 
1091                                 notice( t('Permission denied. Access to this item may be restricted.'));
1092                         else
1093                                 notice( t('Photo not available') . EOL );
1094                         return;
1095                 }
1096
1097                 $prevlink = '';
1098                 $nextlink = '';
1099
1100                 $prvnxt = q("SELECT `resource-id` FROM `photo` WHERE `album` = '%s' AND `uid` = %d AND `scale` = 0 
1101                         $sql_extra ORDER BY `created` DESC ",
1102                         dbesc($ph[0]['album']),
1103                         intval($owner_uid)
1104                 ); 
1105
1106                 if(count($prvnxt)) {
1107                         for($z = 0; $z < count($prvnxt); $z++) {
1108                                 if($prvnxt[$z]['resource-id'] == $ph[0]['resource-id']) {
1109                                         $prv = $z - 1;
1110                                         $nxt = $z + 1;
1111                                         if($prv < 0)
1112                                                 $prv = count($prvnxt) - 1;
1113                                         if($nxt >= count($prvnxt))
1114                                                 $nxt = 0;
1115                                         break;
1116                                 }
1117                         }
1118                         $edit_suffix = ((($cmd === 'edit') && ($can_post)) ? '/edit' : '');
1119                         $prevlink = $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$prv]['resource-id'] . $edit_suffix;
1120                         $nextlink = $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$nxt]['resource-id'] . $edit_suffix;
1121                 }
1122
1123
1124                 if(count($ph) == 1)
1125                         $hires = $lores = $ph[0];
1126                 if(count($ph) > 1) {
1127                         if($ph[1]['scale'] == 2) {
1128                                 // original is 640 or less, we can display it directly
1129                                 $hires = $lores = $ph[0];
1130                         }
1131                         else {
1132                         $hires = $ph[0];
1133                         $lores = $ph[1];
1134                         }
1135                 }
1136
1137                 $album_link = $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($ph[0]['album']);
1138                 $tools = Null;
1139                 $lock = Null;
1140  
1141                 if($can_post && ($ph[0]['uid'] == $owner_uid)) {
1142                         $tools = array(
1143                                 'edit'  => array($a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $datum . (($cmd === 'edit') ? '' : '/edit'), (($cmd === 'edit') ? t('View photo') : t('Edit photo'))),
1144                                 'profile'=>array($a->get_baseurl() . '/profile_photo/use/'.$ph[0]['resource-id'], t('Use as profile photo')),
1145                         );
1146
1147                         // lock
1148                         $lock = ( ( ($ph[0]['uid'] == local_user()) && (strlen($ph[0]['allow_cid']) || strlen($ph[0]['allow_gid']) 
1149                                         || strlen($ph[0]['deny_cid']) || strlen($ph[0]['deny_gid'])) ) 
1150                                         ? t('Private Message')
1151                                         : Null);
1152                         
1153                         
1154                 }
1155
1156                 if(! $cmd !== 'edit') {
1157                         $a->page['htmlhead'] .= '<script>
1158                                 $(document).keydown(function(event) {' . "\n";
1159
1160                         if($prevlink)
1161                                 $a->page['htmlhead'] .= 'if(event.ctrlKey && event.keyCode == 37) { event.preventDefault(); window.location.href = \'' . $prevlink . '\'; }' . "\n";
1162                         if($nextlink)
1163                                 $a->page['htmlhead'] .= 'if(event.ctrlKey && event.keyCode == 39) { event.preventDefault(); window.location.href = \'' . $nextlink . '\'; }' . "\n";
1164                         $a->page['htmlhead'] .= '});</script>';
1165                 }
1166
1167                 if($prevlink)
1168                         $prevlink = array($prevlink, '<div class="icon prev"></div>') ;
1169
1170                 $photo = array(
1171                         'href' => $a->get_baseurl() . '/photo/' . $hires['resource-id'] . '-' . $hires['scale'] . '.' . $phototypes[$hires['type']],
1172                         'title'=> t('View Full Size'),
1173                         'src'  => $a->get_baseurl() . '/photo/' . $lores['resource-id'] . '-' . $lores['scale'] . '.' . $phototypes[$lores['type']] . '?f=&_u=' . datetime_convert('','','','ymdhis')
1174                 );
1175
1176                 if($nextlink)
1177                         $nextlink = array($nextlink, '<div class="icon next"></div>');
1178
1179
1180                 // Do we have an item for this photo?
1181
1182                 $linked_items = q("SELECT * FROM `item` WHERE `resource-id` = '%s' $sql_extra LIMIT 1",
1183                         dbesc($datum)
1184                 );
1185                 if(count($linked_items)) {
1186                         $link_item = $linked_items[0];
1187                         $r = q("SELECT COUNT(*) AS `total`
1188                                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1189                                 WHERE `parent-uri` = '%s' AND `uri` != '%s' AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1190                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1191                                 AND `item`.`uid` = %d 
1192                                 $sql_extra ",
1193                                 dbesc($link_item['uri']),
1194                                 dbesc($link_item['uri']),
1195                                 intval($link_item['uid'])
1196
1197                         );
1198
1199                         if(count($r))
1200                                 $a->set_pager_total($r[0]['total']);
1201
1202
1203                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
1204                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`network`, 
1205                                 `contact`.`rel`, `contact`.`thumb`, `contact`.`self`, 
1206                                 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1207                                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1208                                 WHERE `parent-uri` = '%s' AND `uri` != '%s' AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1209                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1210                                 AND `item`.`uid` = %d
1211                                 $sql_extra
1212                                 ORDER BY `parent` DESC, `id` ASC LIMIT %d ,%d ",
1213                                 dbesc($link_item['uri']),
1214                                 dbesc($link_item['uri']),
1215                                 intval($link_item['uid']),
1216                                 intval($a->pager['start']),
1217                                 intval($a->pager['itemspage'])
1218
1219                         );
1220                 
1221                         if((local_user()) && (local_user() == $link_item['uid'])) {
1222                                 q("UPDATE `item` SET `unseen` = 0 WHERE `parent` = %d and `uid` = %d",
1223                                         intval($link_item['parent']),
1224                                         intval(local_user())
1225                                 );
1226                         }
1227                 }
1228
1229                 $tags=Null;
1230
1231                 if(count($linked_items) && strlen($link_item['tag'])) {
1232                         $arr = explode(',',$link_item['tag']);
1233                         // parse tags and add links
1234                         $tag_str = '';
1235                         foreach($arr as $t) {
1236                                 if(strlen($tag_str))
1237                                         $tag_str .= ', ';
1238                                 $tag_str .= bbcode($t);
1239                         } 
1240                         $tags = array(t('Tags: '), $tag_str);
1241                         if($cmd === 'edit') {
1242                                 $tags[] = $a->get_baseurl() . '/tagrm/' . $link_item['id'];
1243                                 $tags[] = t('[Remove any tag]');
1244                         }
1245                 }
1246
1247
1248                 $edit = Null;
1249                 if(($cmd === 'edit') && ($can_post)) {
1250                         $edit_tpl = get_markup_template('photo_edit.tpl');
1251                         $edit = replace_macros($edit_tpl, array(
1252                                 '$id' => $ph[0]['id'],
1253                                 '$rotate' => t('Rotate CW'),
1254                                 '$album' => template_escape($ph[0]['album']),
1255                                 '$newalbum' => t('New album name'), 
1256                                 '$nickname' => $a->data['user']['nickname'],
1257                                 '$resource_id' => $ph[0]['resource-id'],
1258                                 '$capt_label' => t('Caption'),
1259                                 '$caption' => template_escape($ph[0]['desc']),
1260                                 '$tag_label' => t('Add a Tag'),
1261                                 '$tags' => $link_item['tag'],
1262                                 '$permissions' => t('Permissions'),
1263                                 '$aclselect' => template_escape(populate_acl($ph[0])),
1264                                 '$help_tags' => t('Example: @bob, @Barbara_Jensen, @jim@example.com, #California, #camping'),
1265                                 '$item_id' => ((count($linked_items)) ? $link_item['id'] : 0),
1266                                 '$submit' => t('Submit'),
1267                                 '$delete' => t('Delete Photo')
1268                         ));
1269                 }
1270
1271                 if(count($linked_items)) {
1272
1273                         $cmnt_tpl = get_markup_template('comment_item.tpl');
1274                         $tpl = get_markup_template('photo_item.tpl');
1275                         $return_url = $a->cmd;
1276
1277                         $like_tpl = get_markup_template('like_noshare.tpl');
1278
1279                         $likebuttons = '';
1280
1281                         if($can_post || can_write_wall($a,$owner_uid)) {
1282                                 $likebuttons = replace_macros($like_tpl,array(
1283                                         '$id' => $link_item['id'],
1284                                         '$likethis' => t("I like this \x28toggle\x29"),
1285                                         '$nolike' => t("I don't like this \x28toggle\x29"),
1286                                         '$share' => t('Share'),
1287                                         '$wait' => t('Please wait')
1288                                 ));
1289                         }
1290
1291                         $comments = '';
1292                         if(! count($r)) {
1293                                 if($can_post || can_write_wall($a,$owner_uid)) {
1294                                         if($link_item['last-child']) {
1295                                                 $comments .= replace_macros($cmnt_tpl,array(
1296                                                         '$return_path' => '', 
1297                                                         '$jsreload' => $return_url,
1298                                                         '$type' => 'wall-comment',
1299                                                         '$id' => $link_item['id'],
1300                                                         '$parent' => $link_item['id'],
1301                                                         '$profile_uid' =>  $owner_uid,
1302                                                         '$mylink' => $contact['url'],
1303                                                         '$mytitle' => t('This is you'),
1304                                                         '$myphoto' => $contact['thumb'],
1305                                                         '$comment' => t('Comment'),
1306                                                         '$submit' => t('Submit'),
1307                                                         '$preview' => t('Preview'),
1308                                                         '$ww' => ''
1309                                                 ));
1310                                         }
1311                                 }
1312                         }
1313
1314                         $alike = array();
1315                         $dlike = array();
1316                         
1317                         $like = '';
1318                         $dislike = '';
1319
1320                         // display comments
1321                         if(count($r)) {
1322
1323                                 foreach($r as $item) {
1324                                         like_puller($a,$item,$alike,'like');
1325                                         like_puller($a,$item,$dlike,'dislike');
1326                                 }
1327
1328                                 $like    = ((isset($alike[$link_item['id']])) ? format_like($alike[$link_item['id']],$alike[$link_item['id'] . '-l'],'like',$link_item['id']) : '');
1329                                 $dislike = ((isset($dlike[$link_item['id']])) ? format_like($dlike[$link_item['id']],$dlike[$link_item['id'] . '-l'],'dislike',$link_item['id']) : '');
1330
1331
1332
1333                                 if($can_post || can_write_wall($a,$owner_uid)) {
1334                                         if($link_item['last-child']) {
1335                                                 $comments .= replace_macros($cmnt_tpl,array(
1336                                                         '$return_path' => '',
1337                                                         '$jsreload' => $return_url,
1338                                                         '$type' => 'wall-comment',
1339                                                         '$id' => $link_item['id'],
1340                                                         '$parent' => $link_item['id'],
1341                                                         '$profile_uid' =>  $owner_uid,
1342                                                         '$mylink' => $contact['url'],
1343                                                         '$mytitle' => t('This is you'),
1344                                                         '$myphoto' => $contact['thumb'],
1345                                                         '$comment' => t('Comment'),
1346                                                         '$submit' => t('Submit'),
1347                                                         '$ww' => ''
1348                                                 ));
1349                                         }
1350                                 }
1351
1352
1353                                 foreach($r as $item) {
1354                                         $comment = '';
1355                                         $template = $tpl;
1356                                         $sparkle = '';
1357
1358                                         if(((activity_match($item['verb'],ACTIVITY_LIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE))) && ($item['id'] != $item['parent']))
1359                                                 continue;
1360
1361                                         $redirect_url = $a->get_baseurl() . '/redir/' . $item['cid'] ;
1362                         
1363                                         if($can_post || can_write_wall($a,$owner_uid)) {
1364
1365                                                 if($item['last-child']) {
1366                                                         $comments .= replace_macros($cmnt_tpl,array(
1367                                                                 '$return_path' => '',
1368                                                                 '$jsreload' => $return_url,
1369                                                                 '$type' => 'wall-comment',
1370                                                                 '$id' => $item['item_id'],
1371                                                                 '$parent' => $item['parent'],
1372                                                                 '$profile_uid' =>  $owner_uid,
1373                                                                 '$mylink' => $contact['url'],
1374                                                                 '$mytitle' => t('This is you'),
1375                                                                 '$myphoto' => $contact['thumb'],
1376                                                                 '$comment' => t('Comment'),
1377                                                                 '$submit' => t('Submit'),
1378                                                                 '$ww' => ''
1379                                                         ));
1380                                                 }
1381                                         }
1382
1383
1384                                         if(local_user() && ($item['contact-uid'] == local_user()) 
1385                                                 && ($item['network'] == 'dfrn') && (! $item['self'] )) {
1386                                                 $profile_url = $redirect_url;
1387                                                 $sparkle = ' sparkle';
1388                                         }
1389                                         else {
1390                                                 $profile_url = $item['url'];
1391                                                 $sparkle = '';
1392                                         }
1393  
1394                                         $diff_author = (($item['url'] !== $item['author-link']) ? true : false);
1395
1396                                         $profile_name   = (((strlen($item['author-name']))   && $diff_author) ? $item['author-name']   : $item['name']);
1397                                         $profile_avatar = (((strlen($item['author-avatar'])) && $diff_author) ? $item['author-avatar'] : $item['thumb']);
1398
1399                                         $profile_link = $profile_url;
1400
1401                                         $drop = '';
1402
1403                                         if(($item['contact-id'] == remote_user()) || ($item['uid'] == local_user()))
1404                                                 $drop = replace_macros(get_markup_template('photo_drop.tpl'), array('$id' => $item['id'], '$delete' => t('Delete')));
1405
1406
1407                                         $comments .= replace_macros($template,array(
1408                                                 '$id' => $item['item_id'],
1409                                                 '$profile_url' => $profile_link,
1410                                                 '$name' => template_escape($profile_name),
1411                                                 '$thumb' => $profile_avatar,
1412                                                 '$sparkle' => $sparkle,
1413                                                 '$title' => template_escape($item['title']),
1414                                                 '$body' => template_escape(bbcode($item['body'])),
1415                                                 '$ago' => relative_date($item['created']),
1416                                                 '$indent' => (($item['parent'] != $item['item_id']) ? ' comment' : ''),
1417                                                 '$drop' => $drop,
1418                                                 '$comment' => $comment
1419                                         ));
1420                                 }
1421                         }
1422
1423                         $paginate = paginate($a);
1424                 }
1425                 
1426                 $photo_tpl = get_markup_template('photo_view.tpl');
1427                 $o .= replace_macros($photo_tpl, array(
1428                         '$id' => $ph[0]['id'],
1429                         '$album' => array($album_link,template_escape($ph[0]['album'])),
1430                         '$tools' => $tools,
1431                         '$lock' => $lock,
1432                         '$photo' => $photo,
1433                         '$prevlink' => $prevlink,
1434                         '$nextlink' => $nextlink,
1435                         '$desc' => $ph[0]['desc'],
1436                         '$tags' => template_escape($tags),
1437                         '$edit' => $edit,       
1438                         '$likebuttons' => $likebuttons,
1439                         '$like' => template_escape($like),
1440                         '$dislike' => template_escape($dislike),
1441                         '$comments' => $comments,
1442                         '$paginate' => $paginate,
1443                 ));
1444                 
1445                 return $o;
1446         }
1447
1448         // Default - show recent photos with upload link (if applicable)
1449         //$o = '';
1450
1451         $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' 
1452                 $sql_extra GROUP BY `resource-id`",
1453                 intval($a->data['user']['uid']),
1454                 dbesc('Contact Photos'),
1455                 dbesc( t('Contact Photos'))
1456         );
1457         if(count($r)) {
1458                 $a->set_pager_total(count($r));
1459                 $a->set_pager_itemspage(20);
1460         }
1461
1462         $r = q("SELECT `resource-id`, `id`, `filename`, type, `album`, max(`scale`) AS `scale` FROM `photo`
1463                 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s'  
1464                 $sql_extra GROUP BY `resource-id` ORDER BY `created` DESC LIMIT %d , %d",
1465                 intval($a->data['user']['uid']),
1466                 dbesc('Contact Photos'),
1467                 dbesc( t('Contact Photos')),
1468                 intval($a->pager['start']),
1469                 intval($a->pager['itemspage'])
1470         );
1471
1472
1473
1474         $photos = array();
1475         if(count($r)) {
1476                 $twist = 'rotright';
1477                 foreach($r as $rr) {
1478                         if($twist == 'rotright')
1479                                 $twist = 'rotleft';
1480                         else
1481                                 $twist = 'rotright';
1482                         $ext = $phototypes[$rr['type']];
1483                         
1484                         $photos[] = array(
1485                                 'id'       => $rr['id'],
1486                                 'twist'    => ' ' . $twist . rand(2,4),
1487                                 'link'          => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id'],
1488                                 'title'         => t('View Photo'),
1489                                 'src'           => $a->get_baseurl() . '/photo/' . $rr['resource-id'] . '-' . ((($rr['scale']) == 6) ? 4 : $rr['scale']) . '.' . $ext,
1490                                 'alt'           => template_escape($rr['filename']),
1491                                 'album' => array(
1492                                         'link'  => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($rr['album']),
1493                                         'name'  => template_escape($rr['album']),
1494                                         'alt'   => t('View Album'),
1495                                 ),
1496                                 
1497                         );
1498                 }
1499         }
1500         
1501         $tpl = get_markup_template('photos_recent.tpl'); 
1502         $o .= replace_macros($tpl,array(
1503                 '$title' => t('Recent Photos'),
1504                 '$can_post' => $can_post,
1505                 '$upload' => array(t('Upload New Photos'), $a->get_baseurl().'/photos/'.$a->data['user']['nickname'].'/upload'),
1506                 '$photos' => $photos,
1507         ));
1508
1509         
1510         $o .= paginate($a);
1511         return $o;
1512 }
1513