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