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