Example #1
0
/**
 * Cleans up/fixes a relative paths.
 *
 * As an example '/site/pivotx/../index.php' becomes '/site/index.php'.
 * In addition (non-leading) double slashes are removed.
 *
 * @param string $path
 * @param bool $nodoubleleadingslashes
 * @return string
 */
function fixPath($path, $nodoubleleadingslashes = true)
{
    $path = str_replace("\\", "/", stripTrailingSlash($path));
    // Handle double leading slash (that shouldn't be removed).
    if (!$nodoubleleadingslashes && strpos($path, '//') === 0) {
        $lead = '//';
        $path = substr($path, 2);
    } else {
        $lead = '';
    }
    $patharray = explode('/', preg_replace('#/+#', '/', $path));
    $new_path = array();
    foreach ($patharray as $item) {
        if ($item == '..') {
            // remove the previous element
            @array_pop($new_path);
        } elseif ($item == 'http:') {
            // Don't break for URLs with http:// scheme
            $new_path[] = 'http:/';
        } elseif ($item == 'https:') {
            // Don't break for URLs with https:// scheme
            $new_path[] = 'https:/';
        } elseif ($item != '.') {
            $new_path[] = $item;
        }
    }
    return $lead . implode('/', $new_path);
}
Example #2
0
 /**
  * List browse on the server, so we can insert them in the file input.
  *
  * @param $path
  * @param  Silex\Application $app
  * @param  Request           $request
  * @return mixed
  */
 public function browse($path, Silex\Application $app, Request $request)
 {
     $files = array();
     $folders = array();
     // $key is linked to the fieldname of the original field, so we can
     // Set the selected value in the proper field
     $key = $app['request']->get('key');
     $basefolder = $app['resources']->getPath('files');
     $path = stripTrailingSlash(str_replace("..", "", $path));
     if ($path == 'files') {
         $path = '';
     }
     $currentfolder = realpath($basefolder . $path);
     $ignored = array(".", "..", ".DS_Store", ".gitignore", ".htaccess");
     // Get the pathsegments, so we can show the path..
     $pathsegments = array();
     $cumulative = "";
     if (!empty($path)) {
         foreach (explode("/", $path) as $segment) {
             $cumulative .= $segment . "/";
             $pathsegments[$cumulative] = $segment;
         }
     }
     if (file_exists($currentfolder)) {
         $d = dir($currentfolder);
         while (false !== ($entry = $d->read())) {
             if (in_array($entry, $ignored)) {
                 continue;
             }
             $fullfilename = $currentfolder . "/" . $entry;
             if (is_file($fullfilename)) {
                 $relativepath = str_replace("files/", "", $path . "/" . $entry);
                 $files[$entry] = array('path' => $path, 'filename' => $entry, 'newpath' => $path . "/" . $entry, 'relativepath' => $relativepath, 'writable' => is_writable($fullfilename), 'readable' => is_readable($fullfilename), 'type' => strtolower(getExtension($entry)), 'filesize' => formatFilesize(filesize($fullfilename)), 'modified' => date("Y/m/d H:i:s", filemtime($fullfilename)), 'permissions' => \util::full_permissions($fullfilename));
                 if (in_array(strtolower(getExtension($entry)), array('gif', 'jpg', 'png', 'jpeg'))) {
                     $size = getimagesize($fullfilename);
                     $files[$entry]['imagesize'] = sprintf("%s × %s", $size[0], $size[1]);
                 }
             }
             if (is_dir($fullfilename)) {
                 $folders[$entry] = array('path' => $path, 'foldername' => $entry, 'newpath' => $path . "/" . $entry, 'writable' => is_writable($fullfilename), 'modified' => date("Y/m/d H:i:s", filemtime($fullfilename)));
             }
         }
         $d->close();
     } else {
         $app['session']->getFlashBag()->set('error', __("Folder '%s' could not be found, or is not readable.", array('%s' => $path)));
     }
     $app['twig']->addGlobal('title', __("Files in %s", array('%s' => $path)));
     // Make sure the files and folders are sorted properly.
     ksort($files);
     ksort($folders);
     return $app['render']->render('files_async.twig', array('path' => $path, 'files' => $files, 'folders' => $folders, 'pathsegments' => $pathsegments, 'key' => $key));
 }
Example #3
0
 public function files($path, Silex\Application $app, Request $request)
 {
     $files = array();
     $folders = array();
     $basefolder = BOLT_WEB_DIR . "/";
     $path = stripTrailingSlash(str_replace("..", "", $path));
     $currentfolder = realpath($basefolder . $path);
     if (!$app['filepermissions']->authorized($currentfolder)) {
         $error = __("Display the file or directory '%s' is forbidden.", array('%s' => $path));
         $app->abort(403, $error);
     }
     if (is_writable($currentfolder)) {
         // Define the "Upload here" form.
         $form = $app['form.factory']->createBuilder('form')->add('FileUpload', 'file', array('label' => __("Upload a file to this folder:")))->getForm();
         // Handle the upload.
         if ($request->isMethod('POST')) {
             $form->bind($request);
             if ($form->isValid()) {
                 $files = $request->files->get($form->getName());
                 // Check if we even have an uploaded file.
                 if (isset($files['FileUpload'])) {
                     // clean up and validate filename
                     $originalFilename = $files['FileUpload']->getClientOriginalName();
                     $filename = preg_replace('/[^a-zA-Z0-9_\\.]/', '_', basename($originalFilename));
                     if ($app['filepermissions']->allowedUpload($filename)) {
                         $files['FileUpload']->move($currentfolder, $filename);
                         $app['session']->getFlashBag()->set('info', __("File '%file%' was uploaded successfully.", array('%file%' => $filename)));
                         // Add the file to our stack..
                         $app['stack']->add($path . "/" . $filename);
                     } else {
                         $extensionList = array();
                         foreach ($app['filepermissions']->getAllowedUploadExtensions() as $extension) {
                             $extensionList[] = '<code>.' . htmlspecialchars($extension, ENT_QUOTES) . '</code>';
                         }
                         $extensionList = implode(' ', $extensionList);
                         $app['session']->getFlashBag()->set('error', __("File '%file%' could not be uploaded (wrong/disallowed file type). Make sure the file extension is one of the following: ", array('%file%' => $filename)) . $extensionList);
                     }
                 }
             } else {
                 $app['session']->getFlashBag()->set('error', __("File '%file%' could not be uploaded.", array('%file%' => $filename)));
             }
             return redirect('files', array('path' => $path));
         }
         $formview = $form->createView();
     } else {
         // Folder not writable, don't show an upload.
         $formview = false;
     }
     $ignored = array(".", "..", ".DS_Store", ".gitignore", ".htaccess");
     // Get the pathsegments, so we can show the path..
     $pathsegments = array();
     $cumulative = "";
     if (!empty($path)) {
         foreach (explode("/", $path) as $segment) {
             $cumulative .= $segment . "/";
             $pathsegments[$cumulative] = $segment;
         }
     }
     if (file_exists($currentfolder)) {
         $d = dir($currentfolder);
         while (false !== ($entry = $d->read())) {
             if (in_array($entry, $ignored)) {
                 continue;
             }
             $fullfilename = $currentfolder . "/" . $entry;
             if (!$app['filepermissions']->authorized(realpath($fullfilename))) {
                 continue;
             }
             if (is_file($fullfilename)) {
                 $files[$entry] = array('path' => $path, 'filename' => $entry, 'newpath' => $path . "/" . $entry, 'writable' => is_writable($fullfilename), 'readable' => is_readable($fullfilename), 'type' => getExtension($entry), 'filesize' => formatFilesize(filesize($fullfilename)), 'modified' => date("Y/m/d H:i:s", filemtime($fullfilename)), 'permissions' => \util::full_permissions($fullfilename));
                 if (in_array(getExtension($entry), array('gif', 'jpg', 'png', 'jpeg'))) {
                     $size = getimagesize($fullfilename);
                     $files[$entry]['imagesize'] = sprintf("%s × %s", $size[0], $size[1]);
                 }
             }
             if (is_dir($fullfilename)) {
                 $folders[$entry] = array('path' => $path, 'foldername' => $entry, 'newpath' => $path . "/" . $entry, 'writable' => is_writable($fullfilename), 'modified' => date("Y/m/d H:i:s", filemtime($fullfilename)));
             }
         }
         $d->close();
     } else {
         $app['session']->getFlashBag()->set('error', __("Folder '%s' could not be found, or is not readable.", array('%s' => $path)));
     }
     $app['twig']->addGlobal('title', __("Files in %s", array('%s' => $path)));
     // Make sure the files and folders are sorted properly.
     ksort($files);
     ksort($folders);
     // Select the correct template to render this. If we've got 'CKEditor' in the title, it's a dialog
     // from CKeditor to insert a file..
     if (!$request->query->has('CKEditor')) {
         $twig = 'files.twig';
     } else {
         $twig = 'files_ck.twig';
     }
     return $app['render']->render($twig, array('path' => $path, 'files' => $files, 'folders' => $folders, 'pathsegments' => $pathsegments, 'form' => $formview));
 }
Example #4
0
 public function files($namespace, $path, Silex\Application $app, Request $request)
 {
     // No trailing slashes in the path.
     $path = stripTrailingSlash($path);
     $filesystem = $app['filesystem']->getManager($namespace);
     $fullPath = $filesystem->getAdapter()->applyPathPrefix($path);
     if (!$app['filepermissions']->authorized($fullPath)) {
         $error = __("You don't have the correct permissions to display the file or directory '%s'.", array('%s' => $path));
         $app->abort(403, $error);
     }
     try {
         $list = $filesystem->listContents($path);
         $validFolder = true;
     } catch (\Exception $e) {
         $list = array();
         $app['session']->getFlashBag()->set('error', __("The folder '%s' could not be found, or is not readable.", array('%s' => $path)));
         $formview = false;
         $validFolder = false;
     }
     if ($validFolder) {
         // Define the "Upload here" form.
         $form = $app['form.factory']->createBuilder('form')->add('FileUpload', 'file', array('label' => __("Upload a file to this folder:")))->getForm();
         // Handle the upload.
         if ($request->isMethod('POST')) {
             $form->bind($request);
             if ($form->isValid()) {
                 $files = $request->files->get($form->getName());
                 foreach ($files as $fileToProcess) {
                     $fileToProcess = array('name' => $fileToProcess->getClientOriginalName(), 'tmp_name' => $fileToProcess->getPathName());
                     $originalFilename = $fileToProcess['name'];
                     $filename = preg_replace('/[^a-zA-Z0-9_\\.]/', '_', basename($originalFilename));
                     if ($app['filepermissions']->allowedUpload($filename)) {
                         $handler = $app['upload'];
                         $handler->setPrefix($path . "/");
                         $result = $app['upload']->process($fileToProcess);
                         if ($result->isValid()) {
                             $app['session']->getFlashBag()->set('info', __("File '%file%' was uploaded successfully.", array('%file%' => $filename)));
                             // Add the file to our stack..
                             $app['stack']->add($path . "/" . $filename);
                             $result->confirm();
                         }
                     } else {
                         $extensionList = array();
                         foreach ($app['filepermissions']->getAllowedUploadExtensions() as $extension) {
                             $extensionList[] = '<code>.' . htmlspecialchars($extension, ENT_QUOTES) . '</code>';
                         }
                         $extensionList = implode(' ', $extensionList);
                         $app['session']->getFlashBag()->set('error', __("File '%file%' could not be uploaded (wrong/disallowed file type). Make sure the file extension is one of the following: ", array('%file%' => $filename)) . $extensionList);
                     }
                 }
             } else {
                 $app['session']->getFlashBag()->set('error', __("File '%file%' could not be uploaded.", array('%file%' => $filename)));
             }
             return redirect('files', array('path' => $path));
         }
         $formview = $form->createView();
     }
     list($files, $folders) = $filesystem->browse($path, $app);
     // Get the pathsegments, so we can show the path as breadcrumb navigation..
     $pathsegments = array();
     $cumulative = "";
     if (!empty($path)) {
         foreach (explode("/", $path) as $segment) {
             $cumulative .= $segment . "/";
             $pathsegments[$cumulative] = $segment;
         }
     }
     // Select the correct template to render this. If we've got 'CKEditor' in the title, it's a dialog
     // from CKeditor to insert a file..
     if (!$request->query->has('CKEditor')) {
         $twig = 'files/files.twig';
     } else {
         $app['debugbar'] = false;
         $twig = 'files_ck/files_ck.twig';
     }
     $context = array('path' => $path, 'files' => $files, 'folders' => $folders, 'pathsegments' => $pathsegments, 'form' => $formview, 'namespace' => $namespace);
     return $app['render']->render($twig, array('context' => $context));
 }
 /**
  * Check for common misconfigurations, filerights, and whatnot.
  *
  */
 function checkWarnings()
 {
     global $minrequiredphp, $dbversion, $PIVOTX;
     $this->filelist = array();
     // Check if there are any hooks to execute..
     $PIVOTX['extensions']->executeHook('before_checkwarnings', $dummy);
     // We should only check these warnings when logged in.. Whilst displaying
     // them isn't a direct security problem, we should be careful about
     // giving Teh scr1ptk1ddi3zz any pointers.
     if (!$PIVOTX['session']->isLoggedIn()) {
         return;
     }
     if ($PIVOTX['config']->get('dont_check_filerights') != 1) {
         // Check files in pivotx/db/
         $this->_checkFilerights($PIVOTX['paths']['db_path'], "db/", false);
         if (!empty($this->filelist)) {
             $this->_makeFileWarning("db/");
         }
         // Check files in pivotx/templates/
         $this->_checkFilerights($PIVOTX['paths']['templates_path'], "templates/", true);
         if (!empty($this->filelist)) {
             $this->_makeFileWarning("templates/");
         }
         // Check files in pivotx/images/
         $this->_checkFilerights($PIVOTX['paths']['upload_base_path'], basename($PIVOTX['paths']['upload_base_path']) . "/", true);
         if (!empty($this->filelist)) {
             $this->_makeFileWarning(basename($PIVOTX['paths']['upload_base_path']) . "/");
         }
     }
     // Check minimum PHP version.
     if (!checkVersion(phpversion(), $minrequiredphp)) {
         $thiswarning = sprintf(__("The current version of PHP on the server is %s, which is an older version than PivotX requires (%s). PivotX will most likely not work correctly, until the server is updated to a newer version."), phpversion(), $minrequiredphp);
         $this->warnings[] = "<p>" . $thiswarning . "</p>";
     }
     // Check Safe Mode
     if (ini_get('safe_mode') && !$PIVOTX['config']->get('ignore_safe_mode')) {
         $thiswarning = __("This webserver has safe_mode enabled. This doesn't actually make things any 'safer', just more annoying. Please ask your hosting provider to turn it off. See the documentation for more info: <a href='http://docs.pivotx.net/doku.php?id=dealing_with_safe_mode'>Dealing with safe_mode</a>.");
         $this->warnings[] = "<p>" . $thiswarning . "</p>";
     }
     // Check PivotX Setup
     if ((file_exists($PIVOTX['paths']['pivotx_path'] . '../pivotx-setup-safemode.php') || file_exists($PIVOTX['paths']['pivotx_path'] . '../pivotx-setup.php')) && !$PIVOTX['config']->get('ignore_setupscript')) {
         $thiswarning = __('The PivotX installer script "pivotx-setup.php" is still present in the parent folder. You should be aware that this is a potential security risk. We advise you to remove it, or to set an empty password inside it, so that it can\'t be executed by people with bad intentions.');
         $this->warnings[] = "<p>" . $thiswarning . "</p>";
     }
     // Check (old) Pivot Setup - message can't be ignored
     if (file_exists($PIVOTX['paths']['pivotx_path'] . '../pivot-setup-safemode.php') || file_exists($PIVOTX['paths']['pivotx_path'] . '../pivot-setup.php')) {
         $thiswarning = __('The old Pivot installer script "pivot-setup.php" is still present in the parent folder. Please remove it immediately since it\'s not used for PivotX and it is a potential security risk.');
         $this->warnings[] = "<p>" . $thiswarning . "</p>";
     }
     // Check for erroneous 'canonical_host', but only if we actually use it.
     // The check can definitely be improved ...
     if ($PIVOTX['config']->get('dont_add_canonical') == 0) {
         $canonical_host = $PIVOTX['config']->get('canonical_host');
         if ($canonical_host != $PIVOTX['paths']['host']) {
             $thiswarning = __("You are currently logged in at a different host than your canonical host. " . "If <strong>%s</strong> isn't the canonical host you want, change it on the %s screen.");
             $link = '<a href="' . makeAdminPageLink('advconfiguration') . '">' . __('Advanced Configuration') . '</a>';
             $thiswarning = sprintf($thiswarning, $canonical_host, $link);
             $this->warnings[] = "<p>" . $thiswarning . "</p>";
         }
     }
     // Check for 'preferred_admin_location'.
     if ($PIVOTX['config']->get('preferred_admin_location')) {
         $request_url = (empty($_SERVER['HTTPS']) ? "http://" : "https://") . $_SERVER['HTTP_HOST'] . str_replace("/index.php", "/", $_SERVER['REQUEST_URI']);
         $request = parse_url(stripTrailingSlash($request_url));
         $preferred_url = str_replace("/index.php", "/", $PIVOTX['config']->get('preferred_admin_location'));
         $preferred = parse_url(stripTrailingSlash($preferred_url));
         if (empty($preferred['scheme'])) {
             $preferred['scheme'] = "http";
         }
         if ($request['scheme'] != $preferred['scheme'] || $request['host'] != $preferred['host'] || $request['path'] != $preferred['path']) {
             $thiswarning = __("You are currently logged in at a different location than the preferred one. This might cause problems with wrongly calculated links. Please click here to go to the correct location:");
             $thiswarning .= sprintf(" <a href='%s://%s%s/'>%s%s/</a>", $preferred['scheme'], $preferred['host'], $preferred['path'], $preferred['host'], $preferred['path']);
             $this->warnings[] = "<p>" . $thiswarning . "</p>";
         }
     }
     /* -- Commented this out for now. Takes up to two seconds for some servers,
           -- Which is very bad, considering it's called every time on the dashboard page.
           -- Perhaps move this check to scheduler.php?
               
        // Check if we have 'mod rewrite' enabled, but no .htaccess 
        if( ($PIVOTX['config']->get('mod_rewrite')>0) && (!$PIVOTX['config']->get('ignore_modrewrite_check')) && function_exists('get_headers') ) {
                    
            // Get the headers for a web page that we know always exists
            $url = $PIVOTX['paths']['host'].$PIVOTX['paths']['site_url']."search/modrewritecheck";
            
            $headers = get_headers($url);
            
            // $headers[0] should look like 'HTTP/1.1 200 OK', else give warning
            if (strpos($headers[0], "200 OK")===false) {
                $thiswarning = __('\'Mod rewrite\' is enabled, but it seems like the webserver is not set up correctly to serve pages with non-crufty URLs. You should copy the <tt>example.htaccess</tt> from the PivotX distribution to <tt>.htaccess</tt>. Until you\'ve done this, most pages on your site will give a 404-not-found error.');
                $this->warnings[] = "<p>". $thiswarning ."</p>";
            }
            
            
        }  */
     // Check if magic_quotes_runtime is enabled - Warning is commented out for now
     // because we _should_ be able to handle both cases transparently for the user.
     //if( get_magic_quotes_runtime() && (!$PIVOTX['config']->get('ignore_magic_quotes')) {
     //    $thiswarning = __('Your server has a PHP option set that\'s called "Magic quotes" enabled. This might cause PivotX to run sub-optimally.  Look on <a href="http://docs.pivotx.net/doku.php?id=servers_with_magic_quotes">this page</a> to remedy the situation.');
     //    $this->warnings[] = "<p>". $thiswarning ."</p>";
     //}
     /**
      * Commented this out. since PivotX doesn't need to write files in a higher
      * dir than pivotx/, there is no problem with open_basedir..
      */
     // Check Open Basedir
     //        if( ini_get('open_basedir') ) {
     //            $thiswarning = __("This webserver has open_basedir enabled. You'll have a hard time running PivotX in the current configuration. Please ask your hosting provider to turn it off. See the documentation for more info: <a href='http://docs.pivotx.net/doku.php?id=dealing_with_safe_mode'>Dealing with safe_mode</a>.");
     //            $this->warnings[] = "<p>". $thiswarning ."</p>";
     //        }
     // Check Register Globals
     if (ini_get('register_globals') && !$PIVOTX['config']->get('ignore_register_globals')) {
         $thiswarning = __("This webserver has register_globals enabled. This is a serious potential security issue. Please ask your hosting provider to turn it off. See the PHP documentation for more info: <a href='http://php.net/register_globals'>Register Globals</a>.");
         $this->warnings[] = "<p>" . $thiswarning . "</p>";
     }
     $user = $PIVOTX['users']->getUser($PIVOTX['session']->currentUsername());
     // Check if the password is properly salted.
     if ($user['salt'] == "") {
         $thiswarning = __("Your password is not fully encrypted yet. Please go to %myinfo%, and set your password again.");
         $link = sprintf("<a href=\"index.php?page=myinfo\">%s</a>", __("My Info"));
         $thiswarning = str_replace('%myinfo%', $link, $thiswarning);
         $this->warnings[] = "<p>" . $thiswarning . "</p>";
     }
     // Check if there are any hooks to execute..
     $PIVOTX['extensions']->executeHook('after_checkwarnings', $dummy);
 }
Example #6
0
 public function files($path, Silex\Application $app, Request $request)
 {
     $files = array();
     $folders = array();
     $basefolder = __DIR__ . "/../../../../";
     $path = stripTrailingSlash(str_replace("..", "", $path));
     $currentfolder = realpath($basefolder . $path);
     if (is_writable($currentfolder)) {
         // Define the "Upload here" form.
         $form = $app['form.factory']->createBuilder('form')->add('FileUpload', 'file', array('label' => __("Upload a file to this folder:")))->getForm();
         // Handle the upload.
         if ($request->isMethod('POST')) {
             $form->bind($request);
             if ($form->isValid()) {
                 $files = $request->files->get($form->getName());
                 /* Make sure that Upload Directory is properly configured and writable */
                 $filename = $files['FileUpload']->getClientOriginalName();
                 $files['FileUpload']->move($currentfolder, $filename);
                 echo "path: {$path}";
                 $app['session']->getFlashBag()->set('info', __("File '%file%' was uploaded successfully.", array('%file%' => $filename)));
                 // Add the file to our stack..
                 $app['stack']->add($path . "/" . $filename);
             } else {
                 $app['session']->getFlashBag()->set('error', __("File '%file%' could not be uploaded.", array('%file%' => $filename)));
             }
             return redirect('files', array('path' => $path));
         }
         $formview = $form->createView();
     } else {
         // Folder not writable, don't show an upload.
         $formview = false;
     }
     $ignored = array(".", "..", ".DS_Store", ".gitignore", ".htaccess");
     // Get the pathsegments, so we can show the path..
     $pathsegments = array();
     $cumulative = "";
     if (!empty($path)) {
         foreach (explode("/", $path) as $segment) {
             $cumulative .= $segment . "/";
             $pathsegments[$cumulative] = $segment;
         }
     }
     if (file_exists($currentfolder)) {
         $d = dir($currentfolder);
         while (false !== ($entry = $d->read())) {
             if (in_array($entry, $ignored)) {
                 continue;
             }
             $fullfilename = $currentfolder . "/" . $entry;
             if (is_file($fullfilename)) {
                 $files[$entry] = array('path' => $path, 'filename' => $entry, 'newpath' => $path . "/" . $entry, 'writable' => is_writable($fullfilename), 'readable' => is_readable($fullfilename), 'type' => getExtension($entry), 'filesize' => formatFilesize(filesize($fullfilename)), 'modified' => date("Y/m/d H:i:s", filemtime($fullfilename)), 'permissions' => \util::full_permissions($fullfilename));
                 if (in_array(getExtension($entry), array('gif', 'jpg', 'png', 'jpeg'))) {
                     $size = getimagesize($fullfilename);
                     $files[$entry]['imagesize'] = sprintf("%s × %s", $size[0], $size[1]);
                 }
             }
             if (is_dir($fullfilename)) {
                 $folders[$entry] = array('path' => $path, 'foldername' => $entry, 'newpath' => $path . "/" . $entry, 'writable' => is_writable($fullfilename), 'modified' => date("Y/m/d H:i:s", filemtime($fullfilename)));
             }
         }
         $d->close();
     } else {
         $app['session']->getFlashBag()->set('error', __("Folder '%s' could not be found, or is not readable.", array('%s' => $path)));
     }
     $app['twig']->addGlobal('title', __("Files in %s", array('%s' => $path)));
     // Make sure the files and folders are sorted properly.
     ksort($files);
     ksort($folders);
     // Select the correct template to render this. If we've got 'CKEditor' in the title, it's a dialog
     // from CKeditor to insert a file..
     if (!$request->query->has('CKEditor')) {
         $twig = 'files.twig';
     } else {
         $twig = 'files_ck.twig';
     }
     return $app['render']->render($twig, array('path' => $path, 'files' => $files, 'folders' => $folders, 'pathsegments' => $pathsegments, 'form' => $formview));
 }
Example #7
0
 /**
  * List browse on the server, so we can insert them in the file input.
  *
  * @param $namespace
  * @param $path
  * @param  Silex\Application $app
  * @param  Request           $request
  * @return mixed
  */
 public function browse($namespace, $path, Silex\Application $app, Request $request)
 {
     // No trailing slashes in the path.
     $path = stripTrailingSlash($path);
     $filesystem = $app['filesystem']->getManager($namespace);
     // $key is linked to the fieldname of the original field, so we can
     // Set the selected value in the proper field
     $key = $app['request']->get('key');
     // Get the pathsegments, so we can show the path..
     $pathsegments = array();
     $cumulative = "";
     if (!empty($path)) {
         foreach (explode("/", $path) as $segment) {
             $cumulative .= $segment . "/";
             $pathsegments[$cumulative] = $segment;
         }
     }
     try {
         $list = $filesystem->listContents($path);
         $validFolder = true;
     } catch (\Exception $e) {
         $app['session']->getFlashBag()->set('error', __("Folder '%s' could not be found, or is not readable.", array('%s' => $path)));
         $validFolder = false;
     }
     $app['twig']->addGlobal('title', __("Files in %s", array('%s' => $path)));
     list($files, $folders) = $filesystem->browse($path, $app);
     $context = array('namespace' => $namespace, 'files' => $files, 'folders' => $folders, 'pathsegments' => $pathsegments, 'key' => $key);
     return $app['render']->render('files_async/files_async.twig', array('context' => $context));
 }
Example #8
0
 function files($path, Silex\Application $app, Request $request)
 {
     $files = array();
     $folders = array();
     $basefolder = __DIR__ . "/../../../../";
     $path = stripTrailingSlash(str_replace("..", "", $path));
     $currentfolder = realpath($basefolder . $path);
     $ignored = array(".", "..", ".DS_Store", ".gitignore", ".htaccess");
     // Get the pathsegments, so we can show the path..
     $pathsegments = array();
     $cumulative = "";
     if (!empty($path)) {
         foreach (explode("/", $path) as $segment) {
             $cumulative .= $segment . "/";
             $pathsegments[$cumulative] = $segment;
         }
     }
     if (file_exists($currentfolder)) {
         $d = dir($currentfolder);
         while (false !== ($entry = $d->read())) {
             if (in_array($entry, $ignored)) {
                 continue;
             }
             $fullfilename = $currentfolder . "/" . $entry;
             if (is_file($fullfilename)) {
                 $files[$entry] = array('path' => $path, 'filename' => $entry, 'newpath' => $path . "/" . $entry, 'writable' => is_writable($fullfilename), 'readable' => is_readable($fullfilename), 'type' => getExtension($entry), 'filesize' => formatFilesize(filesize($fullfilename)), 'modified' => date("Y/m/d H:i:s", filemtime($fullfilename)), 'permissions' => \util::full_permissions($fullfilename));
                 if (in_array(getExtension($entry), array('gif', 'jpg', 'png', 'jpeg'))) {
                     $size = getimagesize($fullfilename);
                     $files[$entry]['imagesize'] = sprintf("%s × %s", $size[0], $size[1]);
                 }
             }
             if (is_dir($fullfilename)) {
                 $folders[$entry] = array('path' => $path, 'foldername' => $entry, 'newpath' => $path . "/" . $entry, 'writable' => is_writable($fullfilename), 'modified' => date("Y/m/d H:i:s", filemtime($fullfilename)));
             }
         }
         $d->close();
     } else {
         $app['session']->setFlash('error', "File '" . $file . "' could not be saved: not valid YAML.");
     }
     $app['twig']->addGlobal('title', "Files in " . $path);
     return $app['twig']->render('files.twig', array('path' => $path, 'files' => $files, 'folders' => $folders, 'pathsegments' => $pathsegments));
 }
Example #9
0
    case 'images':
    case 'file':
    case 'files':
        $targetDir = makeUploadFolder();
        $cleanupTargetDir = false;
        break;
}
if (isset($_GET['path']) && $_GET['path'] != '') {
    /* Using same user level as in fileOperations (in lib.php) */
    $PIVOTX['session']->minLevel(PIVOTX_UL_ADVANCED);
    $path = cleanPath($_GET['path']);
    // Don't ever allow uploading outside the images, templates and db folders.
    if (!uploadAllowed($path)) {
        die('{"jsonrpc" : "2.0", "error" : {"code": 104, "message": "Uploading to illegal directory."}, "id" : "id"}');
    }
    $targetDir = stripTrailingSlash($path);
    $cleanupTargetDir = false;
}
// 5 minutes execution time
@set_time_limit(5 * 60);
// usleep(5000);
// Get parameters
$chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0;
$chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0;
$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
if ($fileName == '' && isset($_FILES['file']['name'])) {
    $fileName = $_FILES['file']['name'];
}
// Clean the fileName for security reasons
// This *has* to be the same as the javascript one!
//$fileName = preg_replace('/[^a-zA-Z0-9_. -]+/', ' ', $fileName);
Example #10
0
        }
    }
}
initializePivotX();
// If not installed, redirect to the setup page.
if (!isInstalled()) {
    if (strpos($_SERVER['PHP_SELF'], "pivotx/render.php") > 0) {
        $location = "index.php";
    } else {
        $location = "pivotx/index.php";
    }
    header("Location: " . $location);
    die;
}
// No trailing slashes on the URI, plz.
$_GET['uri'] = stripTrailingSlash($_GET['uri']);
// Check if we need to get the parameters from a 'non crufty' URL..
if (!empty($_GET['rewrite'])) {
    parseRewrittenURL($_GET['rewrite'], $_GET['uri']);
}
// Cleaning user input - safeString-ing all values in the super globals
// ($_GET, $_POST, $_REQUEST and $_COOKIE) that are used in render.php
cleanUserInput();
/**
 * Check if we need to handle a posted comment or trackback
 */
$trackback = getDefault($PIVOTX['config']->get('localised_trackback_name'), "trackback");
if (!empty($_POST['piv_code'])) {
    require_once dirname(__FILE__) . "/modules/module_comments.php";
    handlePostComment();
} elseif (isset($_GET[$trackback])) {
function gd_crop($thumb)
{
    global $img, $PIVOTX;
    $sx = $thumb->x;
    $sy = $thumb->y;
    $sw = $thumb->w;
    $sh = $thumb->h;
    $scalew = $sw / $PIVOTX['image']['mw'];
    $scaleh = $sh / $PIVOTX['image']['mh'];
    if ($thumb->type == "bounded") {
        $factor = $_GET['factor'];
    } else {
        if ($thumb->type == "free") {
            $factor = 1;
        } else {
            $factor = max($scalew, $scaleh);
        }
    }
    $dx = 0;
    $dy = 0;
    $dw = $thumb->w / $factor;
    $dh = $thumb->h / $factor;
    $ext = strtolower($img->ext);
    printf("<div id='editor'><h1 style=\"padding: 6px; margin: 0 0 10px;  border-bottom: 1px solid #AAA;\">%s:  <b>'%s'</b></h1>\n", __("PivotX thumbnail creator"), basename($img->name));
    if ($ext == 'gif') {
        echo "<small style='color:red;'>(" . __("When using GIF files, there is a significant chance that you can't use PivotX to make thumbnails. If you have problems with making thumbnails, we suggest using PNG or JPG files.") . ")</small><br /><br />\n";
    }
    if (!in_array($ext, array('gif', 'jpg', 'png', 'jpeg'))) {
        echo "<strong>" . __("You can only make thumbnails of .gif, .jpg and .png images with PivotX.") . "</strong>\n";
        die;
    }
    $filename = $img->name;
    $sitepath = stripTrailingSlash($PIVOTX['paths']['site_path']);
    // Check if the base path is already in $_GET['crop']..
    if (strpos($_GET['crop'], $sitepath) === 0) {
        $thumbfilename = $_GET['crop'];
        $siteurl = stripTrailingSlash($PIVOTX['paths']['site_url']);
        $thumblink = str_replace($sitepath, $siteurl, $_GET['crop']);
    } else {
        $thumbfilename = $PIVOTX['paths']['upload_base_path'] . $_GET['crop'];
        $thumblink = $PIVOTX['paths']['upload_base_url'] . $_GET['crop'];
    }
    if ($PIVOTX['image']['local']) {
        if ($ext == "jpeg") {
            $ext = "jpg";
        }
        if ($ext == "jpg") {
            $src = imagecreatefromjpeg($filename);
        }
        if ($ext == "png") {
            $src = imagecreatefrompng($filename);
        }
        if ($ext == "gif") {
            $src = imagecreatefromgif($filename);
        }
        if (function_exists('imagecreatetruecolor')) {
            $dst = imagecreatetruecolor($dw, $dh);
            $tmp_img = imagecreatetruecolor($sw, $sh);
        } else {
            $dst = imagecreate($dw, $dh);
        }
        if (function_exists('imagecopyresampled')) {
            // GD 2.0 has a bug that ignores the 'source_x' and 'source_y'..
            // to compensate, we use a temp image..
            imagecopy($tmp_img, $src, 0, 0, $sx, $sy, $sw, $sh);
            imagecopyresampled($dst, $tmp_img, 0, 0, 0, 0, $dw, $dh, $sw, $sh);
        } else {
            imagecopyresized($dst, $src, 0, 0, $sx, $sy, $dw, $dh, $sw, $sh);
        }
        if ($ext == "jpg") {
            imagejpeg($dst, $thumbfilename, $PIVOTX['image']['qual']);
        }
        if ($ext == "png") {
            imagepng($dst, $thumbfilename, ceil($PIVOTX['image']['qual'] / 10));
        }
        // Ensure the created thumb has the correct file permission.
        chmodFile($thumbfilename);
        ImageDestroy($dst);
    } else {
        $remotefile = str_replace($PIVOTX['paths']['upload_base_path'], $PIVOTX['paths']['upload_base_url'], $filename);
        $remotefile = sprintf("%s%s", $PIVOTX['paths']['host'], urlencode($remotefile));
        $remoteurl = getDefault($PIVOTX['config']->get('remote_crop_script'), 'http://www.mijnkopthee.nl/remote/crop.php');
        $remote = sprintf('%s?img=%s&dx=%s&dy=%s&sx=%s&sy=%s&dw=%s&dh=%s&sw=%s&sh=%s&ext=%s', $remoteurl, $remotefile, $dx, $dy, $sx, $sy, $dw, $dh, $sw, $sh, $img->ext);
        if (@($fp = fopen($remote, "rb"))) {
            $handle = fopen($thumb->name, "wb");
            while (!feof($fp)) {
                fwrite($handle, fread($fp, 8192));
            }
            fclose($handle);
            fclose($fp);
        } else {
            echo "<p><strong>" . __("Couldn't make thumbnail remotely using") . " {$remoteurl}</strong></p>";
        }
    }
    srand((double) microtime() * 1000000);
    $rand = rand(10000, 99999);
    echo '<div id="testWrap" style="float:left;">';
    printf("<img src='%s?%s' alt='%s'><br />\n", $thumblink, $rand, $thumblink);
    echo "</div>";
    print_module_footer();
}
Example #12
0
function get_image_attributes(&$img)
{
    global $PIVOTX;
    if (file_exists($img)) {
        $nfo = getImageSize($img);
    } else {
        if (file_exists("../" . $img)) {
            $nfo = getImageSize("../" . $img);
        } else {
            if (file_exists(stripslashes(urldecode("../" . $img)))) {
                $nfo = getImageSize(stripslashes(urldecode("../" . $img)));
            } else {
                if (file_exists($PIVOTX['paths']['upload_base_path'] . $img)) {
                    $link = $PIVOTX['paths']['upload_base_url'] . $img;
                    $img = $PIVOTX['paths']['upload_base_path'] . $img;
                    $nfo = getImageSize($img);
                } else {
                    echo "<br />'" . htmlspecialchars($img) . "' " . __("can not be opened") . ". <br />";
                    echo __("Current path") . ": " . str_replace($PIVOTX['paths']['site_path'], '[site_root]/', getcwd()) . "<br />";
                    die;
                }
            }
        }
    }
    if (empty($link)) {
        $sitepath = stripTrailingSlash($PIVOTX['paths']['site_path']);
        $siteurl = stripTrailingSlash($PIVOTX['paths']['site_url']);
        $link = str_replace($sitepath, $siteurl, $img);
    }
    $result = array('name' => $img, 'w' => $nfo[0], 'h' => $nfo[1], 'x' => 0, 'y' => 0, 'extra' => $nfo, 'link' => $link);
    return $result;
}