]> git.mxchange.org Git - friendica.git/blob - mod/photos.php
a3aa69216284050557ac135e973f5f61b9b2e52d
[friendica.git] / mod / photos.php
1 <?php
2
3 require_once('Photo.php');
4 require_once('include/items.php');
5 require_once('view/acl_selectors.php');
6 require_once('include/bbcode.php');
7
8 function photos_init(&$a) {
9
10         $o = '';
11
12         if($a->argc > 1) {
13                 $nick = $a->argv[1];
14                 $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' LIMIT 1",
15                         dbesc($nick)
16                 );
17
18                 if(! count($r))
19                         return;
20
21                 $a->data['user'] = $r[0];
22
23                 $albums = q("SELECT distinct(`album`) AS `album` FROM `photo` WHERE `uid` = %d",
24                         intval($a->data['user']['uid'])
25                 );
26
27                 if(count($albums)) {
28                         $a->data['albums'] = $albums;
29
30                         $o .= '<h4><a href="' . $a->get_baseurl() . '/profile/' . $a->data['user']['nickname'] . '">' . $a->data['user']['username'] . '</a></h4>';
31                         $o .= '<h4>' . '<a href="' . $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '">' . t('Photo Albums') . '</a></h4>';
32                 
33                         $o .= '<ul>';
34                         foreach($albums as $album) {
35                                 if((! strlen($album['album'])) || ($album['album'] == t('Contact Photos')))
36                                         continue;
37                                 $o .= '<li>' . '<a href="photos/' . $a->argv[1] . '/album/' . bin2hex($album['album']) . '" />' . $album['album'] . '</a></li>'; 
38                         }
39                         $o .= '</ul>';
40                 }
41
42                 if(! x($a->page,'aside'))
43                         $a->page['aside'] = '';
44                 $a->page['aside'] .= $o;
45         }
46         return;
47 }
48
49
50
51
52 function photos_post(&$a) {
53
54
55         if(! local_user()) {
56                 notice( t('Permission denied.') . EOL );
57                 killme();
58         }
59
60         $r = q("SELECT `contact`.*, `user`.`nickname` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` 
61                 WHERE `user`.`uid` = %d AND `self` = 1 LIMIT 1",
62                 intval(local_user())
63         );
64
65         if(! count($r)) {
66                 notice( t('Contact information unavailable') . EOL);
67                 logger('photos_post: unable to locate contact record for logged in user. uid=' . local_user());
68                 killme();
69         }
70
71         $contact_record = $r[0];        
72
73
74         if(($a->argc > 2) && ($a->argv[1] === 'album')) {
75                 $album = hex2bin($a->argv[2]);
76
77                 if($album == t('Profile Photos') || $album == t('Contact Photos')) {
78                         goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
79                         return; // NOTREACHED
80                 }
81
82                 $r = q("SELECT count(*) FROM `photo` WHERE `album` = '%s' AND `uid` = %d",
83                         dbesc($album),
84                         intval(local_user())
85                 );
86                 if(! count($r)) {
87                         notice( t('Album not found.') . EOL);
88                         goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
89                         return; // NOTREACHED
90                 }
91
92                 $newalbum = notags(trim($_POST['albumname']));
93                 if($newalbum != $album) {
94                         q("UPDATE `photo` SET `album` = '%s' WHERE `album` = '%s' AND `uid` = %d",
95                                 dbesc($newalbum),
96                                 dbesc($album),
97                                 intval(local_user())
98                         );
99                         $newurl = str_replace(bin2hex($album),bin2hex($newalbum),$_SESSION['photo_return']);
100                         goaway($a->get_baseurl() . '/' . $newurl);
101                         return; // NOTREACHED
102                 }
103
104                 if($_POST['dropalbum'] == t('Delete Album')) {
105
106                         $res = array();
107                         $r = q("SELECT distinct(`resource-id`) as `rid` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
108                                 intval(local_user()),
109                                 dbesc($album)
110                         );
111                         if(count($r)) {
112                                 foreach($r as $rr) {
113                                         $res[] = "'" . dbesc($rr['rid']) . "'" ;
114                                 }
115                         }
116                         else {
117                                 goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
118                                 return; // NOTREACHED
119                         }
120                         $str_res = implode(',', $res);
121
122                         q("DELETE FROM `photo` WHERE `resource-id` IN ( $str_res ) AND `uid` = %d",
123                                 intval(local_user())
124                         );
125                         $r = q("SELECT `parent-uri` FROM `item` WHERE `resource-id` IN ( $str_res ) AND `uid` = %d",
126                                 intval(local_user())
127                         );
128                         if(count($r)) {
129                                 foreach($r as $rr) {
130                                         q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
131                                                 dbesc(datetime_convert()),
132                                                 dbesc($rr['parent-uri']),
133                                                 intval(local_user())
134                                         );
135
136                                         $drop_id = intval($rr['id']);
137                                         $php_path = ((strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
138
139                                         // send the notification upstream/downstream as the case may be
140
141                                         if($rr['visible'])
142                                                 proc_close(proc_open("\"$php_path\" \"include/notifier.php\" \"drop\" \"$drop_id\" & ",
143                                                         array(),$foo));
144
145                                 }
146                         }
147                 }
148                 goaway($a->get_baseurl() . '/photos/' . $a->data['user']['nickname']);
149                 return; // NOTREACHED
150         }
151
152         if(($a->argc > 1) && (x($_POST,'delete')) && ($_POST['delete'] == t('Delete Photo'))) {
153                 $r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' LIMIT 1",
154                         intval(local_user()),
155                         dbesc($a->argv[1])
156                 );
157                 if(count($r)) {
158                         q("DELETE FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
159                                 intval(local_user()),
160                                 dbesc($r[0]['resource-id'])
161                         );
162                         $i = q("SELECT * FROM `item` WHERE `resource-id` = '%s' AND `uid` = %d LIMIT 1",
163                                 dbesc($r[0]['resource-id']),
164                                 intval(local_user())
165                         );
166                         if(count($i)) {
167                                 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
168                                         dbesc(datetime_convert()),
169                                         dbesc(datetime_convert()),
170                                         dbesc($i[0]['uri']),
171                                         intval(local_user())
172                                 );
173
174                                 $url = $a->get_baseurl();
175                                 $drop_id = intval($i[0]['id']);
176                                 $php_path = ((strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
177
178                                 if($i[0]['visible'])
179                                         proc_close(proc_open("\"$php_path\" \"include/notifier.php\" \"drop\" \"$drop_id\" & ",
180                                                 array(),$foo));
181                         }
182                 }
183
184                 goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
185                 return; // NOTREACHED
186         }
187
188         if(($a->argc > 1) && ((x($_POST,'desc') !== false) || (x($_POST,'newtag') !== false))) {
189
190                 $desc        = ((x($_POST,'desc'))    ? notags(trim($_POST['desc']))   : '');
191                 $rawtags     = ((x($_POST,'newtag'))  ? notags(trim($_POST['newtag'])) : '');
192                 $item_id     = ((x($_POST,'item_id')) ? intval($_POST['item_id'])      : 0);
193                 $resource_id = $a->argv[1];
194
195                 $p = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ORDER BY `scale` DESC",
196                         dbesc($resource_id),
197                         intval(local_user())
198                 );
199                 if((count($p)) && ($p[0]['desc'] !== $desc)) {
200                         $r = q("UPDATE `photo` SET `desc` = '%s' WHERE `resource-id` = '%s' AND `uid` = %d",
201                                 dbesc($desc),
202                                 dbesc($resource_id),
203                                 intval(local_user())
204                         );
205                 }
206                 if(! $item_id) {
207
208                         // Create item container
209
210                         $title = '';
211                         $basename = basename($filename);
212                         $uri = item_new_uri($a->get_hostname(),local_user());
213
214                         $arr = array();
215
216                         $arr['uid']           = local_user();
217                         $arr['uri']           = $uri;
218                         $arr['parent-uri']    = $uri; 
219                         $arr['type']          = 'photo';
220                         $arr['wall']          = 1;
221                         $arr['resource-id']   = $p[0]['resource-id'];
222                         $arr['contact-id']    = $contact_record['id'];
223                         $arr['owner-name']    = $contact_record['name'];
224                         $arr['owner-link']    = $contact_record['url'];
225                         $arr['owner-avatar']  = $contact_record['thumb'];
226                         $arr['author-name']   = $contact_record['name'];
227                         $arr['author-link']   = $contact_record['url'];
228                         $arr['author-avatar'] = $contact_record['thumb'];
229                         $arr['title']         = $title;
230                         $arr['allow_cid']     = $p[0]['allow_cid'];
231                         $arr['allow_gid']     = $p[0]['allow_gid'];
232                         $arr['deny_cid']      = $p[0]['deny_cid'];
233                         $arr['deny_gid']      = $p[0]['deny_gid'];
234                         $arr['last-child']    = 1;
235                         $arr['body']          = '[url=' . $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $p[0]['resource-id'] . ']' 
236                                                 . '[img]' . $a->get_baseurl() . '/photo/' . $p[0]['resource-id'] . '-' . $p[0]['scale'] . '.jpg' . '[/img]' 
237                                                 . '[/url]';
238                 
239                         $item_id = item_store($arr);
240
241                 }
242
243                 if($item_id) {
244                         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
245                                 intval($item_id),
246                                 intval(local_user())
247                         );
248                 }
249                 if(count($r)) {
250                         $old_tag    = $r[0]['tag'];
251                         $old_inform = $r[0]['inform'];
252                 }
253
254                 if(strlen($rawtags)) {
255
256                         $str_tags = '';
257                         $inform   = '';
258
259                         // if the new tag doesn't have a namespace specifier (@foo or #foo) give it a hashtag
260
261                         $x = substr($rawtags,0,1);
262                         if($x !== '@' && $x !== '#')
263                                 $rawtags = '#' . $rawtags;
264
265                         $taginfo = array();
266                         $tags = get_tags($rawtags);
267
268                         if(count($tags)) {
269                                 foreach($tags as $tag) {
270                                         if(strpos($tag,'@') === 0) {
271                                                 $name = substr($tag,1);
272                                                 if((strpos($name,'@')) || (strpos($name,'http://'))) {
273                                                         $newname = $name;
274                                                         $links = @lrdd($name);
275                                                         if(count($links)) {
276                                                                 foreach($links as $link) {
277                                                                         if($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page')
278                                                         $profile = $link['@attributes']['href'];
279                                                                         if($link['@attributes']['rel'] === 'salmon') {
280                                                                                 $salmon = '$url:' . str_replace(',','%sc',$link['@attributes']['href']);
281                                                                                 if(strlen($inform))
282                                                                                         $inform .= ',';
283                                                         $inform .= $salmon;
284                                                                         }
285                                                                 }
286                                                         }
287                                                         $taginfo[] = array($newname,$profile,$salmon);
288                                                 }
289                                                 else {
290                                                         $newname = $name;
291                                                         if(strstr($name,'_')) {
292                                                                 $newname = str_replace('_',' ',$name);
293                                                                 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
294                                                                         dbesc($newname),
295                                                                         intval(local_user())
296                                                                 );
297                                                         }
298                                                         else {
299                                                                 $r = q("SELECT * FROM `contact` WHERE `nick` = '%s' AND `uid` = %d LIMIT 1",
300                                                                         dbesc($name),
301                                                                         intval(local_user())
302                                                                 );
303                                                         }
304                                                         if(count($r)) {
305                                                                 $newname = $r[0]['name'];
306                                                                 $profile = $r[0]['url'];
307                                                                 $notify = 'cid:' . $r[0]['id'];
308                                                                 if(strlen($inform))
309                                                                         $inform .= ',';
310                                                                 $inform .= $notify;
311                                                         }
312                                                 }
313                                                 if($profile) {
314                                                         if(substr($notify,0,4) === 'cid:')
315                                                                 $taginfo[] = array($newname,$profile,$notify,$r[0]);
316                                                         else
317                                                                 $taginfo[] = array($newname,$profile,$notify,null);
318                                                         if(strlen($str_tags))
319                                                                 $str_tags .= ',';
320                                                         $profile = str_replace(',','%2c',$profile);
321                                                         $str_tags .= '@[url=' . $profile . ']' . $newname       . '[/url]';
322                                                 }
323                                         }
324                                 }
325                         }
326
327                         $newtag = $old_tag;
328                         if(strlen($newtag) && strlen($str_tags)) 
329                                 $newtag .= ',';
330                         $newtag .= $str_tags;
331
332                         $newinform = $old_inform;
333                         if(strlen($newinform) && strlen($inform))
334                                 $newinform .= ',';
335                         $newinform .= $inform;
336
337                         $r = q("UPDATE `item` SET `tag` = '%s', `inform` = '%s', `edited` = '%s', `changed` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
338                                 dbesc($newtag),
339                                 dbesc($newinform),
340                                 dbesc(datetime_convert()),
341                                 dbesc(datetime_convert()),
342                                 intval($item_id),
343                                 intval(local_user())
344                         );
345
346                         $best = 0;
347                         foreach($p as $scales) {
348                                 if(intval($scales['scale']) == 2) {
349                                         $best = 2;
350                                         break;
351                                 }
352                                 if(intval($scales['scale']) == 4) {
353                                         $best = 4;
354                                         break;
355                                 }
356                         }
357
358                         if(count($taginfo)) {
359                                 foreach($taginfo as $tagged) {
360                 
361                                         $uri = item_new_uri($a->get_hostname(),local_user());
362
363                                         $arr = array();
364
365                                         $arr['uid']           = local_user();
366                                         $arr['uri']           = $uri;
367                                         $arr['parent-uri']    = $uri;
368                                         $arr['type']          = 'activity';
369                                         $arr['wall']          = 1;
370                                         $arr['contact-id']    = $contact_record['id'];
371                                         $arr['owner-name']    = $contact_record['name'];
372                                         $arr['owner-link']    = $contact_record['url'];
373                                         $arr['owner-avatar']  = $contact_record['thumb'];
374                                         $arr['author-name']   = $contact_record['name'];
375                                         $arr['author-link']   = $contact_record['url'];
376                                         $arr['author-avatar'] = $contact_record['thumb'];
377                                         $arr['title']         = '';
378                                         $arr['allow_cid']     = $p[0]['allow_cid'];
379                                         $arr['allow_gid']     = $p[0]['allow_gid'];
380                                         $arr['deny_cid']      = $p[0]['deny_cid'];
381                                         $arr['deny_gid']      = $p[0]['deny_gid'];
382                                         $arr['last-child']    = 1;
383                                         $arr['visible']       = 1;
384                                         $arr['verb']          = ACTIVITY_TAG;
385                                         $arr['object-type']   = ACTIVITY_OBJ_PERSON;
386                                         $arr['target-type']   = ACTIVITY_OBJ_PHOTO;
387                                         $arr['inform']        = $tagged[2];
388
389                                         $arr['body']          = '[url=' . $tagged[1] . ']' . $tagged[0] . '[/url]' . ' ' . t('was tagged in a') . ' ' . '[url=' . $a->get_baseurl() . '/photos/' . $contact_record['nickname'] . '/image/' . $p[0]['resource-id'] . ']' . t('photo') . '[/url]' . ' ' . t('by') . ' ' . '[url=' . $contact_record['url'] . ']' . $contact_record['name'] . '[/url]' ;
390                                         $arr['body'] .= "\n\n" . '[url=' . $a->get_baseurl() . '/photos/' . $contact_record['nickname'] . '/image/' . $p[0]['resource-id'] . ']' . '[img]' . $a->get_baseurl() . "/photo/" . $p[0]['resource-id'] . '-' . $best . '.jpg' . '[/img][/url]' . "\n" ;
391
392                                         $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $tagged[0] . '</title><id>' . $tagged[1] . '/' . $tagged[0] . '</id>';
393                                         $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $tagged[1] . '" />' . "\n");
394                                         if($tagged[3])
395                                                 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $tagged[3]['photo'] . '" />' . "\n");
396                                         $arr['object'] .= '</link></object>' . "\n";
397
398                                         $arr['target'] = '<target><type>' . ACTIVITY_OBJ_PHOTO . '</type><title>' . $p[0]['desc'] . '</title><id>'
399                                                 . $a->get_baseurl() . '/photos/' . $contact_record['nickname'] . '/image/' . $p[0]['resource-id'] . '</id>';
400                                         $arr['target'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/photos/' . $contact_record['nickname'] . '/image/' . $p[0]['resource-id'] . '" />' . "\n" . '<link rel="preview" type="image/jpeg" href="' . $a->get_baseurl() . "/photo/" . $p[0]['resource-id'] . '-' . $best . '.jpg' . '" />') . '</link></target>';
401
402                                         $item_id = item_store($arr);
403                                         $php_path = ((strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
404                                         proc_close(proc_open("\"$php_path\" \"include/notifier.php\" \"tag\" \"$item_id\" & ",
405                                                 array(),$foo));
406                                 }
407
408                         }
409
410                 }
411                 goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
412                 return; // NOTREACHED
413         }
414
415
416         // default post action - upload a photo
417
418         if(! x($_FILES,'userfile'))
419                 killme();
420
421         if($_POST['partitionCount'])
422                 $java_upload = true;
423         else
424                 $java_upload = false;
425
426         $album =  notags(trim($_POST['album']));
427         $newalbum = notags(trim($_POST['newalbum']));
428
429         if(! strlen($album)) {
430                 if(strlen($newalbum))
431                         $album = $newalbum;
432                 else
433                         $album = datetime_convert('UTC',date_default_timezone_get(),'now', 'Y');
434         }
435
436         $r = q("SELECT * FROM `photo` WHERE `album` = '%s' AND `uid` = %d",
437                 dbesc($album),
438                 intval(local_user())
439         );
440         if((! count($r)) || ($album == t('Profile Photos')))
441                 $visible = 1;
442         else
443                 $visible = 0;
444
445
446         $str_group_allow   = perms2str($_POST['group_allow']);
447         $str_contact_allow = perms2str($_POST['contact_allow']);
448         $str_group_deny    = perms2str($_POST['group_deny']);
449         $str_contact_deny  = perms2str($_POST['contact_deny']);
450
451         $src               = $_FILES['userfile']['tmp_name'];
452         $filename          = basename($_FILES['userfile']['name']);
453         $filesize          = intval($_FILES['userfile']['size']);
454
455         $imagedata = @file_get_contents($src);
456         $ph = new Photo($imagedata);
457
458         if(! $ph->is_valid()) {
459                 notice( t('Unable to process image.') . EOL );
460                 @unlink($src);
461                 killme();
462         }
463
464         @unlink($src);
465
466         $width = $ph->getWidth();
467         $height = $ph->getHeight();
468
469         $smallest = 0;
470
471         $photo_hash = photo_new_resource();
472
473         $r = $ph->store(local_user(), 0, $photo_hash, $filename, $album, 0 , 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
474
475         if(! $r) {
476                 notice( t('Image upload failed.') . EOL );
477                 killme();
478         }
479
480         if($width > 640 || $height > 640) {
481                 $ph->scaleImage(640);
482                 $ph->store(local_user(), 0, $photo_hash, $filename, $album, 1, 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
483                 $smallest = 1;
484         }
485
486         if($width > 320 || $height > 320) {
487                 $ph->scaleImage(320);
488                 $ph->store(local_user(), 0, $photo_hash, $filename, $album, 2, 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
489                 $smallest = 2;
490         }
491         
492         $basename = basename($filename);
493         $uri = item_new_uri($a->get_hostname(), local_user());
494
495         // Create item container
496
497
498         $arr = array();
499
500         $arr['uid']           = local_user();
501         $arr['uri']           = $uri;
502         $arr['parent-uri']    = $uri;
503         $arr['type']          = 'photo';
504         $arr['wall']          = 1;
505         $arr['resource-id']   = $photo_hash;
506         $arr['contact-id']    = $contact_record['id'];
507         $arr['owner-name']    = $contact_record['name'];
508         $arr['owner-link']    = $contact_record['url'];
509         $arr['owner-avatar']  = $contact_record['thumb'];
510         $arr['author-name']   = $contact_record['name'];
511         $arr['author-link']   = $contact_record['url'];
512         $arr['author-avatar'] = $contact_record['thumb'];
513         $arr['title']         = '';
514         $arr['allow_cid']     = $str_contact_allow;
515         $arr['allow_gid']     = $str_group_allow;
516         $arr['deny_cid']      = $str_contact_deny;
517         $arr['deny_gid']      = $str_group_deny;
518         $arr['last-child']    = 1;
519         $arr['visible']       = $visible;
520         $arr['body']          = '[url=' . $a->get_baseurl() . '/photos/' . $contact_record['nickname'] . '/image/' . $photo_hash . ']' 
521                                 . '[img]' . $a->get_baseurl() . "/photo/{$photo_hash}-{$smallest}.jpg" . '[/img]' 
522                                 . '[/url]';
523
524         $item_id = item_store($arr);
525
526         if(! $java_upload) {
527                 goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
528                 return; // NOTREACHED
529         }
530
531         killme();
532         return; // NOTREACHED
533
534 }
535
536
537
538 function photos_content(&$a) {
539
540         // URLs:
541         // photos/name
542         // photos/name/upload
543         // photos/name/album/xxxxx
544         // photos/name/album/xxxxx/edit
545         // photos/name/image/xxxxx
546         // photos/name/image/xxxxx/edit
547
548
549         if(! x($a->data,'user')) {
550                 notice( t('No photos selected') . EOL );
551                 return;
552         }
553
554         $_SESSION['photo_return'] = $a->cmd;
555
556         //
557         // Parse arguments 
558         //
559
560         if($a->argc > 3) {
561                 $datatype = $a->argv[2];
562                 $datum = $a->argv[3];
563         }
564         elseif(($a->argc > 2) && ($a->argv[2] === 'upload'))
565                 $datatype = 'upload';
566         else
567                 $datatype = 'summary';
568
569         if($a->argc > 4)
570                 $cmd = $a->argv[4];
571         else
572                 $cmd = 'view';
573
574         //
575         // Setup permissions structures
576         //
577
578         $owner_uid = $a->data['user']['uid'];
579
580
581
582         $contact = null;
583         $remote_contact = false;
584
585         if(remote_user()) {
586                 $contact_id = $_SESSION['visitor_id'];
587                 $groups = init_groups_visitor($contact_id);
588                 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
589                         intval($contact_id),
590                         intval($owner_uid)
591                 );
592                 if(count($r)) {
593                         $contact = $r[0];
594                         $remote_contact = true;
595                 }
596         }
597
598         if(! $remote_contact) {
599                 if(local_user()) {
600                         $contact_id = $_SESSION['cid'];
601                         $contact = $a->contact;
602                 }
603         }
604
605
606         // default permissions - anonymous user
607
608         $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = '' ";
609
610         // Profile owner - everything is visible
611
612         if(local_user() && (local_user() == $owner_uid)) {
613                 $sql_extra = '';        
614         }
615         elseif(remote_user()) {
616                 // authenticated visitor - here lie dragons
617                 $gs = '<<>>'; // should be impossible to match
618                 if(count($groups)) {
619                         foreach($groups as $g)
620                                 $gs .= '|<' . intval($g) . '>';
621                 } 
622                 $sql_extra = sprintf(
623                         " AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' ) 
624                           AND ( `deny_cid`  = '' OR  NOT `deny_cid` REGEXP '<%d>' ) 
625                           AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
626                           AND ( `deny_gid`  = '' OR NOT `deny_gid` REGEXP '%s') ",
627
628                         intval($_SESSION['visitor_id']),
629                         intval($_SESSION['visitor_id']),
630                         dbesc($gs),
631                         dbesc($gs)
632                 );
633         }
634
635         //
636         // dispatch request
637         //
638
639
640         if($datatype === 'upload') {
641                 if( ! (local_user() && (local_user() == $a->data['user']['uid']))) {
642                         notice( t('Permission denied.'));
643                         return;
644                 }
645                 $albumselect = '<select id="photos-upload-album-select" name="album" size="4">';
646
647                 $albumselect .= '<option value="" selected="selected" >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option>';
648                 if(count($a->data['albums'])) {
649                         foreach($a->data['albums'] as $album) {
650                                 if(($album['album'] === '') || ($album['album'] == t('Contact Photos')))
651                                         continue;
652                                 $albumselect .= '<option value="' . $album['album'] . '">' . $album['album'] . '</option>';
653                         }
654                 }
655
656                 $celeb = ((($a->user['page-flags'] == PAGE_SOAPBOX) || ($a->user['page-flags'] == PAGE_COMMUNITY)) ? true : false);
657
658                 $albumselect .= '</select>';
659                 $tpl = load_view_file('view/photos_upload.tpl');
660                 $o .= replace_macros($tpl,array(
661                         '$pagename' => t('Upload Photos'),
662                         '$sessid' => session_id(),
663                         '$newalbum' => t('New album name: '),
664                         '$existalbumtext' => t('or existing album name: '),
665                         '$filestext' => t('Select files to upload: '),
666                         '$albumselect' => $albumselect,
667                         '$permissions' => t('Permissions'),
668                         '$aclselect' => populate_acl($a->user, $celeb),
669                         '$archive' => $a->get_baseurl() . '/jumploader_z.jar',
670                         '$nojava' => t('Use the following controls only if the Java uploader [above] fails to launch.'),
671                         '$uploadurl' => $a->get_baseurl() . '/photos',
672                         '$submit' => t('Submit')
673                 ));
674
675                 return $o; 
676
677         }
678
679         if($datatype === 'album') {
680
681                 $album = hex2bin($datum);
682
683                 $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` = '%s' 
684                         $sql_extra GROUP BY `resource-id`",
685                         intval($a->data['user']['uid']),
686                         dbesc($album)
687                 );
688                 if(count($r))
689                         $a->set_pager_total(count($r));
690
691
692                 $r = q("SELECT `resource-id`, `id`, `filename`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` = '%s' 
693                         $sql_extra GROUP BY `resource-id` ORDER BY `created` DESC LIMIT %d , %d",
694                         intval($a->data['user']['uid']),
695                         dbesc($album),
696                         intval($a->pager['start']),
697                         intval($a->pager['itemspage'])
698                 );
699
700                 $o .= '<h3>' . $album . '</h3>';
701                 
702                 if($cmd === 'edit') {           
703                         if(($album != t('Profile Photos')) && ($album != t('Contact Photos'))) {
704                                 if(local_user() && (local_user() == $a->data['user']['uid'])) {
705                                         $edit_tpl = load_view_file('view/album_edit.tpl');
706                                         $o .= replace_macros($edit_tpl,array(
707                                                 '$nametext' => t('New album name: '),
708                                                 '$album' => $album,
709                                                 '$hexalbum' => bin2hex($album),
710                                                 '$submit' => t('Submit'),
711                                                 '$dropsubmit' => t('Delete Album')
712                                         ));
713                                 }
714                         }
715                 }
716                 else {
717                         if(($album != t('Profile Photos')) && ($album != t('Contact Photos'))) {
718                                 if(local_user() && (local_user() == $a->data['user']['uid'])) {
719                                         $o .= '<div id="album-edit-link"><a href="'. $a->get_baseurl() . '/photos/' 
720                                                 . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '/edit' . '">' 
721                                                 . t('Edit Album') . '</a></div>';
722                                 }
723                         }
724                 }
725                 $tpl = load_view_file('view/photo_album.tpl');
726                 if(count($r))
727                         foreach($r as $rr) {
728                                 $o .= replace_macros($tpl,array(
729                                         '$id' => $rr['id'],
730                                         '$photolink' => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id'],
731                                         '$phototitle' => t('View Photo'),
732                                         '$imgsrc' => $a->get_baseurl() . '/photo/' . $rr['resource-id'] . '-' . $rr['scale'] . '.jpg',
733                                         '$imgalt' => $rr['filename']
734                                 ));
735
736                 }
737                 $o .= '<div id="photo-album-end"></div>';
738                 return $o;
739
740         }       
741
742
743         if($datatype === 'image') {
744
745                 require_once('security.php');
746                 require_once('bbcode.php');
747
748                 $o = '<div id="live-display"></div>' . "\r\n";
749                 // fetch image, item containing image, then comments
750
751                 $ph = q("SELECT * FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' 
752                         $sql_extra ORDER BY `scale` ASC ",
753                         intval($a->data['user']['uid']),
754                         dbesc($datum)
755                 );
756
757                 if(! count($ph)) {
758                         notice( t('Photo not available') . EOL );
759                         return;
760                 }
761
762                 if(count($ph) == 1)
763                         $hires = $lores = $ph[0];
764                 if(count($ph) > 1) {
765                         if($ph[1]['scale'] == 2) {
766                                 // original is 640 or less, we can display it directly
767                                 $hires = $lores = $ph[0];
768                         }
769                         else {
770                         $hires = $ph[0];
771                         $lores = $ph[1];
772                         }
773                 }
774
775                 
776                 $o .= '<h3>' . '<a href="' . $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($ph[0]['album']) . '">' . $ph[0]['album'] . '</a></h3>';
777  
778                 if(local_user() && ($ph[0]['uid'] == local_user())) {
779                         $o .= '<div id="photo-edit-link-wrap" ><a id="photo-edit-link" href="' . $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $datum . '/edit' . '">' . t('Edit photo') . '</a></div>';
780                 }
781
782
783                 $o .= '<a href="' . $a->get_baseurl() . '/photo/' 
784                         . $hires['resource-id'] . '-' . $hires['scale'] . '.jpg" title="' 
785                         . t('View Full Size') . '" ><img src="' . $a->get_baseurl() . '/photo/' 
786                         . $lores['resource-id'] . '-' . $lores['scale'] . '.jpg' . '" /></a>';
787
788
789                 // Do we have an item for this photo?
790
791                 $linked_items = q("SELECT * FROM `item` WHERE `resource-id` = '%s' $sql_extra LIMIT 1",
792                         dbesc($datum)
793                 );
794                 if(count($linked_items)) {
795                         $link_item = $linked_items[0];
796                         $r = q("SELECT COUNT(*) AS `total`
797                                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
798                                 WHERE `parent-uri` = '%s' AND `uri` != '%s' AND `item`.`deleted` = 0
799                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
800                                 AND `item`.`uid` = %d 
801                                 $sql_extra ",
802                                 dbesc($link_item['uri']),
803                                 dbesc($link_item['uri']),
804                                 intval($link_item['uid'])
805
806                         );
807
808                         if(count($r))
809                                 $a->set_pager_total($r[0]['total']);
810
811
812                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
813                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`network`, 
814                                 `contact`.`rel`, `contact`.`thumb`, `contact`.`self`, 
815                                 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
816                                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
817                                 WHERE `parent-uri` = '%s' AND `uri` != '%s' AND `item`.`deleted` = 0
818                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
819                                 AND `item`.`uid` = %d
820                                 $sql_extra
821                                 ORDER BY `parent` DESC, `id` ASC LIMIT %d ,%d ",
822                                 dbesc($link_item['uri']),
823                                 dbesc($link_item['uri']),
824                                 intval($link_item['uid']),
825                                 intval($a->pager['start']),
826                                 intval($a->pager['itemspage'])
827
828                         );
829                 
830                         if((local_user()) && (local_user() == $link_item['uid'])) {
831                                 q("UPDATE `item` SET `unseen` = 0 WHERE `parent` = %d and `uid` = %d",
832                                         intval($link_item['parent']),
833                                         intval(local_user())
834                                 );
835                         }
836                 }
837
838                 $o .= '<div id="photo-caption" >' . $ph[0]['desc'] . '</div>';
839
840                 if(count($linked_items) && strlen($link_item['tag'])) {
841                         $arr = explode(',',$link_item['tag']);
842                         // parse tags and add links     
843                         $o .= '<div id="in-this-photo-text">' . t('Tags: ') . '</div>';
844                         $o .= '<div id="in-this-photo">';
845                         $tag_str = '';
846                         foreach($arr as $t) {
847                                 if(strlen($tag_str))
848                                         $tag_str .= ', ';
849                                 $tag_str .= bbcode($t);
850                         } 
851                         $o .= $tag_str . '</div>';
852                 }
853
854
855                 if($cmd === 'edit') {
856                         $edit_tpl = load_view_file('view/photo_edit.tpl');
857                         $o .= replace_macros($edit_tpl, array(
858                                 '$id' => $ph[0]['id'],
859                                 '$resource_id' => $ph[0]['resource-id'],
860                                 '$capt_label' => t('Caption'),
861                                 '$caption' => $ph[0]['desc'],
862                                 '$tag_label' => t('Add a Tag'),
863                                 '$tags' => $link_item['tag'],
864                                 '$help_tags' => t('Example: @bob, @Barbara_Jensen, @jim@example.com, #California, #camping'),
865                                 '$item_id' => ((count($linked_items)) ? $link_item['id'] : 0),
866                                 '$submit' => t('Submit'),
867                                 '$delete' => t('Delete Photo')
868
869                         ));
870                 }
871
872                 if(count($linked_items)) {
873
874                         $cmnt_tpl = load_view_file('view/comment_item.tpl');
875                         $tpl = load_view_file('view/photo_item.tpl');
876                         $return_url = $a->cmd;
877
878                         $like_tpl = load_view_file('view/like.tpl');
879
880                         $likebuttons = '';
881
882                         if(can_write_wall($a,$a->data['user']['uid']))
883                                 $likebuttons = replace_macros($like_tpl,array('$id' => $link_item['id']));
884
885                         if(! count($r)) {
886                                 $o .= '<div id="photo-like-div">';
887                                 $o .= $likebuttons;
888                                 $o .= '</div>';
889
890                                 if(can_write_wall($a,$a->data['user']['uid'])) {
891                                         if($link_item['last-child']) {
892                                                 $o .= replace_macros($cmnt_tpl,array(
893                                                         '$return_path' => $return_url,
894                                                         '$type' => 'wall-comment',
895                                                         '$id' => $link_item['id'],
896                                                         '$parent' => $link_item['id'],
897                                                         '$profile_uid' =>  $a->data['user']['uid'],
898                                                         '$mylink' => $contact['url'],
899                                                         '$mytitle' => t('This is you'),
900                                                         '$myphoto' => $contact['thumb'],
901                                                         '$ww' => ''
902                                                 ));
903                                         }
904                                 }
905                         }
906
907                         $alike = array();
908                         $dlike = array();
909
910                         // display comments
911                         if(count($r)) {
912
913                                 foreach($r as $item) {
914                                         like_puller($a,$item,$alike,'like');
915                                         like_puller($a,$item,$dlike,'dislike');
916                                 }
917
918                     $like    = ((isset($alike[$link_item['id']])) ? format_like($alike[$link_item['id']],$alike[$link_item['id'] . '-l'],'like',$link_item['id']) : '');
919                                 $dislike = ((isset($dlike[$link_item['id']])) ? format_like($dlike[$link_item['id']],$dlike[$link_item['id'] . '-l'],'dislike',$link_item['id']) : '');
920
921                                 $o .= '<div id="photo-like-div">';
922                                 $o .= $likebuttons;
923                                 $o .= $like;
924                                 $o .= $dislike;
925                                 $o .= '</div>';
926
927
928
929                                 if(can_write_wall($a,$a->data['user']['uid'])) {
930                                         if($link_item['last-child']) {
931                                                 $o .= replace_macros($cmnt_tpl,array(
932                                                         '$return_path' => $return_url,
933                                                         '$type' => 'wall-comment',
934                                                         '$id' => $link_item['id'],
935                                                         '$parent' => $link_item['id'],
936                                                         '$profile_uid' =>  $a->data['user']['uid'],
937                                                         '$mylink' => $contact['url'],
938                                                         '$mytitle' => t('This is you'),
939                                                         '$myphoto' => $contact['thumb'],
940                                                         '$ww' => ''
941                                                 ));
942                                         }
943                                 }
944
945
946                                 foreach($r as $item) {
947                                         $comment = '';
948                                         $template = $tpl;
949                                         $sparkle = '';
950
951                                         if(((activity_match($item['verb'],ACTIVITY_LIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE))) && ($item['id'] != $item['parent']))
952                                                 continue;
953
954                                         $redirect_url = $a->get_baseurl() . '/redir/' . $item['cid'] ;
955                         
956                                         if(can_write_wall($a,$a->data['user']['uid'])) {
957
958                                                 if($item['last-child']) {
959                                                         $comment = replace_macros($cmnt_tpl,array(
960                                                                 '$return_path' => $return_url,
961                                                                 '$type' => 'wall-comment',
962                                                                 '$id' => $item['item_id'],
963                                                                 '$parent' => $item['parent'],
964                                                                 '$profile_uid' =>  $a->data['user']['uid'],
965                                                                 '$mylink' => $contact['url'],
966                                                                 '$mytitle' => t('This is you'),
967                                                                 '$myphoto' => $contact['thumb'],
968                                                                 '$ww' => ''
969                                                         ));
970                                                 }
971                                         }
972
973
974                                         if(local_user() && ($item['contact-uid'] == local_user()) 
975                                                 && ($item['network'] == 'dfrn') && (! $item['self'] )) {
976                                                 $profile_url = $redirect_url;
977                                                 $sparkle = ' sparkle';
978                                         }
979                                         else {
980                                                 $profile_url = $item['url'];
981                                                 $sparkle = '';
982                                         }
983  
984                                         $profile_name = ((strlen($item['author-name'])) ? $item['author-name'] : $item['name']);
985                                         $profile_avatar = ((strlen($item['author-avatar'])) ? $item['author-avatar'] : $item['thumb']);
986                                         $profile_link = $profile_url;
987
988                                         $drop = '';
989
990                                         if(($item['contact-id'] == $_SESSION['visitor_id']) || ($item['uid'] == local_user()))
991                                                 $drop = replace_macros(load_view_file('view/wall_item_drop.tpl'), array('$id' => $item['id']));
992
993
994                                         $o .= replace_macros($template,array(
995                                                 '$id' => $item['item_id'],
996                                                 '$profile_url' => $profile_link,
997                                                 '$name' => $profile_name,
998                                                 '$thumb' => $profile_avatar,
999                                                 '$sparkle' => $sparkle,
1000                                                 '$title' => $item['title'],
1001                                                 '$body' => bbcode($item['body']),
1002                                                 '$ago' => relative_date($item['created']),
1003                                                 '$indent' => (($item['parent'] != $item['item_id']) ? ' comment' : ''),
1004                                                 '$drop' => $drop,
1005                                                 '$comment' => $comment
1006                                         ));
1007                                 }
1008                         }
1009
1010                         $o .= paginate($a);
1011                 }
1012                 return $o;
1013         }
1014
1015         // Default - show recent photos with upload link (if applicable)
1016         $o = '';
1017
1018         $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` != '%s' 
1019                 $sql_extra GROUP BY `resource-id`",
1020                 intval($a->data['user']['uid']),
1021                 dbesc( t('Contact Photos'))
1022         );
1023         if(count($r))
1024                 $a->set_pager_total(count($r));
1025
1026
1027         $r = q("SELECT `resource-id`, `id`, `filename`, `album`, max(`scale`) AS `scale` FROM `photo` 
1028                 WHERE `uid` = %d AND `album` != '%s' 
1029                 $sql_extra GROUP BY `resource-id` ORDER BY `created` DESC LIMIT %d , %d",
1030                 intval($a->data['user']['uid']),
1031                 dbesc( t('Contact Photos')),
1032                 intval($a->pager['start']),
1033                 intval($a->pager['itemspage'])
1034         );
1035
1036         $o .= '<h3>' . t('Recent Photos') . '</h3>';
1037
1038         if( local_user() && (local_user() == $a->data['user']['uid'])) {
1039                 $o .= '<div id="photo-top-links"><a id="photo-top-upload-link" href="'. $a->get_baseurl() . '/photos/' 
1040                         . $a->data['user']['nickname'] . '/upload' . '">' . t('Upload New Photos') . '</a></div>';
1041         }
1042
1043         $tpl = load_view_file('view/photo_top.tpl');
1044         if(count($r)) {
1045                 foreach($r as $rr) {
1046                         $o .= replace_macros($tpl,array(
1047                                 '$id' => $rr['id'],
1048                                 '$photolink' => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] 
1049                                         . '/image/' . $rr['resource-id'],
1050                                 '$phototitle' => t('View Photo'),
1051                                 '$imgsrc' => $a->get_baseurl() . '/photo/' 
1052                                         . $rr['resource-id'] . '-' . $rr['scale'] . '.jpg',
1053                                 '$albumlink' => $a->get_baseurl() . '/photos/' 
1054                                         . $a->data['user']['nickname'] . '/album/' . bin2hex($rr['album']),
1055                                 '$albumname' => $rr['album'],
1056                                 '$albumalt' => t('View Album'),
1057                                 '$imgalt' => $rr['filename']
1058                         ));
1059
1060                 }
1061                 $o .= '<div id="photo-top-end"></div>';
1062         }
1063         return $o;
1064 }