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