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