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