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