]> git.mxchange.org Git - friendica.git/blob - mod/photos.php
Merge pull request #3078 from Hypolite/issue/#3039-mod-2of3
[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(App $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(App $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 `album` 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 (dbm::is_result($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         $limit = service_class_fetch($a->data['user']['uid'],'photo_upload_limit');
822
823         if ($limit) {
824                 $r = q("select sum(octet_length(data)) as total from photo where uid = %d and scale = 0 and album != 'Contact Photos' ",
825                         intval($a->data['user']['uid'])
826                 );
827                 $size = $r[0]['total'];
828
829                 if (($size + strlen($imagedata)) > $limit) {
830                         notice( upgrade_message() . EOL );
831                         @unlink($src);
832                         $foo = 0;
833                         call_hooks('photo_post_end',$foo);
834                         killme();
835                 }
836         }
837
838         $ph = new Photo($imagedata, $type);
839
840         if (! $ph->is_valid()) {
841                 logger('mod/photos.php: photos_post(): unable to process image' , LOGGER_DEBUG);
842                 notice( t('Unable to process image.') . EOL );
843                 @unlink($src);
844                 $foo = 0;
845                 call_hooks('photo_post_end',$foo);
846                 killme();
847         }
848
849         $exif = $ph->orient($src);
850         @unlink($src);
851
852         $max_length = get_config('system','max_image_length');
853         if (! $max_length)
854                 $max_length = MAX_IMAGE_LENGTH;
855         if ($max_length > 0)
856                 $ph->scaleImage($max_length);
857
858         $width  = $ph->getWidth();
859         $height = $ph->getHeight();
860
861         $smallest = 0;
862
863         $photo_hash = photo_new_resource();
864
865         $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);
866
867         if (! $r) {
868                 logger('mod/photos.php: photos_post(): image store failed' , LOGGER_DEBUG);
869                 notice( t('Image upload failed.') . EOL );
870                 killme();
871         }
872
873         if ($width > 640 || $height > 640) {
874                 $ph->scaleImage(640);
875                 $ph->store($page_owner_uid, $visitor, $photo_hash, $filename, $album, 1, 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
876                 $smallest = 1;
877         }
878
879         if ($width > 320 || $height > 320) {
880                 $ph->scaleImage(320);
881                 $ph->store($page_owner_uid, $visitor, $photo_hash, $filename, $album, 2, 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
882                 $smallest = 2;
883         }
884
885         $basename = basename($filename);
886         $uri = item_new_uri($a->get_hostname(), $page_owner_uid);
887
888         // Create item container
889
890         $lat = $lon = null;
891
892         if ($exif && $exif['GPS']) {
893                 if (feature_enabled($channel_id,'photo_location')) {
894                         $lat = getGps($exif['GPS']['GPSLatitude'], $exif['GPS']['GPSLatitudeRef']);
895                         $lon = getGps($exif['GPS']['GPSLongitude'], $exif['GPS']['GPSLongitudeRef']);
896                 }
897         }
898
899         $arr = array();
900
901         if ($lat && $lon)
902                 $arr['coord'] = $lat . ' ' . $lon;
903
904         $arr['guid']          = get_guid(32);
905         $arr['uid']           = $page_owner_uid;
906         $arr['uri']           = $uri;
907         $arr['parent-uri']    = $uri;
908         $arr['type']          = 'photo';
909         $arr['wall']          = 1;
910         $arr['resource-id']   = $photo_hash;
911         $arr['contact-id']    = $owner_record['id'];
912         $arr['owner-name']    = $owner_record['name'];
913         $arr['owner-link']    = $owner_record['url'];
914         $arr['owner-avatar']  = $owner_record['thumb'];
915         $arr['author-name']   = $owner_record['name'];
916         $arr['author-link']   = $owner_record['url'];
917         $arr['author-avatar'] = $owner_record['thumb'];
918         $arr['title']         = '';
919         $arr['allow_cid']     = $str_contact_allow;
920         $arr['allow_gid']     = $str_group_allow;
921         $arr['deny_cid']      = $str_contact_deny;
922         $arr['deny_gid']      = $str_group_deny;
923         $arr['last-child']    = 1;
924         $arr['visible']       = $visible;
925         $arr['origin']        = 1;
926
927         $arr['body']          = '[url=' . App::get_baseurl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo_hash . ']'
928                                 . '[img]' . App::get_baseurl() . "/photo/{$photo_hash}-{$smallest}.".$ph->getExt() . '[/img]'
929                                 . '[/url]';
930
931         $item_id = item_store($arr);
932         // Update the photo albums cache
933         photo_albums($page_owner_uid, true);
934
935         if ($visible)
936                 proc_run(PRIORITY_HIGH, "include/notifier.php", 'wall-new', $item_id);
937
938         call_hooks('photo_post_end',intval($item_id));
939
940         // addon uploaders should call "killme()" [e.g. exit] within the photo_post_end hook
941         // if they do not wish to be redirected
942
943         goaway($_SESSION['photo_return']);
944         // NOTREACHED
945 }
946
947
948
949 function photos_content(App $a) {
950
951         // URLs:
952         // photos/name
953         // photos/name/upload
954         // photos/name/upload/xxxxx (xxxxx is album name)
955         // photos/name/album/xxxxx
956         // photos/name/album/xxxxx/edit
957         // photos/name/image/xxxxx
958         // photos/name/image/xxxxx/edit
959
960
961         if ((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
962                 notice( t('Public access denied.') . EOL);
963                 return;
964         }
965
966
967         require_once('include/bbcode.php');
968         require_once('include/security.php');
969         require_once('include/conversation.php');
970
971         if (! x($a->data,'user')) {
972                 notice( t('No photos selected') . EOL );
973                 return;
974         }
975
976         $phototypes = Photo::supportedTypes();
977
978         $_SESSION['photo_return'] = $a->cmd;
979
980         //
981         // Parse arguments
982         //
983
984         if ($a->argc > 3) {
985                 $datatype = $a->argv[2];
986                 $datum = $a->argv[3];
987         } elseif (($a->argc > 2) && ($a->argv[2] === 'upload'))
988                 $datatype = 'upload';
989         else
990                 $datatype = 'summary';
991
992         if ($a->argc > 4)
993                 $cmd = $a->argv[4];
994         else
995                 $cmd = 'view';
996
997         //
998         // Setup permissions structures
999         //
1000
1001         $can_post       = false;
1002         $visitor        = 0;
1003         $contact        = null;
1004         $remote_contact = false;
1005         $contact_id     = 0;
1006
1007         $owner_uid = $a->data['user']['uid'];
1008
1009         $community_page = (($a->data['user']['page-flags'] == PAGE_COMMUNITY) ? true : false);
1010
1011         if ((local_user()) && (local_user() == $owner_uid))
1012                 $can_post = true;
1013         else {
1014                 if ($community_page && remote_user()) {
1015                         if (is_array($_SESSION['remote'])) {
1016                                 foreach ($_SESSION['remote'] as $v) {
1017                                         if ($v['uid'] == $owner_uid) {
1018                                                 $contact_id = $v['cid'];
1019                                                 break;
1020                                         }
1021                                 }
1022                         }
1023                         if ($contact_id) {
1024
1025                                 $r = q("SELECT `uid` FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1",
1026                                         intval($contact_id),
1027                                         intval($owner_uid)
1028                                 );
1029                                 if (dbm::is_result($r)) {
1030                                         $can_post = true;
1031                                         $contact = $r[0];
1032                                         $remote_contact = true;
1033                                         $visitor = $contact_id;
1034                                 }
1035                         }
1036                 }
1037         }
1038
1039         // perhaps they're visiting - but not a community page, so they wouldn't have write access
1040
1041         if (remote_user() && (! $visitor)) {
1042                 $contact_id = 0;
1043                 if (is_array($_SESSION['remote'])) {
1044                         foreach ($_SESSION['remote'] as $v) {
1045                                 if ($v['uid'] == $owner_uid) {
1046                                         $contact_id = $v['cid'];
1047                                         break;
1048                                 }
1049                         }
1050                 }
1051                 if ($contact_id) {
1052                         $groups = init_groups_visitor($contact_id);
1053                         $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1",
1054                                 intval($contact_id),
1055                                 intval($owner_uid)
1056                         );
1057                         if (dbm::is_result($r)) {
1058                                 $contact = $r[0];
1059                                 $remote_contact = true;
1060                         }
1061                 }
1062         }
1063
1064         if (! $remote_contact) {
1065                 if (local_user()) {
1066                         $contact_id = $_SESSION['cid'];
1067                         $contact = $a->contact;
1068                 }
1069         }
1070
1071         if ($a->data['user']['hidewall'] && (local_user() != $owner_uid) && (! $remote_contact)) {
1072                 notice( t('Access to this item is restricted.') . EOL);
1073                 return;
1074         }
1075
1076         $sql_extra = permissions_sql($owner_uid,$remote_contact,$groups);
1077
1078         $o = "";
1079
1080         // tabs
1081         $is_owner = (local_user() && (local_user() == $owner_uid));
1082         $o .= profile_tabs($a,$is_owner, $a->data['user']['nickname']);
1083
1084         /**
1085          * Display upload form
1086          */
1087
1088         if ($datatype === 'upload') {
1089                 if (! ($can_post)) {
1090                         notice( t('Permission denied.'));
1091                         return;
1092                 }
1093
1094
1095                 $selname = (($datum) ? hex2bin($datum) : '');
1096
1097
1098                 $albumselect = '';
1099
1100
1101                 $albumselect .= '<option value="" ' . ((! $selname) ? ' selected="selected" ' : '') . '>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option>';
1102                 if (count($a->data['albums'])) {
1103                         foreach ($a->data['albums'] as $album) {
1104                                 if (($album['album'] === '') || ($album['album'] === 'Contact Photos') || ($album['album'] === t('Contact Photos')))
1105                                         continue;
1106                                 $selected = (($selname === $album['album']) ? ' selected="selected" ' : '');
1107                                 $albumselect .= '<option value="' . $album['album'] . '"' . $selected . '>' . $album['album'] . '</option>';
1108                         }
1109                 }
1110
1111                 $uploader = '';
1112
1113                 $ret = array('post_url' => 'photos/' . $a->data['user']['nickname'],
1114                                 'addon_text' => $uploader,
1115                                 'default_upload' => true);
1116
1117
1118                 call_hooks('photo_upload_form',$ret);
1119
1120                 $default_upload_box = replace_macros(get_markup_template('photos_default_uploader_box.tpl'), array());
1121                 $default_upload_submit = replace_macros(get_markup_template('photos_default_uploader_submit.tpl'), array(
1122                         '$submit' => t('Submit'),
1123                 ));
1124
1125                 $usage_message = '';
1126                 $limit = service_class_fetch($a->data['user']['uid'],'photo_upload_limit');
1127                 if ($limit !== false) {
1128
1129                         $r = q("select sum(datasize) as total from photo where uid = %d and scale = 0 and album != 'Contact Photos' ",
1130                                 intval($a->data['user']['uid'])
1131                         );
1132                         $usage_message = sprintf( t("You have used %1$.2f Mbytes of %2$.2f Mbytes photo storage."), $r[0]['total'] / 1024000, $limit / 1024000 );
1133                 }
1134
1135
1136                 // Private/public post links for the non-JS ACL form
1137                 $private_post = 1;
1138                 if ($_REQUEST['public'])
1139                         $private_post = 0;
1140
1141                 $query_str = $a->query_string;
1142                 if (strpos($query_str, 'public=1') !== false)
1143                         $query_str = str_replace(array('?public=1', '&public=1'), array('', ''), $query_str);
1144
1145                 // I think $a->query_string may never have ? in it, but I could be wrong
1146                 // It looks like it's from the index.php?q=[etc] rewrite that the web
1147                 // server does, which converts any ? to &, e.g. suggest&ignore=61 for suggest?ignore=61
1148                 if (strpos($query_str, '?') === false)
1149                         $public_post_link = '?public=1';
1150                 else
1151                         $public_post_link = '&public=1';
1152
1153
1154
1155                 $tpl = get_markup_template('photos_upload.tpl');
1156
1157                 if ($a->theme['template_engine'] === 'internal') {
1158                         $albumselect_e = template_escape($albumselect);
1159                         $aclselect_e = (($visitor) ? '' : template_escape(populate_acl($a->user)));
1160                 } else {
1161                         $albumselect_e = $albumselect;
1162                         $aclselect_e = (($visitor) ? '' : populate_acl($a->user));
1163                 }
1164
1165                 $o .= replace_macros($tpl,array(
1166                         '$pagename' => t('Upload Photos'),
1167                         '$sessid' => session_id(),
1168                         '$usage' => $usage_message,
1169                         '$nickname' => $a->data['user']['nickname'],
1170                         '$newalbum' => t('New album name: '),
1171                         '$existalbumtext' => t('or existing album name: '),
1172                         '$nosharetext' => t('Do not show a status post for this upload'),
1173                         '$albumselect' => $albumselect_e,
1174                         '$permissions' => t('Permissions'),
1175                         '$aclselect' => $aclselect_e,
1176                         '$alt_uploader' => $ret['addon_text'],
1177                         '$default_upload_box' => (($ret['default_upload']) ? $default_upload_box : ''),
1178                         '$default_upload_submit' => (($ret['default_upload']) ? $default_upload_submit : ''),
1179                         '$uploadurl' => $ret['post_url'],
1180
1181                         // ACL permissions box
1182                         '$acl_data' => construct_acl_data($a, $a->user), // For non-Javascript ACL selector
1183                         '$group_perms' => t('Show to Groups'),
1184                         '$contact_perms' => t('Show to Contacts'),
1185                         '$private' => t('Private Photo'),
1186                         '$public' => t('Public Photo'),
1187                         '$is_private' => $private_post,
1188                         '$return_path' => $query_str,
1189                         '$public_link' => $public_post_link,
1190
1191                 ));
1192
1193                 return $o;
1194         }
1195
1196         /*
1197          * Display a single photo album
1198          */
1199
1200         if ($datatype === 'album') {
1201
1202                 $album = hex2bin($datum);
1203
1204                 $r = q("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` = '%s'
1205                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id`",
1206                         intval($owner_uid),
1207                         dbesc($album)
1208                 );
1209                 if (dbm::is_result($r)) {
1210                         $a->set_pager_total(count($r));
1211                         $a->set_pager_itemspage(20);
1212                 }
1213
1214                 if ($_GET['order'] === 'posted')
1215                         $order = 'ASC';
1216                 else
1217                         $order = 'DESC';
1218
1219                 $r = q("SELECT `resource-id`, `id`, `filename`, type, max(`scale`) AS `scale`, `desc` FROM `photo` WHERE `uid` = %d AND `album` = '%s'
1220                         AND `scale` <= 4 $sql_extra GROUP BY `resource-id` ORDER BY `created` $order LIMIT %d , %d",
1221                         intval($owner_uid),
1222                         dbesc($album),
1223                         intval($a->pager['start']),
1224                         intval($a->pager['itemspage'])
1225                 );
1226
1227                 //edit album name
1228                 if ($cmd === 'edit') {
1229                         if (($album !== t('Profile Photos')) && ($album !== 'Contact Photos') && ($album !== t('Contact Photos'))) {
1230                                 if ($can_post) {
1231                                         $edit_tpl = get_markup_template('album_edit.tpl');
1232
1233                                         if ($a->theme['template_engine'] === 'internal') {
1234                                                 $album_e = template_escape($album);
1235                                         } else {
1236                                                 $album_e = $album;
1237                                         }
1238
1239                                         $o .= replace_macros($edit_tpl,array(
1240                                                 '$nametext' => t('New album name: '),
1241                                                 '$nickname' => $a->data['user']['nickname'],
1242                                                 '$album' => $album_e,
1243                                                 '$hexalbum' => bin2hex($album),
1244                                                 '$submit' => t('Submit'),
1245                                                 '$dropsubmit' => t('Delete Album')
1246                                         ));
1247                                 }
1248                         }
1249                 } else {
1250                         if (($album !== t('Profile Photos')) && ($album !== 'Contact Photos') && ($album !== t('Contact Photos'))) {
1251                                 if ($can_post) {
1252                                         $edit = array(t('Edit Album'), 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '/edit');
1253                                 }
1254                         }
1255                 }
1256
1257                 if ($_GET['order'] === 'posted')
1258                         $order =  array(t('Show Newest First'), 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album));
1259                 else
1260                         $order = array(t('Show Oldest First'), 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '?f=&order=posted');
1261
1262                 $photos = array();
1263
1264                 if (dbm::is_result($r))
1265                         $twist = 'rotright';
1266                         foreach ($r as $rr) {
1267                                 if ($twist == 'rotright')
1268                                         $twist = 'rotleft';
1269                                 else
1270                                         $twist = 'rotright';
1271
1272                                 $ext = $phototypes[$rr['type']];
1273
1274                                 if ($a->theme['template_engine'] === 'internal') {
1275                                         $imgalt_e = template_escape($rr['filename']);
1276                                         $desc_e = template_escape($rr['desc']);
1277                                 } else {
1278                                         $imgalt_e = $rr['filename'];
1279                                         $desc_e = $rr['desc'];
1280                                 }
1281
1282                                 $photos[] = array(
1283                                         'id' => $rr['id'],
1284                                         'twist' => ' ' . $twist . rand(2,4),
1285                                         'link' => 'photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id']
1286                                                 . (($_GET['order'] === 'posted') ? '?f=&order=posted' : ''),
1287                                         'title' => t('View Photo'),
1288                                         'src' => 'photo/' . $rr['resource-id'] . '-' . $rr['scale'] . '.' .$ext,
1289                                         'alt' => $imgalt_e,
1290                                         'desc'=> $desc_e,
1291                                         'ext' => $ext,
1292                                         'hash'=> $rr['resource_id'],
1293                                 );
1294                 }
1295
1296                 $tpl = get_markup_template('photo_album.tpl');
1297                 $o .= replace_macros($tpl, array(
1298                                 '$photos' => $photos,
1299                                 '$album' => $album,
1300                                 '$can_post' => $can_post,
1301                                 '$upload' => array(t('Upload New Photos'), 'photos/' . $a->data['user']['nickname'] . '/upload/' . bin2hex($album)),
1302                                 '$order' => $order,
1303                                 '$edit' => $edit,
1304                                 '$paginate' => paginate($a),
1305                         ));
1306
1307                 return $o;
1308
1309         }
1310
1311         /**
1312          * Display one photo
1313          */
1314
1315         if ($datatype === 'image') {
1316
1317                 //$o = '';
1318                 // fetch image, item containing image, then comments
1319
1320                 $ph = q("SELECT * FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'
1321                         $sql_extra ORDER BY `scale` ASC ",
1322                         intval($owner_uid),
1323                         dbesc($datum)
1324                 );
1325
1326                 if (! count($ph)) {
1327                         $ph = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'
1328                                 LIMIT 1",
1329                                 intval($owner_uid),
1330                                 dbesc($datum)
1331                         );
1332                         if (count($ph))
1333                                 notice( t('Permission denied. Access to this item may be restricted.'));
1334                         else
1335                                 notice( t('Photo not available') . EOL );
1336                         return;
1337                 }
1338
1339                 $prevlink = '';
1340                 $nextlink = '';
1341
1342                 if ($_GET['order'] === 'posted')
1343                         $order = 'ASC';
1344                 else
1345                         $order = 'DESC';
1346
1347
1348                 $prvnxt = qu("SELECT `resource-id` FROM `photo` WHERE `album` = '%s' AND `uid` = %d AND `scale` = 0
1349                         $sql_extra ORDER BY `created` $order ",
1350                         dbesc($ph[0]['album']),
1351                         intval($owner_uid)
1352                 );
1353
1354                 if (count($prvnxt)) {
1355                         for($z = 0; $z < count($prvnxt); $z++) {
1356                                 if ($prvnxt[$z]['resource-id'] == $ph[0]['resource-id']) {
1357                                         $prv = $z - 1;
1358                                         $nxt = $z + 1;
1359                                         if ($prv < 0)
1360                                                 $prv = count($prvnxt) - 1;
1361                                         if ($nxt >= count($prvnxt))
1362                                                 $nxt = 0;
1363                                         break;
1364                                 }
1365                         }
1366                         $edit_suffix = ((($cmd === 'edit') && ($can_post)) ? '/edit' : '');
1367                         $prevlink = 'photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$prv]['resource-id'] . $edit_suffix . (($_GET['order'] === 'posted') ? '?f=&order=posted' : '');
1368                         $nextlink = 'photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$nxt]['resource-id'] . $edit_suffix . (($_GET['order'] === 'posted') ? '?f=&order=posted' : '');
1369                 }
1370
1371
1372                 if (count($ph) == 1)
1373                         $hires = $lores = $ph[0];
1374                 if (count($ph) > 1) {
1375                         if ($ph[1]['scale'] == 2) {
1376                                 // original is 640 or less, we can display it directly
1377                                 $hires = $lores = $ph[0];
1378                         } else {
1379                                 $hires = $ph[0];
1380                                 $lores = $ph[1];
1381                         }
1382                 }
1383
1384                 $album_link = 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($ph[0]['album']);
1385                 $tools = Null;
1386                 $lock = Null;
1387
1388                 if ($can_post && ($ph[0]['uid'] == $owner_uid)) {
1389                         $tools = array(
1390                                 'edit'  => array('photos/' . $a->data['user']['nickname'] . '/image/' . $datum . (($cmd === 'edit') ? '' : '/edit'), (($cmd === 'edit') ? t('View photo') : t('Edit photo'))),
1391                                 'profile'=>array('profile_photo/use/'.$ph[0]['resource-id'], t('Use as profile photo')),
1392                         );
1393
1394                         // lock
1395                         $lock = ( ( ($ph[0]['uid'] == local_user()) && (strlen($ph[0]['allow_cid']) || strlen($ph[0]['allow_gid'])
1396                                         || strlen($ph[0]['deny_cid']) || strlen($ph[0]['deny_gid'])) )
1397                                         ? t('Private Message')
1398                                         : Null);
1399
1400
1401                 }
1402
1403                 if ( $cmd === 'edit') {
1404                         $tpl = get_markup_template('photo_edit_head.tpl');
1405                         $a->page['htmlhead'] .= replace_macros($tpl,array(
1406                                 '$prevlink' => $prevlink,
1407                                 '$nextlink' => $nextlink
1408                         ));
1409                 }
1410
1411                 if ($prevlink)
1412                         $prevlink = array($prevlink, '<div class="icon prev"></div>') ;
1413
1414                 $photo = array(
1415                         'href' => 'photo/' . $hires['resource-id'] . '-' . $hires['scale'] . '.' . $phototypes[$hires['type']],
1416                         'title'=> t('View Full Size'),
1417                         'src'  => 'photo/' . $lores['resource-id'] . '-' . $lores['scale'] . '.' . $phototypes[$lores['type']] . '?f=&_u=' . datetime_convert('','','','ymdhis'),
1418                         'height' => $hires['height'],
1419                         'width' => $hires['width'],
1420                         'album' => $hires['album'],
1421                         'filename' => $hires['filename'],
1422                 );
1423
1424                 if ($nextlink)
1425                         $nextlink = array($nextlink, '<div class="icon next"></div>');
1426
1427
1428                 // Do we have an item for this photo?
1429
1430                 // FIXME! - replace following code to display the conversation with our normal
1431                 // conversation functions so that it works correctly and tracks changes
1432                 // in the evolving conversation code.
1433                 // The difference is that we won't be displaying the conversation head item
1434                 // as a "post" but displaying instead the photo it is linked to
1435
1436                 $linked_items = q("SELECT * FROM `item` WHERE `resource-id` = '%s' $sql_extra LIMIT 1",
1437                         dbesc($datum)
1438                 );
1439
1440                 $map = null;
1441
1442                 if (count($linked_items)) {
1443                         $link_item = $linked_items[0];
1444                         $r = qu("SELECT COUNT(*) AS `total`
1445                                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1446                                 WHERE `parent-uri` = '%s' AND `uri` != '%s' AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1447                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1448                                 AND `item`.`uid` = %d
1449                                 $sql_extra ",
1450                                 dbesc($link_item['uri']),
1451                                 dbesc($link_item['uri']),
1452                                 intval($link_item['uid'])
1453
1454                         );
1455
1456                         if (dbm::is_result($r))
1457                                 $a->set_pager_total($r[0]['total']);
1458
1459
1460                         $r = qu("SELECT `item`.*, `item`.`id` AS `item_id`,
1461                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`network`,
1462                                 `contact`.`rel`, `contact`.`thumb`, `contact`.`self`,
1463                                 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1464                                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1465                                 WHERE `parent-uri` = '%s' AND `uri` != '%s' AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1466                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1467                                 AND `item`.`uid` = %d
1468                                 $sql_extra
1469                                 ORDER BY `parent` DESC, `id` ASC LIMIT %d ,%d ",
1470                                 dbesc($link_item['uri']),
1471                                 dbesc($link_item['uri']),
1472                                 intval($link_item['uid']),
1473                                 intval($a->pager['start']),
1474                                 intval($a->pager['itemspage'])
1475
1476                         );
1477
1478                         if ((local_user()) && (local_user() == $link_item['uid'])) {
1479                                 q("UPDATE `item` SET `unseen` = 0 WHERE `parent` = %d and `uid` = %d",
1480                                         intval($link_item['parent']),
1481                                         intval(local_user())
1482                                 );
1483                                 update_thread($link_item['parent']);
1484                         }
1485
1486                         if ($link_item['coord']) {
1487                                 $map = generate_map($link_item['coord']);
1488                         }
1489                 }
1490
1491                 $tags=Null;
1492
1493                 if (count($linked_items) && strlen($link_item['tag'])) {
1494                         $arr = explode(',',$link_item['tag']);
1495                         // parse tags and add links
1496                         $tag_str = '';
1497                         foreach ($arr as $t) {
1498                                 if (strlen($tag_str))
1499                                         $tag_str .= ', ';
1500                                 $tag_str .= bbcode($t);
1501                         }
1502                         $tags = array(t('Tags: '), $tag_str);
1503                         if ($cmd === 'edit') {
1504                                 $tags[] = 'tagrm/' . $link_item['id'];
1505                                 $tags[] = t('[Remove any tag]');
1506                         }
1507                 }
1508
1509
1510                 $edit = Null;
1511                 if (($cmd === 'edit') && ($can_post)) {
1512                         $edit_tpl = get_markup_template('photo_edit.tpl');
1513
1514                         // Private/public post links for the non-JS ACL form
1515                         $private_post = 1;
1516                         if ($_REQUEST['public'])
1517                                 $private_post = 0;
1518
1519                         $query_str = $a->query_string;
1520                         if (strpos($query_str, 'public=1') !== false)
1521                                 $query_str = str_replace(array('?public=1', '&public=1'), array('', ''), $query_str);
1522
1523                         // I think $a->query_string may never have ? in it, but I could be wrong
1524                         // It looks like it's from the index.php?q=[etc] rewrite that the web
1525                         // server does, which converts any ? to &, e.g. suggest&ignore=61 for suggest?ignore=61
1526                         if (strpos($query_str, '?') === false)
1527                                 $public_post_link = '?public=1';
1528                         else
1529                                 $public_post_link = '&public=1';
1530
1531
1532                         if ($a->theme['template_engine'] === 'internal') {
1533                                 $album_e = template_escape($ph[0]['album']);
1534                                 $caption_e = template_escape($ph[0]['desc']);
1535                                 $aclselect_e = template_escape(populate_acl($ph[0]));
1536                         } else {
1537                                 $album_e = $ph[0]['album'];
1538                                 $caption_e = $ph[0]['desc'];
1539                                 $aclselect_e = populate_acl($ph[0]);
1540                         }
1541
1542                         $edit = replace_macros($edit_tpl, array(
1543                                 '$id' => $ph[0]['id'],
1544                                 '$album' => array('albname', t('New album name'), $album_e,''),
1545                                 '$caption' => array('desc', t('Caption'), $caption_e, ''),
1546                                 '$tags' => array('newtag', t('Add a Tag'), "", t('Example: @bob, @Barbara_Jensen, @jim@example.com, #California, #camping')),
1547                                 '$rotate_none' => array('rotate',t('Do not rotate'),0,'', true),
1548                                 '$rotate_cw' => array('rotate',t('Rotate CW (right)'),1,''),
1549                                 '$rotate_ccw' => array('rotate',t('Rotate CCW (left)'),2,''),
1550
1551                                 '$nickname' => $a->data['user']['nickname'],
1552                                 '$resource_id' => $ph[0]['resource-id'],
1553                                 '$permissions' => t('Permissions'),
1554                                 '$aclselect' => $aclselect_e,
1555
1556                                 '$item_id' => ((count($linked_items)) ? $link_item['id'] : 0),
1557                                 '$submit' => t('Submit'),
1558                                 '$delete' => t('Delete Photo'),
1559
1560                                 // ACL permissions box
1561                                 '$acl_data' => construct_acl_data($a, $ph[0]), // For non-Javascript ACL selector
1562                                 '$group_perms' => t('Show to Groups'),
1563                                 '$contact_perms' => t('Show to Contacts'),
1564                                 '$private' => t('Private photo'),
1565                                 '$public' => t('Public photo'),
1566                                 '$is_private' => $private_post,
1567                                 '$return_path' => $query_str,
1568                                 '$public_link' => $public_post_link,
1569                         ));
1570                 }
1571
1572                 if (count($linked_items)) {
1573
1574                         $cmnt_tpl = get_markup_template('comment_item.tpl');
1575                         $tpl = get_markup_template('photo_item.tpl');
1576                         $return_url = $a->cmd;
1577
1578                         $like_tpl = get_markup_template('like_noshare.tpl');
1579
1580                         $likebuttons = '';
1581
1582                         if ($can_post || can_write_wall($a,$owner_uid)) {
1583                                 $likebuttons = replace_macros($like_tpl,array(
1584                                         '$id' => $link_item['id'],
1585                                         '$likethis' => t("I like this \x28toggle\x29"),
1586                                         '$nolike' => (feature_enabled(local_user(), 'dislike') ? t("I don't like this \x28toggle\x29") : ''),
1587                                         '$share' => t('Share'),
1588                                         '$wait' => t('Please wait'),
1589                                         '$return_path' => $a->query_string,
1590                                 ));
1591                         }
1592
1593                         $comments = '';
1594                         if (! dbm::is_result($r)) {
1595                                 if ($can_post || can_write_wall($a,$owner_uid)) {
1596                                         if ($link_item['last-child']) {
1597                                                 $comments .= replace_macros($cmnt_tpl,array(
1598                                                         '$return_path' => '',
1599                                                         '$jsreload' => $return_url,
1600                                                         '$type' => 'wall-comment',
1601                                                         '$id' => $link_item['id'],
1602                                                         '$parent' => $link_item['id'],
1603                                                         '$profile_uid' =>  $owner_uid,
1604                                                         '$mylink' => $contact['url'],
1605                                                         '$mytitle' => t('This is you'),
1606                                                         '$myphoto' => $contact['thumb'],
1607                                                         '$comment' => t('Comment'),
1608                                                         '$submit' => t('Submit'),
1609                                                         '$preview' => t('Preview'),
1610                                                         '$sourceapp' => t($a->sourcename),
1611                                                         '$ww' => '',
1612                                                         '$rand_num' => random_digits(12)
1613                                                 ));
1614                                         }
1615                                 }
1616                         }
1617
1618                         $alike = array();
1619                         $dlike = array();
1620
1621                         $like = '';
1622                         $dislike = '';
1623
1624                         $conv_responses = array(
1625                                 'like' => array('title' => t('Likes','title')),'dislike' => array('title' => t('Dislikes','title')),
1626                                 'attendyes' => array('title' => t('Attending','title')), 'attendno' => array('title' => t('Not attending','title')), 'attendmaybe' => array('title' => t('Might attend','title'))
1627                         );
1628
1629
1630
1631                         // display comments
1632                         if (dbm::is_result($r)) {
1633
1634                                 foreach ($r as $item) {
1635                                         builtin_activity_puller($item, $conv_responses);
1636                                 }
1637
1638                                 $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']) : '');
1639                                 $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']) : '');
1640
1641
1642
1643                                 if ($can_post || can_write_wall($a,$owner_uid)) {
1644                                         if ($link_item['last-child']) {
1645                                                 $comments .= replace_macros($cmnt_tpl,array(
1646                                                         '$return_path' => '',
1647                                                         '$jsreload' => $return_url,
1648                                                         '$type' => 'wall-comment',
1649                                                         '$id' => $link_item['id'],
1650                                                         '$parent' => $link_item['id'],
1651                                                         '$profile_uid' =>  $owner_uid,
1652                                                         '$mylink' => $contact['url'],
1653                                                         '$mytitle' => t('This is you'),
1654                                                         '$myphoto' => $contact['thumb'],
1655                                                         '$comment' => t('Comment'),
1656                                                         '$submit' => t('Submit'),
1657                                                         '$preview' => t('Preview'),
1658                                                         '$sourceapp' => t($a->sourcename),
1659                                                         '$ww' => '',
1660                                                         '$rand_num' => random_digits(12)
1661                                                 ));
1662                                         }
1663                                 }
1664
1665
1666                                 foreach ($r as $item) {
1667                                         $comment = '';
1668                                         $template = $tpl;
1669                                         $sparkle = '';
1670
1671                                         if (((activity_match($item['verb'],ACTIVITY_LIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE))) && ($item['id'] != $item['parent']))
1672                                                 continue;
1673
1674                                         $redirect_url = 'redir/' . $item['cid'] ;
1675
1676
1677                                         if (local_user() && ($item['contact-uid'] == local_user())
1678                                                 && ($item['network'] == NETWORK_DFRN) && (! $item['self'] )) {
1679                                                 $profile_url = $redirect_url;
1680                                                 $sparkle = ' sparkle';
1681                                         } else {
1682                                                 $profile_url = $item['url'];
1683                                                 $sparkle = '';
1684                                         }
1685
1686                                         $diff_author = (($item['url'] !== $item['author-link']) ? true : false);
1687
1688                                         $profile_name   = (((strlen($item['author-name']))   && $diff_author) ? $item['author-name']   : $item['name']);
1689                                         $profile_avatar = (((strlen($item['author-avatar'])) && $diff_author) ? $item['author-avatar'] : $item['thumb']);
1690
1691                                         $profile_link = $profile_url;
1692
1693
1694
1695                                         $dropping = (($item['contact-id'] == $contact_id) || ($item['uid'] == local_user()));
1696                                         $drop = array(
1697                                                 'dropping' => $dropping,
1698                                                 'pagedrop' => false,
1699                                                 'select' => t('Select'),
1700                                                 'delete' => t('Delete'),
1701                                         );
1702
1703
1704                                         if ($a->theme['template_engine'] === 'internal') {
1705                                                 $name_e = template_escape($profile_name);
1706                                                 $title_e = template_escape($item['title']);
1707                                                 $body_e = template_escape(bbcode($item['body']));
1708                                         } else {
1709                                                 $name_e = $profile_name;
1710                                                 $title_e = $item['title'];
1711                                                 $body_e = bbcode($item['body']);
1712                                         }
1713
1714                                         $comments .= replace_macros($template,array(
1715                                                 '$id' => $item['item_id'],
1716                                                 '$profile_url' => $profile_link,
1717                                                 '$name' => $name_e,
1718                                                 '$thumb' => $profile_avatar,
1719                                                 '$sparkle' => $sparkle,
1720                                                 '$title' => $title_e,
1721                                                 '$body' => $body_e,
1722                                                 '$ago' => relative_date($item['created']),
1723                                                 '$indent' => (($item['parent'] != $item['item_id']) ? ' comment' : ''),
1724                                                 '$drop' => $drop,
1725                                                 '$comment' => $comment
1726                                         ));
1727
1728                                         if ($can_post || can_write_wall($a,$owner_uid)) {
1729
1730                                                 if ($item['last-child']) {
1731                                                         $comments .= replace_macros($cmnt_tpl,array(
1732                                                                 '$return_path' => '',
1733                                                                 '$jsreload' => $return_url,
1734                                                                 '$type' => 'wall-comment',
1735                                                                 '$id' => $item['item_id'],
1736                                                                 '$parent' => $item['parent'],
1737                                                                 '$profile_uid' =>  $owner_uid,
1738                                                                 '$mylink' => $contact['url'],
1739                                                                 '$mytitle' => t('This is you'),
1740                                                                 '$myphoto' => $contact['thumb'],
1741                                                                 '$comment' => t('Comment'),
1742                                                                 '$submit' => t('Submit'),
1743                                                                 '$preview' => t('Preview'),
1744                                                                 '$sourceapp' => t($a->sourcename),
1745                                                                 '$ww' => '',
1746                                                                 '$rand_num' => random_digits(12)
1747                                                         ));
1748                                                 }
1749                                         }
1750                                 }
1751                         }
1752
1753                         $paginate = paginate($a);
1754                 }
1755
1756
1757                 $response_verbs = array('like');
1758                 if (feature_enabled($owner_uid,'dislike'))
1759                         $response_verbs[] = 'dislike';
1760                 $responses = get_responses($conv_responses,$response_verbs,'',$link_item);
1761
1762                 $photo_tpl = get_markup_template('photo_view.tpl');
1763
1764                 if ($a->theme['template_engine'] === 'internal') {
1765                         $album_e = array($album_link,template_escape($ph[0]['album']));
1766                         $tags_e = template_escape($tags);
1767                         $like_e = template_escape($like);
1768                         $dislike_e = template_escape($dislike);
1769                 } else {
1770                         $album_e = array($album_link,$ph[0]['album']);
1771                         $tags_e = $tags;
1772                         $like_e = $like;
1773                         $dislike_e = $dislike;
1774                 }
1775
1776                 $o .= replace_macros($photo_tpl, array(
1777                         '$id' => $ph[0]['id'],
1778                         '$album' => $album_e,
1779                         '$tools' => $tools,
1780                         '$lock' => $lock,
1781                         '$photo' => $photo,
1782                         '$prevlink' => $prevlink,
1783                         '$nextlink' => $nextlink,
1784                         '$desc' => $ph[0]['desc'],
1785                         '$tags' => $tags_e,
1786                         '$edit' => $edit,
1787                         '$map' => $map,
1788                         '$map_text' => t('Map'),
1789                         '$likebuttons' => $likebuttons,
1790                         '$like' => $like_e,
1791                         '$dislike' => $dikslike_e,
1792                         'responses' => $responses,
1793                         '$comments' => $comments,
1794                         '$paginate' => $paginate,
1795                 ));
1796
1797                 $a->page['htmlhead'] .= "\n".'<meta name="twitter:card" content="photo" />'."\n";
1798                 $a->page['htmlhead'] .= '<meta name="twitter:title" content="'.$photo["album"].'" />'."\n";
1799                 $a->page['htmlhead'] .= '<meta name="twitter:image" content="'.$photo["href"].'" />'."\n";
1800                 $a->page['htmlhead'] .= '<meta name="twitter:image:width" content="'.$photo["width"].'" />'."\n";
1801                 $a->page['htmlhead'] .= '<meta name="twitter:image:height" content="'.$photo["height"].'" />'."\n";
1802
1803                 return $o;
1804         }
1805
1806         // Default - show recent photos with upload link (if applicable)
1807         //$o = '';
1808
1809         $r = qu("SELECT `resource-id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s'
1810                 $sql_extra GROUP BY `resource-id`",
1811                 intval($a->data['user']['uid']),
1812                 dbesc('Contact Photos'),
1813                 dbesc( t('Contact Photos'))
1814         );
1815         if (dbm::is_result($r)) {
1816                 $a->set_pager_total(count($r));
1817                 $a->set_pager_itemspage(20);
1818         }
1819
1820         $r = qu("SELECT `resource-id`, `id`, `filename`, type, `album`, max(`scale`) AS `scale` FROM `photo`
1821                 WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s'
1822                 $sql_extra GROUP BY `resource-id` ORDER BY `created` DESC LIMIT %d , %d",
1823                 intval($a->data['user']['uid']),
1824                 dbesc('Contact Photos'),
1825                 dbesc( t('Contact Photos')),
1826                 intval($a->pager['start']),
1827                 intval($a->pager['itemspage'])
1828         );
1829
1830         $photos = array();
1831         if (dbm::is_result($r)) {
1832                 $twist = 'rotright';
1833                 foreach ($r as $rr) {
1834                         //hide profile photos to others
1835                         if ((! $is_owner) && (! remote_user()) && ($rr['album'] == t('Profile Photos')))
1836                                         continue;
1837
1838                         if ($twist == 'rotright')
1839                                 $twist = 'rotleft';
1840                         else
1841                                 $twist = 'rotright';
1842
1843                         $ext = $phototypes[$rr['type']];
1844
1845                         if ($a->theme['template_engine'] === 'internal') {
1846                                 $alt_e = template_escape($rr['filename']);
1847                                 $name_e = template_escape($rr['album']);
1848                         } else {
1849                                 $alt_e = $rr['filename'];
1850                                 $name_e = $rr['album'];
1851                         }
1852
1853                         $photos[] = array(
1854                                 'id'            => $rr['id'],
1855                                 'twist'         => ' ' . $twist . rand(2,4),
1856                                 'link'          => 'photos/' . $a->data['user']['nickname'] . '/image/' . $rr['resource-id'],
1857                                 'title'         => t('View Photo'),
1858                                 'src'           => 'photo/' . $rr['resource-id'] . '-' . ((($rr['scale']) == 6) ? 4 : $rr['scale']) . '.' . $ext,
1859                                 'alt'           => $alt_e,
1860                                 'album' => array(
1861                                         'link'  => 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($rr['album']),
1862                                         'name'  => $name_e,
1863                                         'alt'   => t('View Album'),
1864                                 ),
1865
1866                         );
1867                 }
1868         }
1869
1870         $tpl = get_markup_template('photos_recent.tpl');
1871         $o .= replace_macros($tpl, array(
1872                 '$title' => t('Recent Photos'),
1873                 '$can_post' => $can_post,
1874                 '$upload' => array(t('Upload New Photos'), 'photos/'.$a->data['user']['nickname'].'/upload'),
1875                 '$photos' => $photos,
1876                 '$paginate' => paginate($a),
1877         ));
1878
1879         return $o;
1880 }