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