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