public function compileLess($inputFile, $outputFile) { if (!class_exists('lessc')) { require_once KPATH_FRAMEWORK . '/external/lessc/lessc.php'; } // Load the cache. $cacheDir = JPATH_CACHE . '/kunena'; if (!is_dir($cacheDir)) { KunenaFolder::create($cacheDir); } $cacheFile = "{$cacheDir}/kunena.bootstrap.{$inputFile}.cache"; if (is_file($cacheFile)) { $cache = unserialize(file_get_contents($cacheFile)); } else { $cache = KPATH_MEDIA . '/less/bootstrap/' . $inputFile; } $outputFile = KPATH_MEDIA . '/css/joomla25/' . $outputFile; $less = new lessc(); //$less->setVariables($this->style_variables); $newCache = $less->cachedCompile($cache); if (!is_array($cache) || $newCache['updated'] > $cache['updated'] || !is_file($outputFile)) { $cache = serialize($newCache); KunenaFile::write($cacheFile, $cache); KunenaFile::write($outputFile, $newCache['compiled']); } }
/** * Create index.html file into the given folder, if it doesn't exist. * * @param $folder */ static function createIndex($folder) { // Make sure we have an index.html file in the current folder if (!KunenaFile::exists($folder.'/index.html')) { $contents = '<html><body></body></html>'; KunenaFile::write($folder.'/index.html', $contents); } }
/** * Method to determine if script owns the path. * * @param string $path Path to check ownership. * * @return boolean True if the php script owns the path passed. */ public static function isOwner($path) { if (!self::$owner) { $dir = JFactory::getConfig()->get('tmp_path'); $tmp = 'jj'.md5(mt_rand()); $test = $dir . '/' . $tmp; // Create the test file $content = 'test'; $success = KunenaFile::write($test, $content, false); if (!$success) { return false; } self::$owner = fileowner($test); // Delete the test file KunenaFile::delete($test); } // Test ownership return (self::$owner == fileowner($path)); }
/** * Create new re-sized version of the original image. * * @param string $file Incoming file * @param string $folder Folder for the new image. * @param string $filename Filename for the new image. * @param int $maxWidth Maximum width for the image. * @param int $maxHeight Maximum height for the image. * @param int $quality Quality for the file (1-100). * @param int $scale See available KunenaImage constants. * @param int $crop Define if you want crop the image. * * @return bool True on success. */ public static function version($file, $folder, $filename, $maxWidth = 800, $maxHeight = 800, $quality = 70, $scale = KunenaImage::SCALE_INSIDE, $crop = 0) { try { // Create target directory if it does not exist. if (!KunenaFolder::exists($folder) && !KunenaFolder::create($folder)) { return false; } // Make sure that index.html exists in the folder. KunenaFolder::createIndex($folder); $info = KunenaImage::getImageFileProperties($file); if ($info->width > $maxWidth || $info->height > $maxHeight) { // Make sure that quality is in allowed range. if ($quality < 1 || $quality > 100) { $quality = 70; } // Calculate quality for PNG. if ($info->type == IMAGETYPE_PNG) { $quality = intval(($quality - 1) / 10); } $options = array('quality' => $quality); // Resize image and copy it to temporary file. $image = new KunenaImage($file); if ($crop && $info->width > $info->height) { $image = $image->resize($info->width * $maxHeight / $info->height, $maxHeight, false, $scale); $image = $image->crop($maxWidth, $maxHeight); } elseif ($crop && $info->width < $info->height) { $image = $image->resize($maxWidth, $info->height * $maxWidth / $info->width, false, $scale); $image = $image->crop($maxWidth, $maxHeight); } else { $image = $image->resize($maxWidth, $maxHeight, false, $scale); } $temp = KunenaPath::tmpdir() . '/kunena_' . md5(rand()); $image->toFile($temp, $info->type, $options); unset($image); // Move new file to its proper location. if (!KunenaFile::move($temp, "{$folder}/{$filename}")) { unlink($temp); return false; } } else { // Copy original file to the new location. if (!KunenaFile::copy($file, "{$folder}/{$filename}")) { return false; } } } catch (Exception $e) { return false; } return true; }
public function check() { $user = KunenaUserHelper::get($this->userid); $message = KunenaForumMessageHelper::get($this->mesid); if ($this->userid != 0 && !$user->exists()) { $this->setError(JText::sprintf('COM_KUNENA_LIB_TABLE_ATTACHMENTS_ERROR_USER_INVALID', (int) $user->userid)); } if ($message->id && !$message->exists()) { $this->setError(JText::sprintf('COM_KUNENA_LIB_TABLE_ATTACHMENTS_ERROR_MESSAGE_INVALID', (int) $message->id)); } $this->folder = trim($this->folder, '/'); if (!$this->folder) { $this->setError(JText::_('COM_KUNENA_LIB_TABLE_ATTACHMENTS_ERROR_NO_FOLDER')); } if (!$this->filename) { $this->setError(JText::_('COM_KUNENA_LIB_TABLE_ATTACHMENTS_ERROR_NO_FILENAME')); } if (!$this->filename_real) { $this->filename_real = $this->filename; } $file = JPATH_ROOT . "/{$this->folder}/{$this->filename}"; if (!is_file($file)) { $this->setError(JText::sprintf('COM_KUNENA_LIB_TABLE_ATTACHMENTS_ERROR_FILE_MISSING', "{$this->folder}/{$this->filename}")); } else { if (!$this->hash) { $this->hash = md5_file($file); } if (!$this->size) { $this->size = filesize($file); } if (!$this->filetype) { $this->filetype = KunenaFile::getMime($file); } } return $this->getError() == ''; }
/** * @internal * @since K4.0 */ protected function deleteFile() { if (self::$_directory != substr($this->folder, 0, strlen(self::$_directory))) { return; } $path = JPATH_ROOT . "/{$this->folder}"; $filename = $path . '/' . $this->filename; if (is_file($filename)) { KunenaFile::delete($filename); } $filename = $path . '/raw/' . $this->filename; if (is_file($filename)) { KunenaFile::delete($filename); } $filename = $path . '/thumb/' . $this->filename; if (is_file($filename)) { KunenaFile::delete($filename); } }
/** * Upload file by passing it by HTML input * * @param array $fileInput The file object returned by JInput * @param string $destination The path of destination of file uploaded * @param string $type The type of file uploaded: attachment or avatar * * @return object */ public function upload($fileInput, $destination, $type = 'attachment') { $file = new stdClass(); $file->ext = JFile::getExt($fileInput['name']); $file->size = $fileInput['size']; $file->tmp_name = $fileInput['tmp_name']; $file->error = $fileInput['error']; $file->destination = $destination . '.' . $file->ext; $file->success = false; $file->isAvatar = false; if ($type != 'attachment') { $file->isAvatar = true; } if (!is_uploaded_file($file->tmp_name)) { $exception = $this->checkUpload($fileInput); if ($exception) { throw $exception; } } elseif ($file->error != 0) { throw new RuntimeException(JText::_('COM_KUNENA_UPLOAD_ERROR_NOT_UPLOADED'), 500); } // Check if file extension matches any allowed extensions (case insensitive) foreach ($this->validExtensions as $ext) { $extension = JString::substr($file->tmp_name, -JString::strlen($ext)); if (JString::strtolower($extension) == JString::strtolower($ext)) { // File must contain one letter before extension $name = JString::substr($file->tmp_name, 0, -JString::strlen($ext)); $extension = JString::substr($extension, 1); if (!$name) { throw new RuntimeException(JText::sprintf('COM_KUNENA_UPLOAD_ERROR_EXTENSION_FILE', implode(', ', $this->validExtensions)), 400); } } } if (!$this->checkFileSize($file->size, true)) { if ($file->isAvatar) { throw new RuntimeException(JText::_('COM_KUNENA_UPLOAD_ERROR_AVATAR_EXCEED_LIMIT_IN_CONFIGURATION'), 500); } else { throw new RuntimeException(JText::_('COM_KUNENA_UPLOAD_ERROR_FILE_EXCEED_LIMIT_IN_CONFIGURATION'), 500); } } if (!KunenaFile::copy($file->tmp_name, $file->destination)) { throw new RuntimeException(JText::_('COM_KUNENA_UPLOAD_ERROR_FILE_RIGHT_MEDIA_DIR'), 500); } unlink($file->tmp_name); KunenaPath::setPermissions($file->destination); $file->success = true; return $file; }
/** * Find filename which isn't already taken in the filesystem. * * @param string $folder Relative path from JPATH_ROOT. * @param string $basename Filename without extension. * @param string $extension File extension. * @param bool $protected True to randomize the filename. If not given, uses Kunena configuration setting. * * @return string * * @since K4.0 */ public static function getAvailableFilename($folder, $basename, $extension, $protected = null) { if (is_null($protected)) { $protected = (bool) KunenaConfig::getInstance()->attachment_protection; } if ($protected) { // Ignore proposed filename and return totally random and unique name without file extension. do { $name = md5(rand()); } while (file_exists(JPATH_ROOT . "/{$folder}/{$name}")); return $name; } // Lets find out if we need to rename the filename. $basename = preg_replace('/[[:space:]]/', '', KunenaFile::makeSafe($basename)); $extension = trim($extension, '.'); if (empty($basename)) { $basename = 'file_' . substr(md5(rand()), 2, 7); } $newName = "{$basename}.{$extension}"; $date = date('Y-m-d'); // Rename file if there is already one with the same name if (file_exists(JPATH_ROOT . "/{$folder}/{$newName}")) { $newName = "{$basename}_{$date}.{$extension}"; for ($i = 2; file_exists(JPATH_ROOT . "/{$folder}/{$newName}"); $i++) { $newName = "{$basename}_{$date}-{$i}.{$extension}"; } } return $newName; }
function uploadFile($uploadPath, $input = 'kattachment', $filename = '', $ajax = true) { $this->resetStatus(); // create upload directory if it does not exist if (!JFolder::exists($uploadPath)) { if (!JFolder::create($uploadPath)) { $this->fail(JText::_('COM_KUNENA_UPLOAD_ERROR_CREATE_DIR')); return false; } } KunenaFolder::createIndex($uploadPath); // Get file name and validate with path type $this->fileName = JRequest::getString($input . '_name', '', 'post'); $this->fileSize = 0; $chunk = JRequest::getInt('chunk', 0); $chunks = JRequest::getInt('chunks', 0); if ($chunks && $chunk >= $chunks) { $this->error = JText::_('COM_KUNENA_UPLOAD_ERROR_EXTRA_CHUNK'); } //If uploaded by using normal form (no AJAX) if ($ajax == false || isset($_REQUEST["multipart"])) { $file = JRequest::getVar($input, null, 'files', 'array'); // File upload if (!empty($file['error'])) { // Any errors the server registered on uploading switch ($file['error']) { case 0: // UPLOAD_ERR_OK : break; case 1: // UPLOAD_ERR_INI_SIZE : // UPLOAD_ERR_INI_SIZE : case 2: // UPLOAD_ERR_FORM_SIZE : $this->fail(JText::_('COM_KUNENA_UPLOAD_ERROR_SIZE') . 'DEBUG: file[error]' . htmlspecialchars($file['error'], ENT_COMPAT, 'UTF-8')); break; case 3: // UPLOAD_ERR_PARTIAL : $this->fail(JText::_('COM_KUNENA_UPLOAD_ERROR_PARTIAL')); break; case 4: // UPLOAD_ERR_NO_FILE : $this->fail(JText::_('COM_KUNENA_UPLOAD_ERROR_NO_FILE')); break; case 5: // UPLOAD_ERR_NO_TMP_DIR : $this->fail(JText::_('COM_KUNENA_UPLOAD_ERROR_NO_TMP_DIR')); break; case 7: // UPLOAD_ERR_CANT_WRITE, PHP 5.1.0 $this->fail(JText::_('COM_KUNENA_UPLOAD_ERROR_CANT_WRITE')); break; case 8: // UPLOAD_ERR_EXTENSION, PHP 5.2.0 $this->fail(JText::_('COM_KUNENA_UPLOAD_ERROR_PHP_EXTENSION')); break; default: $this->fail(JText::_('COM_KUNENA_UPLOAD_ERROR_UNKNOWN')); } return false; } elseif (!is_uploaded_file($file['tmp_name'])) { $this->fail(JText::_('COM_KUNENA_UPLOAD_ERROR_NOT_UPLOADED')); return false; } $this->fileTemp = $file['tmp_name']; $this->fileSize = $file['size']; if (!$this->fileName) { // Need to add additonal path type check as array getVar does not $this->fileName = $file['name']; } } else { // Currently not in use: this is meant for experimental AJAX uploads // Open temp file $this->fileTemp = KunenaPath::tmpdir() . '/kunena_' . md5($this->_my->id . '/' . $this->_my->username . '/' . $this->fileName); $out = fopen($this->fileTemp, $chunk == 0 ? "wb" : "ab"); if ($out) { // Read binary input stream and append it to temp file $in = fopen("php://input", "rb"); if ($in) { while (($buff = fread($in, 8192)) != false) { fwrite($out, $buff); } } else { $this->fail(JText::_('COM_KUNENA_UPLOAD_ERROR_NO_INPUT')); } clearstatcache(); $fileInfo = fstat($out); $this->fileSize = $fileInfo['size']; fclose($out); if (!$this->error) { $this->checkFileSize($this->fileSize); } if ($chunk + 1 < $chunks) { $this->status = empty($this->error); return $this->status; } } else { $this->fail(JText::_('COM_KUNENA_UPLOAD_ERROR_CANT_WRITE')); } } // Terminate early if we already hit an error if ($this->error) { return false; } // assume the extension is false until we know its ok $extOk = false; $fileparts = $this->getValidExtension($this->validFileExts); $uploadedFileExtension = ''; if ($fileparts) { $this->_isfile = true; $extOk = true; $uploadedFileBasename = $fileparts[0]; $uploadedFileExtension = $fileparts[1]; } $fileparts = $this->getValidExtension($this->validImageExts); if ($fileparts) { $this->_isimage = true; $extOk = true; $uploadedFileBasename = $fileparts[0]; $uploadedFileExtension = $fileparts[1]; } if ($extOk == false) { $imglist = implode(', ', $this->validImageExts); $filelist = implode(', ', $this->validFileExts); if ($imglist && $filelist) { $this->fail(JText::sprintf('COM_KUNENA_UPLOAD_ERROR_EXTENSION', $imglist, $filelist)); } else { if ($imglist && !$filelist) { $this->fail(JText::sprintf('COM_KUNENA_UPLOAD_ERROR_EXTENSION_FILE', $this->_config->filetypes)); } else { if (!$imglist && $filelist) { $this->fail(JText::sprintf('COM_KUNENA_UPLOAD_ERROR_EXTENSION_IMAGE', $this->_config->imagetypes)); } else { $this->fail(JText::sprintf('COM_KUNENA_UPLOAD_ERROR_NOT_ALLOWED', $filelist)); } } } $this->not_valid_img_ext = false; return false; } // Special processing for images if ($this->_isimage) { $this->imageInfo = CKunenaImageHelper::getProperties($this->fileTemp); // Let see if we need to check the MIME type if ($this->_config->checkmimetypes) { // check against whitelist of MIME types $validFileTypes = explode(",", $this->_config->imagemimetypes); //if the temp file does not have a width or a height, or it has a non ok MIME, return if (!is_int($this->imageInfo->width) || !is_int($this->imageInfo->height) || !in_array($this->imageInfo->mime, $validFileTypes)) { $this->fail(JText::sprintf('COM_KUNENA_UPLOAD_ERROR_MIME', $this->imageInfo->mime, $this->_config->imagetypes)); return false; } } // If image is not inside allowed size limits, resize it if ($this->fileSize > $this->imagesize || $this->imageInfo->width > $this->imagewidth || $this->imageInfo->height > $this->imageheight) { $options = array('quality' => $this->imagequality); $imageRaw = new CKunenaImage($this->fileTemp); if ($imageRaw->getError()) { $this->fail(JText::_($imageRaw->getError())); return false; } $image = $imageRaw->resize($this->imagewidth, $this->imageheight); $type = $imageRaw->getType(); unset($imageRaw); $image->toFile($this->fileTemp, $type, $options); clearstatcache(); // Re-calculate physical file size: image has been shrunk $stat = stat($this->fileTemp); if (!$stat) { $this->fail(JText::_('COM_KUNENA_UPLOAD_ERROR_STAT', htmlspecialchars($this->fileTemp, ENT_COMPAT, 'UTF-8'))); return false; } $this->fileSize = $stat['size']; } } $this->checkFileSize($this->fileSize); // Check again for error and terminate early if we already hit an error if ($this->error) { return false; } // Populate hash, file size and other info // Get a hash value from the file $this->fileHash = md5_file($this->fileTemp); // Override filename if given in the parameter if ($filename) { $uploadedFileBasename = $filename; } $uploadedFileBasename = KunenaFile::makeSafe($uploadedFileBasename); if (empty($uploadedFileBasename)) { $uploadedFileBasename = 'h' . substr($this->fileHash, 2, 7); } // Rename file if there is already one with the same name $newFileName = $uploadedFileBasename . "." . $uploadedFileExtension; $newFileName = preg_replace('/[[:space:]]/', '', $newFileName); $uploadedFileBasename = preg_replace('/[[:space:]]/', '', $uploadedFileBasename); if (file_exists($uploadPath . '/' . $newFileName)) { $newFileName = $uploadedFileBasename . "." . $uploadedFileExtension; for ($i = 2; file_exists("{$uploadPath}/{$newFileName}"); $i++) { $newFileName = $uploadedFileBasename . "-{$i}." . $uploadedFileExtension; } } $this->fileName = $newFileName; // All the processing is complete - now we need to move the file(s) into the final location @chmod($this->fileTemp, 0644); if (!JFile::copy($this->fileTemp, $uploadPath . '/' . $this->fileName)) { $this->fail(JText::sprintf('COM_KUNENA_UPLOAD_ERROR_NOT_MOVED', htmlspecialchars($uploadPath . '/' . $this->fileName, ENT_COMPAT, 'UTF-8'))); unlink($this->fileTemp); return false; } unlink($this->fileTemp); JPath::setPermissions($uploadPath . '/' . $this->fileName); $this->ready = true; return $this->status = true; }
public static function version($file, $newpath, $newfile, $maxwidth = 800, $maxheight = 800, $quality = 70, $scale = CKunenaImage::SCALE_INSIDE) { require_once KPATH_SITE . '/lib/kunena.file.class.php'; // create upload directory if it does not exist $imageinfo = self::getProperties($file); if (!$imageinfo) { return false; } if (!JFolder::exists($newpath)) { if (!JFolder::create($newpath)) { return false; } } KunenaFolder::createIndex($newpath); if ($imageinfo->width > $maxwidth || $imageinfo->height > $maxheight) { $image = new CKunenaImage($file); if ($image->getError()) { return false; } if ($quality < 1 || $quality > 100) { $quality = 70; } $options = array('quality' => $quality); $image = $image->resize($maxwidth, $maxheight, true, $scale); $type = $image->getType(); $temp = KunenaPath::tmpdir() . '/kunena_' . md5(rand()); $image->toFile($temp, $type, $options); unset($image); if (!KunenaFile::move($temp, $newpath . '/' . $newfile)) { unlink($temp); return false; } } else { if (!KunenaFile::copy($file, $newpath . '/' . $newfile)) { return false; } } return true; }
function compileLess($inputFile, $outputFile) { if (!class_exists('lessc')) { require_once KPATH_FRAMEWORK . '/external/lessc/lessc.php'; } // Load the cache. $cacheDir = JPATH_CACHE . '/kunena'; if (!is_dir($cacheDir)) { KunenaFolder::create($cacheDir); } $cacheFile = "{$cacheDir}/kunena.{$this->name}.{$inputFile}.cache"; if (is_file($cacheFile)) { $cache = unserialize(file_get_contents($cacheFile)); } else { $cache = JPATH_SITE . '/' . $this->getFile($inputFile, false, 'less'); } $outputDir = KPATH_MEDIA . "/cache/{$this->name}/css"; if (!is_dir($outputDir)) { KunenaFolder::create($outputDir); } $outputFile = "{$outputDir}/{$outputFile}"; $less = new lessc(); $class = $this; $less->registerFunction('url', function ($arg) use($class) { list($type, $q, $values) = $arg; $value = reset($values); return "url({$q}{$class->getFile($value, true, 'media', 'media/kunena')}{$q})"; }); $less->setVariables($this->style_variables); $newCache = $less->cachedCompile($cache); if (!is_array($cache) || $newCache['updated'] > $cache['updated'] || !is_file($outputFile)) { $cache = serialize($newCache); KunenaFile::write($cacheFile, $cache); KunenaFile::write($outputFile, $newCache['compiled']); } }
/** * Delete previoulsy uplaoded avatars from filesystem * * @return void */ protected function deleteOldAvatars() { if (preg_match('|^users/|', $this->me->avatar)) { // Delete old uploaded avatars: if (is_dir(KPATH_MEDIA . '/avatars/resized')) { $deletelist = KunenaFolder::folders(KPATH_MEDIA . '/avatars/resized', '.', false, true); foreach ($deletelist as $delete) { if (is_file($delete . '/' . $this->me->avatar)) { KunenaFile::delete($delete . '/' . $this->me->avatar); } } } if (is_file(KPATH_MEDIA . '/avatars/' . $this->me->avatar)) { KunenaFile::delete(KPATH_MEDIA . '/avatars/' . $this->me->avatar); } } }
/** * Method to save param.ini file on filesystem. * * @param string $template The name of the template. * * * @since 3.0.0 */ protected function _saveParamFile($template) { $params = $this->app->input->get('jform', array(), 'post', 'array'); // Set FTP credentials, if given JClientHelper::setCredentialsFromRequest('ftp'); $ftp = JClientHelper::getCredentials('ftp'); $file = KPATH_SITE . '/template/' . $template . '/params.ini'; if (count($params)) { $registry = new JRegistry(); $registry->loadArray($params); $txt = $registry->toString('INI'); $return = KunenaFile::write($file, $txt); if (!$return) { $this->app->enqueueMessage(JText::_('COM_KUNENA_A_TEMPLATE_MANAGER_OPERATION_FAILED') . ': ' . JText::sprintf('COM_KUNENA_A_TEMPLATE_MANAGER_FAILED_WRITE_FILE', $file)); $this->app->redirect(KunenaRoute::_($this->baseurl, false)); } } }