/** * doExecute * * @return mixed */ protected function doExecute() { $xml = $this->config['dest'] . '/{{extension.name.lower}}.xml'; $content = file_get_contents($xml); $content = str_replace('client="site"', '{{module.client}}', $content); File::write($content, $xml); }
/** * copyFile * * @param string $src * @param string $dest * @param array $replace * * @return void */ protected function copyFile($src, $dest, $replace = array()) { // Replace dest file name. $dest = strtr($dest, $replace); if (is_file($dest)) { $this->io->out('File exists: ' . $dest); } else { $content = strtr(file_get_contents($src), $replace); if (File::write($dest, $content)) { $this->io->out('File created: ' . $dest); } } }
/** * Test move method * * @return void * * @covers Joomla\Filesystem\File::move * @since 1.0 */ public function testMove() { $name = 'tempFile'; $path = __DIR__; $movedFileName = 'movedTempFile'; $data = 'Lorem ipsum dolor sit amet'; // Create a temp file to test copy operation $this->object->write($path . '/' . $name, $data); $this->assertThat(File::move($path . '/' . $name, $path . '/' . $movedFileName), $this->isTrue(), 'Line:' . __LINE__ . ' File should be moved successfully.'); $this->assertThat(File::move($movedFileName, $name, $path), $this->isTrue(), 'Line:' . __LINE__ . ' File should be moved successfully.'); // Using streams. $this->assertThat(File::move($name, $movedFileName, $path, true), $this->isTrue(), 'Line:' . __LINE__ . ' File should be moved successfully.'); File::delete($path . '/' . $movedFileName); }
/** * Extract a Bzip2 compressed file to a given path * * @param string $archive Path to Bzip2 archive to extract * @param string $destination Path to extract archive to * * @return boolean True if successful * * @since 1.0 * @throws \RuntimeException */ public function extract($archive, $destination) { $this->data = null; if (!isset($this->options['use_streams']) || $this->options['use_streams'] == false) { // Old style: read the whole file and then parse it $this->data = file_get_contents($archive); if (!$this->data) { throw new \RuntimeException('Unable to read archive'); } $buffer = bzdecompress($this->data); unset($this->data); if (empty($buffer)) { throw new \RuntimeException('Unable to decompress data'); } if (File::write($destination, $buffer) === false) { throw new \RuntimeException('Unable to write archive'); } } else { // New style! streams! $input = Stream::getStream(); // Use bzip $input->set('processingmethod', 'bz'); if (!$input->open($archive)) { throw new \RuntimeException('Unable to read archive (bz2)'); } $output = Stream::getStream(); if (!$output->open($destination, 'w')) { $input->close(); throw new \RuntimeException('Unable to write archive (bz2)'); } do { $this->data = $input->read($input->get('chunksize', 8196)); if ($this->data) { if (!$output->write($this->data)) { $input->close(); throw new \RuntimeException('Unable to write archive (bz2)'); } } } while ($this->data); $output->close(); $input->close(); } return true; }
/** * Method to get the list of files for the field options. * Specify the target directory with a directory attribute * Attributes allow an exclude mask and stripping of extensions from file name. * Default attribute may optionally be set to null (no file) or -1 (use a default). * * @return array The field option objects. * * @since 1.0 */ protected function getOptions() { $options = array(); // Initialize some field attributes. $filter = (string) $this->element['filter']; $exclude = (string) $this->element['exclude']; $stripExt = (string) $this->element['stripext']; $hideNone = (string) $this->element['hide_none']; $hideDefault = (string) $this->element['hide_default']; // Get the path in which to search for file options. $path = (string) $this->element['directory']; if (!is_dir($path)) { $path = JPATH_ROOT . '/' . $path; } // Prepend some default options based on field attributes. if (!$hideNone) { $options[] = HtmlSelect::option('-1', Text::alt('JOPTION_DO_NOT_USE', preg_replace('/[^a-zA-Z0-9_\\-]/', '_', $this->fieldname))); } if (!$hideDefault) { $options[] = HtmlSelect::option('', Text::alt('JOPTION_USE_DEFAULT', preg_replace('/[^a-zA-Z0-9_\\-]/', '_', $this->fieldname))); } // Get a list of files in the search path with the given filter. $files = Folder::files($path, $filter); // Build the options list from the list of files. if (is_array($files)) { foreach ($files as $file) { // Check to see if the file is in the exclude mask. if ($exclude) { if (preg_match(chr(1) . $exclude . chr(1), $file)) { continue; } } // If the extension is to be stripped, do it. if ($stripExt) { $file = File::stripExt($file); } $options[] = HtmlSelect::option($file, $file); } } // Merge any additional options in the XML definition. $options = array_merge(parent::getOptions(), $options); return $options; }
/** * Extract a Gzip compressed file to a given path * * @param string $archive Path to ZIP archive to extract * @param string $destination Path to extract archive to * * @return boolean True if successful * * @since 1.0 * @throws \RuntimeException */ public function extract($archive, $destination) { $this->data = null; if (!isset($this->options['use_streams']) || $this->options['use_streams'] == false) { $this->data = file_get_contents($archive); if (!$this->data) { throw new \RuntimeException('Unable to read archive'); } $position = $this->getFilePosition(); $buffer = gzinflate(substr($this->data, $position, strlen($this->data) - $position)); if (empty($buffer)) { throw new \RuntimeException('Unable to decompress data'); } if (File::write($destination, $buffer) === false) { throw new \RuntimeException('Unable to write archive'); } } else { // New style! streams! $input = Stream::getStream(); // Use gz $input->set('processingmethod', 'gz'); if (!$input->open($archive)) { throw new \RuntimeException('Unable to read archive (gz)'); } $output = Stream::getStream(); if (!$output->open($destination, 'w')) { $input->close(); throw new \RuntimeException('Unable to write archive (gz)'); } do { $this->data = $input->read($input->get('chunksize', 8196)); if ($this->data) { if (!$output->write($this->data)) { $input->close(); throw new \RuntimeException('Unable to write file (gz)'); } } } while ($this->data); $output->close(); $input->close(); } return true; }
public function deleteOldAvatar($item_id, $item_type) { $avatar = $this->getAvatar($item_id, $item_type); if ($avatar) { echo JPATH_SITE . '/src/Cobalt/media/avatars/' . $avatar; File::delete(JPATH_SITE . '/src/Cobalt/media/avatars/' . $avatar); } }
/** * Extract a ZIP compressed file to a given path using native php api calls for speed * * @param string $archive Path to ZIP archive to extract * @param string $destination Path to extract archive into * * @return boolean True on success * * @since 11.1 * @throws RuntimeException */ protected function extractNative($archive, $destination) { $zip = zip_open($archive); if (is_resource($zip)) { // Make sure the destination folder exists if (!Folder::create($destination)) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to create destination'); } else { throw new RuntimeException('Unable to create destination'); } } // Read files in the archive while ($file = @zip_read($zip)) { if (zip_entry_open($zip, $file, "r")) { if (substr(zip_entry_name($file), strlen(zip_entry_name($file)) - 1) != "/") { $buffer = zip_entry_read($file, zip_entry_filesize($file)); if (File::write($destination . '/' . zip_entry_name($file), $buffer) === false) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to write entry'); } else { throw new RuntimeException('Unable to write entry'); } } zip_entry_close($file); } } else { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to read entry'); } else { throw new RuntimeException('Unable to read entry'); } } } @zip_close($zip); } else { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to open archive'); } else { throw new RuntimeException('Unable to open archive'); } } return true; }
public function store() { //Load Tables $app = \Cobalt\Container::fetch('app'); $row = new BrandingTable(); $data = $app->input->getRequest('post'); //date generation $date = DateHelper::formatDBDate(date('Y-m-d H:i:s')); $data['modified'] = $date; $this->changeDefault($data['id']); $fieldName = 'site_logo'; //any errors the server registered on uploading $fileError = $_FILES[$fieldName]['error']; if ($fileError > 0) { unset($data['site_logo']); } else { //check the file extension is ok $fileName = $_FILES[$fieldName]['name']; $fileTemp = $_FILES[$fieldName]['tmp_name']; $uploadedFileNameParts = explode('.', $fileName); $uploadedFileExtension = array_pop($uploadedFileNameParts); $validFileExts = explode(',', 'jpeg,jpg,png,gif,pdf,doc,docx,odt,rtf,ppt,xls,txt'); //assume the extension is false until we know its ok $extOk = false; //go through every ok extension, if the ok extension matches the file extension (case insensitive) //then the file extension is ok foreach ($validFileExts as $key => $value) { if (preg_match("/{$value}/i", $uploadedFileExtension)) { $extOk = true; } } if ($extOk == false) { echo TextHelper::_('INVALID EXTENSION'); return; } //data generation $hashFilename = md5($fileName . $date) . "." . $uploadedFileExtension; //lose any special characters in the filename //$fileName = preg_replace("[^A-Za-z0-9.]", "-", $fileName); //always use constants when making file paths, to avoid the possibilty of remote file inclusion $uploadPath = JPATH_SITE . '/src/Cobalt/media/logos/' . $hashFilename; if (!File::upload($fileTemp, $uploadPath)) { echo TextHelper::_('ERROR MOVING FILE'); return; } $fileSize = filesize($uploadPath); $this->updateSiteLogo($hashFilename); unset($data['site_logo']); } // Bind the form fields to the table if (!$row->bind($data)) { $this->setError($this->db->getErrorMsg()); return false; } // Make sure the record is valid if (!$row->check()) { $this->setError($this->db->getErrorMsg()); return false; } // Store the web link table to the database if (!$row->store()) { $this->setError($this->db->getErrorMsg()); return false; } return true; }
/** * Extract an archive file to a directory. * * @param string $archivename The name of the archive file * @param string $extractdir Directory to unpack into * * @return boolean True for success * * @since 11.1 * @throws InvalidArgumentException */ public static function extract($archivename, $extractdir) { $untar = false; $result = false; $ext = File::getExt(strtolower($archivename)); // Check if a tar is embedded...gzip/bzip2 can just be plain files! if (File::getExt(File::stripExt(strtolower($archivename))) == 'tar') { $untar = true; } switch ($ext) { case 'zip': $adapter = self::getAdapter('zip'); if ($adapter) { $result = $adapter->extract($archivename, $extractdir); } break; case 'tar': $adapter = self::getAdapter('tar'); if ($adapter) { $result = $adapter->extract($archivename, $extractdir); } break; case 'tgz': // This format is a tarball gzip'd $untar = true; case 'gz': case 'gzip': // This may just be an individual file (e.g. sql script) $adapter = self::getAdapter('gzip'); if ($adapter) { $config = Factory::getConfig(); $tmpfname = $config->get('tmp_path') . '/' . uniqid('gzip'); $gzresult = $adapter->extract($archivename, $tmpfname); if ($gzresult instanceof Exception) { @unlink($tmpfname); return false; } if ($untar) { // Try to untar the file $tadapter = self::getAdapter('tar'); if ($tadapter) { $result = $tadapter->extract($tmpfname, $extractdir); } } else { $path = Path::clean($extractdir); Folder::create($path); $result = File::copy($tmpfname, $path . '/' . File::stripExt(basename(strtolower($archivename))), null, 1); } @unlink($tmpfname); } break; case 'tbz2': // This format is a tarball bzip2'd $untar = true; case 'bz2': case 'bzip2': // This may just be an individual file (e.g. sql script) $adapter = self::getAdapter('bzip2'); if ($adapter) { $config = Factory::getConfig(); $tmpfname = $config->get('tmp_path') . '/' . uniqid('bzip2'); $bzresult = $adapter->extract($archivename, $tmpfname); if ($bzresult instanceof Exception) { @unlink($tmpfname); return false; } if ($untar) { // Try to untar the file $tadapter = self::getAdapter('tar'); if ($tadapter) { $result = $tadapter->extract($tmpfname, $extractdir); } } else { $path = Path::clean($extractdir); Folder::create($path); $result = File::copy($tmpfname, $path . '/' . File::stripExt(basename(strtolower($archivename))), null, 1); } @unlink($tmpfname); } break; default: throw new InvalidArgumentException('Unknown Archive Type'); } if (!$result || $result instanceof Exception) { return false; } return true; }
/** * 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. * * @since 11.1 */ public static function isOwner($path) { jimport('joomla.filesystem.file'); $tmp = md5(mt_rand()); $ssp = ini_get('session.save_path'); $jtp = JPATH_SITE . '/tmp'; // Try to find a writable directory $dir = is_writable('/tmp') ? '/tmp' : false; $dir = !$dir && is_writable($ssp) ? $ssp : false; $dir = !$dir && is_writable($jtp) ? $jtp : false; if ($dir) { $test = $dir . '/' . $tmp; // Create the test file $blank = ''; File::write($test, $blank, false); // Test ownership $return = fileowner($test) == fileowner($path); // Delete the test file File::delete($test); return $return; } return false; }
/** * Extract a ZIP compressed file to a given path * * @param string $archive Path to ZIP archive to extract * @param string $destination Path to extract archive into * @param array $options Extraction options [unused] * * @return boolean True if successful * * @throws RuntimeException * @since 11.1 */ public function extract($archive, $destination, array $options = array()) { $this->_data = null; $this->_metadata = null; $this->_data = file_get_contents($archive); if (!$this->_data) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to read archive'); } else { throw new RuntimeException('Unable to read archive'); } } $this->_getTarInfo($this->_data); for ($i = 0, $n = count($this->_metadata); $i < $n; $i++) { $type = strtolower($this->_metadata[$i]['type']); if ($type == 'file' || $type == 'unix file') { $buffer = $this->_metadata[$i]['data']; $path = Path::clean($destination . '/' . $this->_metadata[$i]['name']); // Make sure the destination folder exists if (!Folder::create(dirname($path))) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to create destination'); } else { throw new RuntimeException('Unable to create destination'); } } if (File::write($path, $buffer) === false) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to write entry'); } else { throw new RuntimeException('Unable to write entry'); } } } } return true; }
/** * Extract a Bzip2 compressed file to a given path * * @param string $archive Path to Bzip2 archive to extract * @param string $destination Path to extract archive to * @param array $options Extraction options [unused] * * @return boolean True if successful * * @since 11.1 * @throws RuntimeException */ public function extract($archive, $destination, array $options = array()) { $this->_data = null; if (!extension_loaded('bz2')) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'The bz2 extension is not available.'); } else { throw new RuntimeException('The bz2 extension is not available.'); } } if (!isset($options['use_streams']) || $options['use_streams'] == false) { // Old style: read the whole file and then parse it $this->_data = file_get_contents($archive); if (!$this->_data) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to read archive'); } else { throw new RuntimeException('Unable to read archive'); } } $buffer = bzdecompress($this->_data); unset($this->_data); if (empty($buffer)) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to decompress data'); } else { throw new RuntimeException('Unable to decompress data'); } } if (File::write($destination, $buffer) === false) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to write archive'); } else { throw new RuntimeException('Unable to write archive'); } } } else { // New style! streams! $input = Factory::getStream(); // Use bzip $input->set('processingmethod', 'bz'); if (!$input->open($archive)) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to read archive (bz2)'); } else { throw new RuntimeException('Unable to read archive (bz2)'); } } $output = Factory::getStream(); if (!$output->open($destination, 'w')) { $input->close(); if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to write archive (bz2)'); } else { throw new RuntimeException('Unable to write archive (bz2)'); } } do { $this->_data = $input->read($input->get('chunksize', 8196)); if ($this->_data) { if (!$output->write($this->_data)) { $input->close(); if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to write archive (bz2)'); } else { throw new RuntimeException('Unable to write archive (bz2)'); } } } } while ($this->_data); $output->close(); $input->close(); } return true; }
/** * Extract an archive file to a directory. * * @param string $archivename The name of the archive file * @param string $extractdir Directory to unpack into * * @return boolean True for success * * @since 1.0 * @throws \InvalidArgumentException */ public function extract($archivename, $extractdir) { $ext = pathinfo($archivename, PATHINFO_EXTENSION); $path = pathinfo($archivename, PATHINFO_DIRNAME); $filename = pathinfo($archivename, PATHINFO_FILENAME); switch ($ext) { case 'zip': $result = $this->getAdapter('zip')->extract($archivename, $extractdir); break; case 'tar': $result = $this->getAdapter('tar')->extract($archivename, $extractdir); break; case 'tgz': case 'gz': case 'gzip': // This may just be an individual file (e.g. sql script) $tmpfname = $this->options['tmp_path'] . '/' . uniqid('gzip'); $gzresult = $this->getAdapter('gzip')->extract($archivename, $tmpfname); if ($gzresult instanceof \Exception) { @unlink($tmpfname); return false; } if ($ext === 'tgz' || stripos($filename, '.tar') !== false) { $result = $this->getAdapter('tar')->extract($tmpfname, $extractdir); } else { Folder::create($path); $result = File::copy($tmpfname, $extractdir, null, 0); } @unlink($tmpfname); break; case 'tbz2': case 'bz2': case 'bzip2': // This may just be an individual file (e.g. sql script) $tmpfname = $this->options['tmp_path'] . '/' . uniqid('bzip2'); $bzresult = $this->getAdapter('bzip2')->extract($archivename, $tmpfname); if ($bzresult instanceof \Exception) { @unlink($tmpfname); return false; } if ($ext === 'tbz2' || stripos($filename, '.tar') !== false) { $result = $this->getAdapter('tar')->extract($tmpfname, $extractdir); } else { Folder::create($path); $result = File::copy($tmpfname, $extractdir, null, 0); } @unlink($tmpfname); break; default: throw new \InvalidArgumentException(sprintf('Unknown archive type: %s', $ext)); } if (!$result || $result instanceof \Exception) { return false; } return true; }
/** * Delete a folder. * * @param string $path The path to the folder to delete. * * @return boolean True on success. * * @since 11.1 */ public static function delete($path) { @set_time_limit(ini_get('max_execution_time')); // Sanity check if (!$path) { // Bad programmer! Bad Bad programmer! Log::add(__METHOD__ . ': ' . Text::_('JLIB_FILESYSTEM_ERROR_DELETE_BASE_DIRECTORY'), Log::WARNING, 'jerror'); return false; } $FTPOptions = ClientHelper::getCredentials('ftp'); // Check to make sure the path valid and clean $path = Path::clean($path); // Is this really a folder? if (!is_dir($path)) { Log::add(Text::sprintf('JLIB_FILESYSTEM_ERROR_PATH_IS_NOT_A_FOLDER', $path), Log::WARNING, 'jerror'); return false; } // Remove all the files in folder if they exist; disable all filtering $files = self::files($path, '.', false, true, array(), array()); if (!empty($files)) { jimport('joomla.filesystem.file'); if (File::delete($files) !== true) { // File::delete throws an error return false; } } // Remove sub-folders of folder; disable all filtering $folders = self::folders($path, '.', false, true, array(), array()); foreach ($folders as $folder) { if (is_link($folder)) { // Don't descend into linked directories, just delete the link. jimport('joomla.filesystem.file'); if (File::delete($folder) !== true) { // File::delete throws an error return false; } } elseif (self::delete($folder) !== true) { // JFolder::delete throws an error return false; } } if ($FTPOptions['enabled'] == 1) { // Connect the FTP client $ftp = Ftp::getInstance($FTPOptions['host'], $FTPOptions['port'], array(), $FTPOptions['user'], $FTPOptions['pass']); } // In case of restricted permissions we zap it one way or the other // as long as the owner is either the webserver or the ftp. if (@rmdir($path)) { $ret = true; } elseif ($FTPOptions['enabled'] == 1) { // Translate path and delete $path = Path::clean(str_replace(JPATH_ROOT, $FTPOptions['root'], $path), '/'); // FTP connector throws an error $ret = $ftp->delete($path); } else { Log::add(Text::sprintf('JLIB_FILESYSTEM_ERROR_FOLDER_DELETE', $path), Log::WARNING, 'jerror'); $ret = false; } return $ret; }
/** * Creates the ZIP file. * * Official ZIP file format: http://www.pkware.com/appnote.txt * * @param array &$contents An array of existing zipped files. * @param array &$ctrlDir An array of central directory information. * @param string $path The path to store the archive. * * @return boolean True if successful * * @since 1.0 * @todo Review and finish implementation */ private function createZIPFile(array &$contents, array &$ctrlDir, $path) { $data = implode('', $contents); $dir = implode('', $ctrlDir); $buffer = $data . $dir . $this->ctrlDirEnd . pack('v', count($ctrlDir)) . pack('v', count($ctrlDir)) . pack('V', strlen($dir)) . pack('V', strlen($data)) . ""; if (File::write($path, $buffer) === false) { return false; } else { return true; } }
/** * Method to store a record * * @return boolean True on success */ public function store($data = null) { if ($data) { $data = (array) $data; $_FILES = array(); $_FILES['document'] = $data; $_FILES['tmp_name'] = $data['attachment']; $fileName = $data['value']; $fileTemp = $data['attachment']; $association_id = $data['association_id']; $association_type = $data['association_type']; $uploadedFileExtension = substr(strrchr($fileName, '.'), 1); $data['is_attachment'] = 1; $data['email'] = 1; } else { $association_id = $_POST['association_id']; $association_type = $_POST['association_type']; //this is the name of the field in the html form, filedata is the default name for swfupload //so we will leave it as that $fieldName = 'document'; //any errors the server registered on uploading $fileError = $_FILES[$fieldName]['error']; if ($fileError > 0) { switch ($fileError) { case 1: echo TextHelper::_('FILE TO LARGE THAN PHP INI ALLOWS'); return; case 2: echo TextHelper::_('FILE TO LARGE THAN HTML FORM ALLOWS'); return; case 3: echo TextHelper::_('ERROR PARTIAL UPLOAD'); return; case 4: echo TextHelper::_('ERROR NO FILE'); return; } } //check the file extension is ok $fileName = $_FILES[$fieldName]['name']; $fileTemp = $_FILES[$fieldName]['tmp_name']; } $uploadedFileNameParts = explode('.', $fileName); $uploadedFileExtension = array_pop($uploadedFileNameParts); $validFileExts = explode(',', 'jpeg,jpg,png,gif,pdf,doc,docx,odt,rtf,ppt,xls,txt'); //assume the extension is false until we know its ok $extOk = false; //go through every ok extension, if the ok extension matches the file extension (case insensitive) //then the file extension is ok foreach ($validFileExts as $key => $value) { if (preg_match("/{$value}/i", $uploadedFileExtension)) { $extOk = true; } } if ($extOk == false) { echo TextHelper::_('INVALID EXTENSION'); return; } //data generation $date = DateHelper::formatDBDate(date('Y-m-d H:i:s')); $hashFilename = md5($fileName . $date) . "." . $uploadedFileExtension; //lose any special characters in the filename $fileName = preg_replace("[^A-Za-z0-9.]", "-", $fileName); //always use constants when making file paths, to avoid the possibilty of remote file inclusion $uploadPath = JPATH_SITE . '//documents/' . $hashFilename; if ($data['is_attachment']) { if (!File::write($uploadPath, $fileTemp)) { echo TextHelper::_('ERROR MOVING FILE'); return; } } else { if (!File::upload($fileTemp, $uploadPath)) { echo TextHelper::_('ERROR MOVING FILE'); return; } } $fileSize = filesize($uploadPath); //update the database $newData = array('name' => $fileName, 'filename' => $hashFilename, 'association_id' => $association_id, 'association_type' => $association_type, 'filetype' => $uploadedFileExtension, 'size' => $fileSize / 1024, 'created' => $date); if (array_key_exists('email', $data) && $data['email']) { $newData['email'] = 1; } //Load Tables $row = new DocumentTable(); $oldRow = new DocumentTable(); //date generation $date = DateHelper::formatDBDate(date('Y-m-d H:i:s')); if (!array_key_exists('id', $newData)) { $newData['created'] = $date; $status = "created"; } else { $row->load($data['id']); $oldRow->load($data['id']); $status = "updated"; } $is_image = is_array(getimagesize($uploadPath)) ? true : false; $newData['modified'] = $date; $newData['owner_id'] = UsersHelper::getUserId(); $newData['is_image'] = $is_image; // Bind the form fields to the table if (!$row->bind($newData)) { $this->setError($this->db->getErrorMsg()); return false; } $app = \Cobalt\Container::fetch('app'); //$app->triggerEvent('onBeforeDocumentSave', array(&$row)); // Make sure the record is valid if (!$row->check()) { $this->setError($this->db->getErrorMsg()); return false; } // Store the web link table to the database if (!$row->store()) { $this->setError($this->db->getErrorMsg()); return false; } $id = array_key_exists('id', $data) ? $data['id'] : $this->db->insertId(); ActivityHelper::saveActivity($oldRow, $row, 'document', $status); //$app->triggerEvent('onAfterDocumentSave', array(&$row)); return $id; }
public function uploadLogo() { if ($_FILES['logo']['error']) { return false; } //uploading image $allowedImageTypes = array("image/pjpeg", "image/jpeg", "image/jpg", "image/png", "image/x-png", "image/gif"); if (!in_array($_FILES['logo']['type'], $allowedImageTypes)) { $this->setError(Text::_('INSTL_ERROR_LOGO_FILE_TYPE')); return false; } else { if (!JFile::upload($_FILES['logo']['tmp_name'], JPATH_ROOT . '/uploads/logo/' . JFile::makeSafe($_FILES['logo']['name']))) { $this->setError(Text::_('INSTL_ERROR_UPLOAD_LOGO')); return false; } } return true; }
/** * Delete a folder. * * @param string $path The path to the folder to delete. * * @return boolean True on success. * * @since 1.0 * @throws FilesystemException * @throws \UnexpectedValueException */ public static function delete($path) { @set_time_limit(ini_get('max_execution_time')); // Sanity check if (!$path) { // Bad programmer! Bad Bad programmer! throw new FilesystemException(__METHOD__ . ': You can not delete a base directory.'); } try { // Check to make sure the path valid and clean $path = Path::clean($path); } catch (\UnexpectedValueException $e) { throw $e; } // Is this really a folder? if (!is_dir($path)) { throw new \UnexpectedValueException(sprintf('%1$s: Path is not a folder. Path: %2$s', __METHOD__, $path)); } // Remove all the files in folder if they exist; disable all filtering $files = self::files($path, '.', false, true, array(), array()); if (!empty($files)) { if (File::delete($files) !== true) { // File::delete throws an error return false; } } // Remove sub-folders of folder; disable all filtering $folders = self::folders($path, '.', false, true, array(), array()); foreach ($folders as $folder) { if (is_link($folder)) { // Don't descend into linked directories, just delete the link. if (File::delete($folder) !== true) { // File::delete throws an error return false; } } elseif (self::delete($folder) !== true) { // Folder::delete throws an error return false; } } // In case of restricted permissions we zap it one way or the other // as long as the owner is either the webserver or the ftp. if (@rmdir($path)) { return true; } else { throw new FilesystemException(sprintf('%1$s: Could not delete folder. Path: %2$s', __METHOD__, $path)); } }
/** * Add photo * * @param string $file Filename * * @return mixed Data from Google * * @since 12.3 * @throws UnexpectedValueException */ protected function getMIME($file) { switch (strtolower(File::getExt($file))) { case 'bmp': case 'bm': return 'image/bmp'; case 'gif': return 'image/gif'; case 'jpg': case 'jpeg': case 'jpe': case 'jif': case 'jfif': case 'jfi': return 'image/jpeg'; case 'png': return 'image/png'; case '3gp': return 'video/3gpp'; case 'avi': return 'video/avi'; case 'mov': case 'moov': case 'qt': return 'video/quicktime'; case 'mp4': case 'm4a': case 'm4p': case 'm4b': case 'm4r': case 'm4v': return 'video/mp4'; case 'mpg': case 'mpeg': case 'mp1': case 'mp2': case 'mp3': case 'm1v': case 'm1a': case 'm2a': case 'mpa': case 'mpv': return 'video/mpeg'; case 'asf': return 'video/x-ms-asf'; case 'wmv': return 'video/x-ms-wmv'; default: return false; } }
/** * Extract a ZIP compressed file to a given path * * @param string $archive Path to ZIP archive to extract * @param string $destination Path to extract archive into * * @return boolean True if successful * * @since 1.0 * @throws \RuntimeException */ public function extract($archive, $destination) { $this->data = null; $this->metadata = null; $this->data = file_get_contents($archive); if (!$this->data) { throw new \RuntimeException('Unable to read archive'); } $this->getTarInfo($this->data); for ($i = 0, $n = count($this->metadata); $i < $n; $i++) { $type = strtolower($this->metadata[$i]['type']); if ($type == 'file' || $type == 'unix file') { $buffer = $this->metadata[$i]['data']; $path = Path::clean($destination . '/' . $this->metadata[$i]['name']); // Make sure the destination folder exists if (!Folder::create(dirname($path))) { throw new \RuntimeException('Unable to create destination'); } if (File::write($path, $buffer) === false) { throw new \RuntimeException('Unable to write entry'); } } } return true; }
/** * Save config to file. * * @return void */ public static function saveConfig() { File::write(static::getPath(), static::getConfig()->toString(static::$type)); }
/** * Test write method * * @return void * * @covers Joomla\Filesystem\File::write * @since 1.0 */ public function testWrite() { $name = 'tempFile'; $path = __DIR__; $data = 'Lorem ipsum dolor sit amet'; // Create a file on pre existing path. $this->assertThat(File::write($path . '/' . $name, $data), $this->isTrue(), 'Line:' . __LINE__ . ' File should be written successfully.'); // Create a file on pre existing path by using streams. $this->assertThat(File::write($path . '/' . $name, $data, true), $this->isTrue(), 'Line:' . __LINE__ . ' File should be written successfully.'); // Create a file on non-existing path. $this->assertThat(File::write($path . '/TempFolder/' . $name, $data), $this->isTrue(), 'Line:' . __LINE__ . ' File should be written successfully.'); // Removes file and folder. File::delete($path . '/' . $name); Folder::delete($path . '/TempFolder'); }
/** * Compute the files to be included * * @param string $folder folder name to search into (images, css, js, ...) * @param string $file path to file * @param boolean $relative path to file is relative to /media folder * @param boolean $detect_browser detect browser to include specific browser files * @param boolean $detect_debug detect debug to include compressed files if debug is on * * @return array files to be included * * @see JBrowser * @since 11.1 */ protected static function includeRelativeFiles($folder, $file, $relative, $detect_browser, $detect_debug) { // If http is present in filename if (strpos($file, 'http') === 0) { $includes = array($file); } else { // Extract extension and strip the file $strip = File::stripExt($file); $ext = File::getExt($file); // Prepare array of files $includes = array(); // Detect browser and compute potential files if ($detect_browser) { $navigator = Browser::getInstance(); $browser = $navigator->getBrowser(); $major = $navigator->getMajor(); $minor = $navigator->getMinor(); // Try to include files named filename.ext, filename_browser.ext, filename_browser_major.ext, filename_browser_major_minor.ext // where major and minor are the browser version names $potential = array($strip, $strip . '_' . $browser, $strip . '_' . $browser . '_' . $major, $strip . '_' . $browser . '_' . $major . '_' . $minor); } else { $potential = array($strip); } // If relative search in template directory or media directory if ($relative) { // Get the template $app = Factory::getApplication(); $template = $app->getTemplate(); // For each potential files foreach ($potential as $strip) { $files = array(); // Detect debug mode if ($detect_debug && Factory::getConfig()->get('debug')) { /* * Detect if we received a file in the format name.min.ext * If so, strip the .min part out, otherwise append -uncompressed */ if (strrpos($strip, '.min', '-4')) { $position = strrpos($strip, '.min', '-4'); $filename = str_replace('.min', '.', $strip, $position); $files[] = $filename . $ext; } else { $files[] = $strip . '-uncompressed.' . $ext; } } $files[] = $strip . '.' . $ext; /* * Loop on 1 or 2 files and break on first found. * Add the content of the MD5SUM file located in the same folder to url to ensure cache browser refresh * This MD5SUM file must represent the signature of the folder content */ foreach ($files as $file) { // If the file is in the template folder $path = JPATH_THEMES . "/{$template}/{$folder}/{$file}"; if (file_exists($path)) { $md5 = dirname($path) . '/MD5SUM'; $includes[] = Uri::base(true) . "/templates/{$template}/{$folder}/{$file}" . (file_exists($md5) ? '?' . file_get_contents($md5) : ''); break; } else { // If the file contains any /: it can be in an media extension subfolder if (strpos($file, '/')) { // Divide the file extracting the extension as the first part before / list($extension, $file) = explode('/', $file, 2); // If the file yet contains any /: it can be a plugin if (strpos($file, '/')) { // Divide the file extracting the element as the first part before / list($element, $file) = explode('/', $file, 2); // Try to deal with plugins group in the media folder $path = JPATH_ROOT . "/media/{$extension}/{$element}/{$folder}/{$file}"; if (file_exists($path)) { $md5 = dirname($path) . '/MD5SUM'; $includes[] = Uri::root(true) . "/media/{$extension}/{$element}/{$folder}/{$file}" . (file_exists($md5) ? '?' . file_get_contents($md5) : ''); break; } // Try to deal with classical file in a a media subfolder called element $path = JPATH_ROOT . "/media/{$extension}/{$folder}/{$element}/{$file}"; if (file_exists($path)) { $md5 = dirname($path) . '/MD5SUM'; $includes[] = Uri::root(true) . "/media/{$extension}/{$folder}/{$element}/{$file}" . (file_exists($md5) ? '?' . file_get_contents($md5) : ''); break; } // Try to deal with system files in the template folder $path = JPATH_THEMES . "/{$template}/{$folder}/system/{$element}/{$file}"; if (file_exists($path)) { $md5 = dirname($path) . '/MD5SUM'; $includes[] = Uri::root(true) . "/templates/{$template}/{$folder}/system/{$element}/{$file}" . (file_exists($md5) ? '?' . file_get_contents($md5) : ''); break; } // Try to deal with system files in the media folder $path = JPATH_ROOT . "/media/system/{$folder}/{$element}/{$file}"; if (file_exists($path)) { $md5 = dirname($path) . '/MD5SUM'; $includes[] = Uri::root(true) . "/media/system/{$folder}/{$element}/{$file}" . (file_exists($md5) ? '?' . file_get_contents($md5) : ''); break; } } else { // Try to deals in the extension media folder $path = JPATH_ROOT . "/media/{$extension}/{$folder}/{$file}"; if (file_exists($path)) { $md5 = dirname($path) . '/MD5SUM'; $includes[] = Uri::root(true) . "/media/{$extension}/{$folder}/{$file}" . (file_exists($md5) ? '?' . file_get_contents($md5) : ''); break; } // Try to deal with system files in the template folder $path = JPATH_THEMES . "/{$template}/{$folder}/system/{$file}"; if (file_exists($path)) { $md5 = dirname($path) . '/MD5SUM'; $includes[] = Uri::root(true) . "/templates/{$template}/{$folder}/system/{$file}" . (file_exists($md5) ? '?' . file_get_contents($md5) : ''); break; } // Try to deal with system files in the media folder $path = JPATH_ROOT . "/media/system/{$folder}/{$file}"; if (file_exists($path)) { $md5 = dirname($path) . '/MD5SUM'; $includes[] = Uri::root(true) . "/media/system/{$folder}/{$file}" . (file_exists($md5) ? '?' . file_get_contents($md5) : ''); break; } } } else { $path = JPATH_ROOT . "/media/system/{$folder}/{$file}"; if (file_exists($path)) { $md5 = dirname($path) . '/MD5SUM'; $includes[] = Uri::root(true) . "/media/system/{$folder}/{$file}" . (file_exists($md5) ? '?' . file_get_contents($md5) : ''); break; } } } } } } else { foreach ($potential as $strip) { $files = array(); // Detect debug mode if ($detect_debug && Factory::getConfig()->get('debug')) { $files[] = $strip . '-uncompressed.' . $ext; } $files[] = $strip . '.' . $ext; /* * Loop on 1 or 2 files and break on first found. * Add the content of the MD5SUM file located in the same folder to url to ensure cache browser refresh * This MD5SUM file must represent the signature of the folder content */ foreach ($files as $file) { $path = JPATH_ROOT . "/{$file}"; if (file_exists($path)) { $md5 = dirname($path) . '/MD5SUM'; $includes[] = Uri::root(true) . "/{$file}" . (file_exists($md5) ? '?' . file_get_contents($md5) : ''); break; } } } } } return $includes; }
/** * Extract a Gzip compressed file to a given path * * @param string $archive Path to ZIP archive to extract * @param string $destination Path to extract archive to * @param array $options Extraction options [unused] * * @return boolean True if successful * * @since 11.1 * @throws RuntimeException */ public function extract($archive, $destination, array $options = array()) { $this->_data = null; if (!extension_loaded('zlib')) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'The zlib extension is not available.'); } else { throw new RuntimeException('The zlib extension is not available.'); } } if (!isset($options['use_streams']) || $options['use_streams'] == false) { $this->_data = file_get_contents($archive); if (!$this->_data) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to read archive'); } else { throw new RuntimeException('Unable to read archive'); } } $position = $this->_getFilePosition(); $buffer = gzinflate(substr($this->_data, $position, strlen($this->_data) - $position)); if (empty($buffer)) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to decompress data'); } else { throw new RuntimeException('Unable to decompress data'); } } if (File::write($destination, $buffer) === false) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to write archive'); } else { throw new RuntimeException('Unable to write archive'); } } } else { // New style! streams! $input = Factory::getStream(); // Use gz $input->set('processingmethod', 'gz'); if (!$input->open($archive)) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to read archive (gz)'); } else { throw new RuntimeException('Unable to read archive (gz)'); } } $output = Factory::getStream(); if (!$output->open($destination, 'w')) { $input->close(); if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to write archive (gz)'); } else { throw new RuntimeException('Unable to write archive (gz)'); } } do { $this->_data = $input->read($input->get('chunksize', 8196)); if ($this->_data) { if (!$output->write($this->_data)) { $input->close(); if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to write file (gz)'); } else { throw new RuntimeException('Unable to write file (gz)'); } } } } while ($this->_data); $output->close(); $input->close(); } return true; }
public function upload() { //this is the name of the field in the html form, filedata is the default name for swfupload //so we will leave it as that $fieldName = 'document'; //any errors the server registered on uploading $fileError = $_FILES[$fieldName]['error']; if ($fileError > 0) { switch ($fileError) { case 1: echo TextHelper::_('FILE TO LARGE THAN PHP INI ALLOWS'); return; case 2: echo TextHelper::_('FILE TO LARGE THAN HTML FORM ALLOWS'); return; case 3: echo TextHelper::_('ERROR PARTIAL UPLOAD'); return; case 4: echo TextHelper::_('ERROR NO FILE'); return; } } //check for filesize $fileSize = $_FILES[$fieldName]['size']; if ($fileSize > 2000000) { echo TextHelper::_('FILE BIGGER THAN 2MB'); } //check the file extension is ok $fileName = $_FILES[$fieldName]['name']; $uploadedFileNameParts = explode('.', $fileName); $uploadedFileExtension = array_pop($uploadedFileNameParts); $validFileExts = explode(',', 'jpeg,jpg,png,gif,pdf,doc,docx,odt,rtf,ppt,xls,txt'); //assume the extension is false until we know its ok $extOk = false; //go through every ok extension, if the ok extension matches the file extension (case insensitive) //then the file extension is ok foreach ($validFileExts as $key => $value) { if (preg_match("/{$value}/i", $uploadedFileExtension)) { $extOk = true; } } if ($extOk == false) { echo TextHelper::_('INVALID EXTENSION'); return; } //the name of the file in PHP's temp directory that we are going to move to our folder $fileTemp = $_FILES[$fieldName]['tmp_name']; //for security purposes, we will also do a getimagesize on the temp file (before we have moved it //to the folder) to check the MIME type of the file, and whether it has a width and height $imageinfo = getimagesize($fileTemp); //lose any special characters in the filename $fileName = ereg_replace("[^A-Za-z0-9.]", "-", $fileName); $hash = md5($fileName) . "." . $uploadedFileExtension; //always use constants when making file paths, to avoid the possibilty of remote file inclusion $uploadPath = JPATH_SITE . '/uploads/' . $hash; $app = \Cobalt\Container::fetch('app'); if (!File::upload($fileTemp, $uploadPath)) { $msg = TextHelper::_('COBALT_DOC_UPLOAD_FAIL'); $app->redirect('index.php?view=admindocuments', $msg); } else { //update the database //date generation $date = date('Y-m-d H:i:s'); $data = array('name' => $fileName, 'filename' => $hash, 'filetype' => $uploadedFileExtension, 'size' => $fileSize / 1024, 'created' => $date, 'shared' => 1, 'is_image' => is_array(getimagesize($uploadPath)) ? true : false); $model = new static(); $session = JFactory::getSession(); if ($model->store($data)) { $msg = TextHelper::_('COM_CRMERY_DOC_UPLOAD_SUCCESS'); $app->redirect('index.php?view=admindocuments&layout=upload_success&format=raw', $msg); $session->set("upload_success", true); } else { $msg = TextHelper::_('COM_CRMERY_DOC_UPLOAD_FAIL'); $app->redirect('index.php?view=admindocuments&layout=upload_success&format=raw', $msg); $session->set("upload_success", false); } } }
/** * Apply the patches * * @throw RuntimeException * * @return integer the number of files patched */ public function apply() { foreach ($this->patches as $patch) { // Separate the input into lines $lines = self::splitLines($patch['udiff']); // Loop for each header while (self::findHeader($lines, $src, $dst)) { $done = false; if ($patch['strip'] === null) { $src = $patch['root'] . preg_replace('#^([^/]*/)*#', '', $src); $dst = $patch['root'] . preg_replace('#^([^/]*/)*#', '', $dst); } else { $src = $patch['root'] . preg_replace('#^([^/]*/){' . (int) $patch['strip'] . '}#', '', $src); $dst = $patch['root'] . preg_replace('#^([^/]*/){' . (int) $patch['strip'] . '}#', '', $dst); } // Loop for each hunk of differences while (self::findHunk($lines, $src_line, $src_size, $dst_line, $dst_size)) { $done = true; // Apply the hunk of differences $this->applyHunk($lines, $src, $dst, $src_line, $src_size, $dst_line, $dst_size); } // If no modifications were found, throw an exception if (!$done) { throw new RuntimeException('Invalid Diff'); } } } // Initialize the counter $done = 0; // Patch each destination file foreach ($this->destinations as $file => $content) { if (File::write($file, implode("\n", $content))) { if (isset($this->sources[$file])) { $this->sources[$file] = $content; } $done++; } } // Remove each removed file foreach ($this->removals as $file) { if (File::delete($file)) { if (isset($this->sources[$file])) { unset($this->sources[$file]); } $done++; } } // Clear the destinations cache $this->destinations = array(); // Clear the removals $this->removals = array(); // Clear the patches $this->patches = array(); return $done; }