function photos_content(&$a) { // URLs: // photos/name // photos/name/album/xxxxx (xxxxx is album name) // photos/name/image/xxxxx if (get_config('system', 'block_public') && !local_channel() && !remote_channel()) { notice(t('Public access denied.') . EOL); return; } $unsafe = array_key_exists('unsafe', $_REQUEST) && $_REQUEST['unsafe'] ? 1 : 0; require_once 'include/bbcode.php'; require_once 'include/security.php'; require_once 'include/conversation.php'; if (!x($a->data, 'channel')) { notice(t('No photos selected') . EOL); return; } $ph = photo_factory(''); $phototypes = $ph->supportedTypes(); $_SESSION['photo_return'] = $a->cmd; // // Parse arguments // $can_comment = perm_is_allowed($a->profile['profile_uid'], get_observer_hash(), 'post_comments'); if (argc() > 3) { $datatype = argv(2); $datum = argv(3); } else { if (argc() > 2) { $datatype = argv(2); $datum = ''; } else { $datatype = 'summary'; } } if (argc() > 4) { $cmd = argv(4); } else { $cmd = 'view'; } // // Setup permissions structures // $can_post = false; $visitor = 0; $owner_uid = $a->data['channel']['channel_id']; $owner_aid = $a->data['channel']['channel_account_id']; $observer = $a->get_observer(); $can_post = perm_is_allowed($owner_uid, $observer['xchan_hash'], 'write_storage'); $can_view = perm_is_allowed($owner_uid, $observer['xchan_hash'], 'view_storage'); if (!$can_view) { notice(t('Access to this item is restricted.') . EOL); return; } $sql_extra = permissions_sql($owner_uid); $o = ""; $o .= "<script> var profile_uid = " . $a->profile['profile_uid'] . "; var netargs = '?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n"; // tabs $_is_owner = local_channel() && local_channel() == $owner_uid; $o .= profile_tabs($a, $_is_owner, $a->data['channel']['channel_address']); /** * Display upload form */ if ($can_post) { $uploader = ''; $ret = array('post_url' => $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'], 'addon_text' => $uploader, 'default_upload' => true); call_hooks('photo_upload_form', $ret); /* Show space usage */ $r = q("select sum(size) as total from photo where aid = %d and scale = 0 ", intval($a->data['channel']['channel_account_id'])); $limit = service_class_fetch($a->data['channel']['channel_id'], 'photo_upload_limit'); if ($limit !== false) { $usage_message = sprintf(t("%1\$.2f MB of %2\$.2f MB photo storage used."), $r[0]['total'] / 1024000, $limit / 1024000); } else { $usage_message = sprintf(t('%1$.2f MB photo storage used.'), $r[0]['total'] / 1024000); } if ($_is_owner) { $channel = $a->get_channel(); $acl = new AccessList($channel); $channel_acl = $acl->get(); $lockstate = $acl->is_private() ? 'lock' : 'unlock'; } $aclselect = $_is_owner ? populate_acl($channel_acl, false) : ''; $selname = $datum ? hex2bin($datum) : ''; $albums = array_key_exists('albums', $a->data) ? $a->data['albums'] : photos_albums_list($a->data['channel'], $a->data['observer']); if (!$selname) { $def_album = get_pconfig($a->data['channel']['channel_id'], 'system', 'photo_path'); if ($def_album) { $selname = filepath_macro($def_album); $albums['album'][] = array('text' => $selname); } } $tpl = get_markup_template('photos_upload.tpl'); $upload_form = replace_macros($tpl, array('$pagename' => t('Upload Photos'), '$sessid' => session_id(), '$usage' => $usage_message, '$nickname' => $a->data['channel']['channel_address'], '$newalbum_label' => t('Enter an album name'), '$newalbum_placeholder' => t('or select an existing album (doubleclick)'), '$visible' => array('visible', t('Create a status post for this upload'), 0, '', array(t('No'), t('Yes'))), '$albums' => $albums['albums'], '$selname' => $selname, '$permissions' => t('Permissions'), '$aclselect' => $aclselect, '$lockstate' => $lockstate, '$uploader' => $ret['addon_text'], '$default' => $ret['default_upload'] ? true : false, '$uploadurl' => $ret['post_url'], '$submit' => t('Submit'))); } // // dispatch request // /* * Display a single photo album */ if ($datatype === 'album') { if (strlen($datum)) { if (strlen($datum) & 1 || !ctype_xdigit($datum)) { notice(t('Album name could not be decoded') . EOL); logger('mod_photos: illegal album encoding: ' . $datum); $datum = ''; } } $album = $datum ? hex2bin($datum) : ''; $r = q("SELECT `resource_id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` = '%s' \n\t\t\tAND `scale` <= 4 and photo_usage IN ( %d, %d ) and is_nsfw = %d {$sql_extra} GROUP BY `resource_id`", intval($owner_uid), dbesc($album), intval(PHOTO_NORMAL), intval(PHOTO_PROFILE), intval($unsafe)); if (count($r)) { $a->set_pager_total(count($r)); $a->set_pager_itemspage(60); } else { goaway($a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address']); } if ($_GET['order'] === 'posted') { $order = 'ASC'; } else { $order = 'DESC'; } $r = q("SELECT p.resource_id, p.id, p.filename, p.type, p.scale, p.description, p.created FROM photo p INNER JOIN\n\t\t\t\t(SELECT resource_id, max(scale) scale FROM photo WHERE uid = %d AND album = '%s' AND scale <= 4 AND photo_usage IN ( %d, %d ) and is_nsfw = %d {$sql_extra} GROUP BY resource_id) ph \n\t\t\t\tON (p.resource_id = ph.resource_id AND p.scale = ph.scale)\n\t\t\tORDER BY created {$order} LIMIT %d OFFSET %d", intval($owner_uid), dbesc($album), intval(PHOTO_NORMAL), intval(PHOTO_PROFILE), intval($unsafe), intval($a->pager['itemspage']), intval($a->pager['start'])); //edit album name $album_edit = null; if ($album !== t('Profile Photos') && $album !== 'Profile Photos' && $album !== 'Contact Photos' && $album !== t('Contact Photos')) { if ($can_post) { if ($a->get_template_engine() === 'internal') { $album_e = template_escape($album); } else { $album_e = $album; } $albums = array_key_exists('albums', $a->data) ? $a->data['albums'] : photos_albums_list($a->data['channel'], $a->data['observer']); // @fixme - syncronise actions with DAV // $edit_tpl = get_markup_template('album_edit.tpl'); // $album_edit = replace_macros($edit_tpl,array( // '$nametext' => t('Enter a new album name'), // '$name_placeholder' => t('or select an existing one (doubleclick)'), // '$nickname' => $a->data['channel']['channel_address'], // '$album' => $album_e, // '$albums' => $albums['albums'], // '$hexalbum' => bin2hex($album), // '$submit' => t('Submit'), // '$dropsubmit' => t('Delete Album') // )); } } if ($_GET['order'] === 'posted') { $order = array(t('Show Newest First'), $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/album/' . bin2hex($album)); } else { $order = array(t('Show Oldest First'), $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/album/' . bin2hex($album) . '?f=&order=posted'); } $photos = array(); if (count($r)) { $twist = 'rotright'; foreach ($r as $rr) { if ($twist == 'rotright') { $twist = 'rotleft'; } else { $twist = 'rotright'; } $ext = $phototypes[$rr['type']]; $imgalt_e = $rr['filename']; $desc_e = $rr['description']; $imagelink = $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/image/' . $rr['resource_id'] . ($_GET['order'] === 'posted' ? '?f=&order=posted' : ''); $photos[] = array('id' => $rr['id'], 'twist' => ' ' . $twist . rand(2, 4), 'link' => $imagelink, 'title' => t('View Photo'), 'src' => $a->get_baseurl() . '/photo/' . $rr['resource_id'] . '-' . $rr['scale'] . '.' . $ext, 'alt' => $imgalt_e, 'desc' => $desc_e, 'ext' => $ext, 'hash' => $rr['resource_id'], 'unknown' => t('Unknown')); } } if ($_REQUEST['aj']) { if ($photos) { $o = replace_macros(get_markup_template('photosajax.tpl'), array('$photos' => $photos)); } else { $o = '<div id="content-complete"></div>'; } echo $o; killme(); } else { $o .= "<script> var page_query = '" . $_GET['q'] . "'; var extra_args = '" . extra_query_args() . "' ; </script>"; $tpl = get_markup_template('photo_album.tpl'); $o .= replace_macros($tpl, array('$photos' => $photos, '$album' => $album, '$album_edit' => array(t('Edit Album'), $album_edit), '$can_post' => $can_post, '$upload' => array(t('Upload'), $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/upload/' . bin2hex($album)), '$order' => $order, '$upload_form' => $upload_form, '$usage' => $usage_message)); } if (!$photos && $_REQUEST['aj']) { $o .= '<div id="content-complete"></div>'; echo $o; killme(); } // $o .= paginate($a); return $o; } /** * Display one photo */ if ($datatype === 'image') { // fetch image, item containing image, then comments $ph = q("SELECT id,aid,uid,xchan,resource_id,created,edited,title,`description`,album,filename,`type`,height,width,`size`,scale,photo_usage,is_nsfw,allow_cid,allow_gid,deny_cid,deny_gid FROM `photo` WHERE `uid` = %d AND `resource_id` = '%s' \n\t\t\t{$sql_extra} ORDER BY `scale` ASC ", intval($owner_uid), dbesc($datum)); if (!$ph) { /* Check again - this time without specifying permissions */ $ph = q("SELECT id FROM photo WHERE uid = %d AND resource_id = '%s' LIMIT 1", intval($owner_uid), dbesc($datum)); if ($ph) { notice(t('Permission denied. Access to this item may be restricted.') . EOL); } else { notice(t('Photo not available') . EOL); } return; } $prevlink = ''; $nextlink = ''; if ($_GET['order'] === 'posted') { $order = 'ASC'; } else { $order = 'DESC'; } $prvnxt = q("SELECT `resource_id` FROM `photo` WHERE `album` = '%s' AND `uid` = %d AND `scale` = 0 \n\t\t\t{$sql_extra} ORDER BY `created` {$order} ", dbesc($ph[0]['album']), intval($owner_uid)); if (count($prvnxt)) { for ($z = 0; $z < count($prvnxt); $z++) { if ($prvnxt[$z]['resource_id'] == $ph[0]['resource_id']) { $prv = $z - 1; $nxt = $z + 1; if ($prv < 0) { $prv = count($prvnxt) - 1; } if ($nxt >= count($prvnxt)) { $nxt = 0; } break; } } $prevlink = $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/image/' . $prvnxt[$prv]['resource_id'] . ($_GET['order'] === 'posted' ? '?f=&order=posted' : ''); $nextlink = $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/image/' . $prvnxt[$nxt]['resource_id'] . ($_GET['order'] === 'posted' ? '?f=&order=posted' : ''); } if (count($ph) == 1) { $hires = $lores = $ph[0]; } if (count($ph) > 1) { if ($ph[1]['scale'] == 2) { // original is 640 or less, we can display it directly $hires = $lores = $ph[0]; } else { $hires = $ph[0]; $lores = $ph[1]; } } $album_link = $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/album/' . bin2hex($ph[0]['album']); $tools = Null; $lock = Null; if ($can_post && $ph[0]['uid'] == $owner_uid) { $tools = array('profile' => array($a->get_baseurl() . '/profile_photo/use/' . $ph[0]['resource_id'], t('Use as profile photo'))); } // lockstate $lockstate = strlen($ph[0]['allow_cid']) || strlen($ph[0]['allow_gid']) || strlen($ph[0]['deny_cid']) || strlen($ph[0]['deny_gid']) ? array('lock', t('Private Photo')) : array('unlock', Null); $a->page['htmlhead'] .= '<script>$(document).keydown(function(event) {' . "\n"; if ($prevlink) { $a->page['htmlhead'] .= 'if(event.ctrlKey && event.keyCode == 37) { event.preventDefault(); window.location.href = \'' . $prevlink . '\'; }' . "\n"; } if ($nextlink) { $a->page['htmlhead'] .= 'if(event.ctrlKey && event.keyCode == 39) { event.preventDefault(); window.location.href = \'' . $nextlink . '\'; }' . "\n"; } $a->page['htmlhead'] .= '});</script>'; if ($prevlink) { $prevlink = array($prevlink, t('Previous')); } $photo = array('href' => $a->get_baseurl() . '/photo/' . $hires['resource_id'] . '-' . $hires['scale'] . '.' . $phototypes[$hires['type']], 'title' => t('View Full Size'), 'src' => $a->get_baseurl() . '/photo/' . $lores['resource_id'] . '-' . $lores['scale'] . '.' . $phototypes[$lores['type']] . '?f=&_u=' . datetime_convert('', '', '', 'ymdhis')); if ($nextlink) { $nextlink = array($nextlink, t('Next')); } // Do we have an item for this photo? $linked_items = q("SELECT * FROM item WHERE resource_id = '%s' and resource_type = 'photo' \n\t\t\t{$sql_extra} LIMIT 1", dbesc($datum)); $map = null; if ($linked_items) { xchan_query($linked_items); $linked_items = fetch_post_tags($linked_items, true); $link_item = $linked_items[0]; $item_normal = item_normal(); $r = q("select * from item where parent_mid = '%s' \n\t\t\t\t{$item_normal} and uid = %d {$sql_extra} ", dbesc($link_item['mid']), intval($link_item['uid'])); if ($r) { xchan_query($r); $r = fetch_post_tags($r, true); $r = conv_sort($r, 'commented'); } $tags = array(); if ($link_item['term']) { $cnt = 0; foreach ($link_item['term'] as $t) { $tags[$cnt] = array(0 => format_term_for_display($t)); if ($can_post && $ph[0]['uid'] == $owner_uid) { $tags[$cnt][1] = 'tagrm/drop/' . $link_item['id'] . '/' . bin2hex($t['term']); //?f=&item=' . $link_item['id']; $tags[$cnt][2] = t('Remove'); } $cnt++; } } if (local_channel() && local_channel() == $link_item['uid']) { q("UPDATE `item` SET item_unseen = 0 WHERE parent = %d and uid = %d and item_unseen = 1", intval($link_item['parent']), intval(local_channel())); } if ($link_item['coord']) { $map = generate_map($link_item['coord']); } } // logger('mod_photo: link_item' . print_r($link_item,true)); // FIXME - remove this when we move to conversation module $r = $r[0]['children']; $edit = null; if ($can_post) { $album_e = $ph[0]['album']; $caption_e = $ph[0]['description']; $aclselect_e = $_is_owner ? populate_acl($ph[0]) : ''; $albums = array_key_exists('albums', $a->data) ? $a->data['albums'] : photos_albums_list($a->data['channel'], $a->data['observer']); $_SESSION['album_return'] = bin2hex($ph[0]['album']); $edit = array('edit' => t('Edit photo'), 'id' => $link_item['id'], 'rotatecw' => t('Rotate CW (right)'), 'rotateccw' => t('Rotate CCW (left)'), 'albums' => $albums['albums'], 'album' => $album_e, 'newalbum_label' => t('Enter a new album name'), 'newalbum_placeholder' => t('or select an existing one (doubleclick)'), 'nickname' => $a->data['channel']['channel_address'], 'resource_id' => $ph[0]['resource_id'], 'capt_label' => t('Caption'), 'caption' => $caption_e, 'tag_label' => t('Add a Tag'), 'permissions' => t('Permissions'), 'aclselect' => $aclselect_e, 'lockstate' => $lockstate[0], 'help_tags' => t('Example: @bob, @Barbara_Jensen, @jim@example.com'), 'item_id' => count($linked_items) ? $link_item['id'] : 0, 'adult_enabled' => feature_enabled($owner_uid, 'adult_photo_flagging'), 'adult' => array('adult', t('Flag as adult in album view'), intval($ph[0]['is_nsfw']), ''), 'submit' => t('Submit'), 'delete' => t('Delete Photo')); } if (count($linked_items)) { $cmnt_tpl = get_markup_template('comment_item.tpl'); $tpl = get_markup_template('photo_item.tpl'); $return_url = $a->cmd; $like_tpl = get_markup_template('like_noshare.tpl'); $likebuttons = ''; if ($can_post || $can_comment) { $likebuttons = array('id' => $link_item['id'], 'likethis' => t("I like this (toggle)"), 'nolike' => t("I don't like this (toggle)"), 'share' => t('Share'), 'wait' => t('Please wait')); } $comments = ''; if (!count($r)) { if ($can_post || $can_comment) { $commentbox = replace_macros($cmnt_tpl, array('$return_path' => '', '$mode' => 'photos', '$jsreload' => $return_url, '$type' => 'wall-comment', '$id' => $link_item['id'], '$parent' => $link_item['id'], '$profile_uid' => $owner_uid, '$mylink' => $observer['xchan_url'], '$mytitle' => t('This is you'), '$myphoto' => $observer['xchan_photo_s'], '$comment' => t('Comment'), '$submit' => t('Submit'), '$preview' => t('Preview'), '$ww' => '', '$feature_encrypt' => false)); } } $alike = array(); $dlike = array(); $like = ''; $dislike = ''; $conv_responses = array('like' => array('title' => t('Likes', 'title')), 'dislike' => array('title' => t('Dislikes', 'title')), 'agree' => array('title' => t('Agree', 'title')), 'disagree' => array('title' => t('Disagree', 'title')), 'abstain' => array('title' => t('Abstain', 'title')), 'attendyes' => array('title' => t('Attending', 'title')), 'attendno' => array('title' => t('Not attending', 'title')), 'attendmaybe' => array('title' => t('Might attend', 'title'))); if ($r) { foreach ($r as $item) { builtin_activity_puller($item, $conv_responses); } $like_count = x($alike, $link_item['mid']) ? $alike[$link_item['mid']] : ''; $like_list = x($alike, $link_item['mid']) ? $alike[$link_item['mid'] . '-l'] : ''; if (count($like_list) > MAX_LIKERS) { $like_list_part = array_slice($like_list, 0, MAX_LIKERS); array_push($like_list_part, '<a href="#" data-toggle="modal" data-target="#likeModal-' . $this->get_id() . '"><b>' . t('View all') . '</b></a>'); } else { $like_list_part = ''; } $like_button_label = tt('Like', 'Likes', $like_count, 'noun'); //if (feature_enabled($conv->get_profile_owner(),'dislike')) { $dislike_count = x($dlike, $link_item['mid']) ? $dlike[$link_item['mid']] : ''; $dislike_list = x($dlike, $link_item['mid']) ? $dlike[$link_item['mid'] . '-l'] : ''; $dislike_button_label = tt('Dislike', 'Dislikes', $dislike_count, 'noun'); if (count($dislike_list) > MAX_LIKERS) { $dislike_list_part = array_slice($dislike_list, 0, MAX_LIKERS); array_push($dislike_list_part, '<a href="#" data-toggle="modal" data-target="#dislikeModal-' . $this->get_id() . '"><b>' . t('View all') . '</b></a>'); } else { $dislike_list_part = ''; } //} $like = isset($alike[$link_item['mid']]) ? format_like($alike[$link_item['mid']], $alike[$link_item['mid'] . '-l'], 'like', $link_item['mid']) : ''; $dislike = isset($dlike[$link_item['mid']]) ? format_like($dlike[$link_item['mid']], $dlike[$link_item['mid'] . '-l'], 'dislike', $link_item['mid']) : ''; // display comments foreach ($r as $item) { $comment = ''; $template = $tpl; $sparkle = ''; if ((activity_match($item['verb'], ACTIVITY_LIKE) || activity_match($item['verb'], ACTIVITY_DISLIKE)) && $item['id'] != $item['parent']) { continue; } $redirect_url = $a->get_baseurl() . '/redir/' . $item['cid']; $profile_url = zid($item['author']['xchan_url']); $sparkle = ''; $profile_name = $item['author']['xchan_name']; $profile_avatar = $item['author']['xchan_photo_m']; $profile_link = $profile_url; $drop = ''; if ($observer['xchan_hash'] === $item['author_xchan'] || $observer['xchan_hash'] === $item['owner_xchan']) { $drop = replace_macros(get_markup_template('photo_drop.tpl'), array('$id' => $item['id'], '$delete' => t('Delete'))); } $name_e = $profile_name; $title_e = $item['title']; unobscure($item); $body_e = prepare_text($item['body'], $item['mimetype']); $comments .= replace_macros($template, array('$id' => $item['id'], '$mode' => 'photos', '$profile_url' => $profile_link, '$name' => $name_e, '$thumb' => $profile_avatar, '$sparkle' => $sparkle, '$title' => $title_e, '$body' => $body_e, '$ago' => relative_date($item['created']), '$indent' => $item['parent'] != $item['id'] ? ' comment' : '', '$drop' => $drop, '$comment' => $comment)); } if ($can_post || $can_comment) { $commentbox = replace_macros($cmnt_tpl, array('$return_path' => '', '$jsreload' => $return_url, '$type' => 'wall-comment', '$id' => $link_item['id'], '$parent' => $link_item['id'], '$profile_uid' => $owner_uid, '$mylink' => $observer['xchan_url'], '$mytitle' => t('This is you'), '$myphoto' => $observer['xchan_photo_s'], '$comment' => t('Comment'), '$submit' => t('Submit'), '$ww' => '')); } } $paginate = paginate($a); } $album_e = array($album_link, $ph[0]['album']); $like_e = $like; $dislike_e = $dislike; $response_verbs = array('like'); if (feature_enabled($owner_uid, 'dislike')) { $response_verbs[] = 'dislike'; } $responses = get_responses($conv_responses, $response_verbs, '', $link_item); $photo_tpl = get_markup_template('photo_view.tpl'); $o .= replace_macros($photo_tpl, array('$id' => $ph[0]['id'], '$album' => $album_e, '$tools' => $tools, '$lock' => $lockstate[1], '$photo' => $photo, '$prevlink' => $prevlink, '$nextlink' => $nextlink, '$desc' => $ph[0]['description'], '$filename' => $ph[0]['filename'], '$unknown' => t('Unknown'), '$tag_hdr' => t('In This Photo:'), '$tags' => $tags, 'responses' => $responses, '$edit' => $edit, '$map' => $map, '$map_text' => t('Map'), '$likebuttons' => $likebuttons, '$like' => $like_e, '$dislike' => $dislike_e, '$like_count' => $like_count, '$like_list' => $like_list, '$like_list_part' => $like_list_part, '$like_button_label' => $like_button_label, '$like_modal_title' => t('Likes', 'noun'), '$dislike_modal_title' => t('Dislikes', 'noun'), '$dislike_count' => $dislike_count, '$dislike_list' => $dislike_list, '$dislike_list_part' => $dislike_list_part, '$dislike_button_label' => $dislike_button_label, '$modal_dismiss' => t('Close'), '$comments' => $comments, '$commentbox' => $commentbox, '$paginate' => $paginate)); $a->data['photo_html'] = $o; return $o; } // Default - show recent photos with upload link (if applicable) //$o = ''; $r = q("SELECT `resource_id`, max(`scale`) AS `scale` FROM `photo` WHERE `uid` = %d AND `album` != '%s' AND `album` != '%s' \n\t\tand photo_usage in ( %d, %d ) and is_nsfw = %d {$sql_extra} GROUP BY `resource_id`", intval($a->data['channel']['channel_id']), dbesc('Contact Photos'), dbesc(t('Contact Photos')), intval(PHOTO_NORMAL), intval(PHOTO_PROFILE), intval($unsafe)); if (count($r)) { $a->set_pager_total(count($r)); $a->set_pager_itemspage(60); } $r = q("SELECT p.resource_id, p.id, p.filename, p.type, p.album, p.scale, p.created FROM photo p INNER JOIN \n\t\t(SELECT resource_id, max(scale) scale FROM photo \n\t\t\tWHERE uid=%d AND album != '%s' AND album != '%s' \n\t\t\tAND photo_usage IN ( %d, %d ) and is_nsfw = %d {$sql_extra} group by resource_id) ph \n\t\tON (p.resource_id = ph.resource_id and p.scale = ph.scale) ORDER by p.created DESC LIMIT %d OFFSET %d", intval($a->data['channel']['channel_id']), dbesc('Contact Photos'), dbesc(t('Contact Photos')), intval(PHOTO_NORMAL), intval(PHOTO_PROFILE), intval($unsafe), intval($a->pager['itemspage']), intval($a->pager['start'])); $photos = array(); if (count($r)) { $twist = 'rotright'; foreach ($r as $rr) { if ($twist == 'rotright') { $twist = 'rotleft'; } else { $twist = 'rotright'; } $ext = $phototypes[$rr['type']]; if ($a->get_template_engine() === 'internal') { $alt_e = template_escape($rr['filename']); $name_e = template_escape($rr['album']); } else { $alt_e = $rr['filename']; $name_e = $rr['album']; } $photos[] = array('id' => $rr['id'], 'twist' => ' ' . $twist . rand(2, 4), 'link' => $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/image/' . $rr['resource_id'], 'title' => t('View Photo'), 'src' => $a->get_baseurl() . '/photo/' . $rr['resource_id'] . '-' . ($rr['scale'] == 6 ? 4 : $rr['scale']) . '.' . $ext, 'alt' => $alt_e, 'album' => array('link' => $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/album/' . bin2hex($rr['album']), 'name' => $name_e, 'alt' => t('View Album'))); } } if ($_REQUEST['aj']) { if ($photos) { $o = replace_macros(get_markup_template('photosajax.tpl'), array('$photos' => $photos)); } else { $o = '<div id="content-complete"></div>'; } echo $o; killme(); } else { $o .= "<script> var page_query = '" . $_GET['q'] . "'; var extra_args = '" . extra_query_args() . "' ; </script>"; $tpl = get_markup_template('photos_recent.tpl'); $o .= replace_macros($tpl, array('$title' => t('Recent Photos'), '$can_post' => $can_post, '$upload' => array(t('Upload'), $a->get_baseurl() . '/photos/' . $a->data['channel']['channel_address'] . '/upload'), '$photos' => $photos, '$upload_form' => $upload_form, '$usage' => $usage_message)); } if (!$photos && $_REQUEST['aj']) { $o .= '<div id="content-complete"></div>'; echo $o; killme(); } // paginate($a); return $o; }
function chat_content(&$a) { if (local_channel()) { $channel = $a->get_channel(); } $ob = $a->get_observer(); $observer = get_observer_hash(); if (!$observer) { notice(t('Permission denied.') . EOL); return; } if (!perm_is_allowed($a->profile['profile_uid'], $observer, 'chat')) { notice(t('Permission denied.') . EOL); return; } if (argc() > 3 && intval(argv(2)) && argv(3) === 'leave') { chatroom_leave($observer, argv(2), $_SERVER['REMOTE_ADDR']); goaway(z_root() . '/channel/' . argv(1)); } if (argc() > 3 && intval(argv(2)) && argv(3) === 'status') { $ret = array('success' => false); $room_id = intval(argv(2)); if (!$room_id || !$observer) { return; } $r = q("select * from chatroom where cr_id = %d limit 1", intval($room_id)); if (!$r) { json_return_and_die($ret); } require_once 'include/security.php'; $sql_extra = permissions_sql($r[0]['cr_uid']); $x = q("select * from chatroom where cr_id = %d and cr_uid = %d {$sql_extra} limit 1", intval($room_id), intval($r[0]['cr_uid'])); if (!$x) { json_return_and_die($ret); } $y = q("select count(*) as total from chatpresence where cp_room = %d", intval($room_id)); if ($y) { $ret['success'] = true; $ret['chatroom'] = $r[0]['cr_name']; $ret['inroom'] = $y[0]['total']; } // figure out how to present a timestamp of the last activity, since we don't know the observer's timezone. $z = q("select created from chat where chat_room = %d order by created desc limit 1", intval($room_id)); if ($z) { $ret['last'] = $z[0]['created']; } json_return_and_die($ret); } if (argc() > 2 && intval(argv(2))) { $room_id = intval(argv(2)); $bookmark_link = get_bookmark_link($ob); $x = chatroom_enter($observer, $room_id, 'online', $_SERVER['REMOTE_ADDR']); if (!$x) { return; } $x = q("select * from chatroom where cr_id = %d and cr_uid = %d {$sql_extra} limit 1", intval($room_id), intval($a->profile['profile_uid'])); if ($x) { $acl = new AccessList(false); $acl->set($x[0]); $private = $acl->is_private(); $room_name = $x[0]['cr_name']; if ($bookmark_link) { $bookmark_link .= '&url=' . z_root() . '/chat/' . argv(1) . '/' . argv(2) . '&title=' . urlencode($x[0]['cr_name']) . ($private ? '&private=1' : '') . '&ischat=1'; } } else { notice(t('Room not found') . EOL); return; } $o = replace_macros(get_markup_template('chat.tpl'), array('$is_owner' => local_channel() && local_channel() == $x[0]['cr_uid'] ? true : false, '$room_name' => $room_name, '$room_id' => $room_id, '$baseurl' => z_root(), '$nickname' => argv(1), '$submit' => t('Submit'), '$leave' => t('Leave Room'), '$drop' => t('Delete This Room'), '$away' => t('I am away right now'), '$online' => t('I am online'), '$bookmark_link' => $bookmark_link, '$bookmark' => t('Bookmark this room'))); return $o; } if (local_channel() && argc() > 2 && argv(2) === 'new') { $acl = new AccessList($channel); $channel_acl = $acl->get(); require_once 'include/acl_selectors.php'; $o = replace_macros(get_markup_template('chatroom_new.tpl'), array('$header' => t('New Chatroom'), '$name' => array('room_name', t('Chatroom Name'), '', ''), '$chat_expire' => array('chat_expire', t('Expiration of chats (minutes)'), 120, ''), '$permissions' => t('Permissions'), '$acl' => populate_acl($channel_acl, false), '$submit' => t('Submit'))); return $o; } require_once 'include/conversation.php'; $o = profile_tabs($a, local_channel() && local_channel() == $a->profile['profile_uid'] ? true : false, $a->profile['channel_address']); require_once 'include/widgets.php'; $o .= replace_macros(get_markup_template('chatrooms.tpl'), array('$header' => sprintf(t('%1$s\'s Chatrooms'), $a->profile['name']), '$baseurl' => z_root(), '$nickname' => $channel['channel_address'], '$rooms' => widget_chatroom_list(array()), '$newroom' => t('New Chatroom'), '$is_owner' => local_channel() && local_channel() == $a->profile['profile_uid'] ? 1 : 0)); return $o; }
function events_post(&$a) { logger('post: ' . print_r($_REQUEST, true), LOGGER_DATA); if (!local_channel()) { return; } if ($_FILES && array_key_exists('userfile', $_FILES) && intval($_FILES['userfile']['size'])) { $src = $_FILES['userfile']['tmp_name']; if ($src) { $result = parse_ical_file($src, local_channel()); if ($result) { info(t('Calendar entries imported.') . EOL); } else { notice(t('No calendar entries found.') . EOL); } @unlink($src); } goaway(z_root() . '/events'); } $event_id = x($_POST, 'event_id') ? intval($_POST['event_id']) : 0; $event_hash = x($_POST, 'event_hash') ? $_POST['event_hash'] : ''; $xchan = x($_POST, 'xchan') ? dbesc($_POST['xchan']) : ''; $uid = local_channel(); $start_text = escape_tags($_REQUEST['start_text']); $finish_text = escape_tags($_REQUEST['finish_text']); $adjust = intval($_POST['adjust']); $nofinish = intval($_POST['nofinish']); $categories = escape_tags(trim($_POST['category'])); // only allow editing your own events. if ($xchan && $xchan !== get_observer_hash()) { return; } if ($start_text) { $start = $start_text; } else { $start = sprintf('%d-%d-%d %d:%d:0', $startyear, $startmonth, $startday, $starthour, $startminute); } if ($nofinish) { $finish = NULL_DATE; } if ($finish_text) { $finish = $finish_text; } else { $finish = sprintf('%d-%d-%d %d:%d:0', $finishyear, $finishmonth, $finishday, $finishhour, $finishminute); } if ($adjust) { $start = datetime_convert(date_default_timezone_get(), 'UTC', $start); if (!$nofinish) { $finish = datetime_convert(date_default_timezone_get(), 'UTC', $finish); } } else { $start = datetime_convert('UTC', 'UTC', $start); if (!$nofinish) { $finish = datetime_convert('UTC', 'UTC', $finish); } } // Don't allow the event to finish before it begins. // It won't hurt anything, but somebody will file a bug report // and we'll waste a bunch of time responding to it. Time that // could've been spent doing something else. $summary = escape_tags(trim($_POST['summary'])); $desc = escape_tags(trim($_POST['desc'])); $location = escape_tags(trim($_POST['location'])); $type = escape_tags(trim($_POST['type'])); require_once 'include/text.php'; linkify_tags($a, $desc, local_channel()); linkify_tags($a, $location, local_channel()); //$action = ($event_hash == '') ? 'new' : "event/" . $event_hash; //fixme: this url gives a wsod if there is a linebreak detected in one of the variables ($desc or $location) //$onerror_url = $a->get_baseurl() . "/events/" . $action . "?summary=$summary&description=$desc&location=$location&start=$start_text&finish=$finish_text&adjust=$adjust&nofinish=$nofinish&type=$type"; $onerror_url = $a->get_baseurl() . "/events"; if (strcmp($finish, $start) < 0 && !$nofinish) { notice(t('Event can not end before it has started.') . EOL); if (intval($_REQUEST['preview'])) { echo t('Unable to generate preview.'); killme(); } goaway($onerror_url); } if (!$summary || !$start) { notice(t('Event title and start time are required.') . EOL); if (intval($_REQUEST['preview'])) { echo t('Unable to generate preview.'); killme(); } goaway($onerror_url); } $share = intval($_POST['share']) ? intval($_POST['share']) : 0; $channel = $a->get_channel(); $acl = new AccessList(false); if ($event_id) { $x = q("select * from event where id = %d and uid = %d limit 1", intval($event_id), intval(local_channel())); if (!$x) { notice(t('Event not found.') . EOL); if (intval($_REQUEST['preview'])) { echo t('Unable to generate preview.'); killme(); } return; } $acl->set($x[0]); $created = $x[0]['created']; $edited = datetime_convert(); if ($x[0]['allow_cid'] === '<' . $channel['channel_hash'] . '>' && $x[0]['allow_gid'] === '' && $x[0]['deny_cid'] === '' && $x[0]['deny_gid'] === '') { $share = false; } else { $share = true; } } else { $created = $edited = datetime_convert(); if ($share) { $acl->set_from_array($_POST); } else { $acl->set(array('allow_cid' => '<' . $channel['channel_hash'] . '>', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '')); } } $post_tags = array(); $channel = $a->get_channel(); $ac = $acl->get(); if (strlen($categories)) { $cats = explode(',', $categories); foreach ($cats as $cat) { $post_tags[] = array('uid' => $profile_uid, 'type' => TERM_CATEGORY, 'otype' => TERM_OBJ_POST, 'term' => trim($cat), 'url' => $channel['xchan_url'] . '?f=&cat=' . urlencode(trim($cat))); } } $datarray = array(); $datarray['start'] = $start; $datarray['finish'] = $finish; $datarray['summary'] = $summary; $datarray['description'] = $desc; $datarray['location'] = $location; $datarray['type'] = $type; $datarray['adjust'] = $adjust; $datarray['nofinish'] = $nofinish; $datarray['uid'] = local_channel(); $datarray['account'] = get_account_id(); $datarray['event_xchan'] = $channel['channel_hash']; $datarray['allow_cid'] = $ac['allow_cid']; $datarray['allow_gid'] = $ac['allow_gid']; $datarray['deny_cid'] = $ac['deny_cid']; $datarray['deny_gid'] = $ac['deny_gid']; $datarray['private'] = $acl->is_private() ? 1 : 0; $datarray['id'] = $event_id; $datarray['created'] = $created; $datarray['edited'] = $edited; if (intval($_REQUEST['preview'])) { $html = format_event_html($datarray); echo $html; killme(); } $event = event_store_event($datarray); if ($post_tags) { $datarray['term'] = $post_tags; } $item_id = event_store_item($datarray, $event); if ($item_id) { $r = q("select * from item where id = %d", intval($item_id)); if ($r) { xchan_query($r); $sync_item = fetch_post_tags($r); $z = q("select * from event where event_hash = '%s' and uid = %d limit 1", dbesc($r[0]['resource_id']), intval($channel['channel_id'])); if ($z) { build_sync_packet($channel['channel_id'], array('event_item' => array(encode_item($sync_item[0], true)), 'event' => $z)); } } } if ($share) { proc_run('php', "include/notifier.php", "event", "{$item_id}"); } }
function item_post(&$a) { // This will change. Figure out who the observer is and whether or not // they have permission to post here. Else ignore the post. if (!local_channel() && !remote_channel() && !x($_REQUEST, 'commenter')) { return; } require_once 'include/security.php'; $uid = local_channel(); $channel = null; $observer = null; /** * Is this a reply to something? */ $parent = x($_REQUEST, 'parent') ? intval($_REQUEST['parent']) : 0; $parent_mid = x($_REQUEST, 'parent_mid') ? trim($_REQUEST['parent_mid']) : ''; $remote_xchan = x($_REQUEST, 'remote_xchan') ? trim($_REQUEST['remote_xchan']) : false; $r = q("select * from xchan where xchan_hash = '%s' limit 1", dbesc($remote_xchan)); if ($r) { $remote_observer = $r[0]; } else { $remote_xchan = $remote_observer = false; } $profile_uid = x($_REQUEST, 'profile_uid') ? intval($_REQUEST['profile_uid']) : 0; require_once 'include/identity.php'; $sys = get_sys_channel(); if ($sys && $profile_uid && $sys['channel_id'] == $profile_uid && is_site_admin()) { $uid = intval($sys['channel_id']); $channel = $sys; $observer = $sys; } if (x($_REQUEST, 'dropitems')) { require_once 'include/items.php'; $arr_drop = explode(',', $_REQUEST['dropitems']); drop_items($arr_drop); $json = array('success' => 1); echo json_encode($json); killme(); } call_hooks('post_local_start', $_REQUEST); // logger('postvars ' . print_r($_REQUEST,true), LOGGER_DATA); $api_source = x($_REQUEST, 'api_source') && $_REQUEST['api_source'] ? true : false; $consensus = intval($_REQUEST['consensus']); // 'origin' (if non-zero) indicates that this network is where the message originated, // for the purpose of relaying comments to other conversation members. // If using the API from a device (leaf node) you must set origin to 1 (default) or leave unset. // If the API is used from another network with its own distribution // and deliveries, you may wish to set origin to 0 or false and allow the other // network to relay comments. // If you are unsure, it is prudent (and important) to leave it unset. $origin = $api_source && array_key_exists('origin', $_REQUEST) ? intval($_REQUEST['origin']) : 1; // To represent message-ids on other networks - this will create an item_id record $namespace = $api_source && array_key_exists('namespace', $_REQUEST) ? strip_tags($_REQUEST['namespace']) : ''; $remote_id = $api_source && array_key_exists('remote_id', $_REQUEST) ? strip_tags($_REQUEST['remote_id']) : ''; $owner_hash = null; $message_id = x($_REQUEST, 'message_id') && $api_source ? strip_tags($_REQUEST['message_id']) : ''; $created = x($_REQUEST, 'created') ? datetime_convert('UTC', 'UTC', $_REQUEST['created']) : datetime_convert(); $post_id = x($_REQUEST, 'post_id') ? intval($_REQUEST['post_id']) : 0; $app = x($_REQUEST, 'source') ? strip_tags($_REQUEST['source']) : ''; $return_path = x($_REQUEST, 'return') ? $_REQUEST['return'] : ''; $preview = x($_REQUEST, 'preview') ? intval($_REQUEST['preview']) : 0; $categories = x($_REQUEST, 'category') ? escape_tags($_REQUEST['category']) : ''; $webpage = x($_REQUEST, 'webpage') ? intval($_REQUEST['webpage']) : 0; $pagetitle = x($_REQUEST, 'pagetitle') ? escape_tags(urlencode($_REQUEST['pagetitle'])) : ''; $layout_mid = x($_REQUEST, 'layout_mid') ? escape_tags($_REQUEST['layout_mid']) : ''; $plink = x($_REQUEST, 'permalink') ? escape_tags($_REQUEST['permalink']) : ''; $obj_type = x($_REQUEST, 'obj_type') ? escape_tags($_REQUEST['obj_type']) : ACTIVITY_OBJ_NOTE; // allow API to bulk load a bunch of imported items with sending out a bunch of posts. $nopush = x($_REQUEST, 'nopush') ? intval($_REQUEST['nopush']) : 0; /* * Check service class limits */ if ($uid && !x($_REQUEST, 'parent') && !x($_REQUEST, 'post_id')) { $ret = item_check_service_class($uid, $_REQUEST['webpage'] == ITEM_TYPE_WEBPAGE ? true : false); if (!$ret['success']) { notice(t($ret['message']) . EOL); if (x($_REQUEST, 'return')) { goaway($a->get_baseurl() . "/" . $return_path); } killme(); } } if ($pagetitle) { require_once 'library/urlify/URLify.php'; $pagetitle = strtolower(URLify::transliterate($pagetitle)); } $item_flags = $item_restrict = 0; $route = ''; $parent_item = null; $parent_contact = null; $thr_parent = ''; $parid = 0; $r = false; if ($parent || $parent_mid) { if (!x($_REQUEST, 'type')) { $_REQUEST['type'] = 'net-comment'; } if ($obj_type == ACTIVITY_OBJ_POST) { $obj_type = ACTIVITY_OBJ_COMMENT; } if ($parent) { $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($parent)); } elseif ($parent_mid && $uid) { // This is coming from an API source, and we are logged in $r = q("SELECT * FROM `item` WHERE `mid` = '%s' AND `uid` = %d LIMIT 1", dbesc($parent_mid), intval($uid)); } // if this isn't the real parent of the conversation, find it if ($r !== false && count($r)) { $parid = $r[0]['parent']; $parent_mid = $r[0]['mid']; if ($r[0]['id'] != $r[0]['parent']) { $r = q("SELECT * FROM `item` WHERE `id` = `parent` AND `parent` = %d LIMIT 1", intval($parid)); } } if ($r === false || !count($r)) { notice(t('Unable to locate original post.') . EOL); if (x($_REQUEST, 'return')) { goaway($a->get_baseurl() . "/" . $return_path); } killme(); } // can_comment_on_post() needs info from the following xchan_query xchan_query($r); $parent_item = $r[0]; $parent = $r[0]['id']; // multi-level threading - preserve the info but re-parent to our single level threading $thr_parent = $parent_mid; $route = $parent_item['route']; } if (!$observer) { $observer = $a->get_observer(); } if ($parent) { logger('mod_item: item_post parent=' . $parent); $can_comment = false; if (array_key_exists('owner', $parent_item) && intval($parent_item['owner']['abook_self'])) { $can_comment = perm_is_allowed($profile_uid, $observer['xchan_hash'], 'post_comments'); } else { $can_comment = can_comment_on_post($observer['xchan_hash'], $parent_item); } if (!$can_comment) { notice(t('Permission denied.') . EOL); if (x($_REQUEST, 'return')) { goaway($a->get_baseurl() . "/" . $return_path); } killme(); } } else { if (!perm_is_allowed($profile_uid, $observer['xchan_hash'], 'post_wall')) { notice(t('Permission denied.') . EOL); if (x($_REQUEST, 'return')) { goaway($a->get_baseurl() . "/" . $return_path); } killme(); } } // is this an edited post? $orig_post = null; if ($namespace && $remote_id) { // It wasn't an internally generated post - see if we've got an item matching this remote service id $i = q("select iid from item_id where service = '%s' and sid = '%s' limit 1", dbesc($namespace), dbesc($remote_id)); if ($i) { $post_id = $i[0]['iid']; } } if ($post_id) { $i = q("SELECT * FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1", intval($profile_uid), intval($post_id)); if (!count($i)) { killme(); } $orig_post = $i[0]; } if (!$channel) { if ($uid && $uid == $profile_uid) { $channel = $a->get_channel(); } else { // posting as yourself but not necessarily to a channel you control $r = q("select * from channel left join account on channel_account_id = account_id where channel_id = %d LIMIT 1", intval($profile_uid)); if ($r) { $channel = $r[0]; } } } if (!$channel) { logger("mod_item: no channel."); if (x($_REQUEST, 'return')) { goaway($a->get_baseurl() . "/" . $return_path); } killme(); } $owner_xchan = null; $r = q("select * from xchan where xchan_hash = '%s' limit 1", dbesc($channel['channel_hash'])); if ($r && count($r)) { $owner_xchan = $r[0]; } else { logger("mod_item: no owner."); if (x($_REQUEST, 'return')) { goaway($a->get_baseurl() . "/" . $return_path); } killme(); } $walltowall = false; $walltowall_comment = false; if ($remote_xchan) { $observer = $remote_observer; } if ($observer) { logger('mod_item: post accepted from ' . $observer['xchan_name'] . ' for ' . $owner_xchan['xchan_name'], LOGGER_DEBUG); // wall-to-wall detection. // For top-level posts, if the author and owner are different it's a wall-to-wall // For comments, We need to additionally look at the parent and see if it's a wall post that originated locally. if ($observer['xchan_name'] != $owner_xchan['xchan_name']) { if ($parent_item && ($parent_item['item_wall'] && $parent_item['item_origin'])) { $walltowall_comment = true; $walltowall = true; } if (!$parent) { $walltowall = true; } } } $acl = new AccessList($channel); $public_policy = x($_REQUEST, 'public_policy') ? escape_tags($_REQUEST['public_policy']) : map_scope($channel['channel_r_stream'], true); if ($webpage) { $public_policy = ''; } if ($public_policy) { $private = 1; } if ($orig_post) { $private = 0; // webpages are allowed to change ACLs after the fact. Normal conversation items aren't. if ($webpage) { $acl->set_from_array($_REQUEST); } else { $acl->set($orig_post); $public_policy = $orig_post['public_policy']; $private = $orig_post['item_private']; } if ($private || $public_policy || $acl->is_private()) { $private = 1; } $location = $orig_post['location']; $coord = $orig_post['coord']; $verb = $orig_post['verb']; $app = $orig_post['app']; $title = escape_tags(trim($_REQUEST['title'])); $body = trim($_REQUEST['body']); $item_flags = $orig_post['item_flags']; $item_origin = $orig_post['item_origin']; $item_unseen = $orig_post['item_unseen']; $item_starred = $orig_post['item_starred']; $item_uplink = $orig_post['item_uplink']; $item_consensus = $orig_post['item_consensus']; $item_wall = $orig_post['item_wall']; $item_thread_top = $orig_post['item_thread_top']; $item_notshown = $orig_post['item_notshown']; $item_nsfw = $orig_post['item_nsfw']; $item_relay = $orig_post['item_relay']; $item_mentionsme = $orig_post['item_mentionsme']; $item_nocomment = $orig_post['item_nocomment']; $item_obscured = $orig_post['item_obscured']; $item_verified = $orig_post['item_verified']; $item_retained = $orig_post['item_retained']; $item_rss = $orig_post['item_rss']; $item_deleted = $orig_post['item_deleted']; $item_type = $orig_post['item_type']; $item_hidden = $orig_post['item_hidden']; $item_unpublished = $orig_post['item_unpublished']; $item_delayed = $orig_post['item_delayed']; $item_pending_remove = $orig_post['item_pending_remove']; $item_blocked = $orig_post['item_blocked']; $postopts = $orig_post['postopts']; $created = $orig_post['created']; $mid = $orig_post['mid']; $parent_mid = $orig_post['parent_mid']; $plink = $orig_post['plink']; } else { if (!$walltowall && (array_key_exists('contact_allow', $_REQUEST) || array_key_exists('group_allow', $_REQUEST) || array_key_exists('contact_deny', $_REQUEST) || array_key_exists('group_deny', $_REQUEST))) { $acl->set_from_array($_REQUEST); } $location = notags(trim($_REQUEST['location'])); $coord = notags(trim($_REQUEST['coord'])); $verb = notags(trim($_REQUEST['verb'])); $title = escape_tags(trim($_REQUEST['title'])); $body = trim($_REQUEST['body']); $body .= trim($_REQUEST['attachment']); $postopts = ''; $private = intval($acl->is_private() || $public_policy); // If this is a comment, set the permissions from the parent. if ($parent_item) { $private = 0; $acl->set($parent_item); $private = intval($acl->is_private() || $parent_item['item_private']); $public_policy = $parent_item['public_policy']; $owner_hash = $parent_item['owner_xchan']; } if (!strlen($body)) { if ($preview) { killme(); } info(t('Empty post discarded.') . EOL); if (x($_REQUEST, 'return')) { goaway($a->get_baseurl() . "/" . $return_path); } killme(); } } $expires = NULL_DATE; if (feature_enabled($profile_uid, 'content_expire')) { if (x($_REQUEST, 'expire')) { $expires = datetime_convert(date_default_timezone_get(), 'UTC', $_REQUEST['expire']); if ($expires <= datetime_convert()) { $expires = NULL_DATE; } } } $mimetype = notags(trim($_REQUEST['mimetype'])); if (!$mimetype) { $mimetype = 'text/bbcode'; } if ($preview) { $body = z_input_filter($profile_uid, $body, $mimetype); } // Verify ability to use html or php!!! $execflag = false; if ($mimetype === 'application/x-php') { $z = q("select account_id, account_roles, channel_pageflags from account left join channel on channel_account_id = account_id where channel_id = %d limit 1", intval($profile_uid)); if ($z && ($z[0]['account_roles'] & ACCOUNT_ROLE_ALLOWCODE || $z[0]['channel_pageflags'] & PAGE_ALLOWCODE)) { if ($uid && get_account_id() == $z[0]['account_id']) { $execflag = true; } else { notice(t('Executable content type not permitted to this channel.') . EOL); if (x($_REQUEST, 'return')) { goaway($a->get_baseurl() . "/" . $return_path); } killme(); } } } $gacl = $acl->get(); $str_contact_allow = $gacl['allow_cid']; $str_group_allow = $gacl['allow_gid']; $str_contact_deny = $gacl['deny_cid']; $str_group_deny = $gacl['deny_gid']; if ($mimetype === 'text/bbcode') { require_once 'include/text.php'; if ($uid && $uid == $profile_uid && feature_enabled($uid, 'markdown')) { require_once 'include/bb2diaspora.php'; $body = escape_tags($body); $body = preg_replace_callback('/\\[share(.*?)\\]/ism', 'share_shield', $body); $body = diaspora2bb($body, true); $body = preg_replace_callback('/\\[share(.*?)\\]/ism', 'share_unshield', $body); } // BBCODE alert: the following functions assume bbcode input // and will require alternatives for alternative content-types (text/html, text/markdown, text/plain, etc.) // we may need virtual or template classes to implement the possible alternatives // Work around doubled linefeeds in Tinymce 3.5b2 // First figure out if it's a status post that would've been // created using tinymce. Otherwise leave it alone. $plaintext = true; // $plaintext = ((feature_enabled($profile_uid,'richtext')) ? false : true); // if((! $parent) && (! $api_source) && (! $plaintext)) { // $body = fix_mce_lf($body); // } // If we're sending a private top-level message with a single @-taggable channel as a recipient, @-tag it, if our pconfig is set. if (!$parent && get_pconfig($profile_uid, 'system', 'tagifonlyrecip') && substr_count($str_contact_allow, '<') == 1 && $str_group_allow == '' && $str_contact_deny == '' && $str_group_deny == '') { $x = q("select abook_id, abook_their_perms from abook where abook_xchan = '%s' and abook_channel = %d limit 1", dbesc(str_replace(array('<', '>'), array('', ''), $str_contact_allow)), intval($profile_uid)); if ($x && $x[0]['abook_their_perms'] & PERMS_W_TAGWALL) { $body .= "\n\n@group+" . $x[0]['abook_id'] . "\n"; } } /** * fix naked links by passing through a callback to see if this is a red site * (already known to us) which will get a zrl, otherwise link with url, add bookmark tag to both. * First protect any url inside certain bbcode tags so we don't double link it. */ $body = preg_replace_callback('/\\[code(.*?)\\[\\/(code)\\]/ism', 'red_escape_codeblock', $body); $body = preg_replace_callback('/\\[url(.*?)\\[\\/(url)\\]/ism', 'red_escape_codeblock', $body); $body = preg_replace_callback('/\\[zrl(.*?)\\[\\/(zrl)\\]/ism', 'red_escape_codeblock', $body); $body = preg_replace_callback("/([^\\]\\='" . '"' . "\\/]|^|\\#\\^)(https?\\:\\/\\/[a-zA-Z0-9\\:\\/\\-\\?\\&\\;\\.\\=\\@\\_\\~\\#\\%\$\\!\\+\\,]+)/ism", 'red_zrl_callback', $body); $body = preg_replace_callback('/\\[\\$b64zrl(.*?)\\[\\/(zrl)\\]/ism', 'red_unescape_codeblock', $body); $body = preg_replace_callback('/\\[\\$b64url(.*?)\\[\\/(url)\\]/ism', 'red_unescape_codeblock', $body); $body = preg_replace_callback('/\\[\\$b64code(.*?)\\[\\/(code)\\]/ism', 'red_unescape_codeblock', $body); // fix any img tags that should be zmg $body = preg_replace_callback('/\\[img(.*?)\\](.*?)\\[\\/img\\]/ism', 'red_zrlify_img_callback', $body); $body = bb_translate_video($body); /** * Fold multi-line [code] sequences */ $body = preg_replace('/\\[\\/code\\]\\s*\\[code\\]/ism', "\n", $body); $body = scale_external_images($body, false); // Look for tags and linkify them $results = linkify_tags($a, $body, $uid ? $uid : $profile_uid); if ($results) { // Set permissions based on tag replacements set_linkified_perms($results, $str_contact_allow, $str_group_allow, $profile_uid, $parent_item, $private); $post_tags = array(); foreach ($results as $result) { $success = $result['success']; if ($success['replaced']) { $post_tags[] = array('uid' => $profile_uid, 'type' => $success['termtype'], 'otype' => TERM_OBJ_POST, 'term' => $success['term'], 'url' => $success['url']); } } } /** * * When a photo was uploaded into the message using the (profile wall) ajax * uploader, The permissions are initially set to disallow anybody but the * owner from seeing it. This is because the permissions may not yet have been * set for the post. If it's private, the photo permissions should be set * appropriately. But we didn't know the final permissions on the post until * now. So now we'll look for links of uploaded photos and attachments that are in the * post and set them to the same permissions as the post itself. * * If the post was end-to-end encrypted we can't find images and attachments in the body, * use our media_str input instead which only contains these elements - but only do this * when encrypted content exists because the photo/attachment may have been removed from * the post and we should keep it private. If it's encrypted we have no way of knowing * so we'll set the permissions regardless and realise that the media may not be * referenced in the post. * * What is preventing us from being able to upload photos into comments is dealing with * the photo and attachment permissions, since we don't always know who was in the * distribution for the top level post. * * We might be able to provide this functionality with a lot of fiddling: * - if the top level post is public (make the photo public) * - if the top level post was written by us or a wall post that belongs to us (match the top level post) * - if the top level post has privacy mentions, add those to the permissions. * - otherwise disallow the photo *or* make the photo public. This is the part that gets messy. */ if (!$preview) { fix_attached_photo_permissions($profile_uid, $owner_xchan['xchan_hash'], strpos($body, '[/crypt]') ? $_POST['media_str'] : $body, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny); fix_attached_file_permissions($channel, $observer['xchan_hash'], strpos($body, '[/crypt]') ? $_POST['media_str'] : $body, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny); } $attachments = ''; $match = false; if (preg_match_all('/(\\[attachment\\](.*?)\\[\\/attachment\\])/', $body, $match)) { $attachments = array(); foreach ($match[2] as $mtch) { $attach_link = ''; $hash = substr($mtch, 0, strpos($mtch, ',')); $rev = intval(substr($mtch, strpos($mtch, ','))); $r = attach_by_hash_nodata($hash, $rev); if ($r['success']) { $attachments[] = array('href' => $a->get_baseurl() . '/attach/' . $r['data']['hash'], 'length' => $r['data']['filesize'], 'type' => $r['data']['filetype'], 'title' => urlencode($r['data']['filename']), 'revision' => $r['data']['revision']); } $ext = substr($r['data']['filename'], strrpos($r['data']['filename'], '.')); if (strpos($r['data']['filetype'], 'audio/') !== false) { $attach_link = '[audio]' . z_root() . '/attach/' . $r['data']['hash'] . '/' . $r['data']['revision'] . ($ext ? $ext : '') . '[/audio]'; } elseif (strpos($r['data']['filetype'], 'video/') !== false) { $attach_link = '[video]' . z_root() . '/attach/' . $r['data']['hash'] . '/' . $r['data']['revision'] . ($ext ? $ext : '') . '[/video]'; } $body = str_replace($match[1], $attach_link, $body); } } } // BBCODE end alert if (strlen($categories)) { $cats = explode(',', $categories); foreach ($cats as $cat) { $post_tags[] = array('uid' => $profile_uid, 'type' => TERM_CATEGORY, 'otype' => TERM_OBJ_POST, 'term' => trim($cat), 'url' => $owner_xchan['xchan_url'] . '?f=&cat=' . urlencode(trim($cat))); } } $item_unseen = local_channel() != $profile_uid ? 1 : 0; $item_wall = $post_type === 'wall' || $post_type === 'wall-comment' ? 1 : 0; $item_origin = $origin ? 1 : 0; $item_consensus = $consensus ? 1 : 0; // determine if this is a wall post if ($parent) { $item_wall = $parent_item['item_wall']; } else { if (!$webpage) { $item_wall = 1; } } if ($moderated) { $item_blocked = ITEM_MODERATED; } if (!strlen($verb)) { $verb = ACTIVITY_POST; } $notify_type = $parent ? 'comment-new' : 'wall-new'; if (!$mid) { $mid = $message_id ? $message_id : item_message_id(); } if (!$parent_mid) { $parent_mid = $mid; } if ($parent_item) { $parent_mid = $parent_item['mid']; } // Fallback so that we alway have a thr_parent if (!$thr_parent) { $thr_parent = $mid; } $datarray = array(); $item_thead_top = !$parent ? 1 : 0; if (!$plink && $item_thread_top) { $plink = z_root() . '/channel/' . $channel['channel_address'] . '/?f=&mid=' . $mid; } $datarray['aid'] = $channel['channel_account_id']; $datarray['uid'] = $profile_uid; $datarray['owner_xchan'] = $owner_hash ? $owner_hash : $owner_xchan['xchan_hash']; $datarray['author_xchan'] = $observer['xchan_hash']; $datarray['created'] = $created; $datarray['edited'] = $orig_post ? datetime_convert() : $created; $datarray['expires'] = $expires; $datarray['commented'] = $orig_post ? datetime_convert() : $created; $datarray['received'] = $orig_post ? datetime_convert() : $created; $datarray['changed'] = $orig_post ? datetime_convert() : $created; $datarray['mid'] = $mid; $datarray['parent_mid'] = $parent_mid; $datarray['mimetype'] = $mimetype; $datarray['title'] = $title; $datarray['body'] = $body; $datarray['app'] = $app; $datarray['location'] = $location; $datarray['coord'] = $coord; $datarray['verb'] = $verb; $datarray['obj_type'] = $obj_type; $datarray['allow_cid'] = $str_contact_allow; $datarray['allow_gid'] = $str_group_allow; $datarray['deny_cid'] = $str_contact_deny; $datarray['deny_gid'] = $str_group_deny; $datarray['item_private'] = $private; $datarray['item_wall'] = $item_wall; $datarray['attach'] = $attachments; $datarray['thr_parent'] = $thr_parent; $datarray['postopts'] = $postopts; $datarray['item_unseen'] = $item_unseen; $datarray['item_wall'] = $item_wall; $datarray['item_origin'] = $item_origin; $datarray['item_type'] = $webpage; $datarray['item_thread_top'] = $item_thread_top; $datarray['item_unseen'] = $item_unseen; $datarray['item_starred'] = $item_starred; $datarray['item_uplink'] = $item_uplink; $datarray['item_consensus'] = $item_consensus; $datarray['item_notshown'] = $item_notshown; $datarray['item_nsfw'] = $item_nsfw; $datarray['item_relay'] = $item_relay; $datarray['item_mentionsme'] = $item_mentionsme; $datarray['item_nocomment'] = $item_nocomment; $datarray['item_obscured'] = $item_obscured; $datarray['item_verified'] = $item_verified; $datarray['item_retained'] = $item_retained; $datarray['item_rss'] = $item_rss; $datarray['item_deleted'] = $item_deleted; $datarray['item_hidden'] = $item_hidden; $datarray['item_unpublished'] = $item_unpublished; $datarray['item_delayed'] = $item_delayed; $datarray['item_pending_remove'] = $item_pending_remove; $datarray['item_blocked'] = $item_blocked; $datarray['layout_mid'] = $layout_mid; $datarray['public_policy'] = $public_policy; $datarray['comment_policy'] = map_scope($channel['channel_w_comment']); $datarray['term'] = $post_tags; $datarray['plink'] = $plink; $datarray['route'] = $route; // preview mode - prepare the body for display and send it via json if ($preview) { require_once 'include/conversation.php'; $datarray['owner'] = $owner_xchan; $datarray['author'] = $observer; $datarray['attach'] = json_encode($datarray['attach']); $o = conversation($a, array($datarray), 'search', false, 'preview'); // logger('preview: ' . $o, LOGGER_DEBUG); echo json_encode(array('preview' => $o)); killme(); } if ($orig_post) { $datarray['edit'] = true; } call_hooks('post_local', $datarray); if (x($datarray, 'cancel')) { logger('mod_item: post cancelled by plugin.'); if ($return_path) { goaway($a->get_baseurl() . "/" . $return_path); } $json = array('cancel' => 1); if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) { $json['reload'] = $a->get_baseurl() . '/' . $_REQUEST['jsreload']; } echo json_encode($json); killme(); } if (mb_strlen($datarray['title']) > 255) { $datarray['title'] = mb_substr($datarray['title'], 0, 255); } if (array_key_exists('item_private', $datarray) && $datarray['item_private']) { $datarray['body'] = trim(z_input_filter($datarray['uid'], $datarray['body'], $datarray['mimetype'])); if ($uid) { if ($channel['channel_hash'] === $datarray['author_xchan']) { $datarray['sig'] = base64url_encode(rsa_sign($datarray['body'], $channel['channel_prvkey'])); $datarray['item_verified'] = 1; } } } if ($orig_post) { $datarray['id'] = $post_id; item_store_update($datarray, $execflag); update_remote_id($channel, $post_id, $webpage, $pagetitle, $namespace, $remote_id, $mid); if (!$parent) { $r = q("select * from item where id = %d", intval($post_id)); if ($r) { xchan_query($r); $sync_item = fetch_post_tags($r); $rid = q("select * from item_id where iid = %d", intval($post_id)); build_sync_packet($uid, array('item' => array(encode_item($sync_item[0], true)), 'item_id' => $rid)); } } if (!$nopush) { proc_run('php', "include/notifier.php", 'edit_post', $post_id); } if (x($_REQUEST, 'return') && strlen($return_path)) { logger('return: ' . $return_path); goaway($a->get_baseurl() . "/" . $return_path); } killme(); } else { $post_id = 0; } $post = item_store($datarray, $execflag); $post_id = $post['item_id']; if ($post_id) { logger('mod_item: saved item ' . $post_id); if ($parent) { // only send comment notification if this is a wall-to-wall comment, // otherwise it will happen during delivery if ($datarray['owner_xchan'] != $datarray['author_xchan'] && intval($parent_item['item_wall'])) { notification(array('type' => NOTIFY_COMMENT, 'from_xchan' => $datarray['author_xchan'], 'to_xchan' => $datarray['owner_xchan'], 'item' => $datarray, 'link' => $a->get_baseurl() . '/display/' . $datarray['mid'], 'verb' => ACTIVITY_POST, 'otype' => 'item', 'parent' => $parent, 'parent_mid' => $parent_item['mid'])); } } else { $parent = $post_id; if ($datarray['owner_xchan'] != $datarray['author_xchan']) { notification(array('type' => NOTIFY_WALL, 'from_xchan' => $datarray['author_xchan'], 'to_xchan' => $datarray['owner_xchan'], 'item' => $datarray, 'link' => $a->get_baseurl() . '/display/' . $datarray['mid'], 'verb' => ACTIVITY_POST, 'otype' => 'item')); } if ($uid && $uid == $profile_uid && is_item_normal($datarray)) { q("update channel set channel_lastpost = '%s' where channel_id = %d", dbesc(datetime_convert()), intval($uid)); } } // photo comments turn the corresponding item visible to the profile wall // This way we don't see every picture in your new photo album posted to your wall at once. // They will show up as people comment on them. if (intval($parent_item['item_hidden'])) { $r = q("UPDATE item SET item_hidden = 0 WHERE id = %d", intval($parent_item['id'])); } } else { logger('mod_item: unable to retrieve post that was just stored.'); notice(t('System error. Post not saved.') . EOL); goaway($a->get_baseurl() . "/" . $return_path); // NOTREACHED } update_remote_id($channel, $post_id, $webpage, $pagetitle, $namespace, $remote_id, $mid); if ($parent && $parent != $post_id) { // Store the comment signature information in case we need to relay to Diaspora $ditem = $datarray; $ditem['author'] = $observer; store_diaspora_comment_sig($ditem, $channel, $parent_item, $post_id, $walltowall_comment ? 1 : 0); } else { $r = q("select * from item where id = %d", intval($post_id)); if ($r) { xchan_query($r); $sync_item = fetch_post_tags($r); $rid = q("select * from item_id where iid = %d", intval($post_id)); build_sync_packet($uid, array('item' => array(encode_item($sync_item[0], true)), 'item_id' => $rid)); } } $datarray['id'] = $post_id; $datarray['llink'] = $a->get_baseurl() . '/display/' . $channel['channel_address'] . '/' . $post_id; call_hooks('post_local_end', $datarray); if (!$nopush) { proc_run('php', 'include/notifier.php', $notify_type, $post_id); } logger('post_complete'); // figure out how to return, depending on from whence we came if ($api_source) { return $post; } if ($return_path) { goaway($a->get_baseurl() . "/" . $return_path); } $json = array('success' => 1); if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) { $json['reload'] = $a->get_baseurl() . '/' . $_REQUEST['jsreload']; } logger('post_json: ' . print_r($json, true), LOGGER_DEBUG); echo json_encode($json); killme(); // NOTREACHED }
/** * @brief * * @param array $channel * @param array $observer * @param array $args * @return array */ function photo_upload($channel, $observer, $args) { $a = get_app(); $ret = array('success' => false); $channel_id = $channel['channel_id']; $account_id = $channel['channel_account_id']; if (!perm_is_allowed($channel_id, $observer['xchan_hash'], 'write_storage')) { $ret['message'] = t('Permission denied.'); return $ret; } // call_hooks('photo_upload_begin', $args); /* * Determine the album to use */ $album = $args['album']; if (intval($args['visible']) || $args['visible'] === 'true') { $visible = 1; } else { $visible = 0; } // Set to default channel permissions. If the parent directory (album) has permissions set, // use those instead. If we have specific permissions supplied, they take precedence over // all other settings. 'allow_cid' being passed from an external source takes priority over channel settings. // ...messy... needs re-factoring once the photos/files integration stabilises $acl = new AccessList($channel); if (array_key_exists('directory', $args) && $args['directory']) { $acl->set($args['directory']); } if (array_key_exists('allow_cid', $args)) { $acl->set($args); } if (array_key_exists('group_allow', $args) || array_key_exists('contact_allow', $args) || array_key_exists('group_deny', $args) || array_key_exists('contact_deny', $args)) { $acl->set_from_array($args); } $ac = $acl->get(); $os_storage = 0; if ($args['os_path'] && $args['getimagesize']) { $imagedata = @file_get_contents($args['os_path']); $filename = $args['filename']; $filesize = strlen($imagedata); // this is going to be deleted if it exists $src = '/tmp/deletemenow'; $type = $args['getimagesize']['mime']; $os_storage = 1; } elseif ($args['data']) { // allow an import from a binary string representing the image. // This bypasses the upload step and max size limit checking $imagedata = $args['data']; $filename = $args['filename']; $filesize = strlen($imagedata); // this is going to be deleted if it exists $src = '/tmp/deletemenow'; $type = $args['type']; } else { $f = array('src' => '', 'filename' => '', 'filesize' => 0, 'type' => ''); // call_hooks('photo_upload_file',$f); if (x($f, 'src') && x($f, 'filesize')) { $src = $f['src']; $filename = $f['filename']; $filesize = $f['filesize']; $type = $f['type']; } else { $src = $_FILES['userfile']['tmp_name']; $filename = basename($_FILES['userfile']['name']); $filesize = intval($_FILES['userfile']['size']); $type = $_FILES['userfile']['type']; } if (!$type) { $type = guess_image_type($filename); } logger('photo_upload: received file: ' . $filename . ' as ' . $src . ' (' . $type . ') ' . $filesize . ' bytes', LOGGER_DEBUG); $maximagesize = get_config('system', 'maximagesize'); if ($maximagesize && $filesize > $maximagesize) { $ret['message'] = sprintf(t('Image exceeds website size limit of %lu bytes'), $maximagesize); @unlink($src); call_hooks('photo_upload_end', $ret); return $ret; } if (!$filesize) { $ret['message'] = t('Image file is empty.'); @unlink($src); call_hooks('photo_post_end', $ret); return $ret; } logger('photo_upload: loading the contents of ' . $src, LOGGER_DEBUG); $imagedata = @file_get_contents($src); } $r = q("select sum(size) as total from photo where aid = %d and scale = 0 ", intval($account_id)); $limit = service_class_fetch($channel_id, 'photo_upload_limit'); if ($r && $limit !== false && $r[0]['total'] + strlen($imagedata) > $limit) { $ret['message'] = upgrade_message(); @unlink($src); call_hooks('photo_post_end', $ret); return $ret; } $ph = photo_factory($imagedata, $type); if (!$ph->is_valid()) { $ret['message'] = t('Unable to process image'); logger('photo_upload: unable to process image'); @unlink($src); call_hooks('photo_upload_end', $ret); return $ret; } $exif = $ph->orient($args['os_path'] ? $args['os_path'] : $src); @unlink($src); $max_length = get_config('system', 'max_image_length'); if (!$max_length) { $max_length = MAX_IMAGE_LENGTH; } if ($max_length > 0) { $ph->scaleImage($max_length); } $width = $ph->getWidth(); $height = $ph->getHeight(); $smallest = 0; $photo_hash = $args['resource_id'] ? $args['resource_id'] : photo_new_resource(); $visitor = ''; if ($channel['channel_hash'] !== $observer['xchan_hash']) { $visitor = $observer['xchan_hash']; } $errors = false; $p = array('aid' => $account_id, 'uid' => $channel_id, 'xchan' => $visitor, 'resource_id' => $photo_hash, 'filename' => $filename, 'album' => $album, 'scale' => 0, 'photo_usage' => PHOTO_NORMAL, 'allow_cid' => $ac['allow_cid'], 'allow_gid' => $ac['allow_gid'], 'deny_cid' => $ac['deny_cid'], 'deny_gid' => $ac['deny_gid'], 'os_storage' => $os_storage, 'os_path' => $args['os_path']); if ($args['created']) { $p['created'] = $args['created']; } if ($args['edited']) { $p['edited'] = $args['edited']; } if ($args['title']) { $p['title'] = $args['title']; } if ($args['description']) { $p['description'] = $args['description']; } $link = array(); $r0 = $ph->save($p); $link[0] = array('rel' => 'alternate', 'type' => 'text/html', 'href' => $url = rawurlencode(z_root() . '/photo/' . $photo_hash . '-0.' . $ph->getExt()), 'width' => $ph->getWidth(), 'height' => $ph->getHeight()); if (!$r0) { $errors = true; } unset($p['os_storage']); unset($p['os_path']); if (($width > 1024 || $height > 1024) && !$errors) { $ph->scaleImage(1024); } $p['scale'] = 1; $r1 = $ph->save($p); $link[1] = array('rel' => 'alternate', 'type' => 'text/html', 'href' => $url = rawurlencode(z_root() . '/photo/' . $photo_hash . '-1.' . $ph->getExt()), 'width' => $ph->getWidth(), 'height' => $ph->getHeight()); if (!$r1) { $errors = true; } if (($width > 640 || $height > 640) && !$errors) { $ph->scaleImage(640); } $p['scale'] = 2; $r2 = $ph->save($p); $link[2] = array('rel' => 'alternate', 'type' => 'text/html', 'href' => $url = rawurlencode(z_root() . '/photo/' . $photo_hash . '-2.' . $ph->getExt()), 'width' => $ph->getWidth(), 'height' => $ph->getHeight()); if (!$r2) { $errors = true; } if (($width > 320 || $height > 320) && !$errors) { $ph->scaleImage(320); } $p['scale'] = 3; $r3 = $ph->save($p); $link[3] = array('rel' => 'alternate', 'type' => 'text/html', 'href' => $url = rawurlencode(z_root() . '/photo/' . $photo_hash . '-3.' . $ph->getExt()), 'width' => $ph->getWidth(), 'height' => $ph->getHeight()); if (!$r3) { $errors = true; } if ($errors) { q("delete from photo where resource_id = '%s' and uid = %d", dbesc($photo_hash), intval($channel_id)); $ret['message'] = t('Photo storage failed.'); logger('photo_upload: photo store failed.'); call_hooks('photo_upload_end', $ret); return $ret; } $item_hidden = $visible ? 0 : 1; $lat = $lon = null; if ($exif && $exif['GPS']) { if (feature_enabled($channel_id, 'photo_location')) { $lat = getGps($exif['GPS']['GPSLatitude'], $exif['GPS']['GPSLatitudeRef']); $lon = getGps($exif['GPS']['GPSLongitude'], $exif['GPS']['GPSLongitudeRef']); } } $title = $args['description'] ? $args['description'] : $args['filename']; $large_photos = feature_enabled($channel['channel_id'], 'large_photos'); linkify_tags($a, $args['body'], $channel_id); if ($large_photos) { $scale = 1; $width = $link[1]['width']; $height = $link[1]['height']; $tag = $r1 ? '[zmg=' . $width . 'x' . $height . ']' : '[zmg]'; } else { $scale = 2; $width = $link[2]['width']; $height = $link[2]['height']; $tag = $r2 ? '[zmg=' . $width . 'x' . $height . ']' : '[zmg]'; } $body = '[zrl=' . z_root() . '/photos/' . $channel['channel_address'] . '/image/' . $photo_hash . ']' . $tag . z_root() . "/photo/{$photo_hash}-{$scale}." . $ph->getExt() . '[/zmg]' . '[/zrl]'; // Create item object $object = array('type' => ACTIVITY_OBJ_PHOTO, 'title' => $title, 'id' => rawurlencode(z_root() . '/photos/' . $channel['channel_address'] . '/image/' . $photo_hash), 'link' => $link, 'bbcode' => $body); // Create item container if ($args['item']) { foreach ($args['item'] as $i) { $item = get_item_elements($i); $force = false; if ($item['mid'] === $item['parent_mid']) { $item['body'] = $object ? $args['body'] : $body . "\r\n" . $args['body']; $item['obj_type'] = $object ? ACTIVITY_OBJ_PHOTO : ''; $item['object'] = $object ? json_encode($object) : ''; if ($item['author_xchan'] === $channel['channel_hash']) { $item['sig'] = base64url_encode(rsa_sign($item['body'], $channel['channel_prvkey'])); $item['item_verified'] = 1; } else { $item['sig'] = ''; } $force = true; } $r = q("select id, edited from item where mid = '%s' and uid = %d limit 1", dbesc($item['mid']), intval($channel['channel_id'])); if ($r) { if ($item['edited'] > $r[0]['edited'] || $force) { $item['id'] = $r[0]['id']; $item['uid'] = $channel['channel_id']; item_store_update($item); continue; } } else { $item['aid'] = $channel['channel_account_id']; $item['uid'] = $channel['channel_id']; $item_result = item_store($item); } } } else { $mid = item_message_id(); $arr = array(); if ($lat && $lon) { $arr['coord'] = $lat . ' ' . $lon; } $arr['aid'] = $account_id; $arr['uid'] = $channel_id; $arr['mid'] = $mid; $arr['parent_mid'] = $mid; $arr['item_hidden'] = $item_hidden; $arr['resource_type'] = 'photo'; $arr['resource_id'] = $photo_hash; $arr['owner_xchan'] = $channel['channel_hash']; $arr['author_xchan'] = $observer['xchan_hash']; $arr['title'] = $title; $arr['allow_cid'] = $ac['allow_cid']; $arr['allow_gid'] = $ac['allow_gid']; $arr['deny_cid'] = $ac['deny_cid']; $arr['deny_gid'] = $ac['deny_gid']; $arr['verb'] = ACTIVITY_POST; $arr['obj_type'] = $object ? ACTIVITY_OBJ_PHOTO : ''; $arr['object'] = $object ? json_encode($object) : ''; $arr['item_wall'] = 1; $arr['item_origin'] = 1; $arr['item_thread_top'] = 1; $arr['item_private'] = intval($acl->is_private()); $arr['plink'] = z_root() . '/channel/' . $channel['channel_address'] . '/?f=&mid=' . $arr['mid']; $arr['body'] = $object ? $args['body'] : $body . "\r\n" . $args['body']; // this one is tricky because the item and the photo have the same permissions, those of the photo. // Use the channel read_stream permissions to get the correct public_policy for the item and recalculate the // private flag accordingly. This may cause subtle bugs due to custom permissions roles. We want to use // public policy when federating items to other sites, but should probably ignore them when accessing the item // in the photos pages - using the photos permissions instead. We need the public policy to keep the photo // linked item from leaking into the feed when somebody has a channel with read_stream restrictions. $arr['public_policy'] = map_scope($channel['channel_r_stream'], true); if ($arr['public_policy']) { $arr['item_private'] = 1; } $result = item_store($arr); $item_id = $result['item_id']; if ($visible) { proc_run('php', "include/notifier.php", 'wall-new', $item_id); } } $ret['success'] = true; $ret['item'] = $arr; $ret['body'] = $body; $ret['resource_id'] = $photo_hash; $ret['photoitem_id'] = $item_id; call_hooks('photo_upload_end', $ret); return $ret; }
/** * remote post * * https://yoursite/rpost?f=&title=&body=&remote_return= * * This can be called via either GET or POST, use POST for long body content as suhosin often limits GET parameter length * * f= placeholder, often required * title= Title of post * body= Body of post * url= URL which will be parsed and the results appended to the body * source= Source application * remote_return= absolute URL to return after posting is finished * type= choices are 'html' or 'bbcode', default is 'bbcode' * */ function rpost_content(&$a) { $o = ''; if (!local_channel()) { if (remote_channel()) { // redirect to your own site. // We can only do this with a GET request so you'll need to keep the text short or risk getting truncated // by the wretched beast called 'suhosin'. All the browsers now allow long GET requests, but suhosin // blocks them. $url = get_rpost_path($a->get_observer()); // make sure we're not looping to our own hub if ($url && !stristr($url, $a->get_hostname())) { foreach ($_REQUEST as $key => $arg) { $url .= '&' . $key . '=' . $arg; } goaway($url); } } // The login procedure is going to bugger our $_REQUEST variables // so save them in the session. if (array_key_exists('body', $_REQUEST)) { $_SESSION['rpost'] = $_REQUEST; } return login(); } // If we have saved rpost session variables, but nothing in the current $_REQUEST, recover the saved variables if (!array_key_exists('body', $_REQUEST) && array_key_exists('rpost', $_SESSION)) { $_REQUEST = $_SESSION['rpost']; unset($_SESSION['rpost']); } if (array_key_exists('channel', $_REQUEST)) { $r = q("select channel_id from channel where channel_account_id = %d and channel_address = '%s' limit 1", intval(get_account_id()), dbesc($_REQUEST['channel'])); if ($r) { require_once 'include/security.php'; $change = change_channel($r[0]['channel_id']); } } if ($_REQUEST['remote_return']) { $_SESSION['remote_return'] = $_REQUEST['remote_return']; } if (argc() > 1 && argv(1) === 'return') { if ($_SESSION['remote_return']) { goaway($_SESSION['remote_return']); } goaway(z_root() . '/network'); } $plaintext = true; // if(feature_enabled(local_channel(),'richtext')) // $plaintext = false; if (array_key_exists('type', $_REQUEST) && $_REQUEST['type'] === 'html') { require_once 'include/html2bbcode.php'; $_REQUEST['body'] = html2bbcode($_REQUEST['body']); } $channel = $a->get_channel(); $acl = new AccessList($channel); $channel_acl = $acl->get(); if ($_REQUEST['url']) { $x = z_fetch_url(z_root() . '/linkinfo?f=&url=' . urlencode($_REQUEST['url'])); if ($x['success']) { $_REQUEST['body'] = $_REQUEST['body'] . $x['body']; } } $x = array('is_owner' => true, 'allow_location' => intval(get_pconfig($channel['channel_id'], 'system', 'use_browser_location')) ? '1' : '', 'default_location' => $channel['channel_location'], 'nickname' => $channel['channel_address'], 'lockstate' => $acl->is_private() ? 'lock' : 'unlock', 'acl' => populate_acl($channel_acl), 'bang' => '', 'visitor' => true, 'profile_uid' => local_channel(), 'title' => $_REQUEST['title'], 'body' => $_REQUEST['body'], 'attachment' => $_REQUEST['attachment'], 'source' => x($_REQUEST, 'source') ? strip_tags($_REQUEST['source']) : '', 'return_path' => 'rpost/return'); $editor = status_editor($a, $x); $o .= replace_macros(get_markup_template('edpost_head.tpl'), array('$title' => t('Edit post'), '$editor' => $editor)); return $o; }
function thing_content(&$a) { // @FIXME one problem with things is we can't share them unless we provide the channel in the url // so we can definitively lookup the owner. if (argc() == 2) { $r = q("select obj_channel from obj where obj_type = %d and obj_obj = '%s' limit 1", intval(TERM_OBJ_THING), dbesc(argv(1))); if ($r) { $sql_extra = permissions_sql($r[0]['obj_channel']); } $r = q("select * from obj where obj_type = %d and obj_obj = '%s' {$sql_extra} limit 1", intval(TERM_OBJ_THING), dbesc(argv(1))); if ($r) { return replace_macros(get_markup_template('show_thing.tpl'), array('$header' => t('Show Thing'), '$edit' => t('Edit'), '$delete' => t('Delete'), '$canedit' => local_channel() && local_channel() == $r[0]['obj_channel'] ? true : false, '$thing' => $r[0])); } else { notice(t('item not found.') . EOL); return; } } $channel = $a->get_channel(); if (!(local_channel() && $channel)) { notice(t('Permission denied.') . EOL); return; } $acl = new AccessList($channel); $channel_acl = $acl->get(); $lockstate = $acl->is_private() ? 'lock' : 'unlock'; $thing_hash = ''; if (argc() == 3 && argv(1) === 'edit') { $thing_hash = argv(2); $r = q("select * from obj where obj_type = %d and obj_obj = '%s' limit 1", intval(TERM_OBJ_THING), dbesc($thing_hash)); if (!$r || $r[0]['obj_channel'] != local_channel()) { notice(t('Permission denied.') . EOL); return ''; } $o .= replace_macros(get_markup_template('thing_edit.tpl'), array('$thing_hdr' => t('Edit Thing'), '$multiprof' => feature_enabled(local_channel(), 'multi_profiles'), '$profile_lbl' => t('Select a profile'), '$profile_select' => contact_profile_assign($r[0]['obj_page']), '$verb_lbl' => $channel['channel_name'], '$verb_select' => obj_verb_selector($r[0]['obj_verb']), '$activity' => array('activity', t('Post an activity'), true, t('Only sends to viewers of the applicable profile')), '$thing_hash' => $thing_hash, '$thing_lbl' => t('Name of thing e.g. something'), '$thething' => $r[0]['obj_term'], '$url_lbl' => t('URL of thing (optional)'), '$theurl' => $r[0]['obj_url'], '$img_lbl' => t('URL for photo of thing (optional)'), '$imgurl' => $r[0]['obj_imgurl'], '$permissions' => t('Permissions'), '$aclselect' => populate_acl($channel_acl, false), '$lockstate' => $lockstate, '$submit' => t('Submit'))); return $o; } if (argc() == 3 && argv(1) === 'drop') { $thing_hash = argv(2); $r = q("select * from obj where obj_type = %d and obj_obj = '%s' limit 1", intval(TERM_OBJ_THING), dbesc($thing_hash)); if (!$r || $r[0]['obj_channel'] != local_channel()) { notice(t('Permission denied.') . EOL); return ''; } $x = q("delete from obj where obj_obj = '%s' and obj_type = %d and obj_channel = %d", dbesc($thing_hash), intval(TERM_OBJ_THING), intval(local_channel())); $r[0]['obj_deleted'] = 1; build_sync_packet(0, array('obj' => $r)); return $o; } $o .= replace_macros(get_markup_template('thing_input.tpl'), array('$thing_hdr' => t('Add Thing to your Profile'), '$multiprof' => feature_enabled(local_channel(), 'multi_profiles'), '$profile_lbl' => t('Select a profile'), '$profile_select' => contact_profile_assign(''), '$verb_lbl' => $channel['channel_name'], '$activity' => array('activity', t('Post an activity'), array_key_exists('activity', $_REQUEST) ? $_REQUEST['activity'] : true, t('Only sends to viewers of the applicable profile')), '$verb_select' => obj_verb_selector(), '$thing_lbl' => t('Name of thing e.g. something'), '$url_lbl' => t('URL of thing (optional)'), '$img_lbl' => t('URL for photo of thing (optional)'), '$permissions' => t('Permissions'), '$aclselect' => populate_acl($channel_acl, false), '$lockstate' => $lockstate, '$submit' => t('Submit'))); return $o; }
/** * @brief * * @param array $channel * @param array $observer * @param array $args * @return array */ function photo_upload($channel, $observer, $args) { $ret = array('success' => false); $channel_id = $channel['channel_id']; $account_id = $channel['channel_account_id']; if (!perm_is_allowed($channel_id, $observer['xchan_hash'], 'write_storage')) { $ret['message'] = t('Permission denied.'); return $ret; } // call_hooks('photo_upload_begin', $args); /* * Determine the album to use */ $album = $args['album']; if (intval($args['visible']) || $args['visible'] === 'true') { $visible = 1; } else { $visible = 0; } // Set to default channel permissions. If the parent directory (album) has permissions set, // use those instead. If we have specific permissions supplied, they take precedence over // all other settings. 'allow_cid' being passed from an external source takes priority over channel settings. // ...messy... needs re-factoring once the photos/files integration stabilises $acl = new AccessList($channel); if (array_key_exists('directory', $args) && $args['directory']) { $acl->set($args['directory']); } if (array_key_exists('allow_cid', $args)) { $acl->set($args); } if (array_key_exists('group_allow', $args) || array_key_exists('contact_allow', $args) || array_key_exists('group_deny', $args) || array_key_exists('contact_deny', $args)) { $acl->set_from_array($args); } $ac = $acl->get(); $os_storage = 0; if ($args['os_path'] && $args['getimagesize']) { $imagedata = @file_get_contents($args['os_path']); $filename = $args['filename']; $filesize = strlen($imagedata); // this is going to be deleted if it exists $src = '/tmp/deletemenow'; $type = $args['getimagesize']['mime']; $os_storage = 1; } elseif ($args['data']) { // allow an import from a binary string representing the image. // This bypasses the upload step and max size limit checking $imagedata = $args['data']; $filename = $args['filename']; $filesize = strlen($imagedata); // this is going to be deleted if it exists $src = '/tmp/deletemenow'; $type = $args['type']; } else { $f = array('src' => '', 'filename' => '', 'filesize' => 0, 'type' => ''); // call_hooks('photo_upload_file',$f); if (x($f, 'src') && x($f, 'filesize')) { $src = $f['src']; $filename = $f['filename']; $filesize = $f['filesize']; $type = $f['type']; } else { $src = $_FILES['userfile']['tmp_name']; $filename = basename($_FILES['userfile']['name']); $filesize = intval($_FILES['userfile']['size']); $type = $_FILES['userfile']['type']; } if (!$type) { $type = guess_image_type($filename); } logger('photo_upload: received file: ' . $filename . ' as ' . $src . ' (' . $type . ') ' . $filesize . ' bytes', LOGGER_DEBUG); $maximagesize = get_config('system', 'maximagesize'); if ($maximagesize && $filesize > $maximagesize) { $ret['message'] = sprintf(t('Image exceeds website size limit of %lu bytes'), $maximagesize); @unlink($src); call_hooks('photo_upload_end', $ret); return $ret; } if (!$filesize) { $ret['message'] = t('Image file is empty.'); @unlink($src); call_hooks('photo_post_end', $ret); return $ret; } logger('photo_upload: loading the contents of ' . $src, LOGGER_DEBUG); $imagedata = @file_get_contents($src); } $r = q("select sum(size) as total from photo where aid = %d and scale = 0 ", intval($account_id)); $limit = service_class_fetch($channel_id, 'photo_upload_limit'); if ($r && $limit !== false && $r[0]['total'] + strlen($imagedata) > $limit) { $ret['message'] = upgrade_message(); @unlink($src); call_hooks('photo_post_end', $ret); return $ret; } $ph = photo_factory($imagedata, $type); if (!$ph->is_valid()) { $ret['message'] = t('Unable to process image'); logger('photo_upload: unable to process image'); @unlink($src); call_hooks('photo_upload_end', $ret); return $ret; } $exif = $ph->orient($args['os_path'] ? $args['os_path'] : $src); @unlink($src); $max_length = get_config('system', 'max_image_length'); if (!$max_length) { $max_length = MAX_IMAGE_LENGTH; } if ($max_length > 0) { $ph->scaleImage($max_length); } $width = $ph->getWidth(); $height = $ph->getHeight(); $smallest = 0; $photo_hash = $args['resource_id'] ? $args['resource_id'] : photo_new_resource(); $visitor = ''; if ($channel['channel_hash'] !== $observer['xchan_hash']) { $visitor = $observer['xchan_hash']; } $errors = false; $p = array('aid' => $account_id, 'uid' => $channel_id, 'xchan' => $visitor, 'resource_id' => $photo_hash, 'filename' => $filename, 'album' => $album, 'scale' => 0, 'photo_usage' => PHOTO_NORMAL, 'allow_cid' => $ac['allow_cid'], 'allow_gid' => $ac['allow_gid'], 'deny_cid' => $ac['deny_cid'], 'deny_gid' => $ac['deny_gid'], 'os_storage' => $os_storage, 'os_path' => $args['os_path']); if ($args['created']) { $p['created'] = $args['created']; } if ($args['edited']) { $p['edited'] = $args['edited']; } if ($args['title']) { $p['title'] = $args['title']; } if ($args['description']) { $p['description'] = $args['description']; } $r1 = $ph->save($p); if (!$r1) { $errors = true; } unset($p['os_storage']); unset($p['os_path']); if (($width > 640 || $height > 640) && !$errors) { $ph->scaleImage(640); $p['scale'] = 1; $r2 = $ph->save($p); $smallest = 1; if (!$r2) { $errors = true; } } if (($width > 320 || $height > 320) && !$errors) { $ph->scaleImage(320); $p['scale'] = 2; $r3 = $ph->save($p); $smallest = 2; if (!$r3) { $errors = true; } } if ($errors) { q("delete from photo where resource_id = '%s' and uid = %d", dbesc($photo_hash), intval($channel_id)); $ret['message'] = t('Photo storage failed.'); logger('photo_upload: photo store failed.'); call_hooks('photo_upload_end', $ret); return $ret; } // This will be the width and height of the smallest representation $width_x_height = $ph->getWidth() . 'x' . $ph->getHeight(); // Create item container $item_hidden = $visible ? 0 : 1; $lat = $lon = null; if ($exif && $exif['GPS']) { if (feature_enabled($channel_id, 'photo_location')) { $lat = getGps($exif['GPS']['GPSLatitude'], $exif['GPS']['GPSLatitudeRef']); $lon = getGps($exif['GPS']['GPSLongitude'], $exif['GPS']['GPSLongitudeRef']); } } if ($args['item']) { foreach ($args['item'] as $i) { $item = get_item_elements($i); $force = false; if ($item['mid'] === $item['parent_mid']) { $item['body'] = '[zrl=' . z_root() . '/photos/' . $channel['channel_address'] . '/image/' . $photo_hash . ']' . $tag . z_root() . "/photo/{$photo_hash}-{$smallest}." . $ph->getExt() . '[/zmg]' . '[/zrl]'; if ($item['author_xchan'] === $channel['channel_hash']) { $item['sig'] = base64url_encode(rsa_sign($item['body'], $channel['channel_prvkey'])); $item['item_verified'] = 1; } else { $item['sig'] = ''; } $force = true; } $r = q("select id, edited from item where mid = '%s' and uid = %d limit 1", dbesc($item['mid']), intval($channel['channel_id'])); if ($r) { if ($item['edited'] > $r[0]['edited'] || $force) { $item['id'] = $r[0]['id']; $item['uid'] = $channel['channel_id']; item_store_update($item); continue; } } else { $item['aid'] = $channel['channel_account_id']; $item['uid'] = $channel['channel_id']; $item_result = item_store($item); } } } else { $title = ''; $mid = item_message_id(); $arr = array(); if ($lat && $lon) { $arr['coord'] = $lat . ' ' . $lon; } $arr['aid'] = $account_id; $arr['uid'] = $channel_id; $arr['mid'] = $mid; $arr['parent_mid'] = $mid; $arr['item_hidden'] = $item_hidden; $arr['resource_type'] = 'photo'; $arr['resource_id'] = $photo_hash; $arr['owner_xchan'] = $channel['channel_hash']; $arr['author_xchan'] = $observer['xchan_hash']; $arr['title'] = $title; $arr['allow_cid'] = $ac['allow_cid']; $arr['allow_gid'] = $ac['allow_gid']; $arr['deny_cid'] = $ac['deny_cid']; $arr['deny_gid'] = $ac['deny_gid']; $arr['verb'] = ACTIVITY_POST; $arr['item_wall'] = 1; $arr['item_origin'] = 1; $arr['item_thread_top'] = 1; $arr['item_private'] = intval($acl->is_private()); $arr['plink'] = z_root() . '/channel/' . $channel['channel_address'] . '/?f=&mid=' . $arr['mid']; // We should also put a width_x_height on large photos. Left as an exercise for // devs looking for simple stuff to fix. $larger = feature_enabled($channel['channel_id'], 'large_photos'); if ($larger) { $tag = '[zmg]'; if ($r2) { $smallest = 1; } else { $smallest = 0; } } else { if ($width_x_height) { $tag = '[zmg=' . $width_x_height . ']'; } else { $tag = '[zmg]'; } } $arr['body'] = '[zrl=' . z_root() . '/photos/' . $channel['channel_address'] . '/image/' . $photo_hash . ']' . $tag . z_root() . "/photo/{$photo_hash}-{$smallest}." . $ph->getExt() . '[/zmg]' . '[/zrl]'; $result = item_store($arr); $item_id = $result['item_id']; if ($visible) { proc_run('php', "include/notifier.php", 'wall-new', $item_id); } } $ret['success'] = true; $ret['item'] = $arr; $ret['body'] = $arr['body']; $ret['resource_id'] = $photo_hash; $ret['photoitem_id'] = $item_id; call_hooks('photo_upload_end', $ret); return $ret; }