function pleac_Splitting_a_Filename_into_Its_Component_Parts()
{
    $base = basename($path);
    $dir = dirname($path);
    // PHP's equivalent to Perl's 'fileparse'
    $pathinfo = pathinfo($path);
    $base = $pathinfo['basename'];
    $dir = $pathinfo['dirname'];
    $ext = $pathinfo['extension'];
    // ----------------------------
    $path = '/usr/lib/libc.a';
    printf("dir is %s, file is %s\n", dirname($path), basename($path));
    // ------------
    $path = '/usr/lib/libc.a';
    $pathinfo = pathinfo($path);
    printf("dir is %s, name is %s, extension is %s\n", $pathinfo['dirname'], $pathinfo['basename'], $pathinfo['extension']);
    // ----------------------------
    // Handle Mac example as a simple parse task. However, AFAIK, 'pathinfo' is cross-platform,
    // so should handle file path format differences transparently
    $path = 'Hard%20Drive:System%20Folder:README.txt';
    $macp = array_combine(array('drive', 'folder', 'filename'), split("\\:", str_replace('%20', ' ', $path)));
    $macf = array_combine(array('name', 'extension'), split("\\.", $macp['filename']));
    printf("dir is %s, name is %s, extension is %s\n", $macp['drive'] . ':' . $macp['folder'], $macf['name'], '.' . $macf['extension']);
    // ----------------------------
    // Not really necessary since we have, 'pathinfo', but better matches Perl example
    function file_extension($filename, $separator = '.')
    {
        return end(split("\\" . $separator, $filename));
    }
    // ----
    echo file_extension('readme.txt') . "\n";
}
Ejemplo n.º 2
0
 /**
  * Instantiate the translation language
  *
  * @param TranslationLanguage $a_language
  * @throws GenericException If the file is inexistant or invalid
  */
 public function __construct(TranslationLanguage $a_language)
 {
     $this->locale_string = array();
     $this->language = $a_language;
     if (file_exists($this->language->file_path)) {
         if (file_extension($this->language->file_path) == "json") {
             $file = fopen($this->language->file_path, 'r');
             $content = fread($file, filesize($this->language->file_path));
             $content = json_decode($content);
             $array = array();
             $indexes = array();
             foreach ($content as $part => $sub_content) {
                 $indexes[$part] = $sub_content;
             }
             if (isset($indexes['locale'])) {
                 foreach ($indexes['locale'] as $key => $value) {
                     $array[$key] = $value;
                 }
             } else {
                 $array['datehour'] = "%x %H:%M";
                 $array['date'] = "%x";
                 $array['hour'] = "%H:%M";
             }
             $this->locale_entries = $array;
         } else {
             throw new GenericException("Invalid File");
         }
     } else {
         throw new GenericException("Inexistant File");
     }
 }
Ejemplo n.º 3
0
 function uploadAttributes($file_name, $file_size, $path, $id = '')
 {
     $access_key_id = $this->getOption('AWSAccessKeyID');
     $secret_access_key = $this->getOption('AWSSecretAccessKey');
     $bucket = $this->getOption('S3Bucket');
     if (!($bucket && $access_key_id && $secret_access_key)) {
         throw new UnexpectedValueException('Configuration options AWSAccessKeyID, AWSSecretAccessKey, SQSQueueURL, S3Bucket required');
     }
     $extension = file_extension($file_name);
     $mime = mime_from_path($file_name);
     if (!($mime && $extension)) {
         throw new UnexpectedValueException('Could not determine mime type or extension of: ' . $file_name);
     }
     if (!$id) {
         $id = unique_id($mime);
     }
     $s3_options = array();
     $s3_options['bucket'] = $bucket;
     $s3_options['AWSAccessKeyId'] = $access_key_id;
     $s3_options['AWSSecretAccessKey'] = $secret_access_key;
     $s3_options['uniq_id'] = $id;
     $s3_options['path'] = $path . '.' . $extension;
     $s3_options['mime'] = $mime;
     $s3data = s3_upload_data($s3_options);
     $result = '';
     if (!empty($s3data)) {
         $s3data['mime'] = $mime;
         $s3data['keyid'] = $access_key_id;
         //$s3data['id'] = $id;
         foreach ($s3data as $k => $v) {
             $result .= ' ' . $k . '="' . $v . '"';
         }
     }
     return $result;
 }
	function createScriptObjectFromFilename ($pagename, $fname, $data='') {
		$ext = file_extension($fname);
		switch ($ext) {
			case 'gpt': return new GnuplotScriptObject($pagename, $fname, true);
		}
		return false;
	}
Ejemplo n.º 5
0
function test_file_extension()
{
    assert_equal(file_extension('my_file'), '');
    assert_equal(file_extension('my_file.txt'), 'txt');
    assert_equal(file_extension('my_file.html.php'), 'php');
    assert_equal(file_extension('my_file.JPG'), 'JPG');
}
	function process ($fo, $out) {
		if (!file_exists($fo))
			die("file '$fo' not found");
		$format = file_extension($out);
		if ($format != 'ps' && $format != 'pdf')
			$format = 'pdf';
		RunTool('fo2rtf', "FO=$fo OUT=$out", 'pipe-callback', array('FO2RTF', 'messageCallback'));
	}
function getBoundingBox ($fname) {
	$ext = file_extension($fname);
	switch ($ext) {
		case 'eps':	return getEPSBoundingBox($fname);
		case 'pdf': return getPDFBoundingBox($fname);
	}
	return false;
}
Ejemplo n.º 8
0
function show_file_name($file_name, $charnum)
{
    if (strlen($file_name) <= $charnum + 7) {
        return $file_name;
    } else {
        return substr($file_name, 0, $charnum) . '.......' . file_extension($file_name);
    }
}
function getBoundingBox ($fname) {
	$ext = file_extension($fname);
	if ($ext == 'eps')
		return getEPSBoundingBox($fname);
	if ($ext == 'pdf')
		return getPDFBoundingBox($fname);
	return false;
}
Ejemplo n.º 10
0
 function redirect($url_path)
 {
     $this->load->model('link_model');
     $link = $this->link_model->get_links(array('url_path' => $url_path));
     if (empty($link)) {
         return show_404($url_path);
     }
     $link = $link[0];
     // get serialized url/groups data
     $data = unserialize($link['parameter']);
     if (empty($data)) {
         return show_error('Invalid link.');
     }
     // if this is an absolute link, we'll try and make it relative
     if (strpos($data['url'], $this->config->item('base_url')) === 0) {
         // it begins with the URL, so we can just strip this to get a relative path
         $data['url'] = substr_replace($data['url'], '', 0, strlen($this->config->item('base_url')));
     } elseif (strpos($data['url'], FCPATH) === 0) {
         $data['url'] = substr_replace($data['url'], '', 0, strlen(FCPATH));
     }
     // add APPPATH to make this an absolute path
     $data['url'] = FCPATH . $data['url'];
     // check permissions
     if (!$this->user_model->in_group($data['groups'])) {
         return show_error('Insufficient access privileges.');
     } else {
         // load and return file
         $this->load->helper('file_extension');
         // set filename
         $filename = (isset($data['filename']) and !empty($data['filename'])) ? $data['filename'] : $link['url_path'] . '.' . file_extension($data['url']);
         $extension = file_extension($data['url']);
         // get the mime type
         include APPPATH . 'config/mimes.php';
         if (!isset($mimes[$extension])) {
             die(show_error('Failed to retrieve mime-type data for file extension "' . $extension . '".'));
         }
         $mime_type = $mimes[$extension];
         // some mime types are arrays...
         if (is_array($mime_type)) {
             $mime_type = $mime_type[0];
         }
         // don't limit to small files
         set_time_limit(0);
         header("Pragma: public");
         // required
         header("Expires: 0");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         header("Cache-Control: private", FALSE);
         // required for certain browsers
         header("Content-Type: " . $mime_type);
         header("Content-Disposition: attachment; filename=\"" . $filename . "\";");
         header("Content-Transfer-Encoding: binary");
         header("Content-Length: " . filesize($data['url']));
         readfile($data['url'], "r");
         die;
     }
 }
Ejemplo n.º 11
0
/**
 * Return the possible MIME type of a function
 * @param string filename		The name of the file to be delt with
 * @return string				Hopefully the MIME type of the file
 * @author Peter Goodman
 */
function get_mimetype($filename)
{
    global $mimetypes;
    $ext = file_extension($filename);
    $mimetype = $mimetypes[FALSE];
    if (isset($mimetypes[$ext])) {
        $mimetype = $mimetypes[$ext];
    }
    return $mimetype;
}
Ejemplo n.º 12
0
 function image_show_jpeg_only()
 {
   $ext = file_extension(params(0));
   $filename = option('public_dir').params(0);
   if(params('size') == 'thumb') $filename .= ".thb";
   $filename .= '.jpg';
 
   if(!file_exists($filename)) halt(NOT_FOUND, "$filename doesn't exists");
   render_file($filename);
 }
Ejemplo n.º 13
0
	function accept_upload(&$upload)
	{
		$this->upload['filename'] = trim($upload['name']);
		$this->upload['filesize'] = intval($upload['size']);
		$this->upload['location'] = trim($upload['tmp_name']);
		$this->upload['extension'] = strtolower(file_extension($this->upload['filename']));
		$this->upload['thumbnail'] = '';
		$this->upload['filestuff'] = '';
		return true;
	}
Ejemplo n.º 14
0
 public function file($filename)
 {
     $format = file_extension($filename, $id);
     if ($id === 'list') {
         return $this->index($format);
     }
     $repo = getRepository($this->repository);
     $instance = $repo->get($this->model, $id);
     $data = $repo->export($this->model, $instance, $this->maxRecursion);
     return $this->format($data, $format);
 }
Ejemplo n.º 15
0
/**
 * Sube un archivo a la carpeta uploads
 * @param unknown_type $arr_file_desc
 * @param unknown_type $destino
 * @param unknown_type $name
 */
function subirArchivo($arr_file_desc, $destino = null, $name = null)
{
    $arr_file = array();
    $file_extension = file_extension($arr_file_desc['name']);
    if ($destino == null) {
        $dia = date("j");
        $mes = date("n");
        $anyo = date("Y");
        $new_relative_path = $anyo . BARRA_SERVIDOR . $mes . BARRA_SERVIDOR . $dia;
    } else {
        $new_relative_path = $destino;
    }
    if ($name != null) {
        $new_file_name = $name;
    } else {
        $new_file_name = str_replace("." . $file_extension, "", $arr_file_desc['name']);
    }
    // Creamos la ruta de carpetas
    createPath($new_relative_path);
    // Si existe el archivo, con un contador cambio el nombre hasta que deje de existir
    $cont = 0;
    while (file_exists(UPLOAD_DIR . BARRA_SERVIDOR . $new_relative_path . BARRA_SERVIDOR . $new_file_name . "." . $file_extension)) {
        $cont++;
        $new_file_name .= $cont;
    }
    if (file_exists($arr_file_desc['tmp_name'])) {
        if (!copy($arr_file_desc['tmp_name'], UPLOAD_DIR . BARRA_SERVIDOR . $new_relative_path . BARRA_SERVIDOR . $new_file_name . "." . $file_extension)) {
            print "Error, no ha sido posible la copia del archivo";
        } else {
            //borro el archivo temporal
            unlink($arr_file_desc['tmp_name']);
        }
    } else {
        header('Content-type: application/json');
        //objeto json que devolverá la respuesta
        $jsondata = array();
        $jsondata['error'] = true;
        $jsondata['msg'] = "No se ha podido subir el archivo, intentelo de nuevo o contacte con su administrador.";
        echo json_encode($jsondata);
        exit;
    }
    $new_file_path = $new_relative_path . BARRA_SERVIDOR . $new_file_name . "." . $file_extension;
    $origen_dir = UPLOAD_DIR . BARRA_SERVIDOR . substr($new_file_path, 0, strrpos($new_file_path, BARRA_SERVIDOR)) . BARRA_SERVIDOR;
    $nombre_archivo = substr($new_file_path, strrpos($new_file_path, BARRA_SERVIDOR) + 1);
    $nombre_sin_extension = substr($nombre_archivo, 0, strrpos($nombre_archivo, "."));
    $extension = substr($new_file_path, strrpos($new_file_path, ".") + 1);
    //si es una imagen, creo una más pequeña para agilizar la carga con thumbnails
    if ($extension == "jpg" || $extension == "gif" || $extension == "png") {
        //$info = getimagesize ($new_file_path);
        img_resize($origen_dir . $nombre_archivo, THUMBNAIL_WIDTH, $origen_dir, $nombre_sin_extension . "." . $extension, THUMBNAIL_HEIGHT);
    }
    // Devuelvo la ruta sin la carpeta padre por si se cambia en la configuracion
    return $new_file_path;
}
Ejemplo n.º 16
0
 /**
  * Construct the Translation handler
  * Extract string from the translation file
  * 
  * @param TranslationLanguage $a_language
  * @throws GenericException If the file is inexistant or invalid
  */
 public function __construct(TranslationLanguage $a_language)
 {
     $this->language = $a_language;
     $this->locale = new TranslationLocale($this->language);
     if (file_exists($this->language->file_path)) {
         if (file_extension($this->language->file_path) != "json") {
             throw new GenericException("Invalid File");
         }
     } else {
         throw new GenericException("Inexistant File");
     }
 }
Ejemplo n.º 17
0
 function upload($input_name, $destination_name, $allowed_filetypes)
 {
     $ret = TRUE;
     if ($ret && !is_writeable(dirname($destination_name))) {
         $ret = FALSE;
     }
     $filetype = file_extension($_FILES[$input_name]['name']);
     if ($ret && !in_array($filetype, $allowed_filetypes)) {
         $ret = FALSE;
     }
     if ($ret && !@move_uploaded_file($_FILES[$input_name]['tmp_name'], $destination_name)) {
         $ret = FALSE;
     }
     return $ret;
 }
Ejemplo n.º 18
0
function upload_file_ftp($host, $name, $pass, $var, $upload_path, $file_name_prefix)
{
    if (isset($_FILES[$var]) && $_FILES[$var]['error'] == UPLOAD_ERR_OK && is_file_type('firmware', $_FILES[$var]['name'])) {
        $ext = file_extension($_FILES[$var]['name']);
        if ($ext == 'jpeg') {
            $ext = 'jpg';
        }
        $conn_id = ftp_connect($host);
        $login_result = ftp_login($conn_id, $name, $pass);
        ftp_pasv($conn_id, true);
        if (ftp_put($conn_id, $upload_path . $file_name_prefix . '.' . $ext, $_FILES[$var]['tmp_name'], FTP_BINARY)) {
            ftp_quit($conn_id);
            return $file_name_prefix . '.' . $ext;
        }
    }
    return '';
}
	function getHTML ($attr) {
		if ($this->fname == '')
			return '';
		$ext = strtolower(file_extension($this->fname));
		$appletdir = $this->dir()."/".file_strip_extension($this->fname);
		$appleturl = dirname($this->url())."/".file_strip_extension($this->fname);
		recursive_mkdir($appletdir);
		if ($ext == 'jar' || $ext == 'zip') {
			$cwd = getcwd();
			chdir($appletdir);
			if ($ext == 'zip')
				RunTool('unzip', "IN=".$this->path(), 'pipe');
			else
				RunTool('unzip', "IN=".$this->path()." FILE=index.html", 'pipe');
			$ok = $this->readHTMLFile('index.html');
			chdir($cwd);
			if (!$ok)
				return '';
		}
		if (!isset($this->attribs['archive']))
			return '';

		// generate html file containing the applet
		$ret = "<html><body>\n";
		$ret.= '<div style="margin:0;padding:0"><applet';
		foreach ($this->attribs as $k=>$v)
			$ret .= " $k=\"$v\"";
		$ret .= ">\n";
		foreach ($this->params as $k=>$v)
			$ret .= "<param name=\"$k\" value=\"$v\"/>\n";
		$ret .= "</applet></div>";
		$ret .= "</body></html>";
		$f = fopen("$appletdir/applet.html", "w");
		fputs($f, $ret);
		fclose($f);

		// return iframe with above applet page
		$ret = "<iframe src='$appleturl/applet.html'";
		$ret.= " scrolling='no' frameborder='0' marginwidth='0' marginheight='0'";
		$ret.= "	width='{$this->attribs['width']}' height='{$this->attribs['height']}'>\n";
		$ret.= "<p>Your browser doesn't support embedded frames</p>\n";
		$ret.= "</iframe>";
		return $ret;
	}
Ejemplo n.º 20
0
 /**
  * Recursieve functie die een map incl. submappen doorzoek naar *.js bestanden
  *
  * @return array
  */
 function minifyAppendFiles(&$files, $path, $targetPrefix, $pathSuffix = '')
 {
     $dir = new \DirectoryIterator($path . $pathSuffix);
     foreach ($dir as $entry) {
         if (substr($entry->getFilename(), 0, 1) == '.') {
             continue;
         }
         if ($entry->isDir()) {
             minifyAppendFiles($files, $path, $targetPrefix, $pathSuffix . $entry->getFilename() . '/');
         } else {
             $extension = strtolower(file_extension($entry->getFilename()));
             if (in_array($extension, array('js', 'css', 'png', 'jpeg', 'jpg'))) {
                 $files[$targetPrefix . substr($entry->getPathname(), strlen($path))] = $entry->getPathname();
                 // Add file (or overrule from app/public/)
             }
         }
     }
     return $files;
 }
Ejemplo n.º 21
0
function mime_from_path($path)
{
    $result = FALSE;
    if ($path) {
        $extension = strtolower(file_extension($path));
        if ($extension) {
            $result = mime_from_extension($extension);
            if (!$result) {
                if (function_exists('mime_content_type')) {
                    $result = @mime_content_type($path);
                }
            }
            if (!$result) {
                $result = mime_type_of_file($path);
            }
        }
    }
    return $result;
}
Ejemplo n.º 22
0
 static function list_content($directory, $filter = "", $exclude = "")
 {
     if (substr($directory, -1) != '/') {
         $directory .= "/";
     }
     $excludeAlways = array(".", "..", "index.php", "Thumbs.db");
     $arrFilter = array();
     $arrExclude = array();
     $results = array();
     if (strlen($filter)) {
         $arrFilter = explode(' ', $filter);
     }
     if (strlen($exclude)) {
         $arrExclude = explode(' ', $exclude);
     }
     $handler = opendir($directory);
     while ($filename = readdir($handler)) {
         if ($arrFilter) {
             if (!in_array(file_extension($filename), $arrFilter)) {
                 continue;
             }
         }
         if ($arrExclude) {
             if (in_array(file_extension($filename), $arrExclude)) {
                 continue;
             }
         }
         $filenamepath = $directory . $filename;
         if (!in_array($filename, $excludeAlways)) {
             if (is_dir($directory . $filename . '/')) {
                 $results[0][] = $filename;
             } else {
                 $filename_stats = stat($filenamepath);
                 $results[1][] = array($filename, nice_size($filename_stats[7]), date('l, F dS 20y - H:i:s', $filename_stats[8]), date('l, F dS 20y - H:i:s', $filename_stats[9]), $filename_stats);
             }
         }
     }
     closedir($handler);
     return $results;
 }
Ejemplo n.º 23
0
 static function minify($contents, $filename)
 {
     mkdirs(TMP_DIR . 'ImageMin/');
     $extension = strtolower(file_extension($filename));
     $tmpFile = TMP_DIR . 'ImageMin/' . basename($filename);
     file_put_contents($tmpFile, $contents);
     if ($extension == 'png') {
         if (self::minifyPNG($tmpFile) === false) {
             return false;
         }
     } elseif (in_array($extension, array('jpg', 'jpeg'))) {
         if (self::minifyJPEG($tmpFile) === false) {
             return false;
         }
     } else {
         notice('Filetype: "' . $extension . '" not supported', $filename);
         return false;
     }
     $output = file_get_contents($tmpFile);
     unlink($tmpFile);
     return $output;
 }
 function upload_file()
 {
     if (!isset($this->file) || is_null($this->file['tmp_name']) || $this->file['name'] == '') {
         //Check File //Chequea sl archivo
         //$this->file['name']=$defecto;// = "Archivo no fue subido";
         $this->ErrorMsg = "Archivo no fue subido";
         return false;
     }
     if ($this->file['size'] > $this->maxsize) {
         //Check Size
         $this->ErrorMsg = "El Archivo Excede el Tamaño permitido de {$this->maxsize} bytes";
         return false;
     }
     if (count($this->allowtypes) > 0 && !in_array($this->file['type'], $this->allowtypes) || count($this->deniedtypes) > 0 && in_array($this->file['type'], $this->deniedtypes)) {
         //Check Type //Chequea el tipo de archivo
         $this->ErrorMsg = "Tipo de Archivo '." . file_extension($this->file['name']) . " -- {$this->file['type']}' No Permitido.";
         return false;
     }
     if (!$this->newfile) {
         $this->newfile = substr(basename($this->file['name']), 0, strrpos($this->file['name'], '.'));
     }
     //No new name specified, default to old name
     $uploaddirtemp = upload_dir($this->uploaddir);
     //Create Upload Dir
     move_uploaded_file($this->file['tmp_name'], $uploaddirtemp . $this->newfile . "." . file_extension($this->file['name']));
     //Move Uploaded File
     if ($maxwidth == "" && ($maxheight = "")) {
         //No need to resize the image, user did not specify to reszie
         $this->final = "." . $this->uploaddir . $this->newfile . "." . file_extension($this->file['name']);
         return true;
     }
     //User is going to resize the image
     resize_image("." . $this->uploaddir . $this->newfile . "." . file_extension($this->file['name']), $this->maxwidth, $this->maxheight, $this->scale, $this->relscale, $this->jpegquality);
     $this->final = "." . $this->uploaddir . $this->newfile . "." . file_extension($this->file['name']);
     return true;
     //Hooray!
 }
Ejemplo n.º 25
0
/**
* Function ListFiles
* 
*   Creates list of files in a given directory and all its subdirectories.
*
* @param string $dir
* @param string $extension
*
* @return ... returns array with file names
*

====== Additional resources on this function ======

(1) PHP scandir function

(2) http://www.webmaster-talk.com/php-forum/41811-list-files-in-directory-sub-directories.html

>>> The site provides the following function (below), which was slightly modified
   to extract only files with specified extension

function ListFiles($dir) {

   if($dh = opendir($dir)) {

       $files = Array();
       $inner_files = Array();

       while($file = readdir($dh)) {
           if($file != "." && $file != ".." && $file[0] != '.') {
               if(is_dir($dir . "/" . $file)) {
                   $inner_files = ListFiles($dir . "/" . $file);
                   if(is_array($inner_files)) $files = array_merge($files, $inner_files); 
               } else {
                   array_push($files, $dir . "/" . $file);
               }
           }
       }

       closedir($dh);
       return $files;
   }
}


====== Usage example: looping through all XML files ======

foreach (list_files('/home', 'xml') as $key=>$file){
   echo $file ."<br />";
}
*
*
*/
function list_files($dir, $extension)
{
    if ($dh = opendir($dir)) {
        $files = array();
        $inner_files = array();
        while ($file = readdir($dh)) {
            if ($file != "." && $file != ".." && $file[0] != '.') {
                if (is_dir($dir . DIRECTORY_SEPARATOR . $file)) {
                    $inner_files = list_files($dir . DIRECTORY_SEPARATOR . $file, $extension);
                    if (is_array($inner_files)) {
                        $files = array_merge($files, $inner_files);
                    }
                } else {
                    if (file_extension($file) == $extension) {
                        //add files with the specified extension
                        array_push($files, $dir . DIRECTORY_SEPARATOR . $file);
                    }
                }
            }
        }
        closedir($dh);
        return $files;
    }
}
Ejemplo n.º 26
0
 /**
  * return the file extension
  *
  * @return string
  */
 public function getExtension()
 {
     return strtolower(file_extension($this->file_name));
 }
Ejemplo n.º 27
0
 if ($limitlower <= 0) {
     $limitlower = 1;
 }
 // Get attachment info
 $attachments = $db->query_read_slave("\n\t\t\tSELECT thread.forumid, post.postid, post.threadid AS p_threadid, post.title AS p_title, post.dateline AS p_dateline, attachment.attachmentid,\n\t\t\t\tthread.title AS t_title, attachment.filename, attachment.counter, attachment.filesize AS size, IF(thumbnail_filesize > 0, 1, 0) AS hasthumbnail,\n\t\t\t\tthumbnail_filesize, user.username, thread.open, attachment.userid " . iif($userid == $vbulletin->userinfo['userid'], ", IF(attachment.postid = 0, 1, 0) AS inprogress") . ",\n\t\t\t\tattachment.dateline, attachment.thumbnail_dateline\n\t\t\tFROM " . TABLE_PREFIX . "attachment AS attachment\n\t\t\tLEFT JOIN " . TABLE_PREFIX . "post AS post ON (post.postid = attachment.postid)\n\t\t\tLEFT JOIN " . TABLE_PREFIX . "thread AS thread ON (post.threadid = thread.threadid)\n\t\t\tLEFT JOIN " . TABLE_PREFIX . "user AS user ON (attachment.userid = user.userid)\n\t\t\tWHERE attachment.userid = {$userid}\n\t\t\t\tAND ((forumid IN (0{$forumids}) AND thread.visible = 1 AND post.visible = 1) " . iif($userid == $vbulletin->userinfo['userid'], "OR attachment.postid = 0") . ")\n\t\t\tORDER BY attachment.attachmentid DESC\n\t\t\tLIMIT " . ($limitlower - 1) . ", {$perpage}\n\t\t");
 $template['attachmentlistbits'] = '';
 while ($post = $db->fetch_array($attachments)) {
     $post['filename'] = htmlspecialchars_uni($post['filename']);
     if (!$post['p_title']) {
         $post['p_title'] = '&laquo;' . $vbphrase['n_a'] . '&raquo;';
     }
     $post['counter'] = vb_number_format($post['counter']);
     $post['size'] = vb_number_format($post['size'], 1, true);
     $post['postdate'] = vbdate($vbulletin->options['dateformat'], $post['p_dateline'], true);
     $post['posttime'] = vbdate($vbulletin->options['timeformat'], $post['p_dateline']);
     $post['attachmentextension'] = strtolower(file_extension($post['filename']));
     $show['thumbnail'] = iif($post['hasthumbnail'] == 1 and $vbulletin->options['attachthumbs'] and $showthumbs, 1, 0);
     $show['inprogress'] = iif(!$post['postid'], true, false);
     $show['deletebox'] = false;
     if ($post['inprogress']) {
         $show['deletebox'] = true;
     } else {
         if ($post['open'] or $vbulletin->options['allowclosedattachdel'] or can_moderate($post['forumid'], 'canopenclose')) {
             if (can_moderate($post['forumid'], 'caneditposts')) {
                 $show['deletebox'] = true;
             } else {
                 $forumperms = fetch_permissions($post['forumid']);
                 if ($forumperms & $vbulletin->bf_ugp_forumpermissions['caneditpost'] and $vbulletin->userinfo['userid'] == $post['userid']) {
                     if ($vbulletin->options['allowattachdel'] or !$vbulletin->options['edittimelimit'] or $post['p_dateline'] >= TIMENOW - $vbulletin->options['edittimelimit'] * 60) {
                         $show['deletebox'] = true;
                     }
Ejemplo n.º 28
0
 function upload_files($type = 'all')
 {
     if (!empty($_FILES) && $this->input->post('token') == md5('unique_salt' . $this->input->post('timestamp'))) {
         $upload_dir = $this->input->post('upload_for');
         if (empty($upload_dir)) {
             $upload_dir = $this->input->get('upload_for');
         }
         $upload_dirs = array('centre', 'child', 'lesson_record_material', 'sow_material', 'app_recommend', 'immunisations');
         if (!in_array($upload_dir, $upload_dirs)) {
             echo json_encode(array('status' => 'False', 'error' => 'Something went Wrong! Please Try again.'));
             return;
         }
         $config['upload_path'] = './uploads/' . $upload_dir . '/';
         switch ($type) {
             case 'images':
                 $config['allowed_types'] = 'jpg|jpeg|gif|png';
                 $config['max_size'] = '51200';
                 break;
             case 'immunisations':
                 $config['allowed_types'] = 'jpg|jpeg|pdf';
                 break;
             default:
                 $config['allowed_types'] = 'jpg|jpeg|gif|png|doc|docx|DOCX|ppt|pptx|xls|XLS|xlsx|XLSX|pdf|PDF|txt|avi|mpeg|swf|zip|mpeg|rv|mov|movie|mpg';
                 $config['max_size'] = '51200';
                 break;
         }
         $file_hash = get_file_name_hash();
         $config['file_name'] = $file_hash;
         //$file_hash;
         $this->load->library('upload', $config);
         if (!$this->upload->do_upload('Filedata')) {
             echo json_encode(array('status' => 'False', 'error' => $this->upload->display_errors()));
         } else {
             //'file_hash' => $file_hash,
             //'file_name' => $_FILES['Filedata']['name'],
             $upload_data = $this->upload->data();
             echo json_encode(array('status' => 'True', 'file_hash' => $file_hash, 'file_name' => $_FILES['Filedata']['name'], 'encoded_file_name' => rawurlencode($upload_data['file_name']), 'file_path' => base_url('uploads/' . $upload_dir . '/' . $upload_data['file_name']), 'image' => in_array(strtolower(file_extension($upload_data['file_name'])), array('jpg', 'jpeg', 'gif', 'png')) ? 'true' : 'false'));
         }
     } else {
         echo json_encode(array('status' => 'False', 'error' => 'Something went Wrong! Please Try again.'));
     }
 }
Ejemplo n.º 29
0
 /**
  *	Parses the appropriate template for contenttype that is to be updated on the calling window during an upload
  *
  * @param	array	Attachment information
  * @param	array	Values array pertaining to contenttype
  * @param	boolean	Disable template comments
  *
  * @return	string
  */
 public function process_display_template($attach, $values = array(), $disablecomment = true)
 {
     $attach['extension'] = strtolower(file_extension($attach['filename']));
     $attach['filename'] = fetch_censored_text(htmlspecialchars_uni($attach['filename'], false));
     $attach['filesize'] = vb_number_format($attach['filesize'], 1, true);
     $attach['imgpath'] = $this->fetch_imgpath($attach['extension']);
     $templater = vB_Template::create('newpost_attachmentbit');
     $templater->register('attach', $attach);
     return $templater->render($disablecomment);
 }
Ejemplo n.º 30
0
/**
 * Detect MIME Content-type for a file
 *
 * @param string $filename Path to the tested file.
 * @return string
 */
function file_mime_content_type($filename)
{
    $ext = file_extension($filename);
    /* strtolower isn't necessary */
    if ($mime = mime_type($ext)) {
        return $mime;
    } elseif (function_exists('finfo_open')) {
        $finfo = finfo_open(FILEINFO_MIME);
        $mime = finfo_file($finfo, $filename);
        finfo_close($finfo);
        return $mime;
    } else {
        return 'application/octet-stream';
    }
}