Using php for an automatic updating sitemap - php

How would I get this to index pages that have no ending at all? My website is created of pages similar to this http://www.example.com/example/post-id-the-post-title-would-go-here and because it has no ending it does not display within the sitemap.
Update
Config.php
define( 'SITEMAP_DIR', './' );
define( 'SITEMAP_DIR_URL', 'http://www.example.com' );
define( 'RECURSIVE', true );
$filetypes = array( 'php', 'html', 'pdf' );
// The replace array, this works as file => replacement, so 'index.php' => '', would make the index.php be listed as just /
$replace = array( 'index.php' => '' );
$xsl = 'xml.xsl';
$chfreq = 'daily';
$prio = 1;
$ignore = array( 'config.php' );
I am not interested in rewriting the urls because I have already done this from the http://www.exaple.com/index.php?a=track&id=17 when I first started.
Sitemap.php
require './config.php';
// Get the keys so we can check quickly
$replace_files = array_keys( $replace );
// Sent the correct header so browsers display properly, with or without XSL.
header( 'Content-Type: application/xml' );
echo '<?xml version="1.0" encoding="utf-8"?>' . "\n";
$ignore = array_merge( $ignore, array( '.', '..', 'config.php', 'xml-sitemap.php' ) );
if ( isset( $xsl ) && !empty( $xsl ) )
echo '<?xml-stylesheet type="text/xsl" href="' . SITEMAP_DIR_URL . $xsl . '"?>' . "\n";
function parse_dir( $dir, $url ) {
global $ignore, $filetypes, $replace, $chfreq, $prio;
$handle = opendir( $dir );
while ( false !== ( $file = readdir( $handle ) ) ) {
// Check if this file needs to be ignored, if so, skip it.
if ( in_array( utf8_encode( $file ), $ignore ) )
continue;
if ( is_dir( $file ) ) {
if ( defined( 'RECURSIVE' ) && RECURSIVE )
parse_dir( $file, $url . $file . '/' );
}
// Check whether the file has on of the extensions allowed for this XML sitemap
$fileinfo = pathinfo( $dir . $file );
if ( in_array( $fileinfo['extension'], $filetypes ) ) {
// Create a W3C valid date for use in the XML sitemap based on the file modification time
if (filemtime( $dir .'/'. $file )==FALSE) {
$mod = date( 'c', filectime( $dir . $file ) );
} else {
$mod = date( 'c', filemtime( $dir . $file ) );
}
// Replace the file with it's replacement from the settings, if needed.
if ( in_array( $file, $replace ) )
$file = $replace[$file];
// Start creating the output
?>
<url>
<loc><?php echo $url . rawurlencode( $file ); ?></loc>
<lastmod><?php echo $mod; ?></lastmod>
<changefreq><?php echo $chfreq; ?></changefreq>
<priority><?php echo $prio; ?></priority>
</url><?php
}
}
closedir( $handle );
}
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"><?php
parse_dir( SITEMAP_DIR, SITEMAP_DIR_URL );
?>
</urlset>

Related

PHP zip file downloads locally but not in production

I am working on some files to download in a zip. Works fine locally but not in any environment (staging or production). Using WP VIP also, not sure if that helps. I'm a little new to VIP. Really racked by brains here and can't seem to figure out the issue.
I've read the resources on PHP zip creation. I do get the "Unable to add zip file.', 500 );" error producing.
Code below:
$context = [];
$post = theme()->twig()->create_post();
$tab_index = filter_input( INPUT_GET, 'tab-index', FILTER_SANITIZE_NUMBER_INT );
$content_calendar = $post->get_field('content_calendar');
if ( ! isset( $content_calendar[ $tab_index ] ) ) {
\wp_send_json_error( 'Invalid tab-index.', 400 );
exit;
}
$tab = $content_calendar[ $tab_index ];
// Create zip name;
$name = 'content-calendar-' . $tab_index;
$group_index = filter_input( INPUT_GET, 'group-index', FILTER_SANITIZE_NUMBER_INT );
if ( null !== $group_index ) {
if ( ! isset( $tab['groups'][ $group_index ] ) ) {
\wp_send_json_error( 'Invalid group-index.', 400 );
exit;
}
$groups = [ $tab['groups'][ $group_index ] ];
// Append group to name
$name .= '-' . $group_index;
} else {
$groups = $tab['groups'];
}
// Extract paths from resources with assets
$paths = [];
foreach ( $groups as $group ) {
foreach ( $group['resources'] as $resource ) {
if ( $resource['social_resource'] ) {
$asset_id = get_field( 'asset', $resource['social_resource'] );
if ( $asset_id ) {
$paths[] = get_attached_file( $asset_id, true );
}
}
}
}
// Remove invalid or duplicate URLs
$paths = array_unique( array_filter( $paths ) );
if ( empty( $paths ) ) {
\wp_send_json_error( 'No files to download.', 400 );
exit;
}
// Generate file names
$zipfile = wp_upload_dir()['basedir'] . '/' . $name . '.zip';
$zipname = $name . '-' . date('Y-m-d') . '.zip';
// Generate file
$zip = new ZipArchive;
if ( true !== $zip->open( $zipfile, ZipArchive::CREATE | ZipArchive::OVERWRITE ) ) {
\wp_send_json_error( 'Unable to create zip file.', 500 );
exit;
}
foreach ( $paths as $path ) {
if ( true !== $zip->addFile( $path, basename( $path ) ) ) {
$zip->close();
\wp_send_json_error( 'Unable to add file to zip.', 500 );
exit;
}
}
$zip->close();
// Send headers and stream file
header( 'Content-Type: application/zip' );
header( 'Content-disposition: attachment; filename=' . $zipname );
header( 'Content-Length: ' . filesize( $zipfile ) );
readfile( $zipfile );
exit;
Any help is appreciated.

Extend PHP regex to cover "srcset" and "style" attributes

I've created a WordPress plugin that turn all links into protocol-relative URLs (removing http: and https:) based off the tags and attributes that I list in the $tag and $attribute variables. This is part of the function. To save space, the rest of the code can be found here.
$content_type = NULL;
# Check for 'Content-Type' headers only
foreach ( headers_list() as $header ) {
if ( strpos( strtolower( $header ), 'content-type:' ) === 0 ) {
$pieces = explode( ':', strtolower( $header ) );
$content_type = trim( $pieces[1] );
break;
}
}
# If the content-type is 'NULL' or 'text/html', apply rewrite
if ( is_null( $content_type ) || substr( $content_type, 0, 9 ) === 'text/html' ) {
$tag = 'a|base|div|form|iframe|img|link|meta|script|svg';
$attribute = 'action|content|data-project-file|href|src|srcset|style';
# If 'Protocol Relative URL' option is checked, only apply change to internal links
if ( $this->option == 1 ) {
# Remove protocol from home URL
$website = preg_replace( '/https?:\/\//', '', home_url() );
# Remove protocol from internal links
$links = preg_replace( '/(<(' . $tag . ')([^>]*)(' . $attribute . ')=["\'])https?:\/\/' . $website . '/i', '$1//' . $website, $links );
}
# Else, remove protocols from all links
else {
$links = preg_replace( '/(<(' . $tag . ')([^>]*)(' . $attribute . ')=["\'])https?:\/\//i', '$1//', $links );
}
}
# Return protocol relative links
return $links;
This works as intended, but it doesn't work on these examples:
<!-- Within the 'style' attribute -->
<div class="some-class" style='background-color:rgba(255,255,255,0);background-image:url("http://placehold.it/300x200");background-position:center center;background-repeat:no-repeat'>
<!-- Within the 'srcset' attribute -->
<img src="http://placehold.it/600x300" srcset="http://placehold.it/500 500x, http://placehold.it/100 100w">
However, the code partially works for these examples.
<div class="some-class" style='background-color:rgba(255,255,255,0);background-image:url("http://placehold.it/300x200");background-position:center center;background-repeat:no-repeat'>
<img src="http://placehold.it/600x300" srcset="//placehold.it/500 500x, http://placehold.it/100 100w">
I've played around with adding additional values to the $tag and $attribute variables, but that didn't help. I'd assume I need to update the rest of my regex to cover these two additional tags? Or is there is a different way to approach it, such as DOMDocument?
I was able to simplify the code by doing the following:
$content_type = NULL;
# Check for 'Content-Type' headers only
foreach ( headers_list() as $header ) {
if ( strpos( strtolower( $header ), 'content-type:' ) === 0 ) {
$pieces = explode( ':', strtolower( $header ) );
$content_type = trim( $pieces[1] );
break;
}
}
# If the content-type is 'NULL' or 'text/html', apply rewrite
if ( is_null( $content_type ) || substr( $content_type, 0, 9 ) === 'text/html' ) {
# Remove protocol from home URL
$website = $_SERVER['HTTP_HOST'];
$links = str_replace( 'https?://' . $website, '//' . $website, $links );
$links = preg_replace( '|https?://(.*?)|', '//$1', $links );
}
# Return protocol relative links
return $links;

$_POST variable staying the same

I'm having trouble with this code and using different emails to view images in a directory (processed/$email) and the email changes per user's respective form entry, yet only shows the images from the most recent folder created regardless of the email given.
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="POST">
E-mail:
<input type="text" name="email" id="email2"><br>
<br>
<input type="submit" value="Retrieve" name="submit"><br><br>
</form>
and here's the PHP:
<?php
function scanDirectoryImages($directory, array $exts = array('jpeg', 'jpg', 'gif', 'png'))
{
if (substr($directory, -1) == '/') {
$directory = substr($directory, 0, -1);
}
$html = '';
if (
is_readable($directory)
&& (file_exists($directory) || is_dir($directory))
) {
$directoryList = opendir($directory);
while($file = readdir($directoryList)) {
if ($file != '.' && $file != '..') {
$path = $directory . '/' . $file;
if (is_readable($path)) {
if (is_dir($path)) {
return scanDirectoryImages($path, $exts);
}
if (
is_file($path)
&& in_array(end(explode('.', end(explode('/', $path)))), $exts)
) {
$html .= '<a href="' . $path . '"><img src="' . $path
. '" style="max-height:250px;max-width:250px" /> </a>';
}
}
}
}
closedir($directoryList);
}
return $html;
}
echo scanDirectoryImages(processed.$_POST['email2']);
?>
I've tried unsetting variables, etc. It doesn't work. When I go back to the form from any page, it's still only showing the most recently uploaded folder of images. The only thing that will make it show new images is if there is a new directory. I feel like I must be approaching this fundamentally wrong somehow and I'm new to PHP so some help would be hugely appreciated.
The original function has a recursive nature to it but doesn't utilise the existing suite of recursiveIterator classes - hopefully the below will be of use in that respect. When I tried your original function all I got it to return was a folder name and not a list of files / images.
function scanImageDirectory( $directory, $root, $exts=array('jpg','jpeg','png','gif'), $exclusions=array('bmp') ){
$html=array();
$dirItr = new RecursiveDirectoryIterator( $directory );
$filterItr = new DirFileFilter( $dirItr, $exclusions, $directory, 'all' );
$recItr = new RecursiveIteratorIterator( $filterItr, RecursiveIteratorIterator::SELF_FIRST );
foreach( $recItr as $filepath => $info ){
if( $info->isFile() && in_array( strtolower( pathinfo( $info, PATHINFO_EXTENSION ) ), $exts ) ) {
$filename=str_replace( array( realpath( $root ), chr(92) ), array( '', chr(47) ), realpath( $info ) );
$html[]="<a href='{$filename}' target='_blank'><img src='{$filename}' alt='{$info->getFilename()}' /></a>";
}
}
return implode( PHP_EOL,$html );
}
$dir=ROOT.'/images/css/icons/browsers';
$root='c:/wwwroot';
echo scanImageDirectory( $dir, $root );
Or, as example for your situation
$dir="processed/{$_POST['email']}";
$root=$_SERVER['DOCUMENT_ROOT'];
echo scanImageDirectory( $dir, $root );
I realise that the class DirFileFilter is one I wrote and not a native PHP class - this can only be described as an id-10-T error.. Apologies - here is that class.
class DirFileFilter extends RecursiveFilterIterator{
protected $exclude;
protected $root;
protected $mode;
public function __construct( $iterator, array $exclude, $root, $mode='all' ){
parent::__construct( $iterator );
$this->exclude = $exclude;
$this->root = $root;
$this->mode = $mode;
}
public function accept(){
$folpath=rtrim( str_replace( $this->root, '', $this->getPathname() ), '\\' );
$ext=strtolower( pathinfo( $this->getFilename(), PATHINFO_EXTENSION ) );
switch( $this->mode ){
case 'all':
return !( in_array( $this->getFilename(), $this->exclude ) or in_array( $folpath, $this->exclude ) or in_array( $ext, $this->exclude ) );
case 'files':
return ( $this->isFile() && ( !in_array( $this->getFilename(), $this->exclude ) or !in_array( $ext, $this->exclude ) ) );
break;
case 'dirs':
case 'folders':
return ( $this->isDir() && !( in_array( $this->getFilename(), $this->exclude ) ) && !in_array( $folpath, $this->exclude ) );
break;
default:
echo 'config error: ' . $this->mode .' is not recognised';
break;
}
return false;
}
public function getChildren(){
return new self( $this->getInnerIterator()->getChildren(), $this->exclude, $this->root, $this->mode );
}
}

upload excel file to wordpress media from simple php file script [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to upload the excel file to wordpress from outside php file script .I tried to search it but not got.
Can any one help me in this?
if ( !function_exists('media_handle_upload') ) {
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
$url = "http://example.com/demo.xls";
$tmp = download_url( $url );
if( is_wp_error( $tmp ) ){
// download failed, handle error
}
$post_id = 1;
$desc = "Description";
$file_array = array();
// Set variables for storage
// fix file filename for query strings
preg_match('/[^\?]+\.(jpg|jpe|jpeg|xls|png)/i', $url, $matches);
$file_array['name'] = basename($matches[0]);
$file_array['tmp_name'] = $tmp;
// If error storing temporarily, unlink
if ( is_wp_error( $tmp ) ) {
#unlink($file_array['tmp_name']);
$file_array['tmp_name'] = '';
}
// do the validation and storage stuff
$id = media_handle_sideload( $file_array, $post_id, $desc );
// If error storing permanently, unlink
if ( is_wp_error($id) ) {
#unlink($file_array['tmp_name']);
return $id;
}
$src = wp_get_attachment_url( $id );
Try this code
function upload_user_file( $file = array() ) {
require_once( ABSPATH . 'wp-admin/includes/admin.php' );
$file_return = wp_handle_upload( $file, array('test_form' => false ) );
if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
return false;
} else {
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
$attachment_id = wp_insert_attachment( $attachment, $file_return['url'] );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
if( 0 < intval( $attachment_id ) ) {
return $attachment_id;
}
}
return false;
}
if($_FILES['upload']['name']){
if( ! empty( $_FILES ) ) {
foreach( $_FILES as $file ) {
if( is_array( $file ) ) {
$attachment_id = upload_user_file( $file );
}
}
}
}
}
?>
<form enctype="multipart/form-data" method="post">
<input type="hidden" name="posted" value="posted"/>
<input type="file" name="upload"/>
<input type="submit" value="Save" />
</form>

Include php file randomly

I have a question about php include. Here goes the existing code that i have.
<?php
srand();
$files = array("folder/content1.php", "folder/content2.php", "folder/content3.php", "folder/content4.php");
$rand = array_rand($files);
include ($files[$rand]);
?>
This code actually works very well for me now as the content displaying randomly. But, i would like to get something better. Because, by using this code, everytime i have added a new content like content5.php, content6.php and so on, i have to bother to update the code above to make new content.php appear.
Is there any solution i can have, to not to bother the code above everytime i add a new content.php and the new content.php appears automatically when added? Is it possible?
Updated: New testing code(tested failed again with part of my page mising)
<?php
$sDirectory = 'myfolder';
if( is_dir( $sDirectory ) )
{
$rDir = opendir( $sDirectory );
while( ( $sFile = readdir( $rDir ) ) !== FALSE )
{
if( ( $sFile == '.' ) || ( $sFile === '..' ) )
{
continue;
}
$aFiles[] = $sDirectory . '/' . $sFile;
}
}
$sRandom = array_rand( $aFiles );
require_once( $aFiles[ $sRandom ] );
?>
$sDirectory = 'includes';
if( is_dir( $sDirectory ) )
{
$rDir = opendir( $sDirectory );
while( ( $sFile = readdir( $rDir ) ) !== FALSE )
{
if( ( $sFile == '.' ) || ( $sFile === '..' ) )
{
continue;
}
$aFiles[] = $sDirectory . '/' . $sFile;
}
}
$sRandom = array_rand( $aFiles );
require_once( $aFiles[ $sRandom ] );

Categories