* getImages

Есть сниппет getImages. Вопрос как можно заставить сортировать файлы по рандому?
getImages_Sort = 'RAND()' не работает. И что нужно добавить в сниппет что б заработал рандом?


<?php
/*
 * getImages
 *
 * DESCRIPTION
 *
 * This Snippet retrieves image files from a directory, processes them through 
 * template chunks and returns the resulting gallery.
 *
 * PARAMETERS:
 *
 * &getImages_Folder string - The name of the image folder to search. optional. Default: assets/photos
 * &getImages_Ext string - The extension of the images. optional. Default: jpg
 * &getImages_Sort string - the way you would like the images sorted. optional Default: filemtime
 * &getImages_Image_Tpl string - The name of a Chunk used to format Images. optional. Default: getImages_Image_Tpl
 * &getImages_Page_Tpl string - The name of a Chunk used to format the page. optional. Default: getImages_Page_Tpl
 * &getImages_Width integer - A number representing the width images to return. optional. Default: 150
 * &getImages_Height integer - A number representing the height images to return. optional. Default: 100
 * &getImages_Border integer - A number representing the border width. optional. Default: 0
 * &getImages_Class string - A class name to pass. optional. Default: ''
 * &getImages_PageClass string - A class name to pass. optional. Default: ''
 * &getImages_InfoClass string - A class name to pass. optional. Default: ''
 * &getImages_ExifClass string - A class name to pass. optional. Default: ''
 * &getImages_Id string - An id name to pass. optional. Default: ''
 * &getImages_PageId string - An id name to pass. optional. Default: ''
 * &getImages_InfoId string - An id name to pass. optional. Default: ''
 * &getImages_ExifId string - An id name to pass. optional. Default: ''
 * &getImages_Paging boolean - 1 to split images between pages. 0 for no split. optional. Default: 1
 * &limit string - A number representing the number of images to display per page (see getPage). optional. Default: 10
 * &pageLimit string - A number representing the number of page links to display (see getPage). optional. Default: 5
 *
 * version 2.3.0
 * author Jerry Mercer (ultravision.net)
 *
 * USAGE:
 *
 * [[!getImages? 
 * &getImages_Folder=`assets/photos` 
 * &getImages_Ext =`jpg,gif,png,JPG,GIF,PNG`
 * &getImages_Sort = `filemtime`
 * &getImages_Image_Tpl =`getImages_Image_Tpl`
 * &getImages_Page_Tpl =`getImages_Page_Tpl`
 * &getImages_Width =`150`
 * &getImages_Heigth=`100`
 * &getImages_Border=`2`
 * &getImages_Class =`imgClass`
 * &getImages_PageClass =`section`
 * &getImages_InfoClass =`info`
 * &getImages_ExifClass =`exif`
 * &getImages_Id =`imgId`
 * &getImages_PageId =`section`
 * &getImages_InfoId =`info`
 * &getImages_ExifId =`exif`
 * &getImages_Paging =`1`
 * &limit =`6`
 * &pageLimit=`3`
 * ]]
 *
 */

/***** SET VARIABLES *****/
$folder = isset($_GET['folder']) ? $_GET['folder'] : ''; // use to get folder from URL
// $folder = $modx->getOption('getImages_Folder', $scriptProperties, 'assets/photos'); // use to get default folder, or from parameters
$ext = $modx->getOption('getImages_Ext', $scriptProperties, 'jpg'); // What extension(s) do we use
$fileSort = $modx->getOption('getImages_Sort', $scriptProperties, 'filemtime'); // What to sort the images by
$image_tpl = $modx->getOption('getImages_Image_Tpl', $scriptProperties, 'getImages_Image_Tpl'); // template for each image
$page_tpl = $modx->getOption('getImages_Page_Tpl', $scriptProperties, 'getImages_Page_Tpl'); // template for completed page 
$width = $modx->getOption('getImages_Width', $scriptProperties, 300); // Width to use
$height = $modx->getOption('getImages_Height', $scriptProperties, 225);// Height to use
$border = $modx->getOption('getImages_Border', $scriptProperties, 0); // Border to use
$class = $modx->getOption('getImages_Class', $scriptProperties, ''); // class name
$pageClass = $modx->getOption('getImages_PageClass', $scriptProperties, ''); // class name
$infoClass = $modx->getOption('getImages_InfoClass', $scriptProperties, ''); // class name
$exifClass = $modx->getOption('getImages_ExifClass', $scriptProperties, ''); // class name
$id = $modx->getOption('getImages_Id', $scriptProperties, ''); // id name
$pageId = $modx->getOption('getImages_PageId', $scriptProperties, ''); // id name
$infoId = $modx->getOption('getImages_InfoId', $scriptProperties, ''); // id name
$exifId = $modx->getOption('getImages_ExifId', $scriptProperties, ''); // id name
$paging = $modx->getOption('getImages_Paging', $scriptProperties, 1); // Do we use paging

$fPath = ''; // initialize full path to image variable
$imgFile = ''; // initialize full file name of image variable
$imgName = ''; // initialize image name variable
$path = ''; // initialize fPath less file name variable
$pPath = ''; // initialize path to parent folder variable
$parent = ''; // initialize parent folder variable
$fHTML = ''; // initialize formatted HTML from template chunk variable
$c = 1; // initialize counter for foreach loop variable

/***** CREATE IMAGE ARRAY *****/
$allImages = glob($folder.'/*.{'.$ext.'}', GLOB_BRACE); // get images($images) from image folder($folder)
array_multisort(array_map($fileSort, $allImages), SORT_DESC, $allImages); // sort the array 
$tot = count($allImages);	        // counter for all images in folder

if ($paging > 0) {
	$images = array_slice($allImages, $offset, $limit);// Type your code here
}
else {
	$images = $allImages;
}

/***** CREATE THE IMAGE SECTION FOR OUR PAGE *****/
foreach ($images as $image) // loop through the images array
{
	$modx->setPlaceholder('id', $id); // set id place-holder for use in template chunk
	$modx->setPlaceholder('count', $c); // set count place-holder
	$fPath = $image; // set full path to image
	$imgFile = basename($fPath); // strip to just image file name
	$imgName = rtrim($imgFile, ".".substr(strrchr($imgFile, "."), 1)); // strip extension
	$path = preg_replace('/'. preg_quote($imgFile, '/') . '$/', '', $fPath); // get path without file name	
	$fold = basename($path); // strip to get image folder
	$pPath = preg_replace('/'. preg_quote($fold, '/') . '\/$/', '', $path); // get path to parent folder 
	$parent = basename($pPath); // strip to get just parent folder
	$exif_data = exif_read_data ($fPath ,'IFD0' ,0 ); // read the exif data from the image
	$modx->setPlaceholder('imgLink', $fPath); // set imgLink place-holder
	$modx->setPlaceholder('imgName', $imgName); // set imgName place-holder
	$modx->setPlaceholder('path', $path); // set path place-holder
	$modx->setPlaceholder('pPath', $pPath); // set parent path place-holder
	$modx->setPlaceholder('parent', $parent); // set parent place-holder
	$modx->setPlaceholder('imgFile', $imgFile); // set imgFile place-holder
	$modx->setPlaceholder('folder', $fold); // set folder place-holder
	$modx->setPlaceholder('imgCamera', $exif_data['Model']); // set imgCamera place-holder
	$modx->setPlaceholder('imgDate', $exif_data['DateTime']); // set imgDate place-holder
	$fHTML = $modx->parseChunk($image_tpl); //call the formatting chunk
	$photos .= $fHTML; // insert completed image sections into a string
	$c = $c+1; // increment the counter	
}

/***** COMPLETE THE PAGE *****/
$modx->setPlaceholder('width', $width); // set width place-holder
$modx->setPlaceholder('height', $height); // set height place-holder
$modx->setPlaceholder('border', $border); // set border place-holder
$modx->setPlaceholder('class', $class); // set class place-holder
$modx->setPlaceholder('pageClass', $pageClass); // set class place-holder
$modx->setPlaceholder('infoClass', $infoClass); // set class place-holder
$modx->setPlaceholder('exifClass', $exifClass); // set class place-holder
$modx->setPlaceholder('id', $id); // set id place-holder
$modx->setPlaceholder('pageId', $pageId); // set id place-holder
$modx->setPlaceholder('infoId', $infoId); // set id place-holder
$modx->setPlaceholder('exifId', $exifId); // set id place-holder
$modx->setPlaceholder('total', $tot); // set total place-holder
$modx->setPlaceholder('photos', $photos); // set photos place-holder
$page = $modx->parseChunk($page_tpl); //call the formatting chunk and fill with the results

/***** RETURN COMPLETED PAGE *****/
return $page;
Виктор
04 мая 2015, 12:21
modx.pro
2 765
0

Комментарии: 2

Сергей Фещуков
04 мая 2015, 15:47
0
Изображения берутся не запросом из таблицы, поэтому вариант с RAND() вообще ни к месту. Ищите в google варианты как произвольно сортировать массивы.
В PHP есть функция shuffle для перемешивания массивов.
php.net/manual/ru/function.shuffle.php
    Владимир
    04 мая 2015, 18:49
    0
    Снипет randomImage
    отсюда modx.com/extras/package/revoutilities
    <?php
    /**
     * 
     * A utilities snippet for MODX Revolution
     * 
     * This snippet will return a random image path from a given folder/directory 
     * 
     * @package RevoUtilities
     * 
     * useage
     * [[!randomImage? &folder=`assets/content/images/`]]
     * 
     */
    
     /**
     * display a random image for a selected directory
     */
    $image_path = '';
    
    /**
     * 1. get all of the image files in the directory
     * 2. randomly pick one and send the path back
     */
    $base_url = $modx->getOption('folder', $scriptProperties, 'assets/content/backgrounds/');
    
    //$site_path = str_replace('core/', '', $modx->getOption('core_path'));
    $current_dir = MODX_BASE_PATH.$base_url;// this is the base 
    
    $allowed_types = array('gif', 'jpeg', 'jpg', 'png');
    
    $file_type_array = array(
            # documents
            'doc' =>'application/msword',
            'docx' =>'application/msword',
            //'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'rtf' => 'application/rtf',
            'txt' => 'text/plain',
            'pdf' => 'application/pdf',
            # powerpoint
            'pot' => 'application/mspowerpoint',
            'pps' => 'application/mspowerpoint',
            'ppt' => 'application/mspowerpoint',
            'ppz' => 'application/mspowerpoint',
            # excel
            'csv' => 'application/x-msdownload',
            'xlc' => 'application/vnd.ms-excel',
            'xls' => 'application/vnd.ms-excel',
            # web images
            'gif' => 'image/gif',
            'jpeg' => 'image/jpeg',
            'jpg' => 'image/jpeg',
            'png' => 'image/png', 
            'tif' => 'image/tiff',
            'tiff' => 'image/tiff',
            # web files
            'css' => 'text/css',
            'htm' => 'text/html',
            'html' => 'text/html',
            'xml' => 'text/xml',
            'js' => 'application/x-javascript',
            # video
            'avi' => 'video/x-msvideo',
            'dl' => 'video/dl',
            'fli' => 'video/fli',
            'fli' => 'video/x-fli',
            'flv' => 'video/flv',
            'gl' => 'video/gl',
            'mp2' => 'video/mpeg',
            'mpe' => 'video/mpeg',
            'mpeg' => 'video/mpeg',
            'mpg' => 'video/mpeg',
            'mov' => 'video/quicktime',
            'qt' => 'video/quicktime',
            'viv' => 'video/vnd.vivo', 
            'vivo' => 'video/vnd.vivo', 
            'wmv' => 'video/x-ms-wmv',
            'wmx' => 'video/x-ms-wmx',
            'wvx' => 'video/x-ms-wvx',
            'asf' => 'video/x-ms-asf',
            'asx' => 'video/x-ms-asx',
            'movie' => 'video/x-sgi-movie'
        );
    
    
    // Array that will hold the dir/folders names.
    $dir_array = array();
    //$dir_info_array = array();
    $file_array = array();
    $file_info_array = array();
    
    $open_dir = opendir( $current_dir ) ;
    
    while ( $tmp_file = readdir( $open_dir ) ) {
        if ( $tmp_file != '.' && $tmp_file != '..' ) {
            # dir
            if ( is_dir( $current_dir.$tmp_file ) ) {
                $dir_array[] = $tmp_file;
            # files
            } elseif ( is_file($current_dir.$tmp_file) ) {
                $file_size = @filesize( $current_dir.$tmp_file ) ;
                if ( !$file_size ) {
                    $file_size = 0 ;
                }
                if ( $file_size < 1024*1024) {
                    $file_size = round( $file_size / 1024 ).'kb';
                    if ( $file_size < 1 ) {
                        $file_size = '1kb';
                    }
                } else {
                    $file_size = round( $file_size/(1024*1024) ).'mb';
                }
                
                # get the type of file
                $file_ext = substr($tmp_file, strripos($tmp_file, '.')+1 );
                
                if ( in_array($file_ext, $allowed_types) ){
                    $file_array[] = $tmp_file;
                    $file_info_array[$tmp_file] = array(
                        'type' => '', // jpg, html, php, ect.
                        'content_type' => $file_type_array[$file_ext],
                        'size' => $file_size,
                        'date' => date("M/j/Y g:ia",filemtime($current_dir.$tmp_file)) );
                } else {
                    continue;
                }
            }
        }
    }
    closedir($open_dir);
    
    $image_path = $base_url.( $file_array[array_rand($file_array)] );
    
    return $image_path;
      Авторизуйтесь или зарегистрируйтесь, чтобы оставлять комментарии.
      2