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