]> git.mxchange.org Git - friendica.git/blob - mod/photos.php
add micro profile photo
[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],'@[url=' . str_replace(',','%2c',$profile) . ']' . $newname  . '[/url]');
316                                                         else
317                                                                 $taginfo[] = array($newname,$profile,$notify,null,$str_tags .= '@[url=' . $profile . ']' . $newname     . '[/url]');
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['tag']           = $tagged[4];
388                                         $arr['inform']        = $tagged[2];
389
390                                         $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]' ;
391                                         $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" ;
392
393                                         $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $tagged[0] . '</title><id>' . $tagged[1] . '/' . $tagged[0] . '</id>';
394                                         $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $tagged[1] . '" />' . "\n");
395                                         if($tagged[3])
396                                                 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $tagged[3]['photo'] . '" />' . "\n");
397                                         $arr['object'] .= '</link></object>' . "\n";
398
399                                         $arr['target'] = '<target><type>' . ACTIVITY_OBJ_PHOTO . '</type><title>' . $p[0]['desc'] . '</title><id>'
400                                                 . $a->get_baseurl() . '/photos/' . $contact_record['nickname'] . '/image/' . $p[0]['resource-id'] . '</id>';
401                                         $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>';
402
403                                         $item_id = item_store($arr);
404                                         $php_path = ((strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
405                                         proc_close(proc_open("\"$php_path\" \"include/notifier.php\" \"tag\" \"$item_id\" & ",
406                                                 array(),$foo));
407                                 }
408
409                         }
410
411                 }
412                 goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
413                 return; // NOTREACHED
414         }
415
416
417         // default post action - upload a photo
418
419         if(! x($_FILES,'userfile'))
420                 killme();
421
422         if($_POST['partitionCount'])
423                 $java_upload = true;
424         else
425                 $java_upload = false;
426
427         $album =  notags(trim($_POST['album']));
428         $newalbum = notags(trim($_POST['newalbum']));
429
430         if(! strlen($album)) {
431                 if(strlen($newalbum))
432                         $album = $newalbum;
433                 else
434                         $album = datetime_convert('UTC',date_default_timezone_get(),'now', 'Y');
435         }
436
437         $r = q("SELECT * FROM `photo` WHERE `album` = '%s' AND `uid` = %d",
438                 dbesc($album),
439                 intval(local_user())
440         );
441         if((! count($r)) || ($album == t('Profile Photos')))
442                 $visible = 1;
443         else
444                 $visible = 0;
445
446
447         $str_group_allow   = perms2str($_POST['group_allow']);
448         $str_contact_allow = perms2str($_POST['contact_allow']);
449         $str_group_deny    = perms2str($_POST['group_deny']);
450         $str_contact_deny  = perms2str($_POST['contact_deny']);
451
452         $src               = $_FILES['userfile']['tmp_name'];
453         $filename          = basename($_FILES['userfile']['name']);
454         $filesize          = intval($_FILES['userfile']['size']);
455
456         $imagedata = @file_get_contents($src);
457         $ph = new Photo($imagedata);
458
459         if(! $ph->is_valid()) {
460                 notice( t('Unable to process image.') . EOL );
461                 @unlink($src);
462                 killme();
463         }
464
465         @unlink($src);
466
467         $width = $ph->getWidth();
468         $height = $ph->getHeight();
469
470         $smallest = 0;
471
472         $photo_hash = photo_new_resource();
473
474         $r = $ph->store(local_user(), 0, $photo_hash, $filename, $album, 0 , 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
475
476         if(! $r) {
477                 notice( t('Image upload failed.') . EOL );
478                 killme();
479         }
480
481         if($width > 640 || $height > 640) {
482                 $ph->scaleImage(640);
483                 $ph->store(local_user(), 0, $photo_hash, $filename, $album, 1, 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
484                 $smallest = 1;
485         }
486
487         if($width > 320 || $height > 320) {
488                 $ph->scaleImage(320);
489                 $ph->store(local_user(), 0, $photo_hash, $filename, $album, 2, 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
490                 $smallest = 2;
491         }
492         
493         $basename = basename($filename);
494         $uri = item_new_uri($a->get_hostname(), local_user());
495
496         // Create item container
497
498
499         $arr = array();
500
501         $arr['uid']           = local_user();
502         $arr['uri']           = $uri;
503         $arr['parent-uri']    = $uri;
504         $arr['type']          = 'photo';
505         $arr['wall']          = 1;
506         $arr['resource-id']   = $photo_hash;
507         $arr['contact-id']    = $contact_record['id'];
508         $arr['owner-name']    = $contact_record['name'];
509         $arr['owner-link']    = $contact_record['url'];
510         $arr['owner-avatar']  = $contact_record['thumb'];
511         $arr['author-name']   = $contact_record['name'];
512         $arr['author-link']   = $contact_record['url'];
513         $arr['author-avatar'] = $contact_record['thumb'];
514         $arr['title']         = '';
515         $arr['allow_cid']     = $str_contact_allow;
516         $arr['allow_gid']     = $str_group_allow;
517         $arr['deny_cid']      = $str_contact_deny;
518         $arr['deny_gid']      = $str_group_deny;
519         $arr['last-child']    = 1;
520         $arr['visible']       = $visible;
521         $arr['body']          = '[url=' . $a->get_baseurl() . '/photos/' . $contact_record['nickname'] . '/image/' . $photo_hash . ']' 
522                                 . '[img]' . $a->get_baseurl() . "/photo/{$photo_hash}-{$smallest}.jpg" . '[/img]' 
523                                 . '[/url]';
524
525         $item_id = item_store($arr);
526
527         if(! $java_upload) {
528                 goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
529                 return; // NOTREACHED
530         }
531
532         killme();
533         return; // NOTREACHED
534
535 }
536
537
538
539 function photos_content(&$a) {
540
541         // URLs:
542         // photos/name
543         // photos/name/upload
544         // photos/name/album/xxxxx
545         // photos/name/album/xxxxx/edit
546         // photos/name/image/xxxxx
547         // photos/name/image/xxxxx/edit
548
549
550         if(! x($a->data,'user')) {
551                 notice( t('No photos selected') . EOL );
552                 return;
553         }
554
555         $_SESSION['photo_return'] = $a->cmd;
556
557         //
558         // Parse arguments 
559         //
560
561         if($a->argc > 3) {
562                 $datatype = $a->argv[2];
563                 $datum = $a->argv[3];
564         }
565         elseif(($a->argc > 2) && ($a->argv[2] === 'upload'))
566                 $datatype = 'upload';
567         else
568                 $datatype = 'summary';
569
570         if($a->argc > 4)
571                 $cmd = $a->argv[4];
572         else
573                 $cmd = 'view';
574
575         //
576         // Setup permissions structures
577         //
578
579         $owner_uid = $a->data['user']['uid'];
580
581
582
583         $contact = null;
584         $remote_contact = false;
585
586         if(remote_user()) {
587                 $contact_id = $_SESSION['visitor_id'];
588                 $groups = init_groups_visitor($contact_id);
589                 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
590                         intval($contact_id),
591                         intval($owner_uid)
592                 );
593                 if(count($r)) {
594                         $contact = $r[0];
595                         $remote_contact = true;
596                 }
597         }
598
599         if(! $remote_contact) {
600                 if(local_user()) {
601                         $contact_id = $_SESSION['cid'];
602                         $contact = $a->contact;
603                 }
604         }
605
606
607         // default permissions - anonymous user
608
609         $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = '' ";
610
611         // Profile owner - everything is visible
612
613         if(local_user() && (local_user() == $owner_uid)) {
614                 $sql_extra = '';        
615         }
616         elseif(remote_user()) {
617                 // authenticated visitor - here lie dragons
618                 $gs = '<<>>'; // should be impossible to match
619                 if(count($groups)) {
620                         foreach($groups as $g)
621                                 $gs .= '|<' . intval($g) . '>';
622                 } 
623                 $sql_extra = sprintf(
624                         " AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' ) 
625                           AND ( `deny_cid`  = '' OR  NOT `deny_cid` REGEXP '<%d>' ) 
626                           AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
627                           AND ( `deny_gid`  = '' OR NOT `deny_gid` REGEXP '%s') ",
628
629                         intval($_SESSION['visitor_id']),
630                         intval($_SESSION['visitor_id']),
631                         dbesc($gs),
632                         dbesc($gs)
633                 );
634         }
635
636         //
637         // dispatch request
638         //
639
640
641         if($datatype === 'upload') {
642                 if( ! (local_user() && (local_user() == $a->data['user']['uid']))) {
643                         notice( t('Permission denied.'));
644                         return;
645                 }
646                 $albumselect = '<select id="photos-upload-album-select" name="album" size="4">';
647
648                 $albumselect .= '<option value="" selected="selected" >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option>';
649                 if(count($a->data['albums'])) {
650                         foreach($a->data['albums'] as $album) {
651                                 if(($album['album'] === '') || ($album['album'] == t('Contact Photos')))
652                                         continue;
653                                 $albumselect .= '<option value="' . $album['album'] . '">' . $album['album'] . '</option>';
654                         }
655                 }
656
657                 $celeb = ((($a->user['page-flags'] == PAGE_SOAPBOX) || ($a->user['page-flags'] == PAGE_COMMUNITY)) ? true : false);
658
659                 $albumselect .= '</select>';
660                 $tpl = load_view_file('view/photos_upload.tpl');
661                 $o .= replace_macros($tpl,array(
662                         '$pagename' => t('Upload Photos'),
663                         '$sessid' => session_id(),
664                         '$newalbum' => t('New album name: '),
665                         '$existalbumtext' => t('or existing album name: '),
666                         '$filestext' => t('Select files to upload: '),
667                         '$albumselect' => $albumselect,
668                         '$permissions' => t('Permissions'),
669                         '$aclselect' => populate_acl($a->user, $celeb),
670                         '$archive' => $a->get_baseurl() . '/jumploader_z.jar',
671                         '$nojava' => t('Use the following controls only if the Java uploader [above] fails to launch.'),
672                         '$uploadurl' => $a->get_baseurl() . '/photos',
673                         '$submit' => t('Submit')
674                 ));
675
676                 return $o; 
677
678         }
679
680         if($datatype === 'album') {
681
682                 $album = hex2bin($datum);
683
684                 $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` = '%s' 
685                         $sql_extra GROUP BY `resource-id`",
686                         intval($a->data['user']['uid']),
687                         dbesc($album)
688                 );
689                 if(count($r))
690                         $a->set_pager_total(count($r));
691
692
693                 $r = q("SELECT `resource-id`, `id`, `filename`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` = '%s' 
694                         $sql_extra GROUP BY `resource-id` ORDER BY `created` DESC LIMIT %d , %d",
695                         intval($a->data['user']['uid']),
696                         dbesc($album),
697                         intval($a->pager['start']),
698                         intval($a->pager['itemspage'])
699                 );
700
701                 $o .= '<h3>' . $album . '</h3>';
702                 
703                 if($cmd === 'edit') {           
704                         if(($album != t('Profile Photos')) && ($album != t('Contact Photos'))) {
705                                 if(local_user() && (local_user() == $a->data['user']['uid'])) {
706                                         $edit_tpl = load_view_file('view/album_edit.tpl');
707                                         $o .= replace_macros($edit_tpl,array(
708                                                 '$nametext' => t('New album name: '),
709                                                 '$album' => $album,
710                                                 '$hexalbum' => bin2hex($album),
711                                                 '$submit' => t('Submit'),
712                                                 '$dropsubmit' => t('Delete Album')
713                                         ));
714                                 }
715                         }
716                 }
717                 else {
718                         if(($album != t('Profile Photos')) && ($album != t('Contact Photos'))) {
719                                 if(local_user() && (local_user() == $a->data['user']['uid'])) {
720                                         $o .= '<div id="album-edit-link"><a href="'. $a->get_baseurl() . '/photos/' 
721                                                 . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '/edit' . '">' 
722                                                 . t('Edit Album') . '</a></div>';
723                                 }
724                         }
725                 }
726                 $tpl = load_view_file('view/photo_album.tpl');
727                 if(count($r))
728                         foreach($r as $rr) {
729                                 $o .= replace_macros($tpl,array(
730                                         '$id' => $rr['id'],
731                                         '$photolink' => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id'],
732                                         '$phototitle' => t('View Photo'),
733                                         '$imgsrc' => $a->get_baseurl() . '/photo/' . $rr['resource-id'] . '-' . $rr['scale'] . '.jpg',
734                                         '$imgalt' => $rr['filename']
735                                 ));
736
737                 }
738                 $o .= '<div id="photo-album-end"></div>';
739                 return $o;
740
741         }       
742
743
744         if($datatype === 'image') {
745
746                 require_once('security.php');
747                 require_once('bbcode.php');
748
749                 $o = '<div id="live-display"></div>' . "\r\n";
750                 // fetch image, item containing image, then comments
751
752                 $ph = q("SELECT * FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' 
753                         $sql_extra ORDER BY `scale` ASC ",
754                         intval($a->data['user']['uid']),
755                         dbesc($datum)
756                 );
757
758                 if(! count($ph)) {
759                         notice( t('Photo not available') . EOL );
760                         return;
761                 }
762
763                 if(count($ph) == 1)
764                         $hires = $lores = $ph[0];
765                 if(count($ph) > 1) {
766                         if($ph[1]['scale'] == 2) {
767                                 // original is 640 or less, we can display it directly
768                                 $hires = $lores = $ph[0];
769                         }
770                         else {
771                         $hires = $ph[0];
772                         $lores = $ph[1];
773                         }
774                 }
775
776                 
777                 $o .= '<h3>' . '<a href="' . $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($ph[0]['album']) . '">' . $ph[0]['album'] . '</a></h3>';
778  
779                 if(local_user() && ($ph[0]['uid'] == local_user())) {
780                         $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>';
781                 }
782
783
784                 $o .= '<a href="' . $a->get_baseurl() . '/photo/' 
785                         . $hires['resource-id'] . '-' . $hires['scale'] . '.jpg" title="' 
786                         . t('View Full Size') . '" ><img src="' . $a->get_baseurl() . '/photo/' 
787                         . $lores['resource-id'] . '-' . $lores['scale'] . '.jpg' . '" /></a>';
788
789
790                 // Do we have an item for this photo?
791
792                 $linked_items = q("SELECT * FROM `item` WHERE `resource-id` = '%s' $sql_extra LIMIT 1",
793                         dbesc($datum)
794                 );
795                 if(count($linked_items)) {
796                         $link_item = $linked_items[0];
797                         $r = q("SELECT COUNT(*) AS `total`
798                                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
799                                 WHERE `parent-uri` = '%s' AND `uri` != '%s' AND `item`.`deleted` = 0
800                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
801                                 AND `item`.`uid` = %d 
802                                 $sql_extra ",
803                                 dbesc($link_item['uri']),
804                                 dbesc($link_item['uri']),
805                                 intval($link_item['uid'])
806
807                         );
808
809                         if(count($r))
810                                 $a->set_pager_total($r[0]['total']);
811
812
813                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
814                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`network`, 
815                                 `contact`.`rel`, `contact`.`thumb`, `contact`.`self`, 
816                                 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
817                                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
818                                 WHERE `parent-uri` = '%s' AND `uri` != '%s' AND `item`.`deleted` = 0
819                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
820                                 AND `item`.`uid` = %d
821                                 $sql_extra
822                                 ORDER BY `parent` DESC, `id` ASC LIMIT %d ,%d ",
823                                 dbesc($link_item['uri']),
824                                 dbesc($link_item['uri']),
825                                 intval($link_item['uid']),
826                                 intval($a->pager['start']),
827                                 intval($a->pager['itemspage'])
828
829                         );
830                 
831                         if((local_user()) && (local_user() == $link_item['uid'])) {
832                                 q("UPDATE `item` SET `unseen` = 0 WHERE `parent` = %d and `uid` = %d",
833                                         intval($link_item['parent']),
834                                         intval(local_user())
835                                 );
836                         }
837                 }
838
839                 $o .= '<div id="photo-caption" >' . $ph[0]['desc'] . '</div>';
840
841                 if(count($linked_items) && strlen($link_item['tag'])) {
842                         $arr = explode(',',$link_item['tag']);
843                         // parse tags and add links     
844                         $o .= '<div id="in-this-photo-text">' . t('Tags: ') . '</div>';
845                         $o .= '<div id="in-this-photo">';
846                         $tag_str = '';
847                         foreach($arr as $t) {
848                                 if(strlen($tag_str))
849                                         $tag_str .= ', ';
850                                 $tag_str .= bbcode($t);
851                         } 
852                         $o .= $tag_str . '</div>';
853                 }
854
855
856                 if($cmd === 'edit') {
857                         $edit_tpl = load_view_file('view/photo_edit.tpl');
858                         $o .= replace_macros($edit_tpl, array(
859                                 '$id' => $ph[0]['id'],
860                                 '$resource_id' => $ph[0]['resource-id'],
861                                 '$capt_label' => t('Caption'),
862                                 '$caption' => $ph[0]['desc'],
863                                 '$tag_label' => t('Add a Tag'),
864                                 '$tags' => $link_item['tag'],
865                                 '$help_tags' => t('Example: @bob, @Barbara_Jensen, @jim@example.com, #California, #camping'),
866                                 '$item_id' => ((count($linked_items)) ? $link_item['id'] : 0),
867                                 '$submit' => t('Submit'),
868                                 '$delete' => t('Delete Photo')
869
870                         ));
871                 }
872
873                 if(count($linked_items)) {
874
875                         $cmnt_tpl = load_view_file('view/comment_item.tpl');
876                         $tpl = load_view_file('view/photo_item.tpl');
877                         $return_url = $a->cmd;
878
879                         $like_tpl = load_view_file('view/like.tpl');
880
881                         $likebuttons = '';
882
883                         if(can_write_wall($a,$a->data['user']['uid']))
884                                 $likebuttons = replace_macros($like_tpl,array('$id' => $link_item['id']));
885
886                         if(! count($r)) {
887                                 $o .= '<div id="photo-like-div">';
888                                 $o .= $likebuttons;
889                                 $o .= '</div>';
890
891                                 if(can_write_wall($a,$a->data['user']['uid'])) {
892                                         if($link_item['last-child']) {
893                                                 $o .= replace_macros($cmnt_tpl,array(
894                                                         '$return_path' => $return_url,
895                                                         '$type' => 'wall-comment',
896                                                         '$id' => $link_item['id'],
897                                                         '$parent' => $link_item['id'],
898                                                         '$profile_uid' =>  $a->data['user']['uid'],
899                                                         '$mylink' => $contact['url'],
900                                                         '$mytitle' => t('This is you'),
901                                                         '$myphoto' => $contact['thumb'],
902                                                         '$ww' => ''
903                                                 ));
904                                         }
905                                 }
906                         }
907
908                         $alike = array();
909                         $dlike = array();
910
911                         // display comments
912                         if(count($r)) {
913
914                                 foreach($r as $item) {
915                                         like_puller($a,$item,$alike,'like');
916                                         like_puller($a,$item,$dlike,'dislike');
917                                 }
918
919                     $like    = ((isset($alike[$link_item['id']])) ? format_like($alike[$link_item['id']],$alike[$link_item['id'] . '-l'],'like',$link_item['id']) : '');
920                                 $dislike = ((isset($dlike[$link_item['id']])) ? format_like($dlike[$link_item['id']],$dlike[$link_item['id'] . '-l'],'dislike',$link_item['id']) : '');
921
922                                 $o .= '<div id="photo-like-div">';
923                                 $o .= $likebuttons;
924                                 $o .= $like;
925                                 $o .= $dislike;
926                                 $o .= '</div>';
927
928
929
930                                 if(can_write_wall($a,$a->data['user']['uid'])) {
931                                         if($link_item['last-child']) {
932                                                 $o .= replace_macros($cmnt_tpl,array(
933                                                         '$return_path' => $return_url,
934                                                         '$type' => 'wall-comment',
935                                                         '$id' => $link_item['id'],
936                                                         '$parent' => $link_item['id'],
937                                                         '$profile_uid' =>  $a->data['user']['uid'],
938                                                         '$mylink' => $contact['url'],
939                                                         '$mytitle' => t('This is you'),
940                                                         '$myphoto' => $contact['thumb'],
941                                                         '$ww' => ''
942                                                 ));
943                                         }
944                                 }
945
946
947                                 foreach($r as $item) {
948                                         $comment = '';
949                                         $template = $tpl;
950                                         $sparkle = '';
951
952                                         if(((activity_match($item['verb'],ACTIVITY_LIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE))) && ($item['id'] != $item['parent']))
953                                                 continue;
954
955                                         $redirect_url = $a->get_baseurl() . '/redir/' . $item['cid'] ;
956                         
957                                         if(can_write_wall($a,$a->data['user']['uid'])) {
958
959                                                 if($item['last-child']) {
960                                                         $comment = replace_macros($cmnt_tpl,array(
961                                                                 '$return_path' => $return_url,
962                                                                 '$type' => 'wall-comment',
963                                                                 '$id' => $item['item_id'],
964                                                                 '$parent' => $item['parent'],
965                                                                 '$profile_uid' =>  $a->data['user']['uid'],
966                                                                 '$mylink' => $contact['url'],
967                                                                 '$mytitle' => t('This is you'),
968                                                                 '$myphoto' => $contact['thumb'],
969                                                                 '$ww' => ''
970                                                         ));
971                                                 }
972                                         }
973
974
975                                         if(local_user() && ($item['contact-uid'] == local_user()) 
976                                                 && ($item['network'] == 'dfrn') && (! $item['self'] )) {
977                                                 $profile_url = $redirect_url;
978                                                 $sparkle = ' sparkle';
979                                         }
980                                         else {
981                                                 $profile_url = $item['url'];
982                                                 $sparkle = '';
983                                         }
984  
985                                         $profile_name = ((strlen($item['author-name'])) ? $item['author-name'] : $item['name']);
986                                         $profile_avatar = ((strlen($item['author-avatar'])) ? $item['author-avatar'] : $item['thumb']);
987                                         $profile_link = $profile_url;
988
989                                         $drop = '';
990
991                                         if(($item['contact-id'] == $_SESSION['visitor_id']) || ($item['uid'] == local_user()))
992                                                 $drop = replace_macros(load_view_file('view/wall_item_drop.tpl'), array('$id' => $item['id']));
993
994
995                                         $o .= replace_macros($template,array(
996                                                 '$id' => $item['item_id'],
997                                                 '$profile_url' => $profile_link,
998                                                 '$name' => $profile_name,
999                                                 '$thumb' => $profile_avatar,
1000                                                 '$sparkle' => $sparkle,
1001                                                 '$title' => $item['title'],
1002                                                 '$body' => bbcode($item['body']),
1003                                                 '$ago' => relative_date($item['created']),
1004                                                 '$indent' => (($item['parent'] != $item['item_id']) ? ' comment' : ''),
1005                                                 '$drop' => $drop,
1006                                                 '$comment' => $comment
1007                                         ));
1008                                 }
1009                         }
1010
1011                         $o .= paginate($a);
1012                 }
1013                 return $o;
1014         }
1015
1016         // Default - show recent photos with upload link (if applicable)
1017         $o = '';
1018
1019         $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` != '%s' 
1020                 $sql_extra GROUP BY `resource-id`",
1021                 intval($a->data['user']['uid']),
1022                 dbesc( t('Contact Photos'))
1023         );
1024         if(count($r))
1025                 $a->set_pager_total(count($r));
1026
1027
1028         $r = q("SELECT `resource-id`, `id`, `filename`, `album`, max(`scale`) AS `scale` FROM `photo` 
1029                 WHERE `uid` = %d AND `album` != '%s' 
1030                 $sql_extra GROUP BY `resource-id` ORDER BY `created` DESC LIMIT %d , %d",
1031                 intval($a->data['user']['uid']),
1032                 dbesc( t('Contact Photos')),
1033                 intval($a->pager['start']),
1034                 intval($a->pager['itemspage'])
1035         );
1036
1037         $o .= '<h3>' . t('Recent Photos') . '</h3>';
1038
1039         if( local_user() && (local_user() == $a->data['user']['uid'])) {
1040                 $o .= '<div id="photo-top-links"><a id="photo-top-upload-link" href="'. $a->get_baseurl() . '/photos/' 
1041                         . $a->data['user']['nickname'] . '/upload' . '">' . t('Upload New Photos') . '</a></div>';
1042         }
1043
1044         $tpl = load_view_file('view/photo_top.tpl');
1045         if(count($r)) {
1046                 foreach($r as $rr) {
1047                         $o .= replace_macros($tpl,array(
1048                                 '$id' => $rr['id'],
1049                                 '$photolink' => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] 
1050                                         . '/image/' . $rr['resource-id'],
1051                                 '$phototitle' => t('View Photo'),
1052                                 '$imgsrc' => $a->get_baseurl() . '/photo/' 
1053                                         . $rr['resource-id'] . '-' . $rr['scale'] . '.jpg',
1054                                 '$albumlink' => $a->get_baseurl() . '/photos/' 
1055                                         . $a->data['user']['nickname'] . '/album/' . bin2hex($rr['album']),
1056                                 '$albumname' => $rr['album'],
1057                                 '$albumalt' => t('View Album'),
1058                                 '$imgalt' => $rr['filename']
1059                         ));
1060
1061                 }
1062                 $o .= '<div id="photo-top-end"></div>';
1063         }
1064         return $o;
1065 }