]> git.mxchange.org Git - friendica.git/blob - mod/photos.php
remote_user can now support multiple contacts being logged in at once
[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 ",
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                                                         elseif(strstr($name,'_') || strstr($name,' ')) {
485                                                                 $newname = str_replace('_',' ',$name);
486                                                                 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
487                                                                         dbesc($newname),
488                                                                         intval($page_owner_uid)
489                                                                 );
490                                                         }
491                                                         else {
492                                                                 $r = q("SELECT * FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
493                                                                         dbesc($name),
494                                                                         dbesc($name),
495                                                                         intval($page_owner_uid)
496                                                                 );
497                                                         }
498                                                         if(count($r)) {
499                                                                 $newname = $r[0]['name'];
500                                                                 $profile = $r[0]['url'];
501                                                                 $notify = 'cid:' . $r[0]['id'];
502                                                                 if(strlen($inform))
503                                                                         $inform .= ',';
504                                                                 $inform .= $notify;
505                                                         }
506                                                 }
507                                                 if($profile) {
508                                                         if(substr($notify,0,4) === 'cid:')
509                                                                 $taginfo[] = array($newname,$profile,$notify,$r[0],'@[url=' . str_replace(',','%2c',$profile) . ']' . $newname  . '[/url]');
510                                                         else
511                                                                 $taginfo[] = array($newname,$profile,$notify,null,$str_tags .= '@[url=' . $profile . ']' . $newname     . '[/url]');
512                                                         if(strlen($str_tags))
513                                                                 $str_tags .= ',';
514                                                         $profile = str_replace(',','%2c',$profile);
515                                                         $str_tags .= '@[url=' . $profile . ']' . $newname       . '[/url]';
516                                                 }
517                                         }
518                                 }
519                         }
520
521                         $newtag = $old_tag;
522                         if(strlen($newtag) && strlen($str_tags)) 
523                                 $newtag .= ',';
524                         $newtag .= $str_tags;
525
526                         $newinform = $old_inform;
527                         if(strlen($newinform) && strlen($inform))
528                                 $newinform .= ',';
529                         $newinform .= $inform;
530
531                         $r = q("UPDATE `item` SET `tag` = '%s', `inform` = '%s', `edited` = '%s', `changed` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
532                                 dbesc($newtag),
533                                 dbesc($newinform),
534                                 dbesc(datetime_convert()),
535                                 dbesc(datetime_convert()),
536                                 intval($item_id),
537                                 intval($page_owner_uid)
538                         );
539
540                         $best = 0;
541                         foreach($p as $scales) {
542                                 if(intval($scales['scale']) == 2) {
543                                         $best = 2;
544                                         break;
545                                 }
546                                 if(intval($scales['scale']) == 4) {
547                                         $best = 4;
548                                         break;
549                                 }
550                         }
551
552                         if(count($taginfo)) {
553                                 foreach($taginfo as $tagged) {
554                 
555                                         $uri = item_new_uri($a->get_hostname(),$page_owner_uid);
556
557                                         $arr = array();
558
559                                         $arr['uid']           = $page_owner_uid;
560                                         $arr['uri']           = $uri;
561                                         $arr['parent-uri']    = $uri;
562                                         $arr['type']          = 'activity';
563                                         $arr['wall']          = 1;
564                                         $arr['contact-id']    = $owner_record['id'];
565                                         $arr['owner-name']    = $owner_record['name'];
566                                         $arr['owner-link']    = $owner_record['url'];
567                                         $arr['owner-avatar']  = $owner_record['thumb'];
568                                         $arr['author-name']   = $owner_record['name'];
569                                         $arr['author-link']   = $owner_record['url'];
570                                         $arr['author-avatar'] = $owner_record['thumb'];
571                                         $arr['title']         = '';
572                                         $arr['allow_cid']     = $p[0]['allow_cid'];
573                                         $arr['allow_gid']     = $p[0]['allow_gid'];
574                                         $arr['deny_cid']      = $p[0]['deny_cid'];
575                                         $arr['deny_gid']      = $p[0]['deny_gid'];
576                                         $arr['last-child']    = 1;
577                                         $arr['visible']       = 1;
578                                         $arr['verb']          = ACTIVITY_TAG;
579                                         $arr['object-type']   = ACTIVITY_OBJ_PERSON;
580                                         $arr['target-type']   = ACTIVITY_OBJ_PHOTO;
581                                         $arr['tag']           = $tagged[4];
582                                         $arr['inform']        = $tagged[2];
583                                         $arr['origin']        = 1;
584                                         $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]' ;
585                                         $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" ;
586
587                                         $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $tagged[0] . '</title><id>' . $tagged[1] . '/' . $tagged[0] . '</id>';
588                                         $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $tagged[1] . '" />' . "\n");
589                                         if($tagged[3])
590                                                 $arr['object'] .= xmlify('<link rel="photo" type="'.$p[0]['type'].'" href="' . $tagged[3]['photo'] . '" />' . "\n");
591                                         $arr['object'] .= '</link></object>' . "\n";
592
593                                         $arr['target'] = '<target><type>' . ACTIVITY_OBJ_PHOTO . '</type><title>' . $p[0]['desc'] . '</title><id>'
594                                                 . $a->get_baseurl() . '/photos/' . $owner_record['nickname'] . '/image/' . $p[0]['resource-id'] . '</id>';
595                                         $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>';
596
597                                         $item_id = item_store($arr);
598                                         if($item_id) {
599                                                 q("UPDATE `item` SET `plink` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
600                                                         dbesc($a->get_baseurl() . '/display/' . $owner_record['nickname'] . '/' . $item_id),
601                                                         intval($page_owner_uid),
602                                                         intval($item_id)
603                                                 );
604
605                                                 proc_run('php',"include/notifier.php","tag","$item_id");
606                                         }
607                                 }
608
609                         }
610
611                 }
612                 goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
613                 return; // NOTREACHED
614         }
615
616
617         /**
618          * default post action - upload a photo
619          */
620
621         call_hooks('photo_post_init', $_POST);
622
623         /**
624          * Determine the album to use
625          */
626
627         $album    = notags(trim($_REQUEST['album']));
628         $newalbum = notags(trim($_REQUEST['newalbum']));
629
630         logger('mod/photos.php: photos_post(): album= ' . $album . ' newalbum= ' . $newalbum , LOGGER_DEBUG);
631
632         if(! strlen($album)) {
633                 if(strlen($newalbum))
634                         $album = $newalbum;
635                 else
636                         $album = datetime_convert('UTC',date_default_timezone_get(),'now', 'Y');
637         }
638
639         /**
640          *
641          * We create a wall item for every photo, but we don't want to
642          * overwhelm the data stream with a hundred newly uploaded photos.
643          * So we will make the first photo uploaded to this album in the last several hours
644          * visible by default, the rest will become visible over time when and if
645          * they acquire comments, likes, dislikes, and/or tags 
646          *
647          */
648
649         $r = q("SELECT * FROM `photo` WHERE `album` = '%s' AND `uid` = %d AND `created` > UTC_TIMESTAMP() - INTERVAL 3 HOUR ",
650                 dbesc($album),
651                 intval($page_owner_uid)
652         );
653         if((! count($r)) || ($album == t('Profile Photos')))
654                 $visible = 1;
655         else
656                 $visible = 0;
657         
658         if(intval($_REQUEST['not_visible']) || $_REQUEST['not_visible'] === 'true')
659                 $visible = 0;
660
661         $str_group_allow   = perms2str(((is_array($_REQUEST['group_allow']))   ? $_REQUEST['group_allow']   : explode(',',$_REQUEST['group_allow'])));
662         $str_contact_allow = perms2str(((is_array($_REQUEST['contact_allow'])) ? $_REQUEST['contact_allow'] : explode(',',$_REQUEST['contact_allow'])));
663         $str_group_deny    = perms2str(((is_array($_REQUEST['group_deny']))    ? $_REQUEST['group_deny']    : explode(',',$_REQUEST['group_deny'])));
664         $str_contact_deny  = perms2str(((is_array($_REQUEST['contact_deny']))  ? $_REQUEST['contact_deny']  : explode(',',$_REQUEST['contact_deny'])));
665
666         $ret = array('src' => '', 'filename' => '', 'filesize' => 0, 'type' => '');
667
668         call_hooks('photo_post_file',$ret);
669
670         if(x($ret,'src') && x($ret,'filesize')) {
671                 $src      = $ret['src'];
672                 $filename = $ret['filename'];
673                 $filesize = $ret['filesize'];
674                 $type     = $ret['type'];
675         }
676         else {
677                 $src        = $_FILES['userfile']['tmp_name'];
678                 $filename   = basename($_FILES['userfile']['name']);
679                 $filesize   = intval($_FILES['userfile']['size']);
680                 $type       = $_FILES['userfile']['type'];
681         }
682         if ($type=="") $type=guess_image_type($filename);
683
684         logger('photos: upload: received file: ' . $filename . ' as ' . $src . ' ('. $type . ') ' . $filesize . ' bytes', LOGGER_DEBUG);
685
686         $maximagesize = get_config('system','maximagesize');
687
688         if(($maximagesize) && ($filesize > $maximagesize)) {
689                 notice( t('Image exceeds size limit of ') . $maximagesize . EOL);
690                 @unlink($src);
691                 $foo = 0;
692                 call_hooks('photo_post_end',$foo);
693                 return;
694         }
695
696         if(! $filesize) {
697                 notice( t('Image file is empty.') . EOL);
698                 @unlink($src);
699                 $foo = 0;
700                 call_hooks('photo_post_end',$foo);
701                 return;
702         }
703
704         logger('mod/photos.php: photos_post(): loading the contents of ' . $src , LOGGER_DEBUG);
705
706         $imagedata = @file_get_contents($src);
707
708
709
710         $r = q("select sum(octet_length(data)) as total from photo where uid = %d and scale = 0 and album != 'Contact Photos' ",
711                 intval($a->data['user']['uid'])
712         );
713
714         $limit = service_class_fetch($a->data['user']['uid'],'photo_upload_limit');
715
716         if(($limit !== false) && (($r[0]['total'] + strlen($imagedata)) > $limit)) {
717                 notice( upgrade_message() . EOL );
718                 @unlink($src);
719                 $foo = 0;
720                 call_hooks('photo_post_end',$foo);
721                 killme();
722         }
723                 
724
725         $ph = new Photo($imagedata, $type);
726
727         if(! $ph->is_valid()) {
728                 logger('mod/photos.php: photos_post(): unable to process image' , LOGGER_DEBUG);
729                 notice( t('Unable to process image.') . EOL );
730                 @unlink($src);
731                 $foo = 0;
732                 call_hooks('photo_post_end',$foo);
733                 killme();
734         }
735
736         $ph->orient($src);
737         @unlink($src);
738
739         $max_length = get_config('system','max_image_length');
740         if(! $max_length)
741                 $max_length = MAX_IMAGE_LENGTH;
742         if($max_length > 0)
743                 $ph->scaleImage($max_length);
744
745         $width  = $ph->getWidth();
746         $height = $ph->getHeight();
747
748         $smallest = 0;
749
750         $photo_hash = photo_new_resource();
751
752         $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);
753
754         if(! $r) {
755                 logger('mod/photos.php: photos_post(): image store failed' , LOGGER_DEBUG);
756                 notice( t('Image upload failed.') . EOL );
757                 killme();
758         }
759
760         if($width > 640 || $height > 640) {
761                 $ph->scaleImage(640);
762                 $ph->store($page_owner_uid, $visitor, $photo_hash, $filename, $album, 1, 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
763                 $smallest = 1;
764         }
765
766         if($width > 320 || $height > 320) {
767                 $ph->scaleImage(320);
768                 $ph->store($page_owner_uid, $visitor, $photo_hash, $filename, $album, 2, 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
769                 $smallest = 2;
770         }
771         
772         $basename = basename($filename);
773         $uri = item_new_uri($a->get_hostname(), $page_owner_uid);
774
775         // Create item container
776
777         $arr = array();
778
779         $arr['uid']           = $page_owner_uid;
780         $arr['uri']           = $uri;
781         $arr['parent-uri']    = $uri;
782         $arr['type']          = 'photo';
783         $arr['wall']          = 1;
784         $arr['resource-id']   = $photo_hash;
785         $arr['contact-id']    = $owner_record['id'];
786         $arr['owner-name']    = $owner_record['name'];
787         $arr['owner-link']    = $owner_record['url'];
788         $arr['owner-avatar']  = $owner_record['thumb'];
789         $arr['author-name']   = $owner_record['name'];
790         $arr['author-link']   = $owner_record['url'];
791         $arr['author-avatar'] = $owner_record['thumb'];
792         $arr['title']         = '';
793         $arr['allow_cid']     = $str_contact_allow;
794         $arr['allow_gid']     = $str_group_allow;
795         $arr['deny_cid']      = $str_contact_deny;
796         $arr['deny_gid']      = $str_group_deny;
797         $arr['last-child']    = 1;
798         $arr['visible']       = $visible;
799         $arr['origin']        = 1;
800
801         $arr['body']          = '[url=' . $a->get_baseurl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo_hash . ']' 
802                                 . '[img]' . $a->get_baseurl() . "/photo/{$photo_hash}-{$smallest}.".$ph->getExt() . '[/img]' 
803                                 . '[/url]';
804
805         $item_id = item_store($arr);
806
807         if($item_id) {
808                 q("UPDATE `item` SET `plink` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
809                         dbesc($a->get_baseurl() . '/display/' . $owner_record['nickname'] . '/' . $item_id),
810                         intval($page_owner_uid),
811                         intval($item_id)
812                 );
813         }
814         
815         if($visible) 
816                 proc_run('php', "include/notifier.php", 'wall-new', $item_id);
817
818         call_hooks('photo_post_end',intval($item_id));
819
820         // addon uploaders should call "killme()" [e.g. exit] within the photo_post_end hook
821         // if they do not wish to be redirected
822
823         goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
824         // NOTREACHED
825 }
826
827
828
829 function photos_content(&$a) {
830
831         // URLs:
832         // photos/name
833         // photos/name/upload
834         // photos/name/upload/xxxxx (xxxxx is album name)
835         // photos/name/album/xxxxx
836         // photos/name/album/xxxxx/edit
837         // photos/name/image/xxxxx
838         // photos/name/image/xxxxx/edit
839
840
841         if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
842                 notice( t('Public access denied.') . EOL);
843                 return;
844         }
845         
846         
847         require_once('include/bbcode.php');
848         require_once('include/security.php');
849         require_once('include/conversation.php');
850
851         if(! x($a->data,'user')) {
852                 notice( t('No photos selected') . EOL );
853                 return;
854         }
855
856         $phototypes = Photo::supportedTypes();
857
858         $_SESSION['photo_return'] = $a->cmd;
859
860         //
861         // Parse arguments 
862         //
863
864         if($a->argc > 3) {
865                 $datatype = $a->argv[2];
866                 $datum = $a->argv[3];
867         }
868         elseif(($a->argc > 2) && ($a->argv[2] === 'upload'))
869                 $datatype = 'upload';
870         else
871                 $datatype = 'summary';
872
873         if($a->argc > 4)
874                 $cmd = $a->argv[4];
875         else
876                 $cmd = 'view';
877
878         //
879         // Setup permissions structures
880         //
881
882         $can_post       = false;
883         $visitor        = 0;
884         $contact        = null;
885         $remote_contact = false;
886         $contact_id     = 0;
887
888         $owner_uid = $a->data['user']['uid'];
889
890         $community_page = (($a->data['user']['page-flags'] == PAGE_COMMUNITY) ? true : false);
891
892         if((local_user()) && (local_user() == $owner_uid))
893                 $can_post = true;
894         else {
895                 if($community_page && remote_user()) {
896                         if(is_array($_SESSION['remote'])) {
897                                 foreach($_SESSION['remote'] as $v) {
898                                         if($v['uid'] == $owner_uid) {
899                                                 $contact_id = $v['cid'];
900                                                 break;
901                                         }
902                                 }
903                         }
904                         if($contact_id) {
905
906                                 $r = q("SELECT `uid` FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1",
907                                         intval($contact_id),
908                                         intval($owner_uid)
909                                 );
910                                 if(count($r)) {
911                                         $can_post = true;
912                                         $contact = $r[0];
913                                         $remote_contact = true;
914                                         $visitor = $cid;
915                                 }
916                         }
917                 }
918         }
919
920         // perhaps they're visiting - but not a community page, so they wouldn't have write access
921
922         if(remote_user() && (! $visitor)) {
923                 $contact_id = 0;
924                 if(is_array($_SESSION['remote'])) {
925                         foreach($_SESSION['remote'] as $v) {
926                                 if($v['uid'] == $owner_uid) {
927                                         $contact_id = $v['cid'];
928                                         break;
929                                 }
930                         }
931                 }
932                 if($contact_id) {
933                         $groups = init_groups_visitor($contact_id);
934                         $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1",
935                                 intval($contact_id),
936                                 intval($owner_uid)
937                         );
938                         if(count($r)) {
939                                 $contact = $r[0];
940                                 $remote_contact = true;
941                         }
942                 }
943         }
944
945         if(! $remote_contact) {
946                 if(local_user()) {
947                         $contact_id = $_SESSION['cid'];
948                         $contact = $a->contact;
949                 }
950         }
951
952         if($a->data['user']['hidewall'] && (local_user() != $owner_uid) && (! $remote_contact)) {
953                 notice( t('Access to this item is restricted.') . EOL);
954                 return;
955         }
956
957         $sql_extra = permissions_sql($owner_uid,$remote_contact,$groups);
958
959         $o = "";
960
961         // tabs
962         $_is_owner = (local_user() && (local_user() == $owner_uid));
963         $o .= profile_tabs($a,$_is_owner, $a->data['user']['nickname']);        
964
965         //
966         // dispatch request
967         //
968
969
970         if($datatype === 'upload') {
971                 if(! ($can_post)) {
972                         notice( t('Permission denied.'));
973                         return;
974                 }
975
976
977                 $selname = (($datum) ? hex2bin($datum) : '');
978
979
980                 $albumselect = '';
981
982                 
983                 $albumselect .= '<option value="" ' . ((! $selname) ? ' selected="selected" ' : '') . '>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option>';
984                 if(count($a->data['albums'])) {
985                         foreach($a->data['albums'] as $album) {
986                                 if(($album['album'] === '') || ($album['album'] === 'Contact Photos') || ($album['album'] === t('Contact Photos')))
987                                         continue;
988                                 $selected = (($selname === $album['album']) ? ' selected="selected" ' : '');
989                                 $albumselect .= '<option value="' . $album['album'] . '"' . $selected . '>' . $album['album'] . '</option>';
990                         }
991                 }
992
993                 $celeb = ((($a->user['page-flags'] == PAGE_SOAPBOX) || ($a->user['page-flags'] == PAGE_COMMUNITY)) ? true : false);
994
995                 $uploader = '';
996
997                 $ret = array('post_url' => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'],
998                                 'addon_text' => $uploader,
999                                 'default_upload' => true);
1000
1001
1002                 call_hooks('photo_upload_form',$ret);
1003
1004                 $default_upload = '<input id="photos-upload-choose" type="file" name="userfile" />      <div class="photos-upload-submit-wrapper" >
1005                 <input type="submit" name="submit" value="' . t('Submit') . '" id="photos-upload-submit" /> </div>';
1006
1007
1008                 $r = q("select sum(octet_length(data)) as total from photo where uid = %d and scale = 0 and album != 'Contact Photos' ",
1009                         intval($a->data['user']['uid'])
1010                 );
1011
1012
1013                 $limit = service_class_fetch($a->data['user']['uid'],'photo_upload_limit');
1014                 if($limit !== false) {
1015                         $usage_message = sprintf( t("You have used %1$.2f Mbytes of %2$.2f Mbytes photo storage."), $r[0]['total'] / 1024000, $limit / 1024000 );
1016                 }
1017                 else {
1018                         $usage_message = sprintf( t('You have used %1$.2f Mbytes of photo storage.'), $r[0]['total'] / 1024000 );
1019                 }
1020
1021
1022                 $tpl = get_markup_template('photos_upload.tpl');
1023                 $o .= replace_macros($tpl,array(
1024                         '$pagename' => t('Upload Photos'),
1025                         '$sessid' => session_id(),
1026                         '$usage' => $usage_message,
1027                         '$nickname' => $a->data['user']['nickname'],
1028                         '$newalbum' => t('New album name: '),
1029                         '$existalbumtext' => t('or existing album name: '),
1030                         '$nosharetext' => t('Do not show a status post for this upload'),
1031                         '$albumselect' => template_escape($albumselect),
1032                         '$permissions' => t('Permissions'),
1033                         '$aclselect' => (($visitor) ? '' : template_escape(populate_acl($a->user, $celeb))),
1034                         '$uploader' => $ret['addon_text'],
1035                         '$default' => (($ret['default_upload']) ? $default_upload : ''),
1036                         '$uploadurl' => $ret['post_url']
1037
1038                 ));
1039
1040                 return $o; 
1041         }
1042
1043         if($datatype === 'album') {
1044
1045                 $album = hex2bin($datum);
1046
1047                 $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` = '%s' 
1048                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id`",
1049                         intval($owner_uid),
1050                         dbesc($album)
1051                 );
1052                 if(count($r)) {
1053                         $a->set_pager_total(count($r));
1054                         $a->set_pager_itemspage(20);
1055                 }
1056
1057                 $r = q("SELECT `resource-id`, `id`, `filename`, type, max(`scale`) AS `scale`, `desc` FROM `photo` WHERE `uid` = %d AND `album` = '%s' 
1058                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id` ORDER BY `created` DESC LIMIT %d , %d",
1059                         intval($owner_uid),
1060                         dbesc($album),
1061                         intval($a->pager['start']),
1062                         intval($a->pager['itemspage'])
1063                 );
1064
1065                 $o .= '<h3>' . $album . '</h3>';
1066                 
1067                 if($cmd === 'edit') {           
1068                         if(($album !== t('Profile Photos')) && ($album !== 'Contact Photos') && ($album !== t('Contact Photos'))) {
1069                                 if($can_post) {
1070                                         $edit_tpl = get_markup_template('album_edit.tpl');
1071                                         $o .= replace_macros($edit_tpl,array(
1072                                                 '$nametext' => t('New album name: '),
1073                                                 '$nickname' => $a->data['user']['nickname'],
1074                                                 '$album' => template_escape($album),
1075                                                 '$hexalbum' => bin2hex($album),
1076                                                 '$submit' => t('Submit'),
1077                                                 '$dropsubmit' => t('Delete Album')
1078                                         ));
1079                                 }
1080                         }
1081                 }
1082                 else {
1083                         if(($album !== t('Profile Photos')) && ($album !== 'Contact Photos') && ($album !== t('Contact Photos'))) {
1084                                 if($can_post) {
1085                                         $o .= '<div id="album-edit-link"><a href="'. $a->get_baseurl() . '/photos/' 
1086                                                 . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '/edit' . '">' 
1087                                                 . t('Edit Album') . '</a></div>';
1088                                 }
1089                         }
1090                 }
1091
1092                 if($can_post) {
1093                         $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>';
1094                 }
1095
1096                 $tpl = get_markup_template('photo_album.tpl');
1097                 if(count($r))
1098                         $twist = 'rotright';
1099                         foreach($r as $rr) {
1100                                 if($twist == 'rotright')
1101                                         $twist = 'rotleft';
1102                                 else
1103                                         $twist = 'rotright';
1104                                 
1105                                 $ext = $phototypes[$rr['type']];
1106
1107                                 $o .= replace_macros($tpl,array(
1108                                         '$id' => $rr['id'],
1109                                         '$twist' => ' ' . $twist . rand(2,4),
1110                                         '$photolink' => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id'],
1111                                         '$phototitle' => t('View Photo'),
1112                                         '$imgsrc' => $a->get_baseurl() . '/photo/' . $rr['resource-id'] . '-' . $rr['scale'] . '.' .$ext,
1113                                         '$imgalt' => template_escape($rr['filename']),
1114                                         '$desc'=> template_escape($rr['desc'])
1115                                 ));
1116
1117                 }
1118                 $o .= '<div id="photo-album-end"></div>';
1119                 $o .= paginate($a);
1120
1121                 return $o;
1122
1123         }       
1124
1125
1126         if($datatype === 'image') {
1127
1128
1129
1130                 //$o = '';
1131                 // fetch image, item containing image, then comments
1132
1133                 $ph = q("SELECT * FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' 
1134                         $sql_extra ORDER BY `scale` ASC ",
1135                         intval($owner_uid),
1136                         dbesc($datum)
1137                 );
1138
1139                 if(! count($ph)) {
1140                         $ph = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' 
1141                                 LIMIT 1",
1142                                 intval($owner_uid),
1143                                 dbesc($datum)
1144                         );
1145                         if(count($ph)) 
1146                                 notice( t('Permission denied. Access to this item may be restricted.'));
1147                         else
1148                                 notice( t('Photo not available') . EOL );
1149                         return;
1150                 }
1151
1152                 $prevlink = '';
1153                 $nextlink = '';
1154
1155                 $prvnxt = q("SELECT `resource-id` FROM `photo` WHERE `album` = '%s' AND `uid` = %d AND `scale` = 0 
1156                         $sql_extra ORDER BY `created` DESC ",
1157                         dbesc($ph[0]['album']),
1158                         intval($owner_uid)
1159                 ); 
1160
1161                 if(count($prvnxt)) {
1162                         for($z = 0; $z < count($prvnxt); $z++) {
1163                                 if($prvnxt[$z]['resource-id'] == $ph[0]['resource-id']) {
1164                                         $prv = $z - 1;
1165                                         $nxt = $z + 1;
1166                                         if($prv < 0)
1167                                                 $prv = count($prvnxt) - 1;
1168                                         if($nxt >= count($prvnxt))
1169                                                 $nxt = 0;
1170                                         break;
1171                                 }
1172                         }
1173                         $edit_suffix = ((($cmd === 'edit') && ($can_post)) ? '/edit' : '');
1174                         $prevlink = $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$prv]['resource-id'] . $edit_suffix;
1175                         $nextlink = $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$nxt]['resource-id'] . $edit_suffix;
1176                 }
1177
1178
1179                 if(count($ph) == 1)
1180                         $hires = $lores = $ph[0];
1181                 if(count($ph) > 1) {
1182                         if($ph[1]['scale'] == 2) {
1183                                 // original is 640 or less, we can display it directly
1184                                 $hires = $lores = $ph[0];
1185                         }
1186                         else {
1187                         $hires = $ph[0];
1188                         $lores = $ph[1];
1189                         }
1190                 }
1191
1192                 $album_link = $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($ph[0]['album']);
1193                 $tools = Null;
1194                 $lock = Null;
1195  
1196                 if($can_post && ($ph[0]['uid'] == $owner_uid)) {
1197                         $tools = array(
1198                                 'edit'  => array($a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $datum . (($cmd === 'edit') ? '' : '/edit'), (($cmd === 'edit') ? t('View photo') : t('Edit photo'))),
1199                                 'profile'=>array($a->get_baseurl() . '/profile_photo/use/'.$ph[0]['resource-id'], t('Use as profile photo')),
1200                         );
1201
1202                         // lock
1203                         $lock = ( ( ($ph[0]['uid'] == local_user()) && (strlen($ph[0]['allow_cid']) || strlen($ph[0]['allow_gid']) 
1204                                         || strlen($ph[0]['deny_cid']) || strlen($ph[0]['deny_gid'])) ) 
1205                                         ? t('Private Message')
1206                                         : Null);
1207                         
1208                         
1209                 }
1210
1211                 if( $cmd === 'edit') {
1212                         $tpl = get_markup_template('photo_edit_head.tpl');
1213                         $a->page['htmlhead'] .= replace_macros($tpl,array(
1214                                 '$prevlink' => $prevlink,
1215                                 '$nextlink' => $nextlink
1216                         ));
1217                 }
1218
1219                 if($prevlink)
1220                         $prevlink = array($prevlink, '<div class="icon prev"></div>') ;
1221
1222                 $photo = array(
1223                         'href' => $a->get_baseurl() . '/photo/' . $hires['resource-id'] . '-' . $hires['scale'] . '.' . $phototypes[$hires['type']],
1224                         'title'=> t('View Full Size'),
1225                         'src'  => $a->get_baseurl() . '/photo/' . $lores['resource-id'] . '-' . $lores['scale'] . '.' . $phototypes[$lores['type']] . '?f=&_u=' . datetime_convert('','','','ymdhis')
1226                 );
1227
1228                 if($nextlink)
1229                         $nextlink = array($nextlink, '<div class="icon next"></div>');
1230
1231
1232                 // Do we have an item for this photo?
1233
1234                 $linked_items = q("SELECT * FROM `item` WHERE `resource-id` = '%s' $sql_extra LIMIT 1",
1235                         dbesc($datum)
1236                 );
1237                 if(count($linked_items)) {
1238                         $link_item = $linked_items[0];
1239                         $r = q("SELECT COUNT(*) AS `total`
1240                                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1241                                 WHERE `parent-uri` = '%s' AND `uri` != '%s' AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1242                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1243                                 AND `item`.`uid` = %d 
1244                                 $sql_extra ",
1245                                 dbesc($link_item['uri']),
1246                                 dbesc($link_item['uri']),
1247                                 intval($link_item['uid'])
1248
1249                         );
1250
1251                         if(count($r))
1252                                 $a->set_pager_total($r[0]['total']);
1253
1254
1255                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
1256                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`network`, 
1257                                 `contact`.`rel`, `contact`.`thumb`, `contact`.`self`, 
1258                                 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1259                                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1260                                 WHERE `parent-uri` = '%s' AND `uri` != '%s' AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1261                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1262                                 AND `item`.`uid` = %d
1263                                 $sql_extra
1264                                 ORDER BY `parent` DESC, `id` ASC LIMIT %d ,%d ",
1265                                 dbesc($link_item['uri']),
1266                                 dbesc($link_item['uri']),
1267                                 intval($link_item['uid']),
1268                                 intval($a->pager['start']),
1269                                 intval($a->pager['itemspage'])
1270
1271                         );
1272                 
1273                         if((local_user()) && (local_user() == $link_item['uid'])) {
1274                                 q("UPDATE `item` SET `unseen` = 0 WHERE `parent` = %d and `uid` = %d",
1275                                         intval($link_item['parent']),
1276                                         intval(local_user())
1277                                 );
1278                         }
1279                 }
1280
1281                 $tags=Null;
1282
1283                 if(count($linked_items) && strlen($link_item['tag'])) {
1284                         $arr = explode(',',$link_item['tag']);
1285                         // parse tags and add links
1286                         $tag_str = '';
1287                         foreach($arr as $t) {
1288                                 if(strlen($tag_str))
1289                                         $tag_str .= ', ';
1290                                 $tag_str .= bbcode($t);
1291                         } 
1292                         $tags = array(t('Tags: '), $tag_str);
1293                         if($cmd === 'edit') {
1294                                 $tags[] = $a->get_baseurl() . '/tagrm/' . $link_item['id'];
1295                                 $tags[] = t('[Remove any tag]');
1296                         }
1297                 }
1298
1299
1300                 $edit = Null;
1301                 if(($cmd === 'edit') && ($can_post)) {
1302                         $edit_tpl = get_markup_template('photo_edit.tpl');
1303                         $edit = replace_macros($edit_tpl, array(
1304                                 '$id' => $ph[0]['id'],
1305                                 '$rotatecw' => t('Rotate CW (right)'),
1306                                 '$rotateccw' => t('Rotate CCW (left)'),
1307                                 '$album' => template_escape($ph[0]['album']),
1308                                 '$newalbum' => t('New album name'), 
1309                                 '$nickname' => $a->data['user']['nickname'],
1310                                 '$resource_id' => $ph[0]['resource-id'],
1311                                 '$capt_label' => t('Caption'),
1312                                 '$caption' => template_escape($ph[0]['desc']),
1313                                 '$tag_label' => t('Add a Tag'),
1314                                 '$tags' => $link_item['tag'],
1315                                 '$permissions' => t('Permissions'),
1316                                 '$aclselect' => template_escape(populate_acl($ph[0])),
1317                                 '$help_tags' => t('Example: @bob, @Barbara_Jensen, @jim@example.com, #California, #camping'),
1318                                 '$item_id' => ((count($linked_items)) ? $link_item['id'] : 0),
1319                                 '$submit' => t('Submit'),
1320                                 '$delete' => t('Delete Photo')
1321                         ));
1322                 }
1323
1324                 if(count($linked_items)) {
1325
1326                         $cmnt_tpl = get_markup_template('comment_item.tpl');
1327                         $tpl = get_markup_template('photo_item.tpl');
1328                         $return_url = $a->cmd;
1329
1330                         $like_tpl = get_markup_template('like_noshare.tpl');
1331
1332                         $likebuttons = '';
1333
1334                         if($can_post || can_write_wall($a,$owner_uid)) {
1335                                 $likebuttons = replace_macros($like_tpl,array(
1336                                         '$id' => $link_item['id'],
1337                                         '$likethis' => t("I like this \x28toggle\x29"),
1338                                         '$nolike' => t("I don't like this \x28toggle\x29"),
1339                                         '$share' => t('Share'),
1340                                         '$wait' => t('Please wait')
1341                                 ));
1342                         }
1343
1344                         $comments = '';
1345                         if(! count($r)) {
1346                                 if($can_post || can_write_wall($a,$owner_uid)) {
1347                                         if($link_item['last-child']) {
1348                                                 $comments .= replace_macros($cmnt_tpl,array(
1349                                                         '$return_path' => '', 
1350                                                         '$jsreload' => $return_url,
1351                                                         '$type' => 'wall-comment',
1352                                                         '$id' => $link_item['id'],
1353                                                         '$parent' => $link_item['id'],
1354                                                         '$profile_uid' =>  $owner_uid,
1355                                                         '$mylink' => $contact['url'],
1356                                                         '$mytitle' => t('This is you'),
1357                                                         '$myphoto' => $contact['thumb'],
1358                                                         '$comment' => t('Comment'),
1359                                                         '$submit' => t('Submit'),
1360                                                         '$preview' => t('Preview'),
1361                                                         '$sourceapp' => t($a->sourcename),
1362                                                         '$ww' => ''
1363                                                 ));
1364                                         }
1365                                 }
1366                         }
1367
1368                         $alike = array();
1369                         $dlike = array();
1370                         
1371                         $like = '';
1372                         $dislike = '';
1373
1374                         // display comments
1375                         if(count($r)) {
1376
1377                                 foreach($r as $item) {
1378                                         like_puller($a,$item,$alike,'like');
1379                                         like_puller($a,$item,$dlike,'dislike');
1380                                 }
1381
1382                                 $like    = ((isset($alike[$link_item['id']])) ? format_like($alike[$link_item['id']],$alike[$link_item['id'] . '-l'],'like',$link_item['id']) : '');
1383                                 $dislike = ((isset($dlike[$link_item['id']])) ? format_like($dlike[$link_item['id']],$dlike[$link_item['id'] . '-l'],'dislike',$link_item['id']) : '');
1384
1385
1386
1387                                 if($can_post || can_write_wall($a,$owner_uid)) {
1388                                         if($link_item['last-child']) {
1389                                                 $comments .= replace_macros($cmnt_tpl,array(
1390                                                         '$return_path' => '',
1391                                                         '$jsreload' => $return_url,
1392                                                         '$type' => 'wall-comment',
1393                                                         '$id' => $link_item['id'],
1394                                                         '$parent' => $link_item['id'],
1395                                                         '$profile_uid' =>  $owner_uid,
1396                                                         '$mylink' => $contact['url'],
1397                                                         '$mytitle' => t('This is you'),
1398                                                         '$myphoto' => $contact['thumb'],
1399                                                         '$comment' => t('Comment'),
1400                                                         '$submit' => t('Submit'),
1401                                                         '$sourceapp' => t($a->sourcename),
1402                                                         '$ww' => ''
1403                                                 ));
1404                                         }
1405                                 }
1406
1407
1408                                 foreach($r as $item) {
1409                                         $comment = '';
1410                                         $template = $tpl;
1411                                         $sparkle = '';
1412
1413                                         if(((activity_match($item['verb'],ACTIVITY_LIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE))) && ($item['id'] != $item['parent']))
1414                                                 continue;
1415
1416                                         $redirect_url = $a->get_baseurl() . '/redir/' . $item['cid'] ;
1417                         
1418                                         if($can_post || can_write_wall($a,$owner_uid)) {
1419
1420                                                 if($item['last-child']) {
1421                                                         $comments .= replace_macros($cmnt_tpl,array(
1422                                                                 '$return_path' => '',
1423                                                                 '$jsreload' => $return_url,
1424                                                                 '$type' => 'wall-comment',
1425                                                                 '$id' => $item['item_id'],
1426                                                                 '$parent' => $item['parent'],
1427                                                                 '$profile_uid' =>  $owner_uid,
1428                                                                 '$mylink' => $contact['url'],
1429                                                                 '$mytitle' => t('This is you'),
1430                                                                 '$myphoto' => $contact['thumb'],
1431                                                                 '$comment' => t('Comment'),
1432                                                                 '$submit' => t('Submit'),
1433                                                                 '$sourceapp' => t($a->sourcename),
1434                                                                 '$ww' => ''
1435                                                         ));
1436                                                 }
1437                                         }
1438
1439
1440                                         if(local_user() && ($item['contact-uid'] == local_user()) 
1441                                                 && ($item['network'] == 'dfrn') && (! $item['self'] )) {
1442                                                 $profile_url = $redirect_url;
1443                                                 $sparkle = ' sparkle';
1444                                         }
1445                                         else {
1446                                                 $profile_url = $item['url'];
1447                                                 $sparkle = '';
1448                                         }
1449  
1450                                         $diff_author = (($item['url'] !== $item['author-link']) ? true : false);
1451
1452                                         $profile_name   = (((strlen($item['author-name']))   && $diff_author) ? $item['author-name']   : $item['name']);
1453                                         $profile_avatar = (((strlen($item['author-avatar'])) && $diff_author) ? $item['author-avatar'] : $item['thumb']);
1454
1455                                         $profile_link = $profile_url;
1456
1457                                         $drop = '';
1458
1459                                         if(($item['contact-id'] == $contact_id) || ($item['uid'] == local_user()))
1460                                                 $drop = replace_macros(get_markup_template('photo_drop.tpl'), array('$id' => $item['id'], '$delete' => t('Delete')));
1461
1462
1463                                         $comments .= replace_macros($template,array(
1464                                                 '$id' => $item['item_id'],
1465                                                 '$profile_url' => $profile_link,
1466                                                 '$name' => template_escape($profile_name),
1467                                                 '$thumb' => $profile_avatar,
1468                                                 '$sparkle' => $sparkle,
1469                                                 '$title' => template_escape($item['title']),
1470                                                 '$body' => template_escape(bbcode($item['body'])),
1471                                                 '$ago' => relative_date($item['created']),
1472                                                 '$indent' => (($item['parent'] != $item['item_id']) ? ' comment' : ''),
1473                                                 '$drop' => $drop,
1474                                                 '$comment' => $comment
1475                                         ));
1476                                 }
1477                         }
1478
1479                         $paginate = paginate($a);
1480                 }
1481                 
1482                 $photo_tpl = get_markup_template('photo_view.tpl');
1483                 $o .= replace_macros($photo_tpl, array(
1484                         '$id' => $ph[0]['id'],
1485                         '$album' => array($album_link,template_escape($ph[0]['album'])),
1486                         '$tools' => $tools,
1487                         '$lock' => $lock,
1488                         '$photo' => $photo,
1489                         '$prevlink' => $prevlink,
1490                         '$nextlink' => $nextlink,
1491                         '$desc' => $ph[0]['desc'],
1492                         '$tags' => template_escape($tags),
1493                         '$edit' => $edit,       
1494                         '$likebuttons' => $likebuttons,
1495                         '$like' => template_escape($like),
1496                         '$dislike' => template_escape($dislike),
1497                         '$comments' => $comments,
1498                         '$paginate' => $paginate,
1499                 ));
1500                 
1501                 return $o;
1502         }
1503
1504         // Default - show recent photos with upload link (if applicable)
1505         //$o = '';
1506
1507         $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' 
1508                 $sql_extra GROUP BY `resource-id`",
1509                 intval($a->data['user']['uid']),
1510                 dbesc('Contact Photos'),
1511                 dbesc( t('Contact Photos'))
1512         );
1513         if(count($r)) {
1514                 $a->set_pager_total(count($r));
1515                 $a->set_pager_itemspage(20);
1516         }
1517
1518         $r = q("SELECT `resource-id`, `id`, `filename`, type, `album`, max(`scale`) AS `scale` FROM `photo`
1519                 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s'  
1520                 $sql_extra GROUP BY `resource-id` ORDER BY `created` DESC LIMIT %d , %d",
1521                 intval($a->data['user']['uid']),
1522                 dbesc('Contact Photos'),
1523                 dbesc( t('Contact Photos')),
1524                 intval($a->pager['start']),
1525                 intval($a->pager['itemspage'])
1526         );
1527
1528
1529
1530         $photos = array();
1531         if(count($r)) {
1532                 $twist = 'rotright';
1533                 foreach($r as $rr) {
1534                         if($twist == 'rotright')
1535                                 $twist = 'rotleft';
1536                         else
1537                                 $twist = 'rotright';
1538                         $ext = $phototypes[$rr['type']];
1539                         
1540                         $photos[] = array(
1541                                 'id'       => $rr['id'],
1542                                 'twist'    => ' ' . $twist . rand(2,4),
1543                                 'link'          => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id'],
1544                                 'title'         => t('View Photo'),
1545                                 'src'           => $a->get_baseurl() . '/photo/' . $rr['resource-id'] . '-' . ((($rr['scale']) == 6) ? 4 : $rr['scale']) . '.' . $ext,
1546                                 'alt'           => template_escape($rr['filename']),
1547                                 'album' => array(
1548                                         'link'  => $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($rr['album']),
1549                                         'name'  => template_escape($rr['album']),
1550                                         'alt'   => t('View Album'),
1551                                 ),
1552                                 
1553                         );
1554                 }
1555         }
1556         
1557         $tpl = get_markup_template('photos_recent.tpl'); 
1558         $o .= replace_macros($tpl,array(
1559                 '$title' => t('Recent Photos'),
1560                 '$can_post' => $can_post,
1561                 '$upload' => array(t('Upload New Photos'), $a->get_baseurl().'/photos/'.$a->data['user']['nickname'].'/upload'),
1562                 '$photos' => $photos,
1563         ));
1564
1565         
1566         $o .= paginate($a);
1567         return $o;
1568 }
1569