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