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