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