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