public static function run($r)
 {
     if (pts_openbenchmarking_client::user_name() == false) {
         echo PHP_EOL . 'You must first be logged into an OpenBenchmarking.org account.' . PHP_EOL;
         echo PHP_EOL . 'Create An Account: http://openbenchmarking.org/';
         echo PHP_EOL . 'Log-In Command: phoronix-test-suite openbenchmarking-setup' . PHP_EOL . PHP_EOL;
         return false;
     }
     if (($test_suite = pts_types::identifier_to_object($r[0])) != false) {
         pts_client::$display->generic_heading($r[0]);
         if (pts_validation::validate_test_suite($test_suite)) {
             $zip_file = PTS_OPENBENCHMARKING_SCRATCH_PATH . $test_suite->get_identifier(false) . '-' . $test_suite->get_version() . '.zip';
             $zip_created = pts_compression::zip_archive_create($zip_file, $test_suite->xml_parser->getFileLocation());
             if ($zip_created == false) {
                 echo PHP_EOL . 'Failed to create zip file.' . PHP_EOL;
                 return false;
             }
             $zip = new ZipArchive();
             $zip->open($zip_file);
             $zip->renameName(basename($test_suite->xml_parser->getFileLocation()), 'suite-definition.xml');
             $zip->close();
             $commit_description = pts_user_io::prompt_user_input('Enter a test commit description', false);
             echo PHP_EOL;
             $server_response = pts_openbenchmarking::make_openbenchmarking_request('upload_test_suite', array('ts_identifier' => $test_suite->get_identifier_base_name(), 'ts_sha1' => sha1_file($zip_file), 'ts_zip' => base64_encode(file_get_contents($zip_file)), 'ts_zip_name' => basename($zip_file), 'commit_description' => $commit_description));
             echo PHP_EOL;
             $json = json_decode($server_response, true);
             if (isset($json['openbenchmarking']['upload']['error']) && !empty($json['openbenchmarking']['upload']['error'])) {
                 echo 'ERROR: ' . $json['openbenchmarking']['upload']['error'] . PHP_EOL;
             }
             if (isset($json['openbenchmarking']['upload']['id']) && !empty($json['openbenchmarking']['upload']['id'])) {
                 echo 'Command: phoronix-test-suite benchmark ' . $json['openbenchmarking']['upload']['id'] . PHP_EOL;
             }
             if (isset($json['openbenchmarking']['upload']['url']) && !empty($json['openbenchmarking']['upload']['url'])) {
                 pts_openbenchmarking::refresh_repository_lists(null, true);
                 echo 'URL: ' . $json['openbenchmarking']['upload']['url'] . PHP_EOL;
             }
             echo PHP_EOL;
             unlink($zip_file);
         }
     }
 }
Example #2
0
 public function dlSpecBackup($collId, $characterSet, $zipFile = 1)
 {
     global $charset, $paramsArr;
     $tempPath = $this->getTempPath();
     $buFileName = $paramsArr['un'] . '_' . time();
     $zipArchive;
     if ($zipFile && class_exists('ZipArchive')) {
         $zipArchive = new ZipArchive();
         $zipArchive->open($tempPath . $buFileName . '.zip', ZipArchive::CREATE);
     }
     $cSet = str_replace('-', '', strtolower($charset));
     $fileUrl = '';
     //If zip archive can be created, the occurrences, determinations, and image records will be added to single archive file
     //If not, then a CSV file containing just occurrence records will be returned
     echo '<li style="font-weight:bold;">Zip Archive created</li>';
     echo '<li style="font-weight:bold;">Adding occurrence records to archive...';
     ob_flush();
     flush();
     //Adding occurrence records
     $fileName = $tempPath . $buFileName;
     $specFH = fopen($fileName . '_spec.csv', "w");
     //Output header
     $headerStr = 'occid,dbpk,basisOfRecord,otherCatalogNumbers,ownerInstitutionCode, ' . 'family,scientificName,sciname,tidinterpreted,genus,specificEpithet,taxonRank,infraspecificEpithet,scientificNameAuthorship, ' . 'taxonRemarks,identifiedBy,dateIdentified,identificationReferences,identificationRemarks,identificationQualifier, ' . 'typeStatus,recordedBy,recordNumber,associatedCollectors,eventDate,year,month,day,startDayOfYear,endDayOfYear, ' . 'verbatimEventDate,habitat,substrate,occurrenceRemarks,informationWithheld,associatedOccurrences, ' . 'dataGeneralizations,associatedTaxa,dynamicProperties,verbatimAttributes,reproductiveCondition, ' . 'cultivationStatus,establishmentMeans,lifeStage,sex,individualCount,country,stateProvince,county,municipality, ' . 'locality,localitySecurity,localitySecurityReason,decimalLatitude,decimalLongitude,geodeticDatum, ' . 'coordinateUncertaintyInMeters,verbatimCoordinates,georeferencedBy,georeferenceProtocol,georeferenceSources, ' . 'georeferenceVerificationStatus,georeferenceRemarks,minimumElevationInMeters,maximumElevationInMeters,verbatimElevation, ' . 'previousIdentifications,disposition,modified,language,processingstatus,recordEnteredBy,duplicateQuantity,dateLastModified ';
     fputcsv($specFH, explode(',', $headerStr));
     //Query and output values
     $sql = 'SELECT ' . $headerStr . ' FROM omoccurrences ' . 'WHERE collid = ' . $collId . ' AND observeruid = ' . $this->uid;
     if ($rs = $this->conn->query($sql)) {
         while ($r = $rs->fetch_row()) {
             if ($characterSet && $characterSet != $cSet) {
                 $this->encodeArr($r, $characterSet);
             }
             fputcsv($specFH, $r);
         }
         $rs->close();
     }
     fclose($specFH);
     if ($zipFile && $zipArchive) {
         //Add occurrence file and then rename to
         $zipArchive->addFile($fileName . '_spec.csv');
         $zipArchive->renameName($fileName . '_spec.csv', 'occurrences.csv');
         //Add determinations
         /*
         echo 'Done!</li> ';
         echo '<li style="font-weight:bold;">Adding determinations records to archive...';
         ob_flush();
         flush();
         $detFH = fopen($fileName.'_det.csv', "w");
         fputcsv($detFH, Array('detid','occid','sciname','scientificNameAuthorship','identifiedBy','d.dateIdentified','identificationQualifier','identificationReferences','identificationRemarks','sortsequence'));
         //Add determination values
         $sql = 'SELECT d.detid,d.occid,d.sciname,d.scientificNameAuthorship,d.identifiedBy,d.dateIdentified, '.
         	'd.identificationQualifier,d.identificationReferences,d.identificationRemarks,d.sortsequence '.
         	'FROM omdeterminations d INNER JOIN omoccurrences o ON d.occid = o.occid '.
         	'WHERE o.collid = '.$this->collId.' AND o.observeruid = '.$this->uid;
             		if($rs = $this->conn->query($sql)){
         	while($r = $rs->fetch_row()){
         		fputcsv($detFH, $r);
         	}
             			$rs->close();
             		}
             		fclose($detFH);
         $zipArchive->addFile($fileName.'_det.csv');
             		$zipArchive->renameName($fileName.'_det.csv','determinations.csv');
         */
         echo 'Done!</li> ';
         ob_flush();
         flush();
         $fileUrl = str_replace($GLOBALS['serverRoot'], $GLOBALS['clientRoot'], $tempPath . $buFileName . '.zip');
         $zipArchive->close();
         unlink($fileName . '_spec.csv');
         //unlink($fileName.'_det.csv');
     } else {
         $fileUrl = str_replace($GLOBALS['serverRoot'], $GLOBALS['clientRoot'], $tempPath . $buFileName . '_spec.csv');
     }
     return $fileUrl;
 }
Example #3
0
    $string = str_replace(array('é', 'è', 'ê', 'ë', 'à', 'â', 'î', 'ï', 'ô', 'ù', 'û', 'ç'), array('E', 'E', 'E', 'E', 'A', 'A', 'I', 'I', 'O', 'U', 'U', 'C'), $string);
    return $string;
}
if (isset($_SESSION['RANKtrombi'])) {
    $RANK = $_SESSION['RANKtrombi'];
} else {
    $RANK = 0;
    echo "pwet";
}
if ($RANK < RANG_PRIVILEGED_USER) {
    die("Vous n'êtes pas autorisé à obtenir un zip");
} else {
    include "./conx/connexion.php";
    $selectPersonnes = $connexion->prepare('SELECT NOM, PRENOM, VILLE, HOBBY, PHOTO FROM ' . $prefixeDB . 'personnes WHERE PHOTO!="" AND SUG=0 ORDER BY NOM, PRENOM ASC;');
    try {
        $selectPersonnes->execute();
    } catch (Exception $e) {
        die('Erreur mySQL : ' . $e->getMessage() . '"})');
    }
    if (file_exists("../tmp/archive.zip")) {
        unlink("../tmp/archive.zip");
    }
    $zip = new ZipArchive();
    $zip->open('../tmp/archive.zip', ZipArchive::CREATE);
    while ($personne = $selectPersonnes->fetch(PDO::FETCH_ASSOC)) {
        $zip->addFile("../img/" . $personne['PHOTO'] . ".jpg");
        $zip->renameName("../img/" . $personne['PHOTO'] . ".jpg", strtoupperFr($personne['NOM'] . "_" . $personne['PRENOM']) . ".jpg");
    }
    $zip->close();
    echo "<a href='../tmp/archive.zip'>Cliquez pour obtenir le zip</a>";
}
 public function createDwcArchive($fileNameSeed = '')
 {
     $status = false;
     if (!$fileNameSeed) {
         if (count($this->collArr) == 1) {
             $firstColl = current($this->collArr);
             if ($firstColl) {
                 $fileNameSeed = $firstColl['instcode'];
                 if ($firstColl['collcode']) {
                     $fileNameSeed .= '-' . $firstColl['collcode'];
                 }
             }
             if ($this->schemaType == 'backup') {
                 $fileNameSeed .= '_backup_' . $this->ts;
             }
         } else {
             $fileNameSeed = 'SymbiotaOutput_' . $this->ts;
         }
     }
     $fileName = str_replace(array(' ', '"', "'"), '', $fileNameSeed) . '_DwC-A.zip';
     if (!$this->targetPath) {
         $this->setTargetPath();
     }
     $archiveFile = '';
     $this->logOrEcho('Creating DwC-A file: ' . $fileName . "\n");
     if (!class_exists('ZipArchive')) {
         $this->logOrEcho("FATAL ERROR: PHP ZipArchive class is not installed, please contact your server admin\n");
         exit('FATAL ERROR: PHP ZipArchive class is not installed, please contact your server admin');
     }
     $status = $this->writeOccurrenceFile();
     if ($status) {
         $archiveFile = $this->targetPath . $fileName;
         if (file_exists($archiveFile)) {
             unlink($archiveFile);
         }
         $zipArchive = new ZipArchive();
         $status = $zipArchive->open($archiveFile, ZipArchive::CREATE);
         if ($status !== true) {
             exit('FATAL ERROR: unable to create archive file: ' . $status);
         }
         //$this->logOrEcho("DWCA created: ".$archiveFile."\n");
         //Occurrences
         $zipArchive->addFile($this->targetPath . $this->ts . '-occur' . $this->fileExt);
         $zipArchive->renameName($this->targetPath . $this->ts . '-occur' . $this->fileExt, 'occurrences' . $this->fileExt);
         //Determination history
         if ($this->includeDets) {
             $this->writeDeterminationFile();
             $zipArchive->addFile($this->targetPath . $this->ts . '-det' . $this->fileExt);
             $zipArchive->renameName($this->targetPath . $this->ts . '-det' . $this->fileExt, 'identifications' . $this->fileExt);
         }
         //Images
         if ($this->includeImgs) {
             $this->writeImageFile();
             $zipArchive->addFile($this->targetPath . $this->ts . '-images' . $this->fileExt);
             $zipArchive->renameName($this->targetPath . $this->ts . '-images' . $this->fileExt, 'images' . $this->fileExt);
         }
         //Meta file
         $this->writeMetaFile();
         $zipArchive->addFile($this->targetPath . $this->ts . '-meta.xml');
         $zipArchive->renameName($this->targetPath . $this->ts . '-meta.xml', 'meta.xml');
         //EML file
         $this->writeEmlFile();
         $zipArchive->addFile($this->targetPath . $this->ts . '-eml.xml');
         $zipArchive->renameName($this->targetPath . $this->ts . '-eml.xml', 'eml.xml');
         $zipArchive->close();
         unlink($this->targetPath . $this->ts . '-occur' . $this->fileExt);
         if ($this->includeDets) {
             unlink($this->targetPath . $this->ts . '-det' . $this->fileExt);
         }
         if ($this->includeImgs) {
             unlink($this->targetPath . $this->ts . '-images' . $this->fileExt);
         }
         unlink($this->targetPath . $this->ts . '-meta.xml');
         if ($this->schemaType == 'dwc') {
             rename($this->targetPath . $this->ts . '-eml.xml', $this->targetPath . str_replace('.zip', '.eml', $fileName));
         } else {
             unlink($this->targetPath . $this->ts . '-eml.xml');
         }
     } else {
         $errStr = "FAILED to create archive file. No records were located in this collection. If records exist, it may be that they don't have Symbiota GUID assignments. Have the portal manager run the GUID mapper (available in sitemap)";
         $this->logOrEcho($errStr);
     }
     $this->logOrEcho("\n-----------------------------------------------------\n");
     return $archiveFile;
 }
function upload_file($bookId, $name)
{
    global $base;
    global $st;
    $uploadfile = $base . "docs/" . $bookId;
    if (!mkdir($uploadfile) and !file_exists($uploadfile)) {
        echo "<pre>" . translate('Problem creating directory', $st, 'sys') . " " . $uploadfile . "</pre>";
    } else {
        if (!chmod($uploadfile, 0777)) {
            echo "<pre>" . translate('Problem setting permissions', $st, 'sys') . " " . $uploadfile . "</pre>";
        } else {
            $ext = substr($_FILES[$name]['name'], strrpos($_FILES[$name]['name'], '.'));
            if ($ext == '.oxes' or $ext == '.OXES') {
                $_FILES[$name]['name'] = 'upload.oxes';
            }
            if (!move_uploaded_file($_FILES[$name]['tmp_name'], $uploadfile . "/" . $_FILES[$name]['name'])) {
                echo "<pre>" . translate('Problem uploading file', $st, 'sys') . " source: " . $_FILES[$name]['tmp_name'] . " dest: " . $uploadfile . "/" . $_FILES[$name]['name'] . "</pre>";
            } else {
                if (strtolower(substr($_FILES[$name]['name'], -4)) == '.zip') {
                    $znames = array();
                    $zip = new ZipArchive();
                    $res = $zip->open($uploadfile . "/" . $_FILES[$name]['name']);
                    if ($res === TRUE) {
                        for ($i = 0; $i < $zip->numFiles; $i++) {
                            $zname = $zip->getNameIndex($i);
                            if (strtolower(substr($zname, -4)) == '.jpg' or strtolower(substr($zname, -5)) == '.oxes') {
                                $zzname = $zname;
                                $pos = strrpos($zzname, "/");
                                if ($pos !== FALSE) {
                                    $zzname = substr($zzname, $pos + 1);
                                }
                                correctExistingFiles($bookId, $zzname);
                                $zip->renameName($zname, $zzname);
                                $znames[] = $zzname;
                            }
                        }
                        $zip->extractTo($uploadfile . "/", $znames);
                        $zip->close();
                        unlink($uploadfile . "/" . $_FILES[$name]['name']);
                    } else {
                        echo "<pre>" . translate('file unzip failed', $st, 'sys');
                    }
                } else {
                    correctExistingFiles($bookId, $_FILES[$name]['name']);
                }
            }
        }
    }
}
function ssfa_file_manager()
{
    $nonce = $_POST['nextNonce'];
    if (!wp_verify_nonce($nonce, 'ssfa-fm-nonce')) {
        die('Granny flew the coop!');
    }
    $action = $_POST['act'];
    $abspath = $GLOBALS['ssfa_abspath'];
    $install = $GLOBALS['ssfa_install'];
    $remove_install = SSFA_ROOT === 'siteurl' ? false : ($install ? true : false);
    // bulk copy action
    if ($action === 'bulkcopy') {
        $from = stripslashes($_POST['from']);
        $to = stripslashes($_POST['to']);
        $ext = $_POST['exts'];
        $destination = SSFA_ROOT === 'siteurl' ? stripslashes($_POST['destination']) : ($GLOBALS['ssfa_install'] ? ssfa_replace_first($GLOBALS['ssfa_install'], '', stripslashes($_POST['destination'])) : stripslashes($_POST['destination']));
        $from = explode('/*//*/', rtrim("{$from}", '/*//*/'));
        $to = explode('/*//*/', rtrim("{$to}", '/*//*/'));
        $ext = explode('/*//*/', rtrim($ext, '/*//*/'));
        $success = 0;
        $total = 0;
        $renamers = 0;
        foreach ($from as $k => $fro) {
            $fro = SSFA_ROOT === 'siteurl' ? "{$fro}" : ($GLOBALS['ssfa_install'] ? ssfa_replace_first($GLOBALS['ssfa_install'], '', "{$fro}") : "{$fro}");
            $to[$k] = SSFA_ROOT === 'siteurl' ? "{$to[$k]}" : ($GLOBALS['ssfa_install'] ? ssfa_replace_first($GLOBALS['ssfa_install'], '', "{$to[$k]}") : "{$to[$k]}");
            $total++;
            $newfile = $abspath . "{$to[$k]}";
            if (is_file($abspath . "{$fro}") && is_file("{$newfile}")) {
                $i = 1;
                $noext = ssfa_replace_last('.' . $ext[$k], '', "{$newfile}");
                while (is_file("{$newfile}")) {
                    if ($i == 1) {
                        $noext = "{$noext}" . " ({$i})";
                    } else {
                        $j = $i - 1;
                        $noext = rtrim("{$noext}", " ({$j})");
                        $noext = "{$noext}" . " ({$i})";
                    }
                    $i++;
                    $newfile = "{$noext}" . '.' . $ext[$k];
                }
                $renamers++;
            }
            if (is_file($abspath . "{$fro}") && !is_file("{$newfile}")) {
                copy($abspath . "{$fro}", "{$newfile}");
            }
            if (is_file("{$newfile}")) {
                $success++;
            }
        }
        $response = $success == 0 ? 'There was a problem copying the files. Please consult your local pharmacist.' : ($success == 1 ? "One file was copied to {$destination} and it no longer feels special." : ($success > 1 ? "{$success} of {$total} files were successfully cloned and delivered in a black caravan to {$destination}." : null));
        // bulk move action
    } elseif ($action === 'bulkmove') {
        $from = stripslashes($_POST["from"]);
        $to = stripslashes($_POST["to"]);
        $ext = $_POST['exts'];
        $destination = SSFA_ROOT === 'siteurl' ? stripslashes($_POST["destination"]) : ($GLOBALS['ssfa_install'] ? ssfa_replace_first($GLOBALS["ssfa_install"], '', stripslashes($_POST["destination"])) : stripslashes($_POST["destination"]));
        $from = explode('/*//*/', rtrim("{$from}", '/*//*/'));
        $to = explode('/*//*/', rtrim("{$to}", '/*//*/'));
        $ext = explode('/*//*/', rtrim($ext, '/*//*/'));
        $success = 0;
        $total = 0;
        $renamers = 0;
        foreach ($from as $k => $fro) {
            $fro = SSFA_ROOT === 'siteurl' ? "{$fro}" : ($GLOBALS['ssfa_install'] ? ssfa_replace_first($GLOBALS['ssfa_install'], '', "{$fro}") : "{$fro}");
            $to[$k] = SSFA_ROOT === 'siteurl' ? "{$to[$k]}" : ($GLOBALS['ssfa_install'] ? ssfa_replace_first($GLOBALS['ssfa_install'], '', "{$to[$k]}") : "{$to[$k]}");
            $total++;
            $newfile = $abspath . "{$to[$k]}";
            if (is_file($abspath . "{$fro}") && is_file("{$newfile}")) {
                $i = 1;
                $noext = ssfa_replace_last('.' . $ext[$k], '', $newfile);
                while (is_file("{$newfile}")) {
                    if ($i == 1) {
                        $noext = "{$noext}" . " ({$i})";
                    } else {
                        $j = $i - 1;
                        $noext = rtrim("{$noext}", " ({$j})");
                        $noext = "{$noext}" . " ({$i})";
                    }
                    $i++;
                    $newfile = "{$noext}" . '.' . $ext[$k];
                }
                $renamers++;
            }
            if (is_file($abspath . "{$fro}") && !is_file("{$newfile}")) {
                rename($abspath . "{$fro}", "{$newfile}");
            }
            if (is_file("{$newfile}")) {
                $success++;
            }
        }
        $response = $success == 0 ? 'There was a problem moving the files. Please consult your local ouija specialist.' : ($success == 1 ? "One lonesome file was forced to leave all it knew and move to {$destination}." : ($success > 1 ? "{$success} of {$total} files were magically transported to {$destination}. Or was it Delaware?" : null));
        // bulk download action
    } elseif ($action === 'bulkdownload') {
        $files = stripslashes($_POST["files"]);
        $files = explode('/*//*/', rtrim("{$files}", '/*//*/'));
        $zipfiles = array();
        $values = array();
        foreach ($files as $file) {
            $file = $remove_install ? ssfa_replace_first($install, '', $abspath . $file) : $abspath . $file;
            if (file_exists($file)) {
                $zipfiles[] = $file;
                $values[] = basename($file);
            }
        }
        $numvals = array_count_values($values);
        $sitename = get_bloginfo('name');
        $time = uniqid();
        $destination = SSFA_PLUGIN . '/ssfatemp';
        if (!is_dir($destination)) {
            mkdir($destination);
        }
        $filename = $sitename . ' ' . $time . '.zip';
        $link = SSFA_PLUGIN_URL . '/ssfatemp/' . $filename;
        $filename = $destination . '/' . $filename;
        if (count($zipfiles)) {
            $zip = new ZipArchive();
            $zip->open($filename, ZipArchive::CREATE);
            foreach ($zipfiles as $k => $zipfile) {
                $zip->addFile($zipfile, basename($zipfile));
                if ($numvals[basename($zipfile)] > 1) {
                    $parts = pathinfo($zipfile);
                    $zip->renameName(basename($zipfile), $parts['filename'] . '_' . $k . '.' . $parts['extension']);
                }
            }
            $zip->close();
        }
        $response = is_file($filename) ? $link : "Error";
        // bulk delete action
    } elseif ($action === 'bulkdelete') {
        $files = $_POST['files'];
        $files = explode('/*//*/', rtrim($files, '/*//*/'));
        $success = 0;
        $total = 0;
        foreach ($files as $k => $file) {
            $file = SSFA_ROOT === 'siteurl' ? $file : ($GLOBALS['ssfa_install'] ? ssfa_replace_first($GLOBALS['ssfa_install'], '', $file) : $file);
            $total++;
            if (is_file($abspath . $file)) {
                unlink($abspath . $file);
            }
            if (!is_file($abspath . $file)) {
                $success++;
            }
        }
        $response = $success == 0 ? 'There was a problem deleting the files. Please try pressing your delete button emphatically and repeatedly.' : ($success == 1 ? "A million fewer files in the world is a victory. One less file, a tragedy. Farewell, file. Au revoir. Auf Wiedersehen. Adieu." : ($success > 1 ? "{$success} of {$total} files were sent plummeting to the nether regions of cyberspace. Or was it Delaware?" : null));
        // delete action
    } elseif ($action === 'delete') {
        $pp = SSFA_ROOT === 'siteurl' ? $_POST['pp'] : ($GLOBALS['ssfa_install'] ? ssfa_replace_first($GLOBALS['ssfa_install'], '', $_POST['pp']) : $_POST['pp']);
        $oldname = $_POST['oldname'];
        $ext = $_POST['ext'];
        $oldfile = $abspath . "{$pp}/{$oldname}.{$ext}";
        if (is_file("{$oldfile}")) {
            unlink("{$oldfile}");
        }
        if (!is_file("{$oldfile}")) {
            $response = "success";
        } elseif (is_file("oldfile")) {
            $response = "failure";
        }
        // rename action
    } elseif ($action === 'rename') {
        $url = stripslashes($_POST['url']);
        $pp = SSFA_ROOT === 'siteurl' ? $_POST['pp'] : ($GLOBALS['ssfa_install'] ? ssfa_replace_first($GLOBALS['ssfa_install'], '', stripslashes($_POST['pp'])) : stripslashes($_POST['pp']));
        $oldname = stripslashes($_POST['oldname']);
        $rawname = stripslashes($_POST['rawname']);
        $ext = $_POST['ext'];
        $oldfile = $abspath . "{$pp}/{$oldname}.{$ext}";
        $customdata = stripslashes($_POST['customdata']);
        $customdata = rtrim("{$customdata}", ',');
        if ($customdata !== '') {
            $customdata = " [{$customdata}]";
        } else {
            $customdata = null;
        }
        $newfile = $abspath . "{$pp}/{$rawname}{$customdata}.{$ext}";
        if ($newfile !== $oldfile) {
            $i = 1;
            while (is_file($newfile)) {
                if ($i == 1) {
                    $rawname = "{$rawname}" . " ({$i})";
                } else {
                    $j = $i - 1;
                    $rawname = rtrim("{$rawname}", " ({$j})");
                    $rawname = "{$rawname}" . " ({$i})";
                }
                $i++;
                $newfile = $abspath . "{$pp}/{$rawname}{$customdata}.{$ext}";
            }
        }
        if ($customdata !== null) {
            $customdata = " [" . trim(ltrim(rtrim("{$customdata}", "]"), " ["), " ") . "]";
        }
        $newfile = $abspath . "{$pp}/" . trim("{$rawname}", ' ') . "{$customdata}.{$ext}";
        $newurl = str_replace("{$pp}/{$oldname}.{$ext}", "", "{$url}");
        $newurl = "{$newurl}{$pp}/" . trim("{$rawname}", ' ') . "{$customdata}.{$ext}";
        $newoldname = trim("{$rawname}", ' ') . "{$customdata}.{$ext}";
        $download = trim("{$rawname}", ' ') . "{$customdata}.{$ext}";
        if (is_file("{$oldfile}")) {
            rename("{$oldfile}", "{$newfile}");
        }
        $errors = '';
        if (!is_file("{$newfile}")) {
            $errors = 'The file was not renamed.';
        }
        $response = array("errors" => $errors, "download" => $download, "pp" => $pp, "newurl" => $newurl, "extension" => $ext, "oldfile" => $oldfile, "newfile" => $newfile, "rawname" => $rawname, "customdata" => $customdata, "newoldname" => $newoldname);
        // get action path
    } elseif ($action === 'getactionpath') {
        $fileup = $_POST['uploadaction'] === 'true' ? 'fileup-' : '';
        $build = null;
        if (SSFA_ROOT === 'siteurl' || SSFA_ROOT !== 'siteurl' && $GLOBALS['ssfa_install'] == false) {
            $pp = $_POST['pp'];
            $st = trim($_POST['st'], '/');
        } elseif (SSFA_ROOT !== 'siteurl' && $GLOBALS['ssfa_install'] !== false) {
            $pp = ssfa_replace_first($GLOBALS['ssfa_install'], '', $_POST['pp']);
            $st = trim(ssfa_replace_first($GLOBALS['ssfa_install'], '', $_POST['st']), '/');
        }
        if ($pp === '/') {
            $pp = $st;
        }
        $pp = trim($pp, '/');
        $sht = trim($_POST['sht'], '/');
        if (!ssfa_startswith($pp, $st)) {
            $pp = $st;
        }
        $security = $st === $sht ? 0 : 1;
        $nocrumbs = $security ? trim(ssfa_replace_last("{$sht}", '', "{$st}"), '/') : null;
        if (strpos($pp, '..') !== false) {
            $pp = $st;
        }
        $dir = $abspath . $pp;
        $build .= "<option></option>";
        $directories = glob($dir . "/*", GLOB_ONLYDIR);
        if ($directories) {
            foreach ($directories as $k => $folder) {
                $direxcluded = 0;
                if (SSFA_DIR_EXCLUSIONS) {
                    $direxes = preg_split('/(, |,)/', SSFA_DIR_EXCLUSIONS);
                    foreach ($direxes as $direx) {
                        $check = strripos($folder, $direx);
                        if ($check !== false) {
                            $direxcluded = 1;
                            break;
                        }
                    }
                }
                if (!$direxcluded) {
                    $folder = str_replace($abspath, '', $folder);
                    $dirname = explode('/', $folder);
                    $dirname = end($dirname);
                    $build .= '<option value="' . $folder . '">' . $dirname . '</option>';
                }
            }
        } else {
            $build .= '';
        }
        if ($security) {
            $pieces = explode('/', trim(trim(ssfa_replace_first("{$nocrumbs}", '', "{$pp}"), '/'), '/'));
        } else {
            $pieces = explode('/', trim("{$pp}", '/'));
        }
        $piecelink = array();
        $breadcrumbs = null;
        foreach ($pieces as $k => $piece) {
            $i = 0;
            $piecelink[$k] = $security ? "{$nocrumbs}/" : null;
            while ($i <= $k) {
                $piecelink[$k] .= "{$pieces[$i]}/";
                $i++;
            }
            $breadcrumbs .= '<a href="javascript:" data-target="' . trim($piecelink[$k], '/') . '" id="ssfa-' . $fileup . 'action-pathpart-' . $k . '">' . ssfa_strtotitle($piece) . '</a> / ';
        }
        $breadcrumbs = stripslashes($breadcrumbs);
        $pp = stripslashes($pp);
        $build = stripslashes($build);
        $response = array("ops" => $build, "crumbs" => $breadcrumbs, "pp" => $pp);
        // Create Sub-Directory
    } elseif ($action === 'createdir') {
        $parents = trim(str_replace('.', '', $_POST['parents']), '/');
        $newsub = trim(str_replace('.', '', $_POST['newsub']), '/');
        $uid = $_POST['uid'];
        $count = $_POST['count'];
        $page = $_POST['page'];
        $drawericon = $_POST['drawer'];
        $cells = $_POST['cells'];
        $class = $_POST['cls'];
        $base = $_POST['base'];
        $subs = explode('/', $newsub);
        $first = $subs[0];
        $last = $subs[count($subs) - 1];
        $start = trim(ssfa_replace_first($base, '', $parents) . '/' . $first, '/');
        $drawer = str_replace('/', '*', $start);
        $parents = SSFA_ROOT === 'siteurl' ? stripslashes($parents) : ($GLOBALS['ssfa_install'] ? ssfa_replace_first($GLOBALS['ssfa_install'], '', stripslashes($parents)) : stripslashes($parents));
        $final = $abspath . $parents . '/' . $newsub;
        $prettyfolder = str_replace(array('~', '--', '_', '.', '*'), ' ', "{$first}");
        $prettyfolder = preg_replace('/(?<=\\D)-(?=\\D)/', ' ', "{$prettyfolder}");
        $prettyfolder = preg_replace('/(?<=\\D)-(?=\\d)/', ' ', "{$prettyfolder}");
        $prettyfolder = preg_replace('/(?<=\\d)-(?=\\D)/', ' ', "{$prettyfolder}");
        $prettyfolder = ssfa_strtotitle($prettyfolder);
        if (is_dir($final)) {
            $response = array('status' => 'error', 'message' => 'That directory name already exists in this location.');
        } else {
            $first_exists = is_dir($abspath . $parents . '/' . $first) ? true : false;
            if (mkdir($final, 0755, true)) {
                if (!$first_exists) {
                    $status = "insert";
                    $message = "<tr id='ssfa-dir-{$uid}-{$count}' class='ssfa-drawers'>" . "<td id='folder-ssfa-dir-{$uid}-{$count}' data-value=\"00-{$first}\" class='ssfa-sorttype {$class}-first-column'>" . "<a href=\"" . add_query_arg(array('drawer' => $drawer), get_permalink($page)) . "\" data-path=\"" . $start . "\">" . "<span style='font-size:20px; margin-left:3px;' class='ssfa-icon-{$drawericon}' aria-hidden='true'></span>" . "<br>dir" . "</a>" . "</td>" . "<td id='name-ssfa-dir-{$uid}-{$count}' data-value='00-{$first}' class='ssfa-sortname'>" . "<a href=\"" . add_query_arg(array('drawer' => $drawer), get_permalink($page)) . "\">" . "<span style='text-transform:uppercase;'>{$prettyfolder}</span>" . "</a>" . "<input id='rename-ssfa-dir-{$uid}-{$count}' type='text' value=\"{$first}\" " . "style='width:90%; height:26px; font-size:12px; text-align:center; display:none'>" . "</td>";
                    $icell = 1;
                    while ($icell < $cells) {
                        $message .= "<td class='{$class}'> &nbsp; </td>";
                        $icell++;
                    }
                    $message .= "<td id='manager-ssfa-dir-{$uid}-{$count}' class='{$class}'>" . "<a href='' id='rename-ssfa-dir-{$uid}-{$count}'>Rename</a><br><a href='' id='delete-ssfa-dir-{$uid}-{$count}'>Delete</a>" . "</td>";
                    $message .= "</tr>";
                } else {
                    $status = "success";
                    $message = "Your sub-directories have been sucessfully created.";
                }
                $response = array('status' => $status, 'message' => $message, 'uid' => $uid);
            } else {
                $response = array('status' => 'error', 'message' => 'Sorry, there was a problem creating that directory for you.');
            }
        }
        // Rename Directory
    } elseif ($action === 'renamedir') {
        $oldpath = trim(str_replace('..', '', $_POST['oldpath']), '/');
        $oldpath = SSFA_ROOT === 'siteurl' ? stripslashes($oldpath) : ($GLOBALS['ssfa_install'] ? ssfa_replace_first($GLOBALS['ssfa_install'], '', stripslashes($oldpath)) : stripslashes($oldpath));
        $newname = str_replace(array('..', '/'), '', $_POST['newname']);
        $pp = explode('/', $oldpath);
        $newpath = str_replace(end($pp), $newname, $oldpath);
        $olddata = $_POST['datapath'];
        $datapp = explode('/', $olddata);
        $newdata = str_replace(end($datapp), $newname, $olddata);
        $parents = $_POST['parents'];
        $parents = SSFA_ROOT === 'siteurl' ? stripslashes($parents) : ($GLOBALS['ssfa_install'] ? ssfa_replace_first($GLOBALS['ssfa_install'], '', stripslashes($parents)) : stripslashes($parents));
        $old = $parents . '/' . end($pp);
        $dst = $abspath . $newpath;
        $src = $abspath . $old;
        $page = $_POST['page'];
        $drawer = str_replace('/', '*', $newdata);
        $newurl = add_query_arg(array('drawer' => $drawer), get_permalink($page));
        $response = false;
        if (is_dir($dst)) {
            $response = array('status' => 'error', 'message' => 'That directory already exists.');
        } elseif (!is_dir($src)) {
            $response = array('status' => 'error', 'message' => "The directory you're trying to rename could not be found.");
        } else {
            if (!is_dir("{$dst}")) {
                mkdir("{$dst}", 0755, true);
            }
            $dirs = ssfa_recursive_dirs($src);
            if (is_array($dirs)) {
                $dirs = array_reverse($dirs);
                $fcount = 0;
                $fscount = 0;
                $dcount = 1;
                $dscount = 0;
                foreach ($dirs as $dir) {
                    $dcount++;
                    $files = false;
                    $filedest = str_replace("{$src}", "{$dst}", "{$dir}");
                    if (!is_dir($filedest)) {
                        mkdir("{$filedest}", 0755, true);
                    }
                    $files = array_filter(glob("{$dir}" . "/*"), 'is_file');
                    if (is_array($files)) {
                        foreach ($files as $file) {
                            $fcount++;
                            $filename = pathinfo($file, PATHINFO_BASENAME);
                            if (rename("{$file}", "{$filedest}" . "/" . "{$filename}")) {
                                $fscount++;
                            }
                        }
                    }
                    if (rmdir($dir)) {
                        $dscount++;
                    }
                }
            }
            $basefiles = array_filter(glob("{$src}" . "/*"), 'is_file');
            if (is_array($basefiles)) {
                foreach ($basefiles as $file) {
                    $fcount++;
                    $filename = pathinfo($file, PATHINFO_BASENAME);
                    if (rename("{$file}", "{$dst}" . "/" . "{$filename}")) {
                        $fscount++;
                    }
                }
            }
            if (rmdir($src)) {
                $dscount++;
            }
            if ($fcount > 0 && !$fscount) {
                $response = array('status' => 'error', 'message' => 'We tried to move the files into the newly-named directory but none of them would budge.');
            } elseif ($fcount > 0 && $fcount > $fscount) {
                $response = array('status' => 'error', 'message' => "We tried to move the files into the newly-named directory, but there were some stragglers, so we couldn't remove the old directory.");
            } elseif (!is_dir($src)) {
                $response = array('status' => 'success', 'url' => $newurl, 'newdata' => $newdata, 'newname' => $newname);
            } else {
                $response = array('status' => 'error', 'message' => 'An unspecified error occurred.');
            }
        }
        // Delete Directory
    } elseif ($action === 'deletedir') {
        $status = $_POST['status'];
        $path1 = $_POST['path1'];
        $path2 = $_POST['path2'];
        $path = SSFA_ROOT === 'siteurl' ? stripslashes($path1 . '/' . $path2) : ($GLOBALS['ssfa_install'] ? ssfa_replace_first($GLOBALS['ssfa_install'], '', stripslashes($path1 . '/' . $path2)) : stripslashes($path1 . '/' . $path2));
        $src = $abspath . $path;
        $response = false;
        if (!is_dir("{$src}")) {
            $response = array('status' => 'error', 'message' => 'The directory marked for deletion could not be found. ' . $path);
        } else {
            $dirs = ssfa_recursive_dirs($src);
            $dirs = is_array($dirs) ? array_reverse($dirs) : $dirs;
            if ($status === 'life') {
                $dcount = 0;
                $fcount = 0;
                if (is_array($dirs)) {
                    foreach ($dirs as $dir) {
                        $dcount++;
                        $files = false;
                        $files = array_filter(glob("{$dir}" . "/*"), 'is_file');
                        if (is_array($files)) {
                            foreach ($files as $file) {
                                $fcount++;
                            }
                        }
                    }
                }
                $basefiles = array_filter(glob("{$src}" . "/*"), 'is_file');
                if (is_array($basefiles)) {
                    foreach ($basefiles as $file) {
                        $fcount++;
                    }
                }
                if ($fcount == 0) {
                    $status = 'death';
                } else {
                    $filemsg = null;
                    if ($fcount >= 1) {
                        $plufiles = $fcount > 1 ? 'files' : 'file';
                        $filemsg = ' and ' . $fcount . ' ' . $plufiles;
                    }
                    $dirmsg = null;
                    if ($dcount >= 1) {
                        $pludirs = $dcount > 1 ? 'sub-directories' : 'sub-directory';
                        $dirmsg = ', ' . $dcount . ' ' . $pludirs;
                    }
                    $message = 'You are about to delete 1 directory' . $dirmsg . $filemsg . ' from the server. This action is permanent and cannot be undone. Are you sure you wish to proceed?';
                    $response = array('status' => 'confirm', 'message' => $message);
                }
            }
            if ($status === 'death') {
                $pcount = 1;
                $pscount = 0;
                $dcount = 0;
                $dscount = 0;
                $fcount = 0;
                $fscount = 0;
                if (is_array($dirs)) {
                    foreach ($dirs as $dir) {
                        $dcount++;
                        $files = false;
                        $files = array_filter(glob("{$dir}" . "/*"), 'is_file');
                        if (is_array($files)) {
                            foreach ($files as $file) {
                                $fcount++;
                                $file = realpath($file);
                                if (is_readable($file)) {
                                    if (unlink($file)) {
                                        $fscount++;
                                    }
                                }
                            }
                        }
                        if (rmdir($dir)) {
                            $dscount++;
                        }
                    }
                }
                $basefiles = array_filter(glob("{$src}" . "/*"), 'is_file');
                if (is_array($basefiles)) {
                    foreach ($basefiles as $file) {
                        $fcount++;
                        $file = realpath($file);
                        if (is_readable($file)) {
                            if (unlink($file)) {
                                $fscount++;
                            }
                        }
                    }
                }
                if (rmdir($src)) {
                    $pscount++;
                }
                if ($pscount && $fscount || $pscount && !$fcount) {
                    $success = $pscount == $pcount && $dscount == $dcount && $fscount == $fcount ? 'success' : 'partial';
                    $success = $fscount == $fcount && !$fcount ? 'success-single' : $success;
                    $filemsg = null;
                    if ($fcount >= 1) {
                        $plufiles = $fcount > 1 ? 'files' : 'file';
                        $filemsg = ' and ' . $fscount . ' of ' . $fcount . ' ' . $plufiles;
                    } else {
                        $filemsg = ' and ' . $fcount . ' files';
                    }
                    $dirmsg = null;
                    if ($dcount >= 1) {
                        $pludirs = $dcount > 1 ? 'sub-directories' : 'sub-directory';
                        $dirmsg = ', ' . $dscount . ' of ' . $dcount . ' ' . $pludirs;
                    }
                    $message = $pscount . ' of 1 directories' . $dirmsg . $filemsg . ' have been removed from the server.';
                    $response = array('status' => $success, 'message' => $message);
                } else {
                    $response = array('status' => 'error', 'message' => 'Sorry, but there was an error attempting to remove this directory.');
                }
            }
        }
        // report possible saboteur
    } elseif ($action === 'saboteur') {
        $user = wp_get_current_user();
        $name = $user->display_name;
        $id = $user->ID;
        $login = $user->user_login;
        $time = date('Y-m-d H:i:s', strtotime('NOW'));
        foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key) {
            if (array_key_exists($key, $_SERVER) === true) {
                foreach (explode(',', $_SERVER[$key]) as $ip) {
                    if (filter_var($ip, FILTER_VALIDATE_IP) !== false) {
                        $userip = $ip;
                    }
                }
            }
        }
        $to = get_option('admin_email');
        $subject = "Automated Security Alert from File Away re: {$name}";
        $message = "This user may have tried to manipulate restricted directories:\r\n\r\n";
        $message .= "Name: " . $name . "\r\n";
        $message .= "Username: "******"\r\n";
        $message .= "User ID: " . $id . "\r\n";
        $message .= "IP Address: " . $userip . "\r\n";
        $message .= "Time: " . $time . "\r\n\r\n\r\n";
        $message .= "Sincerely,\r\n";
        $message .= "File Away\r\n";
        mail($to, $subject, $message);
        $response = wp_logout_url();
        // FileUp Upload Handler
    } elseif ($action === 'upload') {
        if (isset($_POST) && $_SERVER['REQUEST_METHOD'] == "POST") {
            $file_name = strip_tags($_FILES['upload_file']['name']);
            $new_name = strip_tags($_POST['new_name']);
            $file_id = strip_tags($_POST['upload_file_id']);
            $file_size = $_FILES['upload_file']['size'];
            $max_file_size = (int) $_POST['max_file_size'];
            $file_path = trim($_POST['upload_path'], '/');
            $location = str_replace('//', '/', $abspath . $file_path . '/' . $new_name);
            $dir = dirname($location);
            $_POST['size_check'] = $file_size > $max_file_size ? 'true' : 'false';
            if ($file_size > $max_file_size) {
                echo 'system_error';
            } elseif (strpos($dir, '..') !== false) {
                echo 'system_error';
            } else {
                if (!is_dir($dir)) {
                    mkdir($dir, 0755, true);
                }
                $p = pathinfo($location);
                $filename = $p['filename'];
                $i = 1;
                while (is_file($location)) {
                    if ($i == 1) {
                        $filename = $filename . " ({$i})";
                    } else {
                        $j = $i - 1;
                        $filename = rtrim($filename, " ({$j})");
                        $filename = $filename . " ({$i})";
                    }
                    $i++;
                    $name = $filename . '.' . $p['extension'];
                    $location = $p['dirname'] . '/' . $name;
                }
                $name = $filename . '.' . $p['extension'];
                $location = $p['dirname'] . '/' . $name;
                if (move_uploaded_file(strip_tags($_FILES['upload_file']['tmp_name']), $location)) {
                    echo $file_id;
                } else {
                    echo 'system_error';
                }
            }
            exit;
        } else {
            echo 'system_error';
            exit;
        }
    }
    $response = json_encode($response);
    header("Content-Type: application/json");
    echo $response;
    exit;
}
 public function createDwcArchive($fileNameSeed = '')
 {
     $status = false;
     if (!$fileNameSeed) {
         if (count($this->collArr) == 1) {
             $firstColl = current($this->collArr);
             if ($firstColl) {
                 $fileNameSeed = $firstColl['instcode'];
                 if ($firstColl['collcode']) {
                     $fileNameSeed .= '-' . $firstColl['collcode'];
                 }
             }
             if ($this->schemaType == 'backup') {
                 $fileNameSeed .= '_backup_' . $this->ts;
             }
         } else {
             $fileNameSeed = 'SymbiotaOutput_' . $this->ts;
         }
     }
     $fileName = str_replace(array(' ', '"', "'"), '', $fileNameSeed) . '_DwC-A.zip';
     if (!$this->targetPath) {
         $this->setTargetPath();
     }
     $archiveFile = '';
     $this->logOrEcho('Creating DwC-A file: ' . $fileName . "\n");
     if (!class_exists('ZipArchive')) {
         $this->logOrEcho("FATAL ERROR: PHP ZipArchive class is not installed, please contact your server admin\n");
         exit('FATAL ERROR: PHP ZipArchive class is not installed, please contact your server admin');
     }
     $status = $this->writeOccurrenceFile();
     if ($status) {
         $archiveFile = $this->targetPath . $fileName;
         if (file_exists($archiveFile)) {
             unlink($archiveFile);
         }
         $zipArchive = new ZipArchive();
         $status = $zipArchive->open($archiveFile, ZipArchive::CREATE);
         if ($status !== true) {
             exit('FATAL ERROR: unable to create archive file: ' . $status);
         }
         //$this->logOrEcho("DWCA created: ".$archiveFile."\n");
         //Occurrences
         $zipArchive->addFile($this->targetPath . $this->ts . '-occur' . $this->fileExt);
         $zipArchive->renameName($this->targetPath . $this->ts . '-occur' . $this->fileExt, 'occurrences' . $this->fileExt);
         //Determination history
         if ($this->includeDets) {
             $this->writeDeterminationFile();
             $zipArchive->addFile($this->targetPath . $this->ts . '-det' . $this->fileExt);
             $zipArchive->renameName($this->targetPath . $this->ts . '-det' . $this->fileExt, 'identifications' . $this->fileExt);
         }
         //Images
         if ($this->includeImgs) {
             $this->writeImageFile();
             $zipArchive->addFile($this->targetPath . $this->ts . '-images' . $this->fileExt);
             $zipArchive->renameName($this->targetPath . $this->ts . '-images' . $this->fileExt, 'images' . $this->fileExt);
         }
         //Meta file
         $this->writeMetaFile();
         $zipArchive->addFile($this->targetPath . $this->ts . '-meta.xml');
         $zipArchive->renameName($this->targetPath . $this->ts . '-meta.xml', 'meta.xml');
         //EML file
         $this->writeEmlFile();
         $zipArchive->addFile($this->targetPath . $this->ts . '-eml.xml');
         $zipArchive->renameName($this->targetPath . $this->ts . '-eml.xml', 'eml.xml');
         $zipArchive->close();
         unlink($this->targetPath . $this->ts . '-occur' . $this->fileExt);
         if ($this->includeDets) {
             unlink($this->targetPath . $this->ts . '-det' . $this->fileExt);
         }
         if ($this->includeImgs) {
             unlink($this->targetPath . $this->ts . '-images' . $this->fileExt);
         }
         unlink($this->targetPath . $this->ts . '-meta.xml');
         if ($this->schemaType == 'dwc') {
             rename($this->targetPath . $this->ts . '-eml.xml', $this->targetPath . str_replace('.zip', '.eml', $fileName));
         } else {
             unlink($this->targetPath . $this->ts . '-eml.xml');
         }
     } else {
         $errStr = "<span style='color:red;'>FAILED to create archive file due to failure to return occurrence records. " . "Note that OccurrenceID GUID assignments are required for Darwin Core Archive publishing. " . "Symbiota GUID (recordID) assignments are also required, which can be verified by the portal manager through running the GUID mapping utilitiy available in sitemap</span>";
         $this->logOrEcho($errStr);
         $collid = key($this->collArr);
         if ($collid) {
             $this->deleteArchive($collid);
         }
         unset($this->collArr[$collid]);
     }
     $this->logOrEcho("\n-----------------------------------------------------\n");
     return $archiveFile;
 }
 public function manager()
 {
     $dm = 'Go directly to jail. Do not pass GO. Do not collect $200 dollars.';
     if (!wp_verify_nonce($_POST['nonce'], 'fileaway-nonce')) {
         die($dm);
     }
     $li = is_user_logged_in();
     extract($this->pathoptions);
     $action = $_POST['act'];
     // Flightbox
     if ($action === 'flightbox') {
         if (!wp_verify_nonce($_POST['flightbox_nonce'], 'fileaway-flightbox-nonce')) {
             die($dm);
         }
         list($url, $query) = explode('?boxtype=', $_POST['url']);
         $src = $url;
         $query = 'boxtype=' . $query;
         parse_str($query);
         if (($s2 == 'true' || $s2 == 'skip') && $g == 'false') {
             $s2skip = $s2 == 'skip' ? '&s2member_skip_confirmation' : '';
             $init = fileaway_utility::replacefirst($url, rtrim($this->settings['baseurl'], '/') . '/', $rootpath);
             $sub = fileaway_utility::replacefirst($init, WP_PLUGIN_DIR . '/s2member-files/', '');
             $url = rtrim($this->settings['baseurl'], '/') . '/?s2member_file_download=' . $sub . $s2skip;
         }
         $url = $g == 'true' ? $this->settings['redirect'] : $url;
         $statstatus = $s == 'true' ? ' data-stat="true"' : ' data-stat="false"';
         $linktype = $g == 'true' || $GLOBALS['is_IE'] || $GLOBALS['is_safari'] ? 'target="_blank"' : 'download';
         $uid = (string) $_POST['uid'];
         $icons = (string) $_POST['icons'];
         $next = stripslashes($_POST['next']);
         $prev = stripslashes($_POST['prev']);
         $current = stripslashes($_POST['current']);
         $nolinks = $_POST['nolinks'] == 'true' ? true : false;
         $wh = $_POST['wh'];
         $ww = $_POST['ww'];
         if ($wh > 1000) {
             $font = 20;
             $bar = 40;
             $mrg = 20;
         } elseif ($wh > 800) {
             $font = 16;
             $bar = 32;
             $mrg = 16;
         } elseif ($wh > 600) {
             $font = 14;
             $bar = 28;
             $mrg = 14;
         } elseif ($wh > 400) {
             $font = 12;
             $bar = 24;
             $mrg = 12;
         } else {
             $font = 8;
             $bar = 20;
             $mrg = 8;
         }
         if ($boxtype == 'image') {
             if ($wh < $mh + 150) {
                 $mh = $wh - 150;
             }
             if ($ww < $mw) {
                 $mw = $ww - 150;
             }
             if ($d == 'width') {
                 $ratio = $w / $h;
                 $width = $w < $mw ? $w : $mw;
                 $height = round($width / $ratio, 0);
                 if ($height > $mh) {
                     $d = 'height';
                 }
             }
             if ($d == 'height') {
                 $ratio = $h / $w;
                 $height = $h < $mh ? $h : $mh;
                 $width = round($height / $ratio, 0);
             }
             if ($width < 200) {
                 $offset = ($ww - 230) / 2;
                 $cwidth = 200 + 30;
                 $cheight = $height + $bar + 30;
             } else {
                 $offset = ($ww - ($width + 30)) / 2;
                 $cwidth = $width + 30;
                 $cheight = $height + $bar + 30;
             }
             $csize = 'width:' . $cwidth . 'px; height:' . $cheight . 'px;';
             $isize = 'width:' . $width . 'px; height:' . $height . 'px;';
             $top = $wh < $height + $bar + 30 ? '0' : ($wh - ($height + $bar + 30)) / 2;
             $download_link = $nolinks ? null : '<a href="' . $url . '" class="ssfa-flightbox-download" ' . $linktype . $statstatus . '>' . '<span class="ssfa-icon-arrow-down-2" style="font-size:' . $font . 'px; margin-right:5px; display:inline-block;"></span>' . '</a>';
             $response = array('html' => '<div id="ssfa-flightbox" class="' . $_POST['theme'] . '" style="display:inline-block; ' . $csize . ' left:' . $offset . 'px; top:' . $top . 'px; padding:0px!important;">' . '<div id="ssfa-flightbox-inner" style="opacity:0; margin: 15px 15px 0!important;">' . '<a href="' . $_POST['nexturl'] . '" onclick="' . $next . '"><img src="' . $src . '" style="' . $isize . '"></a>' . '</div>' . '<div class="ssfa-flightbox-controls ' . $icons . '" style="margin:' . $mrg . 'px 15px!important; display:block; text-align:right;">' . '<a href="' . $_POST['prevurl'] . '" onclick="' . $prev . '">' . '<span class="ssfa-icon-arrow-left-2" style="font-size:' . $font . 'px; margin-right:5px; display:inline-block;"></span>' . '</a>' . '<a href="' . $_POST['nexturl'] . '" onclick="' . $next . '">' . '<span class="ssfa-icon-arrow-right-2" style="font-size:' . $font . 'px; margin-right:5px; display:inline-block;"></span>' . '</a>' . $download_link . '<a href="javascript:" onclick="Xflightbox();">' . '<span class="ssfa-icon-console-2" style="font-size:' . $font . 'px; margin-right:0; display:inline-block;"></span>' . '</a>' . '</div>' . '</div>', 'width' => $cwidth . 'px', 'height' => $cheight . 'px', 'top' => $top . 'px', 'offset' => $offset . 'px', 'iframe' => 'false');
         } elseif ($boxtype == 'video') {
             $is_iframe = 'true';
             $ratio = 1920 / 1080;
             $height = round($w / $ratio, 0);
             if ($wh < $height + 150) {
                 $height = $wh - 150;
                 $w = round($height * $ratio, 0);
             }
             $csize = 'width:' . ($w + 30) . 'px; height:' . ($height + $bar + 30) . 'px;';
             $top = $wh < $height + $bar + 30 ? '0' : ($wh - ($height + $bar + 30)) / 2;
             $offset = ($ww - ($w + 30)) / 2;
             if ($e == 'vmeo') {
                 $download = null;
                 $vimeo = explode('vimeo.com/', $src);
                 $vid_id = $vimeo[1];
                 $video = '<iframe src="//player.vimeo.com/video/' . $vid_id . '?title=0&amp;byline=0&amp;portrait=0&amp;color=ffffff&amp;autoplay=0" ' . 'width="' . $w . '" height="' . $height . '" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';
             } elseif ($e == 'tube') {
                 $download = null;
                 if (stripos($src, 'youtu.be/') !== false) {
                     $youtube = explode('youtu.be/', $src);
                     $yt = explode('?', $youtube[1]);
                     $vid_id = $yt[0];
                 } else {
                     $youtube = explode('?', $src);
                     parse_str($youtube[1], $yt);
                     $vid_id = $yt['v'];
                 }
                 $video = '<iframe width="' . $w . '" height="' . $height . '" src="//www.youtube.com/embed/' . $vid_id . '?rel=0" frameborder="0" allowfullscreen></iframe>';
             } elseif ($e == 'flv') {
                 $is_iframe = 'false';
                 $download = $nolinks ? null : '<a href="' . $url . '" class="ssfa-flightbox-download" ' . $linktype . $statstatus . '>' . '<span class="ssfa-icon-arrow-down-2" style="font-size:' . $font . 'px; margin-right:5px; display:inline-block;"></span>' . '</a>';
                 $video = '<object type="application/x-shockwave-flash" data="' . fileaway_url . '/lib/swf/player_flv_maxi.swf" width="' . $w . '" height="' . $height . '">' . '<param name="movie" value="' . fileaway_url . '/lib/swf/player_flv_maxi.swf" />' . '<param name="allowFullScreen" value="true" />' . '<param name="FlashVars" ' . 'value="flv=' . $src . '&amp;margin=0' . '&amp;bgcolor=000000&' . 'amp;bgcolor1=000000' . '&amp;bgcolor2=000000' . '&amp;showstop=1' . '&amp;showvolume=1' . '&amp;showtime=1' . '&amp;showfullscreen=1' . '&amp;buttonovercolor=ffffff' . '&amp;sliderovercolor=ffffff' . '&amp;showiconplay=1' . '&amp;showmouse=autohide" ' . '/>' . '</object>';
             } else {
                 $is_iframe = 'false';
                 $download = $nolinks ? null : '<a href="' . $url . '" class="ssfa-flightbox-download" ' . $linktype . $statstatus . '>' . '<span class="ssfa-icon-arrow-down-2" style="font-size:' . $font . 'px; margin-right:5px; display:inline-block;"></span>' . '</a>';
                 $video = fileaway_utility::video(array('src' => $src, 'height' => $height, 'width' => $w, 'class' => 'ssfa-flightbox-video-player', 'preload' => 'none', 'id' => uniqid('flightbox-video-')));
             }
             $response = array('html' => '<div id="ssfa-flightbox" class="' . $_POST['theme'] . '" style="display:inline-block; ' . $csize . ' left:' . $offset . 'px; top:' . $top . 'px; padding:0!important;">' . '<div id="ssfa-flightbox-inner" style="opacity:0; margin: 15px 15px 0!important;">' . $video . '</div>' . '<div class="ssfa-flightbox-controls ' . $icons . '" style="margin:' . $mrg . 'px 15px!important; display:block; text-align:right;">' . '<a href="' . $_POST['prevurl'] . '" onclick="' . $prev . '">' . '<span class="ssfa-icon-arrow-left-2" style="font-size:' . $font . 'px; margin-right:5px; display:inline-block;"></span>' . '</a>' . '<a href="' . $_POST['nexturl'] . '" onclick="' . $next . '">' . '<span class="ssfa-icon-arrow-right-2" style="font-size:' . $font . 'px; margin-right:5px; display:inline-block;"></span>' . '</a>' . $download . '<a href="javascript:" onclick="Xflightbox();">' . '<span class="ssfa-icon-console-2" style="font-size:' . $font . 'px; margin-right:0; display:inline-block;"></span>' . '</a>' . '</div>' . '</div>', 'width' => $w + 30 . 'px', 'height' => $height + $bar + 30 . 'px', 'top' => $top . 'px', 'offset' => $offset . 'px', 'iframe' => $is_iframe, 'iwidth' => $w, 'iheight' => $height);
         } elseif ($boxtype == 'pdf') {
             $of = $wh < 720 ? 100 : ($wh < 400 ? 50 : 200);
             if ($r == 'tall') {
                 $ratio = 22 / 17;
                 $height = $wh - $of;
                 $width = round($height / $ratio, 0);
                 $rotate = 'expand';
                 $current = str_replace('&r=tall', '&r=wide', $current);
                 $currenturl = str_replace('&r=tall', '&r=wide', $_POST['currenturl']);
             } else {
                 $ratio = 22 / (17 / 1.5);
                 $height = $wh - $of;
                 $width = round($height * $ratio, 0);
                 while ($width > $ww - $of) {
                     $width = $width - 10;
                 }
                 $rotate = 'contract';
                 $current = str_replace('&r=wide', '&r=tall', $current);
                 $currenturl = str_replace('&r=wide', '&r=tall', $_POST['currenturl']);
             }
             if ($width < 200) {
                 $width = 200;
             }
             $csize = 'width:' . ($width + 30) . 'px; height:' . ($height + $bar + 30) . 'px;';
             $top = $wh < $height + $bar + 30 ? '0' : ($wh - ($height + $bar + 30)) / 2;
             $offset = ($ww - ($width + 30)) / 2;
             $download_link = $nolinks ? null : '<a href="' . $url . '" class="ssfa-flightbox-download" ' . $linktype . $statstatus . '>' . '<span class="ssfa-icon-arrow-down-2" style="font-size:' . $font . 'px; margin-right:5px; display:inline-block;"></span>' . '</a>';
             $response = array('html' => '<div id="ssfa-flightbox" class="' . $_POST['theme'] . '" style="display:inline-block; ' . $csize . ' left:' . $offset . 'px; top:' . $top . 'px; padding:0!important;">' . '<div id="ssfa-flightbox-inner" style="opacity:0; margin: 15px 15px 0!important;">' . '<iframe src="' . $src . '" frameborder=0 height="' . $height . '" width="' . $width . '" name="' . fileaway_utility::basename($src) . '" scrolling="no" seamless>' . 'Your browser does not support iframes.' . '</iframe>' . '</div>' . '<div class="ssfa-flightbox-controls ' . $icons . '" style="margin:' . $mrg . 'px 15px!important; display:block; text-align:right;">' . '<a href="' . $_POST['prevurl'] . '" onclick="' . $prev . '">' . '<span class="ssfa-icon-arrow-left-2" style="font-size:' . $font . 'px; margin-right:5px; display:inline-block;"></span>' . '</a>' . '<a href="' . $_POST['nexturl'] . '" onclick="' . $next . '">' . '<span class="ssfa-icon-arrow-right-2" style="font-size:' . $font . 'px; margin-right:5px; display:inline-block;"></span>' . '</a>' . '<a href="' . $currenturl . '" onclick="' . $current . '">' . '<span class="ssfa-icon-' . $rotate . '" style="font-size:' . $font . 'px; margin-right:5px; display:inline-block;"></span>' . '</a>' . $download_link . '<a href="javascript:" onclick="Xflightbox();">' . '<span class="ssfa-icon-console-2" style="font-size:' . $font . 'px; margin-right:0; display:inline-block;"></span>' . '</a>' . '</div>' . '</div>', 'width' => $width + 30 . 'px', 'height' => $height + $bar + 30 . 'px', 'top' => $top . 'px', 'offset' => $offset . 'px', 'iframe' => 'true', 'iwidth' => $width, 'iheight' => $height);
         }
     } elseif ($action === 'createdir') {
         if (!$li) {
             die($dm);
         }
         if (!wp_verify_nonce($_POST['manager_nonce'], 'fileaway-manager-nonce')) {
             die($dm);
         }
         $parents = stripslashes(trim(str_replace('..', '', $_POST['parents']), '/'));
         $newsub = stripslashes(trim(str_replace('..', '', $_POST['newsub']), '/'));
         $uid = $_POST['uid'];
         $count = $_POST['count'];
         $page = $_POST['pg'];
         $querystring = ltrim($_POST['querystring'], '?');
         $drawericon = $_POST['drawer'];
         $drawerid = $_POST['drawerid'];
         $cells = $_POST['cells'];
         $class = $_POST['cls'];
         $base = $_POST['base'];
         $subs = explode('/', $newsub);
         $first = $subs[0];
         $last = $subs[count($subs) - 1];
         $start = trim(fileaway_utility::replacefirst($parents, $base, '') . '/' . $first, '/');
         $drawer = str_replace('/', '*', $start);
         $final = $rootpath . $parents . '/' . $newsub;
         $prettyfolder = str_replace(array('~', '--', '_', '.', '*'), ' ', "{$first}");
         $prettyfolder = preg_replace('/(?<=\\D)-(?=\\D)/', ' ', "{$prettyfolder}");
         $prettyfolder = preg_replace('/(?<=\\D)-(?=\\d)/', ' ', "{$prettyfolder}");
         $prettyfolder = preg_replace('/(?<=\\d)-(?=\\D)/', ' ', "{$prettyfolder}");
         $prettyfolder = fileaway_utility::strtotitle($prettyfolder);
         if (is_dir($final)) {
             $response = array('status' => 'error', 'message' => __('That directory name already exists in this location.', 'file-away'));
         } else {
             $first_exists = is_dir($rootpath . $parents . '/' . $first) ? true : false;
             if (mkdir($final, 0755, true)) {
                 fileaway_utility::indexmulti($rootpath . $parents . '/' . $newsub, $rootpath . $parents . '/');
                 if (!$first_exists) {
                     $status = "insert";
                     $message = "<tr id='ssfa-dir-{$uid}-{$count}' class='ssfa-drawers'>" . "<td id='folder-ssfa-dir-{$uid}-{$count}' data-value=\"# # # # # {$first}\" class='ssfa-sorttype {$class}-first-column'>" . "<a href=\"" . fileaway_utility::querystring(get_permalink($page), $querystring, array($drawerid => $drawer)) . "\" data-name=\"" . $first . "\" data-path=\"" . $start . "\">" . "<span style='font-size:20px; margin-left:3px;' class='ssfa-faminicon ssfa-icon-{$drawericon} ssfa-classic' aria-hidden='true'></span>" . "<br>" . _x('dir', 'abbrv. of *directory*', 'file-away') . "</a>" . "</td>" . "<td id='name-ssfa-dir-{$uid}-{$count}' data-value='# # # # # {$first}' class='ssfa-sortname'>" . "<a class='ssfa-classic' href=\"" . fileaway_utility::querystring(get_permalink($page), $querystring, array($drawerid => $drawer)) . "\">" . "<span class='ssfa-filename' style='text-transform:uppercase;'>{$prettyfolder}</span>" . "</a>" . "<input type='text' id='rename-ssfa-dir-{$uid}-{$count}' type='text' value=\"{$first}\" " . "style='width:90%; text-align:center; display:none'>" . "</td>";
                     $icell = 1;
                     while ($icell < $cells) {
                         $message .= "<td class='{$class}' data-value=\"# # # # # {$first}\"> &nbsp; </td>";
                         $icell++;
                     }
                     $message .= "<td id='manager-ssfa-dir-{$uid}-{$count}' class=\"{$class}\" data-value=\"# # # # # {$first}\">" . "<a href='' id='rename-ssfa-dir-{$uid}-{$count}'>" . __('Rename', 'file-away') . "</a><br>" . "<a href='' id='delete-ssfa-dir-{$uid}-{$count}'>" . __('Delete', 'file-away') . "</a>" . "</td>";
                     $message .= "</tr>";
                 } else {
                     $status = "success";
                     $message = __('Your sub-directories have been successfully created.', 'file-away');
                 }
                 $response = array('status' => $status, 'message' => $message, 'uid' => $uid);
             } else {
                 $response = array('status' => 'error', 'message' => __('Sorry, there was a problem creating that directory for you.', 'file-away'));
             }
         }
     } elseif ($action === 'renamedir') {
         global $wpdb;
         if (!$li) {
             die($dm);
         }
         if (!wp_verify_nonce($_POST['manager_nonce'], 'fileaway-manager-nonce')) {
             die($dm);
         }
         $table = fileaway_stats::$db;
         $table_exists = $wpdb->get_var("SHOW TABLES LIKE '{$table}'") != $table ? false : true;
         $meta_table = fileaway_metadata::$db;
         $meta_table_exists = $wpdb->get_var("SHOW TABLES LIKE '{$meta_table}'") != $meta_table ? false : true;
         $metadata = $_POST['metadata'] == 'true' ? true : false;
         $oldpath = stripslashes(trim(str_replace('..', '', $_POST['oldpath']), '/'));
         $newname = stripslashes(str_replace(array('..', '/'), '', $_POST['newname']));
         $pp = explode('/', $oldpath);
         $newpath = fileaway_utility::replacelast($oldpath, end($pp), $newname);
         $olddata = $_POST['datapath'];
         $datapp = explode('/', $olddata);
         $newdata = fileaway_utility::replacelast($olddata, end($datapp), $newname);
         $parents = stripslashes($_POST['parents']);
         $old = $parents . '/' . end($pp);
         $dst = $rootpath . $newpath;
         $src = $rootpath . $old;
         $check_path = trim(str_replace('/', '', $newpath));
         if ($rootpath . $check_path == $rootpath || $rootpath . $check_path == $rootpath . 'wp-content' || strpos($check_path, 'wp-admin') !== false || strpos($check_path, 'wp-includes') !== false) {
             die($dm);
         }
         $page = $_POST['pg'];
         $querystring = ltrim($_POST['querystring'], '?');
         $drawer = str_replace('/', '*', $newdata);
         $drawerid = $_POST['drawerid'];
         $newurl = fileaway_utility::querystring(get_permalink($page), $querystring, array($drawerid => $drawer));
         $response = false;
         if (is_dir($dst)) {
             $response = array('status' => 'error', 'message' => __('That directory already exists.', 'file-away'));
         } elseif (!is_dir($src)) {
             $response = array('status' => 'error', 'message' => __('The directory you\'re trying to rename could not be found.', 'file-away'));
         } else {
             if (!is_dir("{$dst}")) {
                 mkdir("{$dst}", 0755, true);
             }
             $dirs = fileaway_utility::recursivedirs($src);
             if (is_array($dirs)) {
                 $dirs = array_reverse($dirs);
                 $fcount = 0;
                 $fscount = 0;
                 $dcount = 1;
                 $dscount = 0;
                 foreach ($dirs as $dir) {
                     $dcount++;
                     $files = false;
                     $filedest = str_replace("{$src}", "{$dst}", "{$dir}");
                     if (!is_dir($filedest)) {
                         mkdir("{$filedest}", 0755, true);
                     }
                     $files = array_filter(glob("{$dir}" . "/*"), 'is_file');
                     if (is_array($files)) {
                         foreach ($files as $file) {
                             $fcount++;
                             $filename = fileaway_utility::basename($file);
                             if (rename("{$file}", "{$filedest}" . "/" . "{$filename}")) {
                                 $fscount++;
                                 if ($table_exists) {
                                     fileaway_utility::updatestats('file', fileaway_utility::replacefirst($file, $rootpath, ''), fileaway_utility::replacefirst($filedest . '/' . $filename, $rootpath, ''));
                                 }
                                 if ($metadata && $meta_table_exists) {
                                     fileaway_utility::updatemetadata(false, fileaway_utility::replacefirst($file, $rootpath, ''), fileaway_utility::replacefirst($filedest . '/' . $filename, $rootpath, ''));
                                 }
                             }
                         }
                     }
                     if (rmdir($dir)) {
                         $dscount++;
                     }
                 }
             }
             $basefiles = array_filter(glob("{$src}" . "/*"), 'is_file');
             if (is_array($basefiles)) {
                 foreach ($basefiles as $file) {
                     $fcount++;
                     $filename = fileaway_utility::basename($file);
                     if (rename("{$file}", "{$dst}" . "/" . "{$filename}")) {
                         $fscount++;
                         if ($table_exists) {
                             fileaway_utility::updatestats('file', fileaway_utility::replacefirst($file, $rootpath, ''), fileaway_utility::replacefirst($dst . '/' . $filename, $rootpath, ''));
                         }
                         if ($metadata && $meta_table_exists) {
                             fileaway_utility::updatemetadata(false, fileaway_utility::replacefirst($file, $rootpath, ''), fileaway_utility::replacefirst($dst . '/' . $filename, $rootpath, ''));
                         }
                     }
                 }
             }
             if (rmdir($src)) {
                 $dscount++;
             }
             if ($fcount > 0 && !$fscount) {
                 $response = array('status' => 'error', 'message' => __('We tried to move the files into the newly-named directory but none of them would budge.', 'file-away'));
             } elseif ($fcount > 0 && $fcount > $fscount) {
                 $response = array('status' => 'error', 'message' => __('We tried to move the files into the newly-named directory, but there were some stragglers, so we couldn\'t remove the old directory.', 'file-away'));
             } elseif (!is_dir($src)) {
                 $response = array('status' => 'success', 'url' => $newurl, 'newdata' => $newdata, 'newname' => $newname);
             } else {
                 $response = array('status' => 'error', 'message' => __('An unspecified error occurred.', 'file-away'));
             }
         }
     } elseif ($action === 'deletedir') {
         if (!$li) {
             die($dm);
         }
         if (!wp_verify_nonce($_POST['manager_nonce'], 'fileaway-manager-nonce')) {
             die($dm);
         }
         $status = $_POST['status'];
         $path1 = $_POST['path1'];
         $path2 = $_POST['path2'];
         $path = stripslashes($path1 . '/' . $path2);
         $src = $rootpath . $path;
         if ($src == $rootpath || $src == $rootpath . 'wp-content' || strpos($src, 'wp-admin') !== false || strpos($src, 'wp-includes') !== false) {
             die($dm);
         }
         $response = false;
         if (!is_dir("{$src}")) {
             $response = array('status' => 'error', 'message' => __('The directory marked for deletion could not be found.', 'file-away') . ' ' . $path);
         } else {
             $dirs = fileaway_utility::recursivedirs($src);
             $dirs = is_array($dirs) ? array_reverse($dirs) : $dirs;
             if ($status === 'life') {
                 $dcount = 0;
                 $fcount = 0;
                 if (is_array($dirs)) {
                     foreach ($dirs as $dir) {
                         $dcount++;
                         $files = false;
                         $files = array_filter(glob("{$dir}" . "/*"), 'is_file');
                         if (is_array($files)) {
                             foreach ($files as $file) {
                                 $fcount++;
                             }
                         }
                     }
                 }
                 $basefiles = array_filter(glob("{$src}" . "/*"), 'is_file');
                 if (is_array($basefiles)) {
                     foreach ($basefiles as $file) {
                         $fcount++;
                     }
                 }
                 if ($fcount == 0) {
                     $status = 'death';
                 } else {
                     $filemsg = null;
                     if ($fcount >= 1) {
                         $plufiles = $fcount > 1 ? _x('files', 'plural', 'file-away') : _x('file', 'singular', 'file-away');
                         $filemsg = ' ' . __('and', 'file-away') . ' ' . $fcount . ' ' . $plufiles;
                     }
                     $dirmsg = null;
                     if ($dcount >= 1) {
                         $pludirs = $dcount > 1 ? _x('sub-directories', 'plural', 'file-away') : _x('sub-directory', 'singular', 'file-away');
                         $dirmsg = ', ' . $dcount . ' ' . $pludirs;
                     }
                     $message = sprintf(_x('You are about to delete 1 directory%s from the server. ' . 'This action is permanent and cannot be undone. Are you sure you wish to proceed?', 'Do not put a space between *directory* and the %s variable', 'file-away'), $dirmsg . $filemsg);
                     $response = array('status' => 'confirm', 'message' => $message);
                 }
             }
             if ($status === 'death') {
                 $pcount = 1;
                 $pscount = 0;
                 $dcount = 0;
                 $dscount = 0;
                 $fcount = 0;
                 $fscount = 0;
                 if (is_array($dirs)) {
                     foreach ($dirs as $dir) {
                         $dcount++;
                         $files = false;
                         $files = array_filter(glob("{$dir}" . "/*"), 'is_file');
                         if (is_array($files)) {
                             foreach ($files as $file) {
                                 $fcount++;
                                 $file = realpath($file);
                                 if (is_readable($file)) {
                                     if (unlink($file)) {
                                         $fscount++;
                                     }
                                 }
                             }
                         }
                         if (rmdir($dir)) {
                             $dscount++;
                         }
                     }
                 }
                 $basefiles = array_filter(glob("{$src}" . "/*"), 'is_file');
                 if (is_array($basefiles)) {
                     foreach ($basefiles as $file) {
                         $fcount++;
                         $file = realpath($file);
                         if (is_readable($file)) {
                             if (unlink($file)) {
                                 $fscount++;
                             }
                         }
                     }
                 }
                 if (rmdir($src)) {
                     $pscount++;
                 }
                 if ($pscount && $fscount || $pscount && !$fcount) {
                     $success = $pscount == $pcount && $dscount == $dcount && $fscount == $fcount ? 'success' : 'partial';
                     $success = $fscount == $fcount && !$fcount ? 'success-single' : $success;
                     $filemsg = null;
                     if ($fcount >= 1) {
                         $plufiles = $fcount > 1 ? _x('files', 'plural', 'file-away') : _x('file', 'singular', 'file-away');
                         $filemsg = ' ' . __('and', 'file-away') . ' ' . $fscount . ' ' . __('of', 'file-away') . ' ' . $fcount . ' ' . $plufiles;
                     } else {
                         $filemsg = ' ' . sprintf(__('and %d files', 'file-away'), $fcount);
                     }
                     $dirmsg = null;
                     if ($dcount >= 1) {
                         $pludirs = $dcount > 1 ? _x('sub-directories', 'plural', 'file-away') : _x('sub-directory', 'singular', 'file-away');
                         $dirmsg = ', ' . $dscount . ' ' . __('of', 'file-away') . ' ' . $dcount . ' ' . $pludirs;
                     }
                     $message = sprintf(_x('%d of 1 directory%s have been removed from the server.', 'Do not put a space between *directory* and the %s variable', 'file-away'), $pscount, $dirmsg . $filemsg);
                     $response = array('status' => $success, 'message' => $message);
                 } else {
                     $response = array('status' => 'error', 'message' => __('Sorry, but there was an error attempting to remove this directory.', 'file-away'));
                 }
             }
         }
     } elseif ($action === 'rename') {
         if (!$li) {
             die($dm);
         }
         if (!wp_verify_nonce($_POST['manager_nonce'], 'fileaway-manager-nonce')) {
             die($dm);
         }
         global $wpdb;
         $table = fileaway_stats::$db;
         $table_exists = $wpdb->get_var("SHOW TABLES LIKE '{$table}'") != $table ? false : true;
         $meta_table = fileaway_metadata::$db;
         $meta_table_exists = $wpdb->get_var("SHOW TABLES LIKE '{$meta_table}'") != $meta_table ? false : true;
         $metadata = $_POST['metadata'] == 'true' ? true : false;
         $url = stripslashes($_POST['url']);
         $pp = $problemchild ? fileaway_utility::replacefirst(stripslashes($_POST['pp']), $install, '') : stripslashes($_POST['pp']);
         $oldname = stripslashes($_POST['oldname']);
         $rawname = stripslashes($_POST['rawname']);
         $ext = $_POST['ext'];
         if (strpos(strtolower($ext), 'php') !== false) {
             die($dm);
         }
         if (strpos($url, '.' . $ext . '?type=') !== false) {
             list($url, $querystring) = explode('?', $url);
             $querystring = '?' . $querystring;
         } else {
             $querystring = '';
         }
         $oldfile = $chosenpath . "{$pp}/{$oldname}.{$ext}";
         $customdata = isset($_POST['customdata']) ? $_POST['customdata'] : array();
         if (!$metadata) {
             $not_empty = false;
             if (is_array($customdata)) {
                 $customd = array();
                 foreach ($customdata as $datum) {
                     $customd[] = stripslashes($datum);
                     if (stripslashes($datum) != '') {
                         $not_empty = true;
                     }
                 }
             }
             $customd = $not_empty ? stripslashes(implode(',', $customdata)) : '';
             if ($customd !== '') {
                 $customd = " [{$customd}]";
             } else {
                 $customd = '';
             }
             $newfile = $chosenpath . "{$pp}/{$rawname}{$customd}.{$ext}";
             if ($newfile !== $oldfile) {
                 $i = 1;
                 while (is_file($newfile)) {
                     if ($i == 1) {
                         $rawname = "{$rawname}" . " ({$i})";
                     } else {
                         $j = $i - 1;
                         $rawname = rtrim("{$rawname}", " ({$j})");
                         $rawname = "{$rawname}" . " ({$i})";
                     }
                     $i++;
                     $newfile = $chosenpath . "{$pp}/{$rawname}{$customd}.{$ext}";
                 }
             }
             if ($customd !== '') {
                 $customd = " [" . trim(ltrim(rtrim("{$customd}", "]"), " ["), " ") . "]";
             }
             $newfile = $chosenpath . "{$pp}/" . trim("{$rawname}", ' ') . "{$customd}.{$ext}";
             $newurl = str_replace("{$pp}/{$oldname}.{$ext}", "", fileaway_utility::urlesc("{$url}", true));
             $newurl = fileaway_utility::urlesc("{$newurl}{$pp}/" . trim("{$rawname}") . "{$customd}.{$ext}");
             $newoldname = trim("{$rawname}", ' ') . "{$customd}";
             $download = trim("{$rawname}", ' ') . "{$customd}.{$ext}";
             if (is_file("{$oldfile}")) {
                 rename("{$oldfile}", "{$newfile}");
             }
             $errors = is_file("{$newfile}") ? '' : __('The file was not renamed.', 'file-away');
             if (is_file($newfile) && $table_exists) {
                 fileaway_utility::updatestats('file', fileaway_utility::replacefirst($oldfile, $rootpath, ''), fileaway_utility::replacefirst($newfile, $rootpath, ''));
             }
         } else {
             $not_empty = false;
             if (is_array($customdata)) {
                 $customd = array();
                 foreach ($customdata as $datum) {
                     $customd[] = stripslashes($datum);
                     if (stripslashes($datum) != '') {
                         $not_empty = true;
                     }
                 }
             }
             $customdata = $not_empty ? $customd : '';
             $newfile = $chosenpath . "{$pp}/{$rawname}.{$ext}";
             if ($newfile !== $oldfile) {
                 $i = 1;
                 while (is_file($newfile)) {
                     if ($i == 1) {
                         $rawname = "{$rawname}" . " ({$i})";
                     } else {
                         $j = $i - 1;
                         $rawname = rtrim("{$rawname}", " ({$j})");
                         $rawname = "{$rawname}" . " ({$i})";
                     }
                     $i++;
                     $newfile = $chosenpath . "{$pp}/{$rawname}.{$ext}";
                 }
             }
             $newfile = $chosenpath . "{$pp}/" . trim("{$rawname}", ' ') . ".{$ext}";
             $newurl = str_replace("{$pp}/{$oldname}.{$ext}", "", fileaway_utility::urlesc("{$url}", true));
             $newurl = fileaway_utility::urlesc("{$newurl}{$pp}/" . trim("{$rawname}") . ".{$ext}");
             $newoldname = trim("{$rawname}", ' ');
             $download = trim("{$rawname}", ' ') . ".{$ext}";
             if (is_file("{$oldfile}")) {
                 rename("{$oldfile}", "{$newfile}");
             }
             $errors = is_file("{$newfile}") ? '' : __('The file was not renamed.', 'file-away');
             if (is_file($newfile) && $table_exists) {
                 fileaway_utility::updatestats('file', fileaway_utility::replacefirst($oldfile, $rootpath, ''), fileaway_utility::replacefirst($newfile, $rootpath, ''));
             }
             if (is_file($newfile) && $meta_table_exists) {
                 fileaway_utility::updatemetadata($customdata, fileaway_utility::replacefirst($oldfile, $rootpath, ''), fileaway_utility::replacefirst($newfile, $rootpath, ''));
             }
             if ($customdata === '') {
                 $customdata = array();
             }
         }
         $response = array("errors" => $errors, "download" => $download, "pp" => $pp, "newurl" => $newurl . $querystring, "extension" => $ext, "oldfile" => $oldfile, "newfile" => $newfile, "rawname" => $rawname, "customdata" => $customdata, "newoldname" => $newoldname);
     } elseif ($action === 'delete') {
         if (!$li) {
             die($dm);
         }
         if (!wp_verify_nonce($_POST['manager_nonce'], 'fileaway-manager-nonce')) {
             die($dm);
         }
         $pp = $_POST["pp"];
         $oldname = $_POST["oldname"];
         $ext = $_POST["ext"];
         if (!in_array($ext, array('php', 'htaccess', 'htpasswd')) && strpos($oldname, 'wp-admin') === false && strpos($oldname, 'wp-config') === false && strpos($oldname, 'wp-includes') === false) {
             $oldfile = "{$rootpath}{$pp}/{$oldname}.{$ext}";
             if (!is_file("{$oldfile}")) {
                 $oldfile = stripslashes("{$oldfile}");
             }
             if (is_file("{$oldfile}")) {
                 if (unlink("{$oldfile}")) {
                     $response = "success";
                 } else {
                     $response = "error";
                 }
             } else {
                 $response = "error";
             }
         } else {
             $response = 'error';
         }
     } elseif ($action == 'bulkdownload') {
         if (!wp_verify_nonce($_POST['bulkdownload_nonce'], 'fileaway-bulk-download-nonce')) {
             die($dm);
         }
         $files = $_POST["files"];
         $stats = $_POST['stats'];
         $zipfiles = array();
         $values = array();
         if (is_array($files)) {
             foreach ($files as $file) {
                 if (strpos($file, '..') !== false) {
                     continue;
                 }
                 if (strpos($file, '/') === false) {
                     continue;
                 }
                 if (strpos($file, '.php') !== false) {
                     continue;
                 }
                 if (strpos($file, 'wp-config') !== false) {
                     continue;
                 }
                 if (strpos($file, 'wp-admin') !== false) {
                     continue;
                 }
                 if (strpos($file, 'wp-includes') !== false) {
                     continue;
                 }
                 $file = $rootpath . stripslashes($file);
                 if (file_exists($file)) {
                     $zipfiles[] = $file;
                     $values[] = fileaway_utility::basename($file);
                 }
             }
         }
         $numvals = array_count_values($values);
         $prefix = isset($this->settings['download_prefix']) ? $this->settings['download_prefix'] : false;
         $prefix = $prefix && $prefix !== '' ? $prefix : date('Y-m-d', current_time('timestamp'));
         $time = uniqid();
         $destination = fileaway_dir . '/temp';
         if (!is_dir($destination)) {
             mkdir($destination);
         }
         $filename = stripslashes($prefix) . ' ' . $time . '.zip';
         $link = fileaway_url . '/temp/' . $filename;
         $filename = $destination . '/' . $filename;
         if (count($zipfiles)) {
             $zip = new ZipArchive();
             $zip->open($filename, ZipArchive::CREATE);
             foreach ($zipfiles as $k => $zipfile) {
                 $zip->addFile($zipfile, fileaway_utility::basename($zipfile));
                 if ($numvals[fileaway_utility::basename($zipfile)] > 1) {
                     $parts = fileaway_utility::pathinfo($zipfile);
                     $zip->renameName(fileaway_utility::basename($zipfile), $parts['filename'] . '_' . $k . '.' . $parts['extension']);
                 }
             }
             $zip->close();
         }
         if ($stats == 'true' && count($zipfiles) > 0) {
             $stat = new fileaway_stats();
             $ifiles = array();
             foreach ($zipfiles as $zfile) {
                 $zfile = fileaway_utility::replacefirst($zfile, $rootpath, '');
                 $ifiles[] = $zfile;
                 $stat->insert($zfile, false);
             }
             $current = wp_get_current_user();
             if ($this->settings['instant_stats'] == 'true') {
                 $data = array('timestamp' => date('Y-m-d H:i:s', current_time('timestamp')), 'file' => count($ifiles) . ' ' . strtolower(_x('files', 'plural', 'file-away')), 'files' => "\r\n" . implode("\r\n", $ifiles), 'uid' => $current->ID, 'email' => $current->user_email, 'ip' => $_SERVER['REMOTE_ADDR'], 'agent' => $_SERVER['HTTP_USER_AGENT']);
                 $stat->imail($data);
             }
         }
         $response = is_file($filename) ? $link : "Error";
     } elseif ($action == 'bulkcopy') {
         if (!$li) {
             die($dm);
         }
         if (!wp_verify_nonce($_POST['manager_nonce'], 'fileaway-manager-nonce')) {
             die($dm);
         }
         $from = $_POST['from'];
         $to = $_POST['to'];
         $ext = $_POST['exts'];
         $destination = $problemchild ? fileaway_utility::replacefirst(stripslashes($_POST['destination']), $install, '') : stripslashes($_POST['destination']);
         $success = 0;
         $total = 0;
         $renamers = 0;
         foreach ($from as $k => $fro) {
             $fro = stripslashes($fro);
             $to[$k] = stripslashes($to[$k]);
             $fro = $problemchild ? fileaway_utility::replacefirst("{$fro}", $install, '') : "{$fro}";
             $to[$k] = $problemchild ? fileaway_utility::replacefirst("{$to[$k]}", $install, '') : "{$to[$k]}";
             $total++;
             $newfile = $chosenpath . "{$to[$k]}";
             if (is_file($chosenpath . "{$fro}") && is_file("{$newfile}")) {
                 $i = 1;
                 $noext = fileaway_utility::replacelast("{$newfile}", '.' . $ext[$k], '');
                 while (is_file("{$newfile}")) {
                     if ($i == 1) {
                         $noext = "{$noext}" . " ({$i})";
                     } else {
                         $j = $i - 1;
                         $noext = rtrim("{$noext}", " ({$j})");
                         $noext = "{$noext}" . " ({$i})";
                     }
                     $i++;
                     $newfile = "{$noext}" . '.' . $ext[$k];
                 }
                 $renamers++;
             }
             if (is_file($chosenpath . "{$fro}") && !is_file("{$newfile}")) {
                 copy($chosenpath . "{$fro}", "{$newfile}");
             }
             if (is_file("{$newfile}")) {
                 $success++;
             }
         }
         $response = $success == 0 ? __('There was a problem copying the files. Please consult your local pharmacist.', 'file-away') : ($success == 1 ? sprintf(__('One file was copied to %s and it no longer feels special.', 'file-away'), $destination) : ($success > 1 ? sprintf(__('%d of %d files were successfully cloned and delivered in a black caravan to %s.', 'file-away'), $success, $total, $destination) : null));
     } elseif ($action == 'bulkmove') {
         if (!$li) {
             die($dm);
         }
         if (!wp_verify_nonce($_POST['manager_nonce'], 'fileaway-manager-nonce')) {
             die($dm);
         }
         global $wpdb;
         $table = fileaway_stats::$db;
         $table_exists = $wpdb->get_var("SHOW TABLES LIKE '{$table}'") != $table ? false : true;
         $meta_table = fileaway_metadata::$db;
         $meta_table_exists = $wpdb->get_var("SHOW TABLES LIKE '{$meta_table}'") != $meta_table ? false : true;
         $metadata = $_POST['metadata'] == 'true' ? true : false;
         $from = $_POST["from"];
         $to = $_POST["to"];
         $ext = $_POST['exts'];
         $destination = $problemchild ? fileaway_utility::replacefirst(stripslashes($_POST["destination"]), $install, '') : stripslashes($_POST["destination"]);
         $success = 0;
         $total = 0;
         $renamers = 0;
         foreach ($from as $k => $fro) {
             $fro = stripslashes($fro);
             $to[$k] = stripslashes($to[$k]);
             $fro = $problemchild ? fileaway_utility::replacefirst("{$fro}", $install, '') : "{$fro}";
             $to[$k] = $problemchild ? fileaway_utility::replacefirst("{$to[$k]}", $install, '') : "{$to[$k]}";
             $total++;
             $newfile = $chosenpath . "{$to[$k]}";
             if (is_file($chosenpath . "{$fro}") && is_file("{$newfile}")) {
                 $i = 1;
                 $noext = fileaway_utility::replacelast("{$newfile}", '.' . $ext[$k], '');
                 while (is_file("{$newfile}")) {
                     if ($i == 1) {
                         $noext = "{$noext}" . " ({$i})";
                     } else {
                         $j = $i - 1;
                         $noext = rtrim("{$noext}", " ({$j})");
                         $noext = "{$noext}" . " ({$i})";
                     }
                     $i++;
                     $newfile = "{$noext}" . '.' . $ext[$k];
                 }
                 $renamers++;
             }
             if (is_file($chosenpath . "{$fro}") && !is_file("{$newfile}")) {
                 rename($chosenpath . "{$fro}", "{$newfile}");
             }
             if (is_file("{$newfile}")) {
                 $success++;
                 if ($table_exists) {
                     fileaway_utility::updatestats('file', fileaway_utility::replacefirst($chosenpath . $fro, $rootpath, ''), fileaway_utility::replacefirst($newfile, $rootpath, ''));
                 }
                 if ($metadata && $meta_table_exists) {
                     fileaway_utility::updatemetadata(false, fileaway_utility::replacefirst($chosenpath . $fro, $rootpath, ''), fileaway_utility::replacefirst($newfile, $rootpath, ''));
                 }
             }
         }
         $response = $success == 0 ? __('There was a problem moving the files. Please consult your local ouija specialist.', 'file-away') : ($success == 1 ? sprintf(__('One lonesome file was forced to leave all it knew and move to %s.', 'file-away'), $destination) : ($success > 1 ? sprintf(__('%d of %d files were magically transported to %s.', 'file-away'), $success, $total, $destination) : null));
     } elseif ($action == 'bulkdelete') {
         if (!$li) {
             die($dm);
         }
         if (!wp_verify_nonce($_POST['manager_nonce'], 'fileaway-manager-nonce')) {
             die($dm);
         }
         $files = $_POST['files'];
         $success = 0;
         $total = 0;
         foreach ($files as $k => $file) {
             $file = stripslashes($file);
             if (strpos($file, '.php') === false && strpos($file, 'htaccess') === false && strpos($file, 'htpasswd') === false && strpos($file, 'wp-admin') === false && strpos($file, 'wp-config') === false && strpos($file, 'wp-includes') === false) {
                 $total++;
                 if (is_file($rootpath . $file)) {
                     unlink($rootpath . $file);
                 }
                 if (!is_file($rootpath . $file)) {
                     $success++;
                 }
             }
         }
         $response = $success == 0 ? __('There was a problem deleting the files. Please try pressing your delete button emphatically and repeatedly.', 'file-away') : ($success == 1 ? __('A million fewer files in the world is a victory. One less file, a tragedy. Farewell, file. Au revoir. Auf Wiedersehen. Adieu.', 'file-away') : ($success > 1 ? sprintf(__('%d of %d files were sent plummeting to the nether regions of cyberspace.', 'file-away'), $success, $total) : null));
     } elseif ($action == 'upload') {
         if (isset($_POST) && $_SERVER['REQUEST_METHOD'] == "POST") {
             if (!wp_verify_nonce($_POST['upload_nonce'], 'fileaway-fileup-nonce')) {
                 echo 'system_error';
                 exit;
             }
             $file_name = strip_tags(stripslashes($_FILES['upload_file']['name']));
             $new_name = strip_tags(stripslashes($_POST['new_name']));
             $extension = $_POST['extension'];
             $check_ext = str_replace('/', '', $extension);
             $check_name = str_replace('/', '', $new_name);
             if (empty($check_ext) || empty($check_name)) {
                 echo 'system_error';
                 exit;
             }
             $uploader = stripslashes($_POST['uploader']);
             $file_id = strip_tags($_POST['upload_file_id']);
             $file_size = $_FILES['upload_file']['size'];
             $max_file_size = (int) $_POST['max_file_size'];
             $file_path = trim($_POST['upload_path'], '/');
             if ($uploader) {
                 $user = new WP_User($uploader);
                 $uploadedby = $_POST['identby'] == 'id' ? $user->ID : $user->display_name;
                 if (preg_match('/\\[([^\\]]+)\\]/', $new_name)) {
                     $new_name = fileaway_utility::replacelast($new_name, ']', ',' . $uploadedby . ']');
                 } else {
                     $new_name = fileaway_utility::replacelast($new_name, '.' . $extension, ' [' . $uploadedby . '].' . $extension);
                 }
             }
             $location = str_replace('//', '/', $chosenpath . $file_path . '/' . $new_name);
             $location = stripslashes($location);
             $dir = fileaway_utility::dirname($location);
             $_POST['size_check'] = $file_size > $max_file_size ? 'true' : 'false';
             if ($file_size > $max_file_size) {
                 echo 'system_error';
             } elseif (strpos($location, 'wp-admin') !== false) {
                 echo 'system_error';
             } elseif (strpos($location, 'wp-config') !== false) {
                 echo 'system_error';
             } elseif (strpos($location, '.php') !== false) {
                 echo 'system_error';
             } elseif (strpos($extension, 'php') !== false) {
                 echo 'system_error';
             } elseif (strpos($dir, '..') !== false) {
                 echo 'system_error';
             } else {
                 if (!is_dir($dir)) {
                     mkdir($dir, 0755, true);
                 }
                 $p = fileaway_utility::pathinfo($location);
                 $filename = $p['filename'];
                 $i = 1;
                 $overwrite = $li && stripslashes($_POST['overwrite']) == 'true' ? true : false;
                 if (!$overwrite) {
                     while (is_file($location)) {
                         if ($i == 1) {
                             $filename = $filename . " ({$i})";
                         } else {
                             $j = $i - 1;
                             $filename = rtrim($filename, " ({$j})");
                             $filename = $filename . " ({$i})";
                         }
                         $i++;
                         $name = $filename . '.' . $p['extension'];
                         $location = $p['dirname'] . '/' . $name;
                     }
                 }
                 $name = $filename . '.' . $p['extension'];
                 $location = $p['dirname'] . '/' . $name;
                 if (move_uploaded_file(strip_tags($_FILES['upload_file']['tmp_name']), $location)) {
                     echo $file_id;
                 } else {
                     echo 'system_error';
                 }
             }
             exit;
         } else {
             echo 'system_error';
             exit;
         }
     } elseif ($action == 'actionpath') {
         if (!wp_verify_nonce($_POST['manager_nonce'], 'fileaway-manager-nonce')) {
             die($dm);
         }
         $fileup = $_POST['uploadaction'] === 'true' ? 'fileup-' : '';
         $build = null;
         if ($problemchild) {
             $pathparts = fileaway_utility::replacefirst($_POST['pathparts'], $install, '');
             $start = trim(fileaway_utility::replacefirst($_POST['start'], $install, ''), '/');
         } else {
             $pathparts = $_POST['pathparts'];
             $start = trim($_POST['start'], '/');
         }
         if ($pathparts === '/') {
             $pathparts = $start;
         }
         $pathparts = trim($pathparts, '/');
         $basename = trim($_POST['basename'], '/');
         if (!fileaway_utility::startswith($pathparts, $start)) {
             $pathparts = $start;
         }
         $security = $basename === $start ? false : true;
         $nocrumbs = $security ? trim(fileaway_utility::replacelast("{$start}", "{$basename}", ''), '/') : null;
         if (strpos($pathparts, '..') !== false) {
             $pathparts = $start;
         }
         $dir = $chosenpath . $pathparts;
         $build .= "<option></option>";
         $directories = glob($dir . "/*", GLOB_ONLYDIR);
         if ($directories && is_array($directories)) {
             foreach ($directories as $k => $folder) {
                 $direxcluded = 0;
                 if ($this->settings['direxclusions']) {
                     $direxes = preg_split('/(, |,)/', $this->settings['direxclusions'], -1, PREG_SPLIT_NO_EMPTY);
                     if (is_array($direxes)) {
                         foreach ($direxes as $direx) {
                             $check = strripos($folder, $direx);
                             if ($check !== false) {
                                 $direxcluded = 1;
                                 break;
                             }
                         }
                     }
                 }
                 if (!$direxcluded) {
                     $folder = str_replace($chosenpath, '', $folder);
                     $dirname = explode('/', $folder);
                     $dirname = end($dirname);
                     $build .= '<option value="' . $folder . '">' . $dirname . '</option>';
                 }
             }
         } else {
             $build .= '';
         }
         if ($security) {
             $pieces = explode('/', trim(trim(fileaway_utility::replacefirst("{$pathparts}", "{$nocrumbs}", ''), '/'), '/'));
         } else {
             $pieces = explode('/', trim("{$pathparts}", '/'));
         }
         $piecelink = array();
         $breadcrumbs = null;
         foreach ($pieces as $k => $piece) {
             $i = 0;
             $piecelink[$k] = $security ? "{$nocrumbs}/" : null;
             while ($i <= $k) {
                 $piecelink[$k] .= "{$pieces[$i]}/";
                 $i++;
             }
             $breadcrumbs .= '<a href="javascript:" data-target="' . trim($piecelink[$k], '/') . '" id="ssfa-' . $fileup . 'action-pathpart-' . $k . '">' . fileaway_utility::strtotitle($piece) . '</a> / ';
         }
         $breadcrumbs = stripslashes($breadcrumbs);
         $pathparts = stripslashes($pathparts);
         $build = stripslashes($build);
         $response = array("ops" => $build, "crumbs" => $breadcrumbs, "pathparts" => $pathparts);
     } elseif ($action == 'deletecsv') {
         if (!wp_verify_nonce($_POST['values_nonce'], 'fileaway-values-nonce')) {
             die($dm);
         }
         $src = base64_decode($_POST['src']);
         if (is_file($rootpath . $src)) {
             if (unlink($rootpath . $src)) {
                 $response = array('status' => 'success');
             } else {
                 $response = array('status' => 'error', 'message' => __('There was a problem deleting the files. Please try pressing your delete button emphatically and repeatedly.', 'file-away'));
             }
         } else {
             $response = array('status' => 'error', 'message' => __('The file specified does not exist in this location.', 'file-away'));
         }
     } elseif ($action == 'makecsv') {
         if (!wp_verify_nonce($_POST['values_nonce'], 'fileaway-values-nonce')) {
             die($dm);
         }
         $dir = base64_decode($_POST['path']);
         $filename = trim($_POST['name'], '/');
         if (!fileaway_utility::endswith(strtolower($filename), '.csv')) {
             $filename = $filename . '.csv';
         }
         if (is_file($rootpath . $dir . '/' . $filename)) {
             $response = array('status' => 'error', 'message' => __('A file by that name already exists in this directory.', 'file-away'));
         } else {
             if (strpos($filename, '/') !== false && !is_dir($rootpath . $dir . '/' . fileaway_utility::dirname($filename))) {
                 mkdir($rootpath . $dir . '/' . fileaway_utility::dirname($filename), 0775, true);
             }
             $csv = new fileaway_csv();
             $read = $_POST['read'];
             $write = $_POST['writ'];
             $csv->encoding($read, $write);
             $rows = array();
             $cols = array();
             $csv->titles = preg_split('/(, |,)/', $_POST['cols'], -1, PREG_SPLIT_NO_EMPTY);
             foreach ($csv->titles as $header) {
                 $cols[$header] = '';
             }
             $rows[0] = $cols;
             $csv->data = $rows;
             $csv->save($rootpath . $dir . '/' . $filename);
             if (is_file($rootpath . $dir . '/' . $filename)) {
                 $recursive = $_POST['recursive'] == 'true' ? true : false;
                 $fullpath = $rootpath . $dir;
                 $querystring = ltrim($_POST['querystring'], '?');
                 $files = $recursive ? fileaway_utility::recursefiles($fullpath, array(), array(), '[cC][sS][vV]') : glob("{$fullpath}/*.[cC][sS][vV]");
                 $file_index = array_search($rootpath . $dir . '/' . $filename, $files);
                 $link = fileaway_utility::querystring(get_permalink($_POST['pg']), $querystring, array('fa_csv' => base64_encode(fileaway_utility::basename($filename)), 'fa_index' => $file_index));
                 $response = array('status' => 'success', 'redirect' => $link);
             } else {
                 $reponse = array('status' => 'error', 'message' => sprintf(__('Sorry. There was a problem creating %s', 'file-away'), $filename));
             }
         }
     } elseif ($action == 'values') {
         if (!wp_verify_nonce($_POST['values_nonce'], 'fileaway-values-nonce')) {
             die($dm);
         }
         $src = $rootpath . base64_decode($_POST['src']);
         $csv = new fileaway_csv();
         $csv->sort_by = 'id';
         $csv->auto($src);
         $read = $_POST['read'];
         $write = $_POST['writ'];
         $csv->encoding($read, $write);
         $csv->data[$_POST['row']][$_POST['col']] = $_POST['newvalue'];
         if ($csv->save()) {
             $response = array('status' => 'success');
         } else {
             $csv->data[$_POST['row']][$_POST['col']] = $_POST['oldvalue'];
             if ($csv->save()) {
                 $response = array('status' => 'error', 'message' => __('Sorry about that, but your changes could not be saved.', 'file-away'));
             } else {
                 $response = array('status' => 'error', 'message' => __('Sorry about that, but your changes could not be saved.', 'file-away'));
             }
         }
     } elseif ($action == 'newrow') {
         if (!wp_verify_nonce($_POST['values_nonce'], 'fileaway-values-nonce')) {
             die($dm);
         }
         $response = array();
         $src = $rootpath . base64_decode($_POST['src']);
         $data = array('test', 'test');
         $csv = new fileaway_csv();
         $csv->sort_by = 'id';
         $csv->auto($src);
         $read = $_POST['read'];
         $write = $_POST['writ'];
         $csv->encoding($read, $write);
         foreach ($csv->titles as $col) {
             $csv->data[$_POST['numrows']][$col] = '';
         }
         if ($csv->save()) {
             $response['status'] = 'success';
             $k = $_POST['numrows'];
             $uid = $_POST['uid'];
             $theme = $_POST['theme'];
             $headers = $csv->titles;
             $html = "<tr id='ssfa-values-{$uid}-{$k}' class='ssfa-values-context' data-row='{$k}'>";
             foreach ($headers as $key => $header) {
                 $col1class = $key < 1 ? "class='{$theme}-first-column'" : null;
                 $html .= '<td id="cell-ssfa-values-' . $uid . '-' . $k . '-' . $key . '" ' . $col1class . ' style="cursor:cell">' . '<span id="value-ssfa-values-' . $uid . '-' . $k . '-' . $key . '" data-row="' . $k . '" data-col="' . $header . '" data-colnum="' . $key . '"></span>&nbsp;' . '<input type="text" id="input-ssfa-values-' . $uid . '-' . $k . '-' . $key . '" data-row="' . $k . '" data-col="' . $header . '" data-colnum="' . $key . '" ' . 'value="" style="display:none; width:90%">' . '</td>';
             }
             $html .= "</tr>";
             $response['html'] = $html;
         } else {
             $response = array('status' => 'error', 'message' => __('Sorry about that, but your changes could not be saved.', 'file-away'));
         }
     } elseif ($action == 'deleterow') {
         if (!wp_verify_nonce($_POST['values_nonce'], 'fileaway-values-nonce')) {
             die($dm);
         }
         $src = $rootpath . base64_decode($_POST['src']);
         $csv = new fileaway_csv();
         $csv->sort_by = 'id';
         $csv->auto($src);
         $read = $_POST['read'];
         $write = $_POST['writ'];
         $csv->encoding($read, $write);
         unset($csv->data[$_POST['row']]);
         if ($csv->save()) {
             $response = array('status' => 'success');
         } else {
             $response = array('status' => 'error', 'message' => __('Sorry about that, but your changes could not be saved.', 'file-away'));
         }
     } elseif ($action == 'createcol') {
         if (!wp_verify_nonce($_POST['values_nonce'], 'fileaway-values-nonce')) {
             die($dm);
         }
         $src = $rootpath . base64_decode($_POST['src']);
         $csv = new fileaway_csv();
         $csv->sort_by = 'id';
         $csv->auto($src);
         $read = $_POST['read'];
         $write = $_POST['writ'];
         $csv->encoding($read, $write);
         $headers = $csv->titles;
         $rows = $csv->data;
         if (count($headers) < 2) {
             $csv->delimiter = ",";
         }
         foreach ($rows as $k => $v) {
             fileaway_utility::recreatecol($rows[$k], $_POST['colnum'], 0, $_POST['col']);
         }
         array_splice($headers, $_POST['colnum'], 0, $_POST['col']);
         $csv->titles = $headers;
         $csv->data = $rows;
         if ($csv->save()) {
             $response = array('status' => 'success');
         } else {
             $response = array('status' => 'error', 'message' => __('Sorry about that, but your changes could not be saved.', 'file-away'));
         }
     } elseif ($action == 'colrename') {
         if (!wp_verify_nonce($_POST['values_nonce'], 'fileaway-values-nonce')) {
             die($dm);
         }
         $src = $rootpath . base64_decode($_POST['src']);
         $csv = new fileaway_csv();
         $csv->sort_by = 'id';
         $csv->auto($src);
         $read = $_POST['read'];
         $write = $_POST['writ'];
         $csv->encoding($read, $write);
         $headers = $csv->titles;
         $rows = $csv->data;
         foreach ($rows as $k => $v) {
             fileaway_utility::recreatecol($rows[$k], $_POST['colnum'], 0, $_POST['newname'], $rows[$k][$_POST['oldname']]);
             unset($rows[$k][$_POST['oldname']]);
         }
         $headers[$_POST['colnum']] = $_POST['newname'];
         $csv->titles = $headers;
         $csv->data = $rows;
         if ($csv->save()) {
             $response = array('status' => 'success');
         } else {
             $response = array('status' => 'error', 'message' => __('Sorry about that, but your changes could not be saved.', 'file-away'));
         }
     } elseif ($action == 'coldelete') {
         if (!wp_verify_nonce($_POST['values_nonce'], 'fileaway-values-nonce')) {
             die($dm);
         }
         $src = $rootpath . base64_decode($_POST['src']);
         $csv = new fileaway_csv();
         $csv->sort_by = 'id';
         $csv->auto($src);
         $read = $_POST['read'];
         $write = $_POST['writ'];
         $csv->encoding($read, $write);
         $del_val = $_POST['col'];
         $del_key = $_POST['colnum'];
         $headers = $csv->titles;
         $rows = $csv->data;
         unset($headers[$_POST['colnum']]);
         $headers = array_values($headers);
         foreach ($rows as $k => $v) {
             unset($rows[$k][$_POST['col']]);
         }
         $rows = array_values($rows);
         $csv->titles = $headers;
         $csv->data = $rows;
         if ($csv->save()) {
             $response = array('status' => 'success');
         } else {
             $response = array('status' => 'error', 'message' => __('Sorry about that, but your changes could not be saved.', 'file-away'));
         }
     } elseif ($action == 'backupcsv') {
         if (!wp_verify_nonce($_POST['values_nonce'], 'fileaway-values-nonce')) {
             die($dm);
         }
         $src = $rootpath . base64_decode($_POST['src']);
         $csv = new fileaway_csv();
         $csv->auto($src);
         $read = $_POST['read'];
         $write = $_POST['writ'];
         $csv->encoding($read, $write);
         $bits = fileaway_utility::pathinfo($src);
         $newfile = str_replace('.' . $bits['extension'], ' [' . date('Y-m-d H-i-s', current_time('timestamp')) . '].' . $bits['extension'], $src);
         if ($csv->save($newfile)) {
             $response = array('status' => 'success');
         } else {
             $response = array('status' => 'error', 'message' => __('Sorry about that, but a backup could not be successfully saved.', 'file-away'));
         }
     }
     $response = json_encode($response);
     header("Content-Type: application/json");
     echo $response;
     exit;
 }
                $k++;
            }
        }
        //echo $icon_name. '</br>';
    }
}
if (isset($icon_atlas1)) {
    for ($l = 1; $l <= $k; $l++) {
        $icon_name = 'icon_atlas' . $l;
        $dest256 = $iconsFolder . $_SESSION['UserPath'] . $_SESSION['Username'] . $timestamp . "_" . $icon_name . "_256.dds";
        if (isset(${$icon_name})) {
            $icon_uri_target = $dest256;
            $command_str = $imageMagickConvert . " " . ${$icon_name} . " -define dds:compression=none -define dds:mipmaps=false " . $icon_uri_target;
            exec($command_str);
            $zip->addFile($dest256);
            $zip->renameName($dest256, $timestamp . "_" . $icon_name . "_256.dds");
            $dest128 = $iconsFolder . $_SESSION['UserPath'] . $_SESSION['Username'] . $timestamp . "_" . $icon_name . "_128.dds";
            $icon_uri_target = $dest128;
            $command_str = $imageMagickConvert . " " . ${$icon_name} . " -resize 1024x1024 -define dds:compression=none -define dds:mipmaps=false " . $icon_uri_target;
            exec($command_str);
            $zip->addFile($dest128);
            $zip->renameName($dest128, $timestamp . "_" . $icon_name . "_128.dds");
            $dest80 = $iconsFolder . $_SESSION['UserPath'] . $_SESSION['Username'] . $timestamp . "_" . $icon_name . "_80.dds";
            $icon_uri_target = $dest80;
            $command_str = $imageMagickConvert . " " . ${$icon_name} . " -resize 640x640 -define dds:compression=none -define dds:mipmaps=false " . $icon_uri_target;
            exec($command_str);
            $zip->addFile($dest80);
            $zip->renameName($dest80, $timestamp . "_" . $icon_name . "_80.dds");
            $dest64 = $iconsFolder . $_SESSION['UserPath'] . $_SESSION['Username'] . $timestamp . "_" . $icon_name . "_64.dds";
            $icon_uri_target = $dest64;
            $command_str = $imageMagickConvert . " " . ${$icon_name} . " -resize 512x512 -define dds:compression=none -define dds:mipmaps=false " . $icon_uri_target;
Example #10
0
            continue;
        }
        $ob->out($item->getPathname() . '  =>  ' . $dest . "\n");
        $zip->addFile($item->getPathname(), Backup::encode($dest));
    }
    foreach ($installIterator as $item) {
        if ($item->isDir()) {
            continue;
        }
        $dest = str_replace($installFolder . DIRECTORY_SEPARATOR, '', 'installation' . DIRECTORY_SEPARATOR . $item->getPathname());
        $ob->out($item->getPathname() . '  =>  ' . $dest . "\n");
        $zip->addFile($item->getPathname(), str_replace('\\', '/', $dest));
    }
    $zip->addFile($backupSQLFile->getPathname(), $backupSQLFile->getBasename());
    $zip->deleteName('configuration.dist.php');
    $zip->renameName('configuration.php', 'configuration.dist.php');
    $zip->close();
    echo 'ZIP ok';
} else {
    echo 'failed';
}
?>
</pre>

<script>
	toBottom();
	stop = true;
</script>

<?php 
$ob->endClean();
Example #11
0
 /**
  * ====================================================================
  *  RENAME FILE(S) INSIDE A ZIP FILE
  * ====================================================================
  *
  * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  *  Parameter | Type  | Description
  *  --------- | ----- | -----------------------------------------------
  *  $old      | array | Array of old file name and new file name
  *  --------- | ----- | -----------------------------------------------
  * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  *
  */
 public static function renameFiles($old, $new = "")
 {
     $zip = new ZipArchive();
     if (File::exist(self::$open) && $zip->open(self::$open)) {
         if (is_array($old)) {
             foreach ($old as $k => $v) {
                 $k = File::path($k);
                 $v = File::path($v);
                 $root = trim(File::D($k), DS . '.') !== "" ? File::D($k) . DS : "";
                 $zip->renameName($k, $root . File::B($v));
             }
         } else {
             $old = File::path($old);
             $root = trim(File::D($old), DS . '.') !== "" ? File::D($old) . DS : "";
             $zip->renameName($old, $root . File::B($new));
         }
         $zip->close();
     }
     return new static();
 }
Example #12
0
 /**
  * ZipArchiveクラスを利用した解凍
  *
  * @param string $path Zipファイルパス
  * @return bool
  */
 protected function _extractWithZipArchiveClass($path)
 {
     $encodeCharset = "UTF-8";
     // server os のファイルシステム文字コード
     mb_language('Japanese');
     setlocale(LC_ALL, 'ja_JP.UTF-8');
     // スレッドセーフじゃないので直前で
     $zip = new ZipArchive();
     $result = $zip->open($this->_zipPath);
     if ($result !== true) {
         return false;
     }
     if ($this->_password) {
         $zip->setPassword($this->_password);
     }
     $index = 0;
     while ($zipEntry = $zip->statIndex($index)) {
         $zipEntryName = $zipEntry['name'];
         $destName = mb_convert_encoding($zipEntry['name'], $encodeCharset, 'auto');
         if ($zip->renameName($zipEntryName, $destName) === false) {
             return false;
         }
         if ($zip->extractTo($path, $destName) === false) {
             return false;
         }
         if ($zip->renameName($destName, $zipEntryName) === false) {
             return false;
         }
         $index++;
     }
     $zip->close();
     return true;
 }
 /**
  * GitHub decides on the root directory in the zipball, but we might disagree.
  *
  * @since 1.0
  */
 public function get_zipball()
 {
     add_filter('http_request_args', array($this, 'add_http_args'), 10, 2);
     $zipball = download_url($this->get_api_url('/repos/:owner/:repo/:archive_format'));
     remove_filter('http_request_args', array($this, 'add_http_args'));
     if (is_wp_error($zipball)) {
         $this->return_404();
     }
     $z = new ZipArchive();
     if (true === $z->open($zipball)) {
         $length = strlen($z->getNameIndex(0));
         $status = true;
         for ($i = 0; $i < $z->numFiles; $i++) {
             $name = $z->getNameIndex($i);
             if (!$name) {
                 $status = false;
             }
             $newname = substr_replace($name, $this->config->repo, 0, $length - 1);
             if (!$z->renameName($name, $newname)) {
                 $status = false;
             }
         }
         $z->close();
         if ($status) {
             header('Content-Disposition: attachment; filename=' . $this->config->repo . '.zip');
             header('Content-Type: application/zip');
             header('Content-Length: ' . filesize($zipball));
             ob_clean();
             flush();
             readfile($zipball);
             unlink($zipball);
             exit;
         }
     }
     unlink($zipball);
     $this->return_404();
 }
 public function RawInputFile($FileName, $FileType, $Fields, $SkipLines, $FileCategory, $MergeFieldNumber, $UPCFieldName, $OuterJoin, $TrimData = FALSE, $FileToExtract = NULL, $KeepOldFile = FALSE)
 {
     // Error Checking of parameters
     if (!is_readable($FileName)) {
         trigger_error("Filename {$FileName} does not exist or cannot be read", E_USER_ERROR);
     }
     if (in_array($FileType, $this->ValidFileTypes) === FALSE) {
         trigger_error("Invalid file type passed, {$FileType}", E_USER_ERROR);
     }
     if (!is_array($Fields)) {
         trigger_error("The fields parameter must be an array, {$Fields} passed", E_USER_ERROR);
     }
     if (!is_numeric($SkipLines)) {
         trigger_error("SkipLines must be numeric, {$SkipFirst} passed", E_USER_ERROR);
     }
     if (strlen($FileCategory) == 0) {
         trigger_error("FileType parameter is required", E_USER_ERROR);
     }
     // Erase the supplier errors table
     $sqlStmt = "delete from Supplier_Errors where Supplier_Party_ID = '{$this->PartyID}'";
     $this->FeedsDbObj->DeleteRow($sqlStmt);
     echo "Input file for {$FileCategory} is {$FileName}\n";
     // Store the file specifications
     if (is_null($this->UPCFieldName)) {
         $this->UPCFieldName = $UPCFieldName;
     }
     if (isset($this->FileCategories[$FileCategory])) {
         $this->FileCategories[$FileCategory]++;
     } else {
         $this->FileCategories[$FileCategory] = 1;
     }
     $newFile = tempnam(Config::getTmpDir(), "{$this->PartyID}-");
     if (asort($Fields) === FALSE) {
         trigger_error("Unable to sort fields array", E_USER_ERROR);
     }
     if ($this->IsMiniMSRP === FALSE && $this->GenericFeed === FALSE && $this->MiniFeed === FALSE && $KeepOldFile === FALSE) {
         $this->FilesToPurge[$FileName] = NULL;
     }
     $this->FilesToPurge[$newFile] = NULL;
     if (substr($FileType, 0, 3) == "ZIP") {
         $zip = new ZipArchive();
         if ($zip->open($FileName, ZipArchive::CREATE) !== TRUE) {
             trigger_error("Could not open the Zip File Archive {$FileName}", E_USER_ERROR);
         }
         // Get filename only, ignore rest of path
         $newFileName = pathinfo($newFile, PATHINFO_BASENAME);
         if (is_numeric($FileToExtract)) {
             $zip->renameIndex($FileToExtract, $newFileName);
         } else {
             $zip->renameName($FileToExtract, $newFileName);
         }
         $UnZipDir = Config::getTmpDir() . "/";
         if ($zip->extractTo($UnZipDir, $newFileName) === FALSE) {
             trigger_error("Could not unzip the Zip File Archive {$FileName} file {$newFileName}", E_USER_ERROR);
         }
         $zip->close();
         $FileName = $newFile;
         $newFile = tempnam(Config::getTmpDir(), "{$this->PartyID}-");
         $this->FilesToPurge[$newFile] = NULL;
     }
     // Based on the file type, we will convert to CSV and remove headers.
     switch ($FileType) {
         case "XLS":
             $newFile = $this->HandleXLSFile($FileName, $newFile, $Fields, $SkipLines, $TrimData);
             break;
         case "ZIPCSV":
         case "CSV":
             $newFile = $this->HandleCSVFile($FileName, $newFile, $Fields, $SkipLines, $TrimData);
             break;
         case "DBF":
         case "ZIPDBF":
             $newFile = $this->HandleDBFFile($FileName, $newFile, $Fields, $SkipLines, $TrimData);
             break;
         case "TAB":
         case "ZIPTAB":
             $newFile = $this->HandleTabFile($FileName, $newFile, $Fields, $SkipLines, $TrimData, FALSE);
             break;
         case "TABQ":
         case "ZIPTABQ":
             $newFile = $this->HandleTabFile($FileName, $newFile, $Fields, $SkipLines, $TrimData, TRUE);
             break;
         case "BAR":
         case "ZIPBAR":
             $newFile = $this->HandleDelimitedFile($FileName, $newFile, $Fields, $SkipLines, "|", $TrimData);
             break;
         case "TIL":
         case "ZIPTIL":
             $newFile = $this->HandleDelimitedFile($FileName, $newFile, $Fields, $SkipLines, "~", $TrimData);
             break;
         case "FIXED":
         case "ZIPFIXED":
             $newFile = $this->HandleFixedFile($FileName, $newFile, $Fields, $SkipLines, $TrimData);
     }
     // Re-sequence the columns
     // For fixed file format, we have to redo the fields array since it is not a list of fields. It's a list of starting positions:length
     $i = 1;
     foreach ($Fields as $Key => $Value) {
         if ($FileType == "FIXED" || $FileType == "ZIPFIXED") {
             if ($i == $MergeFieldNumber) {
                 $MergeFieldNumber = $i;
             }
         } else {
             if ($Value == $MergeFieldNumber) {
                 $MergeFieldNumber = $i;
             }
         }
         $Fields[$Key] = $i;
         $i++;
     }
     echo "New file for {$FileCategory} is {$newFile}\n";
     $SpecsArray = array();
     $SpecsArray["FileName"] = $newFile;
     $SpecsArray["Fields"] = $Fields;
     $SpecsArray["FileCategory"] = $FileCategory;
     $SpecsArray["MergeFieldNumber"] = $MergeFieldNumber;
     $SpecsArray["OuterJoin"] = $OuterJoin;
     $this->FileSpecs[] = $SpecsArray;
 }
Example #15
0
 /**
  *	Private: Import/Export Templates
  *	Import/Export templates by XML
  *
  *	@return	void
  */
 private function loadImportExportTemplates()
 {
     if ($_GET['process']) {
         switch ($_GET['process']) {
             case "import":
                 if (empty($_FILES['FileUpload']['name']) && empty($_POST['FilePath'])) {
                     $GLOBALS['result_command'] = $this->lang->words['System']['Templates']['ImportExport']['Import']['Messages']['SelectFile'];
                     $GLOBALS['result_command'] = adminShowMessage($GLOBALS['result_command'], 2);
                 } else {
                     $break = FALSE;
                     $uploaded = FALSE;
                     $is_zip = FALSE;
                     if (!empty($_FILES['FileUpload']['name'])) {
                         $type = $_FILES['FileUpload']['type'];
                         $is_zip = $type == "application/x-gzip" || $type == "application/gzip" ? "gzip" : ($type == "application/zip" ? "zip" : "none");
                         if ($type != "text/xml" && $type != "application/x-gzip" && $type != "application/gzip" && $type != "application/zip") {
                             $GLOBALS['result_command'] = $this->lang->words['System']['Templates']['ImportExport']['Import']['Messages']['InvalidFile'];
                             $GLOBALS['result_command'] = adminShowMessage($GLOBALS['result_command'], 2);
                             $break = TRUE;
                         } else {
                             $filepath = CTM_CACHE_PATH . "temp_cache/" . md5(time() . "&ew_template_temp_file&" . mt_rand()) . ".tmp";
                             if (!copy($_FILES['FileUpload']['tmp_name'], $filepath)) {
                                 $GLOBALS['result_command'] = $this->lang->words['System']['Templates']['ImportExport']['Import']['Messages']['UploadError'];
                                 $GLOBALS['result_command'] = adminShowMessage($GLOBALS['result_command'], 2);
                                 $break = TRUE;
                             } else {
                                 $uploaded = TRUE;
                             }
                         }
                     } else {
                         $filepath = CTM_ROOT_PATH . $_POST['FilePath'];
                         $find_end = strrpos($filepath, ".");
                         $file_end = substr($filepath, $find_end + 1);
                         if (!file_exists($filepath)) {
                             $GLOBALS['result_command'] = $this->lang->words['System']['Templates']['ImportExport']['Import']['Messages']['FileNoExists'];
                             $GLOBALS['result_command'] = adminShowMessage($GLOBALS['result_command'], 2);
                             $break = TRUE;
                         } elseif ($file_end != "xml" && $file_end != "gz" && $file_end != "zip") {
                             $GLOBALS['result_command'] = $this->lang->words['System']['Templates']['ImportExport']['Import']['Messages']['InvalidFile'];
                             $GLOBALS['result_command'] = adminShowMessage($GLOBALS['result_command'], 2);
                             $break = TRUE;
                         } else {
                             $is_zip = $file_end == "gz" ? "gzip" : ($file_end == "zip" ? "zip" : NULL);
                         }
                     }
                     if ($is_zip == "gzip" && $break == false) {
                         if (!function_exists("gzopen") || !function_exists("gzread") || !function_exists("gzclose")) {
                             $GLOBALS['result_command'] = $this->lang->words['System']['Templates']['ImportExport']['Import']['Messages']['UnZipError'];
                             $GLOBALS['result_command'] = adminShowMessage($GLOBALS['result_command'], 2);
                             $break = TRUE;
                         } else {
                             if ($gzip = gzopen($filepath, "r")) {
                                 $tmp_path = CTM_CACHE_PATH . "temp_cache/" . md5(time() . "&" . EffectWebFiles::TEMPLATE_XML_FILENAME . "&" . mt_rand()) . ".tmp";
                                 $gz_content = gzread($gzip, filesize($filepath) * 2);
                                 gzclose($gzip);
                                 if ($uploaded == true) {
                                     unlink($filepath);
                                 }
                                 $fp = fopen($tmp_path, "w");
                                 fwrite($fp, $gz_content);
                                 fclose($fp);
                             } else {
                                 $GLOBALS['result_command'] = $this->lang->words['System']['Templates']['ImportExport']['Import']['Messages']['UnZipError'];
                                 $GLOBALS['result_command'] = adminShowMessage($GLOBALS['result_command'], 2);
                                 $break = TRUE;
                             }
                         }
                     } elseif ($is_zip == "zip" && $break == false) {
                         if (!class_exists("ZipArchive")) {
                             $GLOBALS['result_command'] = $this->lang->words['System']['Templates']['ImportExport']['Import']['Messages']['UnZipError'];
                             $GLOBALS['result_command'] = adminShowMessage($GLOBALS['result_command'], 2);
                             $break = TRUE;
                         } else {
                             $zip = new ZipArchive();
                             if ($zip->open($filepath)) {
                                 $filename = md5(time() . "&" . EffectWebFiles::TEMPLATE_XML_FILENAME . "&" . mt_rand()) . ".tmp";
                                 $tmp_path = CTM_CACHE_PATH . "temp_cache/" . $filename;
                                 $zip->renameName(EffectWebFiles::TEMPLATE_XML_FILENAME, $filename);
                                 $zip->extractTo(CTM_CACHE_PATH . "temp_cache/", array($filename));
                                 $zip->renameName($filename, EffectWebFiles::TEMPLATE_XML_FILENAME);
                                 $zip->close();
                                 if ($uploaded == true) {
                                     unlink($filepath);
                                 }
                             } else {
                                 $GLOBALS['result_command'] = $this->lang->words['System']['Templates']['ImportExport']['Import']['Messages']['UnZipError'];
                                 $GLOBALS['result_command'] = adminShowMessage($GLOBALS['result_command'], 2);
                                 $break = TRUE;
                             }
                         }
                     } else {
                         $tmp_path = $filepath;
                     }
                     if ($break == false) {
                         $xml_content = file_get_contents($tmp_path);
                         if (file_exists($tmp_path) && $tmp_path != $filepath && ($is_zip == "gzip" || $is_zip == "zip")) {
                             unlink($tmp_path);
                         }
                         if ($uploaded == true && $is_zip == "none") {
                             unlink($filepath);
                         }
                         if (!CTM_FileManage::Lib('XML')->IsXML($xml_content) || !strstr($xml_content, "<skin_xml") || !strstr($xml_content, "<skin_info>")) {
                             $GLOBALS['result_command'] = $this->lang->words['System']['Templates']['ImportExport']['Import']['Messages']['FileCorrupted'];
                             $GLOBALS['result_command'] = adminShowMessage($GLOBALS['result_command'], 2);
                         } else {
                             CTM_Template::Lib('ImportExport')->ImportXML($xml_content, $skin_info);
                             if ($skin_info == "XML_CORRUPTED") {
                                 $GLOBALS['result_command'] = $this->lang->words['System']['Templates']['ImportExport']['Import']['Messages']['FileCorrupted'];
                                 $GLOBALS['result_command'] = adminShowMessage($GLOBALS['result_command'], 2);
                             } elseif ($skin_info == "INVALID_CODEKEY") {
                                 $GLOBALS['result_command'] = $this->lang->words['System']['Templates']['ImportExport']['Import']['Messages']['InvalidTemplate'];
                                 $GLOBALS['result_command'] = adminShowMessage($GLOBALS['result_command'], 2);
                             } elseif ($skin_info == "VAR_0_ERROR") {
                                 $GLOBALS['result_command'] = $this->lang->words['System']['Templates']['ImportExport']['Import']['Messages']['LicenseError'];
                                 $GLOBALS['result_command'] = adminShowMessage($GLOBALS['result_command'], 2);
                             } else {
                                 $path = "server_cache/db_php/skin_sources/skin_sources.php";
                                 CTM_Controller::UpdateWebCache("effectwebkernelhash", "hash_file:" . $path, "hash_file:" . md5_file(CTM_CACHE_PATH . $path));
                                 $GLOBALS['result_command'] = $this->lang->words['System']['Templates']['ImportExport']['Import']['Messages']['Success'];
                                 $GLOBALS['result_command'] = sprintf($GLOBALS['result_command'], $skin_info['Name'], $skin_info['SkinSet']);
                                 $GLOBALS['result_command'] = adminShowMessage($GLOBALS['result_command'], 3);
                             }
                         }
                     } else {
                         if ($uploaded == true) {
                             if (file_exists($filepath)) {
                                 unlink($filepath);
                             }
                             if (file_exists($tmp_path)) {
                                 unlink($tmp_path);
                             }
                         }
                     }
                 }
                 break;
             case "export":
                 CTM_Template::Lib('Sources')->OpenDatabase();
                 if (!CTM_Template::Lib('Sources')->CheckSkin($_POST['Template'])) {
                     CTM_Template::Lib('Sources')->CloseDatabase();
                     $GLOBALS['result_command'] = $this->lang->words['System']['Templates']['ImportExport']['Export']['Messages']['TemplateInvalid'];
                     $GLOBALS['result_command'] = adminShowMessage($GLOBALS['result_command'], 2);
                 } else {
                     CTM_Template::Lib('ImportExport')->ExportXML("ew_template", $_POST['Template'], $this->skin_cache_keys, true, CTM_ACP_USE_ZIP);
                 }
                 break;
         }
     }
     CTM_Template::Lib('Sources')->OpenDatabase();
     CTM_Template::Lib('Sources')->GetAllSkins($_templates);
     CTM_Template::Lib('Sources')->CloseDatabase();
     if (count($_templates) > 0) {
         foreach ($_templates as $key => $value) {
             $GLOBALS['templates'][$key] = $value['Name'];
         }
     }
     $GLOBALS['template_default_xml_file'] = EffectWebFiles::TEMPLATE_XML_FILENAME;
 }