Forum Replies Created

Viewing 14 replies - 166 through 179 (of 179 total)
  • Hi Guys I started running with LU5DX thoughts and as per Forest Gump I’m still running.

    The journey has become extended because whilst the resize suggestion of LU5DX worked it also distorts the image shape in an unattractive way, after a bit of searching I realised for my needs the answer is to specify only the width element.

    See first code example below.

    Anyway during the search for how this should be done I came across resize() found on https://joedesigns.com/v22/?page=scripts_widgets&id=67

    a chief benefit of which effectivly a lesson on how to manage a cache
    which I thought would be a sensible addition to activity plus but I needed to modify it in order to handle query scripts in the url.
    i.e https://www.inthesaddle.com/wms/modules/rides/image.php?i=79&w=940&h=320&format=jpg&crop=1

    Anyway my mod of resize() creates the files perfectly. But………
    Something I dont understand is going on whereby the image is not displayed correctly in the browser in its intended context (the members page of the site).

    The files are where they should be and when I view source – everything appears to be how it should be.
    I confirmed this by copying the view source output into localhost/test.html

    where it displays in the browser correctly

    However if the url in the address bar of the browser is localhost/members/andy

    it fails to display as mentioned!!!

    So I guess this is down to permalinks but please correct me / point me in the right direction if you have more insight than I – cheers.

    <div class="bpfb_images">
        <?php $rel = md5(microtime() . rand());
        foreach ($images as $img) {
            if (!$img) continue;
            if (preg_match('!^https?:\/\/!i', $img)) { // Remote image
                ?>
                <a href="<?php echo $img; ?>" class="<?php echo $use_thickbox; ?>" >
                    <img src="<?php echo $img; ?>" width='430' border='1' />
                    </a>
    
            <?php
            } else {
                $info = pathinfo($img);
                $thumbnail = file_exists(bpfb_get_image_dir($activity_blog_id) . $info['filename'] . '-bpfbt.' . strtolower($info['extension'])) ?
                bpfb_get_image_url($activity_blog_id) . $info['filename'] . '-bpfbt.' . strtolower($info['extension'])
                :
                bpfb_get_image_url($activity_blog_id) . $img
                ;
            ?>
                <a href="<?php echo bpfb_get_image_url($activity_blog_id) . $img; ?>" class="<?php echo $use_thickbox; ?>" rel="<?php echo $rel;?>">
                    <img src="<?php echo $thumbnail;?>" />
                </a>
            <?php
            }
        } ?>
    </div>

    With Resize and caching functionality for the produced thumbnail and changes highlighted

    <?PHP
     <strong>require_once (ABSPATH.'/ab-includes/function.resize.php')</strong>
    ?>
    <div class="bpfb_images">
        <?php $rel = md5(microtime() . rand());
        foreach ($images as $img) {
            if (!$img) continue;
            if (preg_match('!^https?:\/\/!i', $img)) { // Remote image 
    
    <strong>            $settings = array('w'=>430,'h'=>430);
                $thumb = resize($img,$settings);</strong>
                ?>
                <a href="<?php echo $img; ?>" class="<?php echo $use_thickbox; ?>" >
                    <strong><img src="<?php echo $thumb; ?>" border='1' /></strong>
                    </a>
    
            <?php
            } else {
                $info = pathinfo($img);
                $thumbnail = file_exists(bpfb_get_image_dir($activity_blog_id) . $info['filename'] . '-bpfbt.' . strtolower($info['extension'])) ?
                bpfb_get_image_url($activity_blog_id) . $info['filename'] . '-bpfbt.' . strtolower($info['extension'])
                :
                bpfb_get_image_url($activity_blog_id) . $img
                ;
            ?>
                <a href="<?php echo bpfb_get_image_url($activity_blog_id) . $img; ?>" class="<?php echo $use_thickbox; ?>" rel="<?php echo $rel;?>">
                    <img src="<?php echo $thumbnail;?>" />
                </a>
            <?php
            }
        } ?>
    </div>

    function.resize.php

    <?php
    /**
     * function by Wes Edling .. https://joedesigns.com
     * feel free to use this in any project, i just ask for a credit in the source code.
     * a link back to my site would be nice too.
     *AS says: - Original link to github found on https://joedesigns.com/v22/?page=scripts_widgets&id=67
     *
     *
     * Changes:
     * 2012/01/30 - David Goodwin - call escapeshellarg on parameters going into the shell
     * 2012/07/12 - Whizzkid - Added support for encoded image urls and images on ssl secured servers [https://]
     */
    
    /**
     * SECURITY:
     * It's a bad idea to allow user supplied data to become the path for the image you wish to retrieve, as this allows them
     * to download nearly anything to your server. If you must do this, it's strongly advised that you put a .htaccess file
     * in the cache directory containing something like the following :
     * <code>php_flag engine off</code>
     * to at least stop arbitrary code execution. You can deal with any copyright infringement issues yourself :)
     */
    
    /**
     * @param string $imagePath - either a local absolute/relative path, or a remote URL (e.g. https://...flickr.com/.../ ). See SECURITY note above.
     * @param array $opts  (w(pixels), h(pixels), crop(boolean), scale(boolean), thumbnail(boolean), maxOnly(boolean), canvas-color(#abcabc), output-filename(string), cache_http_minutes(int))
     * @return new URL for resized image.
     */
    function resize($imagePath,$opts=null){
    	$imagePath = urldecode($imagePath);
    	# start configuration
    	$cacheFolder =  './cache/'; # path to your cache folder, must be writeable by web server
    	$remoteFolder = $cacheFolder.'remote/'; # path to the folder you wish to download remote images into
    
    	$defaults = array('crop' => false, 'scale' => 'false', 'thumbnail' => false, 'maxOnly' => false,
    	   'canvas-color' => 'transparent', 'output-filename' => false,
    	   'cacheFolder' => $cacheFolder, 'remoteFolder' => $remoteFolder, 'quality' => 90, 'cache_http_minutes' => 20);
    
    	$opts = array_merge($defaults, $opts);    
    
    	$cacheFolder = $opts['cacheFolder'];
    	$remoteFolder = $opts['remoteFolder'];
    
    	$path_to_convert = 'convert'; # this could be something like /usr/bin/convert or /opt/local/share/bin/convert
    
    	## you shouldn't need to configure anything else beyond this point
    
    	$purl = parse_url($imagePath);
        $finfo = pathinfo($purl['path']);
    	$ext = $finfo['extension'];
    
        # if the url contains query script there is a problem as typically you will get a file extention of 'php' and you want of course an      # imnage extention. I am sure there is a better way and a wider range of scenarios!
        if ($ext == 'php'){
            $array_needles = array("gif","jpg","png", "bmp","tif"); 
    
            $haystack = $purl['query'];
    
            foreach($array_needles as $item){
                if(stristr($haystack, $item)){
                    //do whatever you want if its found
                    $ext = $item;
                    break;
                }
            }
    
        } 
    
    	# check for remote image..
    	if(isset($purl['scheme']) && ($purl['scheme'] == 'http' || $purl['scheme'] == 'https')):
    		# grab the image, and cache it so we have something to work with..
    	    $filename = $purl['host'].$finfo['dirname'].$finfo['filename'].".".$ext;
            $filename = str_replace('\\','_',$filename);
            $filename = str_replace('/','_',$filename);
    		$local_filepath = $remoteFolder.$filename;
    		$download_image = true;
    		if(file_exists($local_filepath)):
    			if(filemtime($local_filepath) < strtotime('+'.$opts['cache_http_minutes'].' minutes')):
    				$download_image = false;
    			endif;
    		endif;
    		if($download_image == true):
    			$img = file_get_contents($imagePath);
                file_put_contents($local_filepath,$img);
                //copyfile_chunked($imagePath, $local_filepath); you could use this instead
    
    		endif;
    		$imagePath = $local_filepath;
    	endif;
    
    	if(file_exists($imagePath) == false):
    		$imagePath = $_SERVER['DOCUMENT_ROOT'].$imagePath;
    		if(file_exists($imagePath) == false):
    			return 'image not found';
    		endif;
    	endif;
    
    	if(isset($opts['w'])): $w = $opts['w']; endif;
    	if(isset($opts['h'])): $h = $opts['h']; endif;
    
    	$filename = md5_file($imagePath);
    
    	// If the user has requested an explicit output-filename, do not use the cache directory.
    	if(false !== $opts['output-filename']) :
    		$newPath = $opts['output-filename'];
    	else:
            if(!empty($w) and !empty($h)):
                $newPath = $cacheFolder.$filename.'_w'.$w.'_h'.$h.(isset($opts['crop']) && $opts['crop'] == true ? "_cp" : "").(isset($opts['scale']) && $opts['scale'] == true ? "_sc" : "").'.'.$ext;
            elseif(!empty($w)):
                $newPath = $cacheFolder.$filename.'_w'.$w.'.'.$ext;
            elseif(!empty($h)):
                $newPath = $cacheFolder.$filename.'_h'.$h.'.'.$ext;
            else:
                return false;
            endif;
    	endif;
    
    	$create = true;
    
        if(file_exists($newPath) == true):
            $create = false;
            $origFileTime = date("YmdHis",filemtime($imagePath));
            $newFileTime = date("YmdHis",filemtime($newPath));
            if($newFileTime < $origFileTime): # Not using $opts['expire-time'] ??
                $create = true;
            endif;
        endif;
    
    	if($create == true):
    		if(!empty($w) and !empty($h)):
    
    			list($width,$height) = getimagesize($imagePath);
    			$resize = $w;
    
    			if($width > $height):
    				$resize = $w;
    				if(true === $opts['crop']):
    					$resize = "x".$h;
    				endif;
    			else:
    				$resize = "x".$h;
    				if(true === $opts['crop']):
    					$resize = $w;
    				endif;
    			endif;
    
    			if(true === $opts['scale']):
    				$cmd = $path_to_convert ." ". escapeshellarg($imagePath) ." -resize ". escapeshellarg($resize) .
    				" -quality ". escapeshellarg($opts['quality']) . " " . escapeshellarg($newPath);
    			else:
    				$cmd = $path_to_convert." ". escapeshellarg($imagePath) ." -resize ". escapeshellarg($resize) .
    				" -size ". escapeshellarg($w ."x". $h) .
    				" xc:". escapeshellarg($opts['canvas-color']) .
    				" +swap -gravity center -composite -quality ". escapeshellarg($opts['quality'])." ".escapeshellarg($newPath);
    			endif;
    
    		else:
    			$cmd = $path_to_convert." " . escapeshellarg($imagePath) .
    			" -thumbnail ". (!empty($h) ? 'x':'') . $w ."".
    			(isset($opts['maxOnly']) && $opts['maxOnly'] == true ? "\>" : "") .
    			" -quality ". escapeshellarg($opts['quality']) ." ". escapeshellarg($newPath);
    		endif;
    
    		$c = exec($cmd, $output, $return_code);
            if($return_code != 0) {
                error_log("Tried to execute : $cmd, return code: $return_code, output: " . print_r($output, true));
                return false;
    		}
    	endif;
    
    	# return cache file path
    	$retval = str_replace($_SERVER['DOCUMENT_ROOT'],'',$newPath);
        $retval = str_replace("\\","/",$retval);
        return $retval;
    
    }
    
    /**
    * found at https://stackoverflow.com/questions/4000483/how-download-big-file-using-php-low-memory-usage
    *
    * @param mixed $infile
    * @param mixed $outfile
    */
    function copyfile_chunked($infile, $outfile) {
        $chunksize = 10 * (1024 * 1024); // 10 Megs
    
        /**
         * parse_url breaks a part a URL into it's parts, i.e. host, path,
         * query string, etc.
         */
        $parts = parse_url($infile);
        $i_handle = fsockopen($parts['host'], 80, $errstr, $errcode, 5);
        $o_handle = fopen($outfile, 'wb');
    
        if ($i_handle == false || $o_handle == false) {
            return false;
        }
    
        if (!empty($parts['query'])) {
            $parts['path'] .= '?' . $parts['query'];
        }
    
        /**
         * Send the request to the server for the file
         */
        $request = "GET {$parts['path']} HTTP/1.1\r\n";
        $request .= "Host: {$parts['host']}\r\n";
        $request .= "User-Agent: Mozilla/5.0\r\n";
        $request .= "Keep-Alive: 115\r\n";
        $request .= "Connection: keep-alive\r\n\r\n";
        fwrite($i_handle, $request);
    
        /**
         * Now read the headers from the remote server. We'll need
         * to get the content length.
         */
        $headers = array();
        while(!feof($i_handle)) {
            $line = fgets($i_handle);
            if ($line == "\r\n") break;
            $headers[] = $line;
        }
    
        /**
         * Look for the Content-Length header, and get the size
         * of the remote file.
         */
        $length = 0;
        foreach($headers as $header) {
            if (stripos($header, 'Content-Length:') === 0) {
                $length = (int)str_replace('Content-Length: ', '', $header);
                break;
            }
        }
    
        /**
         * Start reading in the remote file, and writing it to the
         * local file one chunk at a time.
         */
        $cnt = 0;
        while(!feof($i_handle)) {
            $buf = '';
            $buf = fread($i_handle, $chunksize);
            $bytes = fwrite($o_handle, $buf);
            if ($bytes == false) {
                return false;
            }
            $cnt += $bytes;
    
            /**
             * We're done reading when we've reached the conent length
             */
            if ($cnt >= $length) break;
        }
    
        fclose($i_handle);
        fclose($o_handle);
        return $cnt;
    }

    Yes its the same here with Suffusion, if by splits the page you mean that sidebar is ejected from its coorrect position and loaded beneath been content area. I suspect it might be a theme with Buddypress issue though as I saw the same thing on several other plugins I looked at installing!

    Yes sorry for late confirmation – yes it does fix it – Thanks Sayontan

    Thread Starter CallMeAndy

    (@callmeandy)

    Well in fact whether excerpt or full post is handled by the theme (Suffusion), and perhaps wrongly I had thought that the paged variable provided the instruction to the theme. I say that because on all the other pages this seems to work.

    I spent some time going through the theme code itself and could not see the answer guess I will just have to delve a bit more throuroughly.

    Yes same problems here. Early days still for me with both Suffusion and wordpress come to that Sayontan, but i am definitely advocate of your work, Suffusion is pretty cool. However I need to make a decision about if to rollback bbPress or await any approval of a new Suffusion version. I wonder how long this process takes for WP? and I take it you are talking about a later version than 4.2.6 which as yet I have not advanced to?

    Thread Starter CallMeAndy

    (@callmeandy)

    So I delved a bit further, and picking at straws really I added some additional clauses not expecting any real difference to the product of the query but ultimately the outcome was a surprise.

    $args = array(
        //'meta_query' => array( 'key' => 'AssocBlogID',  'compare' => '==','value' => $pageID ),
        'meta_key' => 'AssocBlogID', 'compare' => '!=',
        'meta_value' => $pageID,
        'orderby' => 'date',
        'order' => 'DESC',
        'post_type'     =>    'post',
        'post_status' =>    'publish',
        'posts_per_page' => -1,
        'caller_get_posts'=> 1,
        'paged' => $paged,
    );

    Produces this query:
    SELECT wp_posts.* FROM wp_posts INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id) WHERE 1=1 AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish') AND ( (wp_postmeta.meta_key = 'AssocBlogID' AND CAST(wp_postmeta.meta_value AS CHAR) = '435') ) GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC

    Of course removing the caller_get_posts clause brings back in stickys, but these should not be there as they do not have the AssocBlogID meta set. I am obviously missing something else as well, as removing the caller_get_posts from the $args DOES NOT CHANGE THE SQL in wp_query.

    To say I was confounded at this point is an understatement.

    I hadnt realised that caller_get_posts has been depricated, Changing the line to ‘ignore_sticky_posts’ => 1, makes no difference however in gives the same results when included or excluded out still gives the same SQL

    Thats when I twigged and the results are confirmed in phpMyAdmin

    There must be some post processing going on to merge the results to the stickys –

    I had assumed that the way stickies worked was that: from a given set of results the sort order would always hold them at the top of the list. But what seems to be happening is that even when they do not form a part of a queries results they are being added back into the results. i.e All stiky posts are added to the output irrespective of the query unless specifically excluded.

    Thread Starter CallMeAndy

    (@callmeandy)

    Aha Yes I did read it but clearly I missed the $html assignment. Much appreciated your spot on.

    AS

    Thread Starter CallMeAndy

    (@callmeandy)

    Thanks for coming back to me guys.
    However including echo=0 now, as would seem intuitive, is not echoing anything. Its now not rendering any list at all. Previously it was the correct output just in the wrong place.

    Thread Starter CallMeAndy

    (@callmeandy)

    OK Solved the Permalinks problem.

    Its with Apache – httpd.conf

    As I mentioned above no problems with other php installations and I failed to see the obvious – its a problem in the Directory Directive.

    Options Indexes FollowSymLinks fails
    Options FollowSymLinks Works

    As regards the erroneous writing of htaccess this seems to be something to do with using a child theme. I dont know anything really about the way child themes are implemented however the only thing that I was morphing was css using simple html tags all functionality was directly inherited. Removing the child theme resolved this issue.

    Anyway time to move on for me I think.

    Thread Starter CallMeAndy

    (@callmeandy)

    You did indeed follow what I said and you reiterated it above. I merely wished to underline things for anyone else following this thread.

    Thanks for your help.

    So if anyone else can make any suggestions on this it would be appreciated.

    To recap
    on setting permalinks to the Numeric method in admin settings I am getting 404 Page not found messages on all links. In fact it applies to any setting other than the default method.

    Platform is WAMP on localhost.
    The auto creation of htaccess is not being done as per expectations i.e. it is being written to the system root directory i.e “c:\”
    This is neither Apache documentRoot or the WordPress root.
    Also the lines it is writing in the file are incoreect (seemingly like a bug)

    Thread Starter CallMeAndy

    (@callmeandy)

    It isn’t all that demanding really– WordPress Requirements.

    Yes well I meet all the basic requirements, and until trying to sort out permalinks everything was ok. The problem is what is required for wordpress permalinks!

    Explorer can. The shell can’t though and I wasn’t sure which mattered for WAMP.

    I am not sure that the shell is relevent. As I understand things Apache interacts with the kernel. Which as mentioned has no problem undertsanding “/”. I use it this way all the time, first one at random from another project

    include "includes/mastandnav.inc.htm";

    WAMP works fine with forwardslashes I think this is a red herring.

    Settings – Permalinks – Common Settings – Numeric
    As in the adminsitrative interface at wp-admin.

    They are both localised – i.e https://localhost/adventurebod/20120706/adventurebod

    Thread Starter CallMeAndy

    (@callmeandy)

    Thanks for getting back to me.

    It is supposed to do that.

    Yes just wasnt sure if wordPress amended as well as created the htaccess file.

    WordPress shouldn’t be able to do anything at all outside of Apache’s DocumentRoot unless something is badly wrong with your server.

    This is the whole point of my inclduding this note within the post – something is either wrong with wordpress or my environment is not appropriate for WordPress, however the question is what.

    Of course there is a difference between something badly wrong with the server configuration in terms of WordPress’s requisite and that of a valid configuration of Apache for other purposes. I am running about 3 other regular apache/mysql/php applications on it without issue.

    And have developed many AMP websites without issue. So the question remains what does WordPress require?

    Windows convention is to use backslashes (\) for directory delimiters but in fact (try it in windows explorer) it can interpret forward slashes perfectly well. I believe it is a common practice when developing on a WAMP environment, an application that will be deployed in a LAMP production environment, to use the forward slash syntax as deployment issues are then mitigated.

    Either way in case of some sort of wordpress quirk I tried it with both delimiters. Neither have any difference in effect.

    DocumentRoot is most definitely where I stated it to be and there are no embedded hidden characters in httpd.conf. FYI using Notepad++.

    Thread Starter CallMeAndy

    (@callmeandy)

    oh I forgot to mention, in relation to saying the blog is working in the default location, a similar step through reaches the same point in the code as for the repositioned blog however this time the Boolean TRUE is not rejected by mysql_num_fields

    I am getting a similar problem.

    I have done a new install today to a local development machine with XP running Apache. I get just a directory listing if using the index.php in wordpress root, admin page is OK. So I reinstall after moving the installation and clearing database tables in between, just in case data relating to wordpress infrastructure. Still the same.

    The wordpress directory is several steps down from the documentroot. I am using the default installed index.php file. The core files are in the same original location.

    Anyone have anything on this problem it would be appreciated.

Viewing 14 replies - 166 through 179 (of 179 total)