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