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