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