public function index()
 {
     // Define directory separator
     define(MYDS, '/');
     if ($_POST['submit']) {
         $yui = new Yui();
         $yui->compressor_dir = '/assets' . DS . 'compressor' . DS;
         $yui->params = array('nomunge' => $_POST['nomunge'], 'preserve-semi' => $_POST['preserve-semi'], 'disable-optimizations' => $_POST['disable-optimizations']);
         $yui->execute(array_merge($_FILES, $_POST));
         $this->vars['error'] = $yui->error;
         $file_loc = $yui->compressed['dir'] . $yui->compressed['file'];
         $filename = $yui->compressed['file'];
         $filename_zip = current(explode('.', $yui->compressed['file'])) . '.zip';
         $zip_file_with_path = $yui->compressed['dir'] . $filename_zip;
         if ($_POST['zipped'] === "1") {
             $zip = new Zip();
             $zip->addFile($file_loc, $filename);
             $zip->save($zip_file_with_path);
             $this->vars['zipped_file'] = '<a href="' . $zip_file_with_path . '" target="_blank">' . $filename_zip . '</a>';
         }
         $this->vars['compressed_file'] = '<a href="' . $file_loc . '" target="_blank">' . $filename . '</a>';
     }
     $this->layout_vars['page_title'] = 'YUI Compression tool';
     $this->display('home/index', $this->vars);
 }
Esempio n. 2
0
 public static function export($idstr)
 {
     $idArr = is_array($idstr) ? $idstr : explode(",", $idstr);
     if (1 < count($idArr)) {
         $zip = new Zip();
         $exportFileName = Ibos::lang("Form export file pack", "workflow.default", array("{date}" => date("Y-m-d")));
         $zipFileName = FileUtil::getTempPath() . "/" . TIMESTAMP . ".zip";
         foreach ($idArr as $id) {
             $form = self::handleExportSingleForm($id);
             $zip->addFile($form["content"], sprintf("%s.html", ConvertUtil::iIconv($form["title"], CHARSET, "gbk")));
         }
         $fp = fopen($zipFileName, "w");
         if (@fwrite($fp, $zip->file()) !== false) {
             header("Cache-control: private");
             header("Content-type: application/octet-stream");
             header("Accept-Ranges: bytes");
             header("Content-Length: " . sprintf("%u", FileUtil::fileSize($zipFileName)));
             header("Content-Disposition: attachment; filename=" . $exportFileName . ".zip");
             readfile($zipFileName);
             exit;
         }
     } else {
         $id = implode(",", $idArr);
         $form = self::handleExportSingleForm($id);
         ob_end_clean();
         header("Cache-control: private");
         header("Content-type: text/plain");
         header("Accept-Ranges: bytes");
         header("Accept-Length: " . strlen($form["content"]));
         header("Content-Disposition: attachment; filename=" . $form["title"] . ".html");
         echo $form["content"];
     }
 }
function create_zip_Zip($files = array(), $destination = '')
{
    if (count($files)) {
        //create the archive
        if (file_exists($destination)) {
            unlink($destination);
        }
        $zip = new Zip();
        $zip->setZipFile($destination);
        foreach ($files as $file) {
            $zip->addFile(file_get_contents($file), str_replace('/', '', strrchr($file, '/')));
        }
        $zip->finalize();
        $zip->setZipFile($destination);
        //check to make sure the file exists
        return (string) file_exists($destination);
    } else {
        return "No valid files found. Exiting<br/>";
    }
}
Esempio n. 4
0
if (isset($_GET['export'])) {
    //set_time_limit(0);
    $tmpFile = appPATH . 'cache/tmp/pri/modExport.zip';
    is_file($tmpFile) && unlink($tmpFile);
    $zip = new Zip();
    $zip->open($tmpFile, Zip::CREATE);
    $zip->addDir(appPATH . 'm', null, '/(\\.svn)/');
    $zip->addDir(appPATH . 'qg', null, '/(\\.svn)/');
    foreach (scandir(appPATH) as $file) {
        if (!is_file(appPATH . $file)) {
            continue;
        }
        if ($file === 'error_log') {
            continue;
        }
        $zip->addFile(appPATH . $file, $file);
    }
    /* only custom module:
    	foreach (dbEntry_module::all() as $M) {
    		If ($M->server_time) continue;
    		$zip->addDir(sysPATH.$name, 'm/'.$M->name, '/(\.svn)/');
    	}
    
    	/* add mysql export */
    $structExport = '';
    @mkdir('/tmp/');
    @mkdir('/tmp/qgdbexport1/');
    chmod('/tmp/qgdbexport1/', 0777);
    foreach (D()->Tables() as $T) {
        $file = realpath('/tmp/qgdbexport1/') . '/' . $T . '.csv';
        @unlink($file);
 function backup()
 {
     $settings = Plugin::getAllSettings('backup_restore');
     // All of the tablesnames that belong to Wolf CMS core.
     $tablenames = array();
     if (strpos(DB_DSN, 'mysql') !== false) {
         $sql = 'show tables';
     }
     if (strpos(DB_DSN, 'sqlite') !== false) {
         $sql = 'SELECT name FROM SQLITE_MASTER WHERE type="table" ORDER BY name';
     }
     if (strpos(DB_DSN, 'pgsql') !== false) {
         $sql = "select tablename from pg_tables where schemaname='public'";
     }
     Record::logQuery($sql);
     $pdo = Record::getConnection();
     $result = $pdo->query($sql);
     while ($col = $result->fetchColumn()) {
         $tablenames[] = $col;
     }
     // All fields that should be wrapped as CDATA
     $cdata_fields = array('title', 'content', 'content_html');
     // Setup XML for backup
     $xmltext = '<?xml version="1.0" encoding="UTF-8"?><wolfcms></wolfcms>';
     $xmlobj = new SimpleXMLExtended($xmltext);
     $xmlobj->addAttribute('version', CMS_VERSION);
     // Retrieve all database information for placement in XML backup
     global $__CMS_CONN__;
     Record::connection($__CMS_CONN__);
     // Generate XML file entry for each table
     foreach ($tablenames as $tablename) {
         $table = Record::query('SELECT * FROM ' . $tablename);
         $child = $xmlobj->addChild($tablename . 's');
         while ($entry = $table->fetch(PDO::FETCH_ASSOC)) {
             $subchild = $child->addChild($tablename);
             foreach ($entry as $key => $value) {
                 if ($key == 'password' && $settings['pwd'] === '0') {
                     $value = '';
                 }
                 if (in_array($key, $cdata_fields, true)) {
                     $valueChild = $subchild->addCData($key, $value);
                 } else {
                     $valueChild = $subchild->addChild($key, str_replace('&', '&amp;', $value));
                 }
                 if ($value === null) {
                     $valueChild->addAttribute('null', true);
                 }
             }
         }
     }
     // Add XML files entries for all files in upload directory
     if ($settings['backupfiles'] == '1') {
         $dir = realpath(FILES_DIR);
         $this->_backup_directory($xmlobj->addChild('files'), $dir, $dir);
     }
     // Create the XML file
     $file = $xmlobj->asXML();
     $filename = 'wolfcms-backup-' . date($settings['stamp']) . '.' . $settings['extension'];
     // Offer a plain XML file or a zip file for download
     if ($settings['zip'] == '1') {
         // Create a note file
         $note = "---[ NOTES for {$filename} ]---\n\n";
         $note .= "This backup was created for a specific Wolf CMS version, please only restore it\n";
         $note .= "on the same version.\n\n";
         $note .= "When restoring a backup, upload the UNzipped XML backup file, not this zip file.\n\n";
         $note .= 'Created on ' . date('Y-m-d') . ' at ' . date('H:i:s') . ' GTM ' . date('O') . ".\n";
         $note .= 'Created with BackupRestore plugin version ' . BR_VERSION . "\n";
         $note .= 'Created for Wolf CMS version ' . CMS_VERSION . "\n\n";
         $note .= '---[ END NOTES ]---';
         use_helper('Zip');
         $zip = new Zip();
         $zip->clear();
         $zip->addFile($note, 'readme.txt');
         $zip->addFile($file, $filename);
         $zip->download($filename . '.zip');
     } else {
         header('Pragma: public');
         header('Expires: 0');
         header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
         header('Cache-Control: private', false);
         header('Content-Type: text/xml; charset=UTF-8');
         header('Content-Disposition: attachment; filename=' . $filename . ';');
         header('Content-Transfer-Encoding: 8bit');
         header('Content-Length: ' . strlen($file));
         echo $file;
     }
 }
 public function scanner($check_session = true, $show_results = true)
 {
     // Start scanning process
     error_reporting(0);
     ini_set('memory_limit', '256M');
     if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
         define(DIRSEP, '\\');
     } else {
         define(DIRSEP, '/');
     }
     // Skip the 2nd scan process
     $lockFile = $this->tmp_dir . 'scan.lock';
     if (file_exists($lockFile) && time() - filemtime($lockFile) < 60 * 5) {
         $error_msg = 'Another Scanning Process in the memory. Exit.';
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         exit;
     }
     register_shutdown_function('self::AntivirusFileLock');
     $lockFp = fopen($lockFile, 'w');
     // Register any shutdown of the script
     register_shutdown_function('self::AntivirusFinished');
     $error_msg = 'Start Scan Process ver. ' . $this->antivirus_version . ' [scanner ver. ' . self::$scanner_version . ']';
     if (self::$debug) {
         self::DebugLog($error_msg, true);
     }
     // Load extra settings
     if (file_exists($this->work_dir . 'settings.php')) {
         $error_msg = '=> Extra settings loaded';
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         require_once $this->work_dir . 'settings.php';
         if (count($avp_settings)) {
             foreach ($avp_settings as $k => $v) {
                 $v_txt = $v;
                 if ($v === false) {
                     $v_txt = 'BOOL: false';
                 }
                 if ($v === true) {
                     $v_txt = 'BOOL: true';
                 }
                 $error_msg = 'Setting Value: ' . strtoupper($k) . ' = ' . $v_txt;
                 if (self::$debug) {
                     self::DebugLog($error_msg);
                 }
                 if (strtolower($v) == 'false') {
                     $v = false;
                 }
                 if (strtolower($v) == 'true') {
                     $v = true;
                 }
                 define(strtoupper($k), $v);
             }
         }
     }
     // Analyze of exclude folders
     if (file_exists($this->work_dir . 'exclude_folders.php')) {
         $error_msg = '=> Exclude folders file loaded';
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         require_once $this->work_dir . 'exclude_folders.php';
     }
     $tmp_result = set_time_limit(7200);
     $error_msg = 'Change Time limit: ' . self::$bool_list[intval($tmp_result)] . ' , Value: ' . ini_get('max_execution_time');
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     $error_msg = 'Current Memory limit: ' . ini_get('memory_limit');
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     $error_msg = 'OS info: ' . PHP_OS . ' (' . php_uname() . ')';
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     $error_msg = 'PHP ver: ' . PHP_VERSION;
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     unlink($this->tmp_dir . 'flag_terminated.tmp');
     unlink($this->tmp_dir . 'filelist.txt');
     /*if (!class_exists("HTTPClient"))
             {
                 include_once($this->work_dir.'HttpClient.class.php');
             }
     		
     		$HTTPClient = new HTTPClient();*/
     // Some Init data
     $membership = $this->membership;
     $scan_path = $this->scan_path;
     $access_key = $this->access_key;
     $domain = $this->domain;
     $email = $this->email;
     $session_report_key = $this->session_report_key;
     // Some logs
     $error_msg = 'Domain: ' . $domain;
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     $error_msg = 'Scan path: ' . $scan_path;
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     $error_msg = 'Session report key: ' . $session_report_key;
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     $error_msg = 'Report URL: https://www.siteguarding.com/antivirus/viewreport?report_id=' . $session_report_key;
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     $error_msg = 'TMP folder: ' . $this->tmp_dir;
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     if (trim($domain) == '') {
         $error_msg = 'Domain is empty. Please contact SiteGuarding.com support.';
         echo $error_msg;
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         exit;
     }
     if (trim($session_report_key) == '') {
         $error_msg = 'Session key is empty. Please contact SiteGuarding.com support.';
         echo $error_msg;
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         exit;
     }
     if (trim($scan_path) == '') {
         $error_msg = 'Scan Path is empty. Please contact SiteGuarding.com support.';
         echo $error_msg;
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         exit;
     }
     //session_start();
     $current_task = 0;
     $total_tasks = 0;
     $total_tasks += 1;
     // Analyze what way to use for packing
     $total_tasks += 1;
     // Pack files
     $total_tasks += 1;
     // Send files
     $total_tasks += 1;
     // Get report
     /**
      * Analyze what way to use for packing
      */
     $ssh_flag = false;
     if (function_exists('exec')) {
         // Pack files with ssh
         $ssh_flag = true;
     }
     if (defined('SETTINGS_ONLY_ZIP') && SETTINGS_ONLY_ZIP) {
         $ssh_flag = false;
     }
     // Update progress
     $current_task += 1;
     self::UpdateProgressValue($current_task, $total_tasks, 'Initialization.');
     if (self::$debug) {
         self::DebugLog('line');
     }
     $files_list = array();
     if (defined('DEBUG_FILELIST') && DEBUG_FILELIST) {
         self::DebugFile($this->work_dir, true);
     }
     $error_msg = 'Collecting info about the files [METHOD 2]';
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     $exclude_folders_real = array();
     if (count($exclude_folders)) {
         foreach ($exclude_folders as $k => $ex_folder) {
             $ex_folder = $scan_path . trim($ex_folder);
             $exclude_folders_real[$k] = trim(str_replace(DIRSEP . DIRSEP, DIRSEP, $ex_folder));
         }
     } else {
         $exclude_folders_real = array();
     }
     $this->exclude_folders_real = $exclude_folders_real;
     $error_msg = 'Excluded Folders: ' . count($exclude_folders_real);
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     $error_msg = print_r($exclude_folders_real, true);
     if (self::$debug && count($exclude_folders_real) > 0) {
         self::DebugLog($error_msg);
     }
     $dirList = array();
     $dirList[] = $scan_path;
     // Scan all dirs
     while (true) {
         $dirList = array_merge(self::ScanFolder(array_shift($dirList), $files_list), $dirList);
         if (count($dirList) < 1) {
             break;
         }
     }
     $error_msg = 'Save collected file_list';
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     $collected_filelist = $this->tmp_dir . 'filelist.txt';
     $fp = fopen($collected_filelist, 'w');
     $status = fwrite($fp, implode("\n", $files_list));
     fclose($fp);
     if ($status === false) {
         $error_msg = 'Cant save information about the collected files ' . $collected_filelist;
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         // Turn ZIP mode
         $ssh_flag = false;
     }
     $error_msg = 'Total files: ' . count($files_list);
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     if (self::$debug) {
         self::DebugLog('line');
     }
     if ($ssh_flag) {
         // SSH way
         $error_msg = 'Start - Pack with SSH';
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         $cmd = 'cd ' . $scan_path . '' . "\n" . 'tar -czf ' . $this->tmp_dir . 'pack.tar -T ' . $collected_filelist;
         $output = array();
         $result = exec($cmd, $output);
         if (file_exists($this->tmp_dir . 'pack.tar') === false) {
             $ssh_flag = false;
             $error_msg = 'Change pack method from SSH to PHP (ZipArchive)';
             if (self::$debug) {
                 self::DebugLog($error_msg);
             }
         }
     }
     if (!$ssh_flag) {
         // PHP way
         $error_msg = 'Start - Pack with ZipArchive';
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         $file_zip = $this->tmp_dir . 'pack.zip';
         if (file_exists($file_zip)) {
             unlink($file_zip);
         }
         $pack_dir = $scan_path;
         if (class_exists('ZipArchive')) {
             // open archive
             $zip = new ZipArchive();
             if ($zip->open($file_zip, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) === TRUE) {
                 foreach ($files_list as $file_name) {
                     $file_name = $this->scan_path . $file_name;
                     if (strstr(realpath($file_name), "stark") == FALSE) {
                         $short_key = str_replace($scan_path, "", $file_name);
                         $s = $zip->addFile(realpath($file_name), $short_key);
                         if (!$s) {
                             $error_msg = 'Couldnt add file: ' . $file_name;
                             if (self::$debug) {
                                 self::DebugLog($error_msg);
                             }
                         }
                     }
                 }
                 // close and save archive
                 $zip->close();
                 //$result['msg'][] = 'Archive created successfully';
             } else {
                 $error_msg = 'Error: Couldnt open ZIP archive.';
                 echo $error_msg;
                 self::UpdateProgressValue($current_task, $total_tasks, $error_msg);
                 if (self::$debug) {
                     self::DebugLog($error_msg);
                 }
                 exit;
             }
         } else {
             $error_msg = 'Error: ZipArchive class is not exist.';
             if (self::$debug) {
                 self::DebugLog($error_msg);
             }
         }
         $error_msg = 'ZipArchive method - finished';
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         // Check if zip file exists
         if (!file_exists($file_zip)) {
             $error_msg = 'Error: zip file is not exists. Use OwnZipClass';
             if (self::$debug) {
                 self::DebugLog($error_msg);
             }
             $error_msg = 'OwnZipClass method - started';
             if (self::$debug) {
                 self::DebugLog($error_msg);
             }
             $zip = new Zip();
             $zip->setZipFile($file_zip);
             foreach ($files_list as $file_name_short) {
                 $file_name = trim($this->scan_path . $file_name_short);
                 $handle = fopen($file_name, "r");
                 if (filesize($file_name) > 0) {
                     $zip->addFile(fread($handle, filesize($file_name)), $file_name_short, filectime($file_name), NULL, TRUE, Zip::getFileExtAttr($file_name));
                 }
                 fclose($handle);
             }
             $zip->finalize();
             $error_msg = 'OwnZipClass method - finished';
             if (self::$debug) {
                 self::DebugLog($error_msg);
             }
             $ssh_flag = false;
         }
     }
     // Update progress
     $current_task += 1;
     self::UpdateProgressValue($current_task, $total_tasks, 'Collecting information about the files.');
     /**
      * Send files to SG server
      */
     if ($ssh_flag) {
         $archive_filename = $this->tmp_dir . "pack.tar";
         $archive_format = 'tar';
     } else {
         $archive_filename = $this->tmp_dir . "pack.zip";
         $archive_format = 'zip';
     }
     $error_msg = 'Pack file: ' . $archive_filename;
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     // Check if pack file is exist
     if (file_exists($archive_filename) === false) {
         $error_msg = 'Error: Pack file is not exist. Probably not enough space on the server.';
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         echo $error_msg;
         exit;
     }
     $tar_size = filesize($archive_filename);
     $error_msg = 'Pack file is ' . round($tar_size / 1024 / 1024, 2) . 'Mb';
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     if (self::$debug) {
         self::DebugLog('line');
     }
     $error_msg = 'Start - Send Packed files to SG server';
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     $archive_file_url = "/" . str_replace($this->scan_path, "", $this->tmp_dir) . 'pack.' . $archive_format;
     $archive_file_url = str_replace("\\", "/", $archive_file_url);
     $error_msg = 'Pack URL: ' . $archive_file_url;
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     if ($tar_size < 32 * 1024 * 1024 || $membership == 'pro') {
         // Send file
         $post_data = base64_encode(json_encode(array('domain' => $domain, 'access_key' => $access_key, 'email' => $email, 'session_report_key' => $session_report_key, 'archive_format' => $archive_format, 'archive_file_url' => $archive_file_url)));
         $flag_CallBack = false;
         if (defined('CALLBACK_PACK_FILE') && CALLBACK_PACK_FILE) {
             // Callback option
             $flag_CallBack = true;
         } else {
             $result = self::UploadSingleFile($archive_filename, 'uploadfiles_ver2', $post_data);
             if ($result === false) {
                 $error_msg = 'Can not upload pack file for analyze';
                 if (self::$debug) {
                     self::DebugLog($error_msg);
                 }
                 $flag_CallBack = true;
             } else {
                 $error_msg = 'Pack file sent for analyze - OK';
                 if (self::$debug) {
                     self::DebugLog($error_msg);
                 }
                 $flag_CallBack = false;
             }
         }
         // CallBack method
         if ($flag_CallBack) {
             $error_msg = 'Start to use CallBack method';
             if (self::$debug) {
                 self::DebugLog($error_msg);
             }
             $post_data = base64_encode(json_encode(array('domain' => $domain, 'access_key' => $access_key, 'email' => $email, 'session_report_key' => $session_report_key, 'archive_format' => $archive_format, 'archive_file_url' => $archive_file_url)));
             $result = self::UploadSingleFile_Callback($post_data);
             if ($result === false) {
                 $error_msg = 'CallBack method - failed';
                 if (self::$debug) {
                     self::DebugLog($error_msg);
                 }
                 $error_msg = 'Can not upload pack file for analyze';
                 if (self::$debug) {
                     self::DebugLog($error_msg);
                 }
                 echo $error_msg;
                 exit;
             } else {
                 $error_msg = 'CallBack method - OK';
                 if (self::$debug) {
                     self::DebugLog($error_msg);
                 }
             }
         }
     } else {
         $error_msg = 'Pack file is too big (' . $error_msg . '), please contact SiteGuarding.com support or upgrade to PRO version.';
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         echo $error_msg;
         exit;
     }
     // Update progress
     $current_task += 1;
     self::UpdateProgressValue($current_task, $total_tasks, 'Analyzing the files. Preparing the report.');
     if (self::$debug) {
         self::DebugLog('line');
     }
     /**
      * Check and Get report from SG server
      */
     $error_msg = 'Start - Report generating';
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     for ($i = 1; $i <= 10 * 60; $i++) {
         sleep(5);
         /*$post_data = array(
         			'data'=> base64_encode(json_encode(array(
         				'domain' => $domain,
         				'access_key' => $access_key,
         				'session_report_key' => $session_report_key)))
         		);*/
         $post_data = base64_encode(json_encode(array('domain' => $domain, 'access_key' => $access_key, 'session_report_key' => $session_report_key)));
         //$result_json = $HTTPClient->post(self::$SITEGUARDING_SERVER.'?action=getreport_ver2', $post_data);
         $link = self::$SITEGUARDING_SERVER . '?action=getreport_ver2&data=' . $post_data;
         $result_json = file_get_contents($link);
         if ($result_json === false) {
             $error_msg = 'Report can not be generated. Please try again or contact support';
             if (self::$debug) {
                 self::DebugLog($error_msg);
             }
             echo $error_msg;
             exit;
         }
         $result_json = (array) json_decode($result_json, true);
         //if (self::$debug) self::DebugLog(print_r($result_json, true));
         if ($result_json['status'] == 'ready') {
             echo $result_json['text'];
             // Update progress
             $current_task += 1;
             self::UpdateProgressValue($current_task, $total_tasks, 'Done. Sending your report.');
             $error_msg = 'Done. Sending your report by email';
             if (self::$debug) {
                 self::DebugLog($error_msg);
             }
             // Send email to user with the report
             $email_result = self::SendEmail($email, $result_json['text']);
             if ($email_result) {
                 $error_msg = 'Report Sent - OK';
             } else {
                 $error_msg = 'Report Sent - FAILED';
             }
             if (self::$debug) {
                 self::DebugLog($error_msg);
             }
             exit;
         }
     }
     $error_msg = 'Finished [Report is not sent]' . "\n";
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
 }
Esempio n. 7
0
<?php
// Example. Zip all .html files in the current directory and send the file for Download.
// Also adds a static text "Hello World!" to the file Hello.txt
$fileDir = './';
ob_start(); // This is only to show that ob_start can be called, however the buffer must be empty when sending.

include_once("Zip.php");
$fileTime = date("D, d M Y H:i:s T");

$zip = new Zip();
// Archive comments don't really support utf-8. Some tools detect and read it though.
$zip->setComment("Example Zip file.\nАрхив Комментарий\nCreated on " . date('l jS \of F Y h:i:s A'));
// A bit of russian (I hope), to test UTF-8 file names.
$zip->addFile("Привет мир!", "Кириллица имя файла.txt");
$zip->addFile("Привет мир!", "Привет мир. С комментарий к файлу.txt", 0, "Кириллица файл комментарий");
$zip->addFile("Hello World!", "hello.txt");

@$handle = opendir($fileDir);
if ($handle) {
    /* This is the correct way to loop over the directory. */
    while (false !== ($file = readdir($handle))) {
        if (strpos($file, ".php") !== false) {
            $pathData = pathinfo($fileDir . $file);
            $fileName = $pathData['filename'];

            $zip->addFile(file_get_contents($fileDir . $file), $file, filectime($fileDir . $file), NULL, TRUE, Zip::getFileExtAttr($file));
        }
    }
}

// Add a directory, first recursively, then the same directory, but without recursion.
Esempio n. 8
0
        }
        $zip->finalize();
        // as we are not using getZipData or getZipFile, we need to call finalize ourselves.
        $zip->setZipFile($dir . $return_file);
        header("Location: " . $path . $return_file . "");
        break;
    case "download-archive":
        $user_ID = $_GET['id'];
        $dir = '' . SP_CDM_UPLOADS_DIR . '' . $user_ID . '/';
        $path = '' . SP_CDM_UPLOADS_DIR_URL . '' . $user_ID . '/';
        $return_file = "Account.zip";
        $zip = new Zip();
        $r = $wpdb->get_results("SELECT *  FROM " . $wpdb->prefix . "sp_cu   where uid = {$user_ID}  order by date desc", ARRAY_A);
        //@unlink($dir.$return_file);
        for ($i = 0; $i < count($r); $i++) {
            $zip->addFile(file_get_contents($dir . $r[$i]['file']), $r[$i]['file'], filectime($dir . $r[$i]['file']));
        }
        $zip->finalize();
        // as we are not using getZipData or getZipFile, we need to call finalize ourselves.
        $zip->setZipFile($dir . $return_file);
        header("Location: " . $path . $return_file . "");
        break;
    case "email-vendor":
        if (count($_POST['vendor_email']) == 0) {
            echo '<p style="color:red;font-weight:bold">' . __("Please select at least one file!", "sp-cdm") . '</p>';
        } else {
            $files = implode(",", $_POST['vendor_email']);
            $r = $wpdb->get_results("SELECT *  FROM " . $wpdb->prefix . "sp_cu  WHERE id IN (" . $files . ")", ARRAY_A);
            $message .= '

	' . $_POST['vendor-message'] . '<br><br>';
Esempio n. 9
0
 public function export()
 {
     $condition['project_id'] = Request::input('project_id');
     //todo
     $projectName = 'catphp';
     $fields = array('name', '_id', 'content');
     $rs = $this->mongo->find('document', $condition, array('sort' => array('sort' => 1)), $fields);
     $mk = new Parsedown();
     $docs = array();
     foreach ($rs as $row) {
         $doc = array();
         $doc['name'] = $row['name'];
         $doc['content'] = $mk->parse($row['content']);
         $docs[] = $doc;
     }
     $this->assign("docs", $docs);
     $content = $this->render('views/document.html', false);
     // $this->staticize('runtime/index.html');
     $download_config = CatConfig::getInstance(APP_PATH . '/config/download.conf.php');
     $download_zip_name = APP_PATH . '/runtime/' . $projectName . date('YmdHis') . '.zip';
     $zip = new Zip($download_zip_name, ZipArchive::OVERWRITE);
     $zip->addContent($content, 'index.html');
     foreach ($download_config->get('default') as $file) {
         $zip->addFile(APP_PATH . '/runtime/' . $file, $file);
     }
     $zip->close();
     $this->download($download_zip_name, $projectName . '.zip');
     // $this->zip($this->render('views/document.html'));
     // var_dump($download_config->get('default'));
 }
Esempio n. 10
0
 public static function databaseBackup()
 {
     $config = Ibos::app()->setting->toArray();
     $command = Ibos::app()->db->createCommand("SET SQL_QUOTE_SHOW_CREATE=0");
     $command->execute();
     $fileName = EnvUtil::getRequest("filename");
     $hasDangerFileName = preg_match("/(\\.)(exe|jsp|asp|aspx|cgi|fcgi|pl)(\\.|\$)/i", $fileName);
     if (!$fileName || (bool) $hasDangerFileName) {
         return array("type" => "error", "msg" => Ibos::lang("Database export filename invalid", "dashboard.default"));
     }
     $tablePrefix = $config["config"]["db"]["tableprefix"];
     $dbCharset = $config["config"]["db"]["charset"];
     $type = EnvUtil::getRequest("backuptype");
     if ($type == "all") {
         $tableList = self::getTablelist($tablePrefix);
         $tables = self::arrayKeysTo($tableList, "Name");
     } elseif ($type == "custom") {
         $tables = array();
         if (is_null(EnvUtil::getRequest("dbSubmit"))) {
             $tables = Setting::model()->fetchSettingValueByKey("custombackup");
             $tables = unserialize($tables);
         } else {
             $customTables = EnvUtil::getRequest("customtables");
             Setting::model()->updateSettingValueByKey("custombackup", is_null($customTables) ? "" : $customTables);
             $tables =& $customTables;
         }
         if (!is_array($tables) || empty($tables)) {
             return array("type" => "error", "msg" => Ibos::lang("Database export custom invalid", "dashboard.default"));
         }
     }
     $time = date("Y-m-d H:i:s", TIMESTAMP);
     $volume = intval(EnvUtil::getRequest("volume")) + 1;
     $method = EnvUtil::getRequest("method");
     $encode = base64_encode("{$config["timestamp"]}," . VERSION . ",{$type},{$method},{$volume},{$tablePrefix},{$dbCharset}");
     $idString = "# Identify: " . $encode . "\n";
     $sqlCharset = EnvUtil::getRequest("sqlcharset");
     $sqlCompat = EnvUtil::getRequest("sqlcompat");
     $dbVersion = Ibos::app()->db->getServerVersion();
     $useZip = EnvUtil::getRequest("usezip");
     $useHex = EnvUtil::getRequest("usehex");
     $extendIns = EnvUtil::getRequest("extendins");
     $sizeLimit = EnvUtil::getRequest("sizelimit");
     $dumpCharset = !empty($sqlCharset) ? $sqlCharset : str_replace("-", "", CHARSET);
     $isNewSqlVersion = "4.1" < $dbVersion && (!is_null($sqlCompat) || $sqlCompat == "MYSQL41");
     $setNames = !empty($sqlCharset) && $isNewSqlVersion ? "SET NAMES '{$dumpCharset}';\n\n" : "";
     if ("4.1" < $dbVersion) {
         if ($sqlCharset) {
             $command->setText("SET NAMES `{$sqlCharset}`")->execute();
         }
         if ($sqlCompat == "MYSQL40") {
             $command->setText("SET SQL_MODE='MYSQL40'")->execute();
         } elseif ($sqlCompat == "MYSQL41") {
             $command->setText("SET SQL_MODE=''")->execute();
         }
     }
     if (!is_dir(self::BACKUP_DIR)) {
         FileUtil::makeDir(self::BACKUP_DIR, 511);
     }
     $backupFileName = self::BACKUP_DIR . "/" . str_replace(array("/", "\\", ".", "'"), "", $fileName);
     if ($method == "multivol") {
         $sqlDump = "";
         $tableId = intval(EnvUtil::getRequest("tableid"));
         $startFrom = intval(EnvUtil::getRequest("startfrom"));
         if (!$tableId && $volume == 1) {
             foreach ($tables as $table) {
                 $sqlDump .= self::getSqlDumpTableStruct($table, $sqlCompat, $sqlCharset, $dumpCharset);
             }
         }
         for (self::$complete = true; strlen($sqlDump) + 500 < $sizeLimit * 1000; $tableId++) {
             $sqlDump .= self::sqlDumpTable($tables[$tableId], $extendIns, $sizeLimit, $useHex, $startFrom, strlen($sqlDump));
             if (self::$complete) {
                 $startFrom = 0;
             }
         }
         $dumpFile = $backupFileName . "-%s.sql";
         !self::$complete && $tableId--;
         if (trim($sqlDump)) {
             $sqlDump = "{$idString}# <?php exit();?>\n# IBOS Multi-Volume Data Dump Vol.{$volume}\n# Version: IBOS {$config["version"]}\n# Time: {$time}\n# Type: {$type}\n# Table Prefix: {$tablePrefix}\n#\n# IBOS Home: http://www.ibos.com.cn\n# Please visit our website for newest infomation about IBOS\n# --------------------------------------------------------\n\n\n{$setNames}" . $sqlDump;
             $dumpFileName = sprintf($dumpFile, $volume);
             @($fp = fopen($dumpFileName, "wb"));
             @flock($fp, 2);
             if (@(!fwrite($fp, $sqlDump))) {
                 @fclose($fp);
                 return array("type" => "error", "msg" => Ibos::lang("Database export file invalid", "dashboard.default"), "url" => "");
             } else {
                 fclose($fp);
                 if ($useZip == 2) {
                     $fp = fopen($dumpFileName, "r");
                     $content = @fread($fp, filesize($dumpFileName));
                     fclose($fp);
                     $zip = new Zip();
                     $zip->addFile($content, basename($dumpFileName));
                     $fp = fopen(sprintf($backupFileName . "-%s.zip", $volume), "w");
                     if (@fwrite($fp, $zip->file()) !== false) {
                         @unlink($dumpFileName);
                     }
                     fclose($fp);
                 }
                 unset($sqlDump);
                 unset($zip);
                 unset($content);
                 $param = array("setup" => 1, "backuptype" => rawurlencode($type), "filename" => rawurlencode($fileName), "method" => "multivol", "sizelimit" => rawurlencode($sizeLimit), "volume" => rawurlencode($volume), "tableid" => rawurlencode($tableId), "startfrom" => rawurlencode(self::$startRow), "extendins" => rawurlencode($fileName), "sqlcharset" => rawurlencode($sqlCharset), "sqlcompat" => rawurlencode($sqlCompat), "usehex" => $useHex, "usezip" => $useZip);
                 $url = Ibos::app()->urlManager->createUrl("dashboard/database/backup", $param);
                 return array("type" => "success", "msg" => Ibos::lang("Database export multivol redirect", "dashboard.default", array("volume" => $volume)), "url" => $url);
             }
         } else {
             $volume--;
             if ($useZip == 1) {
                 $zip = new Zip();
                 $zipFileName = $backupFileName . ".zip";
                 $unlinks = array();
                 for ($i = 1; $i <= $volume; $i++) {
                     $filename = sprintf($dumpFile, $i);
                     $fp = fopen($filename, "r");
                     $content = @fread($fp, filesize($filename));
                     fclose($fp);
                     $zip->addFile($content, basename($filename));
                     $unlinks[] = $filename;
                 }
                 $fp = fopen($zipFileName, "w");
                 if (@fwrite($fp, $zip->file()) !== false) {
                     foreach ($unlinks as $link) {
                         @unlink($link);
                     }
                 } else {
                     return array("type" => "success", "msg" => Ibos::lang("Database export multivol succeed", "dashboard.default", array("volume" => $volume)), "url" => Ibos::app()->urlManager->createUrl("dashboard/database/restore"));
                 }
                 unset($sqlDump);
                 unset($zip);
                 unset($content);
                 fclose($fp);
                 $filename = $zipFileName;
                 return array("type" => "success", "msg" => Ibos::lang("Database export zip succeed", "dashboard.default"), "param" => array("autoJump" => false));
             } else {
                 return array("type" => "success", "msg" => Ibos::lang("Database export multivol succeed", "dashboard.default", array("volume" => $volume)), "url" => Ibos::app()->urlManager->createUrl("dashboard/database/restore"));
             }
         }
     } else {
         $tablesstr = "";
         foreach ($tables as $table) {
             $tablesstr .= "\"" . $table . "\" ";
         }
         $db = $config["config"]["db"];
         $query = $command->setText("SHOW VARIABLES LIKE 'basedir'")->queryRow();
         $mysqlBase = $query["Value"];
         $dumpFile = addslashes(dirname(dirname(__FILE__))) . "/" . $backupFileName . ".sql";
         @unlink($dumpFile);
         $mysqlBin = $mysqlBase == "/" ? "" : addslashes($mysqlBase) . "bin/";
         shell_exec($mysqlBin . "mysqldump --force --quick " . ("4.1" < $dbVersion ? "--skip-opt --create-options" : "-all") . " --add-drop-table" . (EnvUtil::getRequest("extendins") == 1 ? " --extended-insert" : "") . "" . ("4.1" < $dbVersion && $sqlCompat == "MYSQL40" ? " --compatible=mysql40" : "") . " --host=\"" . $db["host"] . ($db["port"] ? is_numeric($db["port"]) ? " --port=" . $db["port"] : " --socket=\"" . $db["port"] . "\"" : "") . "\" --user=\"" . $db["username"] . "\" --password=\"" . $db["password"] . "\" \"" . $db["dbname"] . "\" " . $tablesstr . " > " . $dumpFile);
         if (@file_exists($dumpFile)) {
             if ($useZip) {
                 $zip = new Zip();
                 $zipfilename = $backupFileName . ".zip";
                 $fp = fopen($dumpFile, "r");
                 $content = @fread($fp, filesize($dumpFile));
                 fclose($fp);
                 $zip->addFile($idString . "# <?php exit();?>\n " . $setNames . "\n #" . $content, basename($dumpFile));
                 $fp = fopen($zipfilename, "w");
                 @fwrite($fp, $zip->file());
                 fclose($fp);
                 @unlink($dumpFile);
                 $filename = $backupFileName . ".zip";
                 unset($sqlDump);
                 unset($zip);
                 unset($content);
                 return array("type" => "success", "msg" => Ibos::lang("Database export zip succeed", "dashboard.default"), "url" => Ibos::app()->urlManager->createUrl("dashboard/database/restore"));
             } else {
                 if (@is_writeable($dumpFile)) {
                     $fp = fopen($dumpFile, "rb+");
                     @fwrite($fp, $idString . "# <?php exit();?>\n " . $setNames . "\n #");
                     fclose($fp);
                 }
                 $filename = $backupFileName . ".sql";
                 return array("type" => "success", "msg" => Ibos::lang("Database export succeed", "dashboard.default"), "param" => Ibos::app()->urlManager->createUrl("dashboard/database/restore"));
             }
         } else {
             return array("type" => "error", "msg" => Ibos::lang("Database shell fail", "dashboard.default"));
         }
     }
 }
Esempio n. 11
0
<?php

// Example. Zip all .html files in the current directory and send the file for Download.
// Also adds a static text "Hello World!" to the file Hello.txt
$fileDir = './';
ob_start();
// This is only to show that ob_start can be called, however the buffer must be empty when sending.
include_once "Zip.php";
$fileTime = date("D, d M Y H:i:s T");
$zip = new Zip();
//$zip->setExtraField(FALSE);
// The comment can only be ASCII, the Chinese characters fail here, and the Zip spec have no flags for handling that.
$zip->setComment("Example 你好 Zip file.\nCreated on " . date('l jS \\of F Y h:i:s A'));
$zip->addFile("你好 1", "hello 1.txt");
$zip->addFile("你好 1", "hello 2.txt", 0, "Hello 1");
$zip->addFile("你好 1", "hello 3.txt", 0, "Hello 你好");
$zip->addFile("你好 2", "你好 1.txt");
$zip->addFile("你好 2", "你好 2.txt", 0, "Hello 1");
$zip->addFile("你好 2", "你好 3.txt", 0, "Hello 你好");
$zip->addFile("你好 3", "你好/hello.txt");
$zip->addFile("你好 4", "你好/你好.txt");
$zip->sendZip("Zip.Test6.zip");
Esempio n. 12
0
include_once("Zip.php");
$fileTime = date("D, d M Y H:i:s T");

// Set a temp file to use, instead of the default system temp file directory. 
// The temp file is used if the generated Zip file is becoming too large to hold in memory.
//Zip::$temp = "./tempFile";

// Setting this to a function to create the temp files requires PHP 5.3 or newer:
//Zip::$temp = function() { return tempnam(sys_get_temp_dir(), 'Zip');};
Zip::$temp = function() { return "./tempFile_" . rand(100000, 999999);};

$zip = new Zip();
// Archive comments don't really support utf-8. Some tools detect and read it though.
$zip->setComment("Example Zip file.\nCreated on " . date('l jS \of F Y h:i:s A'));
// A bit of russian (I hope), to test UTF-8 file names.
$zip->addFile("Hello World!", "hello.txt");

@$handle = opendir($fileDir);
if ($handle) {
    /* This is the correct way to loop over the directory. */
    while (false !== ($file = readdir($handle))) {
        if (strpos($file, ".php") !== false) {
            $pathData = pathinfo($fileDir . $file);
            $fileName = $pathData['filename'];

            $zip->addFile(file_get_contents($fileDir . $file), $file, filectime($fileDir . $file), NULL, TRUE, Zip::getFileExtAttr($file));
        }
    }
}

// Uses my Lipsum generator from https://github.com/Grandt/PHPLipsumGenerator
Esempio n. 13
0
 public function preprocess_util($content, $file)
 {
     if (substr($file, -5) == '.scss') {
         $config = application::get_instance()->config->util;
         $path = PATH_ROOT . '/img';
         $d = array(basename($file) => md5(file_get_contents($file)));
         if (!function_exists('recursive_scss')) {
             function recursive_scss($path, $dir, &$d)
             {
                 $cur = $path . ($dir ? '/' . $dir : '');
                 foreach (scandir($cur) as $fn) {
                     if ($fn == '.' || $fn == '..') {
                         continue;
                     }
                     if (is_dir($cur . '/' . $fn) && !in_array($fn, array('font'))) {
                         recursive_scss($path, $dir . ($dir ? '/' : '') . $fn, $d);
                     } else {
                         if (preg_match('/\\.(' . ($dir == 'sprites' ? 'png|' : '') . 'scss)/i', $fn)) {
                             $d[$dir . ($dir ? '/' : '') . $fn] = md5(file_get_contents($cur . '/' . $fn));
                         }
                     }
                 }
             }
         }
         recursive_scss($path, '', $d);
         if ($d) {
             $res = file_get_contents($config->host . '/x/scss/ch/get/host/' . $_SERVER['HTTP_HOST'] . '/ip/' . $_SERVER['REMOTE_ADDR'] . '/file/' . basename($file));
             if ($res) {
                 if (!class_exists('Zip')) {
                     require PATH_ROOT . '/' . DIR_LIBRARY . '/lib/Zip.php';
                 }
                 $zip = new Zip();
                 $res = json_decode($res, true);
                 foreach ($d as $k => $v) {
                     if ($v != @$res[$k]) {
                         $zip->addFile(file_get_contents($path . '/' . $k), $k);
                     }
                 }
                 $data = urlencode($zip->getZipData());
                 $context = stream_context_create(array('http' => array('method' => 'POST', 'header' => 'Content-Type: multipart/form-data' . "\r\n" . 'Content-Length: ' . strlen($data) . "\r\n", 'content' => $data)));
                 $res = file_get_contents($config->host . '/x/scss/ch/set/host/' . $_SERVER['HTTP_HOST'] . '/ip/' . $_SERVER['REMOTE_ADDR'] . '/file/' . basename($file), false, $context);
                 if ($res) {
                     $res = json_decode($res, true);
                     file_put_contents(PATH_ROOT . '/' . DIR_CACHE . '/css/temp.zip', urldecode($res['data']));
                     require PATH_ROOT . '/' . DIR_LIBRARY . '/lib/Unzip.php';
                     $zip = new Unzip();
                     $zip->extract(PATH_ROOT . '/' . DIR_CACHE . '/css/temp.zip', PATH_ROOT . '/' . DIR_CACHE . '/css');
                     unlink(PATH_ROOT . '/' . DIR_CACHE . '/css/temp.zip');
                     $nfn = str_replace('.scss', '.css', basename($file));
                     $content = @file_get_contents(PATH_ROOT . '/' . DIR_CACHE . '/css/' . $nfn);
                     unlink(PATH_ROOT . '/' . DIR_CACHE . '/css/' . $nfn);
                 }
             }
         }
     }
     return $content;
 }
Esempio n. 14
0
 function download_archive()
 {
     global $wpdb, $current_user;
     if (!is_user_logged_in()) {
         exit;
     }
     $user_ID = $_GET['id'];
     $dir = '' . SP_CDM_UPLOADS_DIR . '' . $user_ID . '/';
     $path = '' . SP_CDM_UPLOADS_DIR_URL . '' . $user_ID . '/';
     $return_file = "Account.zip";
     $zip = new Zip();
     $r = $wpdb->get_results($wpdb->prepare("SELECT *  FROM " . $wpdb->prefix . "sp_cu   where uid = %d  order by date desc", $user_ID), ARRAY_A);
     //@unlink($dir.$return_file);
     for ($i = 0; $i < count($r); $i++) {
         $zip->addFile(file_get_contents($dir . $r[$i]['file']), $r[$i]['file'], filectime($dir . $r[$i]['file']));
     }
     $zip->finalize();
     // as we are not using getZipData or getZipFile, we need to call finalize ourselves.
     $zip->setZipFile($dir . $return_file);
     header("Location: " . $path . $return_file . "");
 }
Esempio n. 15
0
function sp_Admin_uploadFile($files, $user_ID)
{
    global $wpdb;
    $dir = '' . SP_CDM_UPLOADS_DIR . '' . $user_ID . '/';
    $count = sp_array_remove_empty($files['dlg-upload-file']['name']);
    if ($history == 1) {
        $dir = '' . SP_CDM_UPLOADS_DIR . '' . $user_ID . '/';
        $filename = '' . sp_client_upload_filename($user_ID) . '' . $files['dlg-upload-file']['name'][0] . '';
        $filename = strtolower($filename);
        $filename = sanitize_file_name($filename);
        $filename = remove_accents($filename);
        $target_path = $dir . $filename;
        move_uploaded_file($files['dlg-upload-file']['tmp_name'][0], $target_path);
        $ext = preg_replace('/^.*\\./', '', $filename);
        if (get_option('sp_cu_user_projects_thumbs_pdf') == 1 && class_exists('imagick')) {
            $info = new Imagick();
            $formats = $info->queryFormats();
            if (in_array(strtoupper($ext), $formats)) {
                cdm_thumbPdf($target_path);
            }
        }
        return $filename;
    } else {
        if (count($count) > 1) {
            //echo $count;
            //	echo '<pre>';
            //print_r($files);exit;
            //echo '</pre>';
            $fileTime = date("D, d M Y H:i:s T");
            $zip = new Zip();
            for ($i = 0; $i < count($files['dlg-upload-file']['name']); $i++) {
                if ($files['dlg-upload-file']['error'][$i] == 0) {
                    $filename = '' . sp_client_upload_filename($user_ID) . '' . $files['dlg-upload-file']['name'][$i] . '';
                    $filename = strtolower($filename);
                    $filename = sanitize_file_name($filename);
                    $filename = remove_accents($filename);
                    $target_path = $dir . $filename;
                    move_uploaded_file($files['dlg-upload-file']['tmp_name'][$i], $target_path);
                    $zip->addFile(file_get_contents($target_path), $filename, filectime($target_path));
                }
            }
            $zip->finalize();
            // as we are not using getZipData or getZipFile, we need to call finalize ourselves.
            $return_file = "" . rand(100000, 100000000000) . "_Archive.zip";
            $zip->setZipFile($dir . $return_file);
            return $return_file;
        } else {
            $dir = '' . SP_CDM_UPLOADS_DIR . '' . $user_ID . '/';
            $filename = '' . sp_client_upload_filename($user_ID) . '' . $files['dlg-upload-file']['name'][1] . '';
            $filename = strtolower($filename);
            $filename = sanitize_file_name($filename);
            $filename = remove_accents($filename);
            $target_path = $dir . $filename;
            move_uploaded_file($files['dlg-upload-file']['tmp_name'][1], $target_path);
            $ext = preg_replace('/^.*\\./', '', $filename);
            if (get_option('sp_cu_user_projects_thumbs_pdf') == 1 && class_exists('imagick')) {
                $info = new Imagick();
                $formats = $info->queryFormats();
                if (in_array(strtoupper($ext), $formats)) {
                    cdm_thumbPdf($target_path);
                }
            }
            return $filename;
        }
    }
}
Esempio n. 16
0
 function backup()
 {
     $settings = Plugin::getAllSettings('backup_restore');
     // All of the tablesnames that belong to Fresh CMS core.
     $tablenames = array('layout', 'page', 'page_part', 'page_tag', 'permission', 'plugin_settings', 'setting', 'snippet', 'tag', 'user', 'user_permission');
     // All fields that should be wrapped as CDATA
     $cdata_fields = array('content', 'content_html');
     // Setup XML for backup
     $xmltext = '<?xml version="1.0" encoding="UTF-8"?><freshcms></freshcms>';
     $xmlobj = new SimpleXMLExtended($xmltext);
     $xmlobj->addAttribute('version', CMS_VERSION);
     // Retrieve all database information for placement in XML backup
     global $__CMS_CONN__;
     Record::connection($__CMS_CONN__);
     $lasttable = '';
     // Generate XML file entry for each table
     foreach ($tablenames as $tablename) {
         $table = Record::query('SELECT * FROM ' . TABLE_PREFIX . $tablename);
         while ($entry = $table->fetchObject()) {
             if ($lasttable !== $tablename) {
                 $lasttable = $tablename;
                 $child = $xmlobj->addChild($tablename . 's');
             }
             $subchild = $child->addChild($tablename);
             while (list($key, $value) = each($entry)) {
                 if ($key === 'password' && $settings['pwd'] === '0') {
                     $value = '';
                 }
                 if (in_array($key, $cdata_fields, true)) {
                     $subchild->addCData($key, $value);
                 } else {
                     $subchild->addChild($key, $value);
                 }
             }
         }
     }
     // Create the XML file
     $file = $xmlobj->asXML();
     $filename = 'freshcms-backup-' . date($settings['stamp']);
     // Offer a plain XML file or a zip file for download
     if ($settings['zip'] == '1') {
         // Create a note file
         $note = "---[ NOTES for {$filename}.xml ]---\n\n";
         $note .= "This backup was created for a specific Fresh CMS version, please only restore it\n";
         $note .= "on the same version.\n\n";
         $note .= "When restoring a backup, upload the UNzipped XML file, not this zip file.\n\n";
         $note .= 'Created on ' . date('Y-m-d') . ' at ' . date('H:i:s') . ' GTM ' . date('O') . ".\n";
         $note .= 'Created with BackupRestore plugin version ' . BR_VERSION . "\n";
         $note .= 'Created for Fresh CMS version ' . CMS_VERSION . "\n\n";
         $note .= '---[ END NOTES ]---';
         use_helper('Zip');
         $zip = new Zip();
         $zip->clear();
         $zip->addFile($note, 'readme.txt');
         $zip->addFile($file, $filename . '.xml');
         $zip->download($filename . '.zip');
     } else {
         header('Pragma: public');
         header('Expires: 0');
         header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
         header('Cache-Control: private', false);
         header('Content-Type: text/xml; charset=UTF-8');
         header('Content-Disposition: attachment; filename=' . $filename . '.xml;');
         header('Content-Transfer-Encoding: 8bit');
         header('Content-Length: ' . strlen($file));
         echo $file;
     }
 }
Esempio n. 17
0
            Answer($res);
        }
    }
    if (isset($_GET['qgCms_page_files_as_zip'])) {
        $P = Page($_GET['qgCms_page_files_as_zip']);
        if (!$P->access() > 1) {
            exit('no access');
        }
        if (!$P->Files()) {
            exit('no files');
        }
        $Zip = new Zip();
        $tmpfname = appPATH . 'cache/tmp/pri/' . randString() . '.zip';
        $Zip->open($tmpfname, Zip::CREATE);
        foreach ($P->Files() as $File) {
            $Zip->addFile($File->path, $File->name());
        }
        $Zip->close();
        $filename = isset($_GET['filename']) ? $_GET['filename'] : 'files_' . $P . '.zip';
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename=' . $filename);
        header('Content-Length: ' . filesize($tmpfname));
        readfile($tmpfname);
        unlink($tmpfname);
        exit;
    }
});
qg::on('dbFile::access', function ($e) {
    if ($e['access']) {
        return;
    }
Esempio n. 18
0
 public function preprocessUtil($content, $file)
 {
     if (substr($file, -5) == '.scss') {
         $config = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getOptions();
         $cp = defined('CACHE_DIR') ? CACHE_DIR : 'pc';
         $host = @$config['util']['host'];
         $path = PUBLIC_PATH . '/img';
         $d = array(basename($file) => md5(file_get_contents($file)));
         if (!function_exists('recursive_scss')) {
             function recursive_scss($path, $dir, &$d)
             {
                 $cur = $path . ($dir ? '/' . $dir : '');
                 foreach (scandir($cur) as $fn) {
                     if ($fn == '.' || $fn == '..') {
                         continue;
                     }
                     if (is_dir($cur . '/' . $fn) && !in_array($fn, array('font'))) {
                         recursive_scss($path, $dir . ($dir ? '/' : '') . $fn, $d);
                     } else {
                         if (preg_match('/\\.(' . ($dir == 'sprites' ? 'png|' : '') . 'scss)/i', $fn)) {
                             $d[$dir . ($dir ? '/' : '') . $fn] = md5(file_get_contents($cur . '/' . $fn));
                         }
                     }
                 }
             }
         }
         recursive_scss($path, '', $d);
         if ($d) {
             $res = file_get_contents($host . '/x/scss/ch/get/host/' . $_SERVER['HTTP_HOST'] . '/file/' . basename($file));
             if ($res) {
                 if (!class_exists('Zip')) {
                     require 'Zkernel/Other/Lib/ekernel/lib/Zip.php';
                 }
                 $zip = new Zip();
                 $res = json_decode($res, true);
                 $cnt = 0;
                 foreach ($d as $k => $v) {
                     if ($v != @$res[$k]) {
                         $zip->addFile(file_get_contents($path . '/' . $k), $k);
                         $cnt++;
                     }
                 }
                 if ($cnt) {
                     $data = urlencode($zip->getZipData());
                     $context = stream_context_create(array('http' => array('method' => 'POST', 'header' => 'Content-Type: multipart/form-data' . "\r\n" . 'Content-Length: ' . strlen($data) . "\r\n", 'content' => $data)));
                     $res = file_get_contents($host . '/x/scss/ch/set/host/' . $_SERVER['HTTP_HOST'] . '/file/' . basename($file), false, $context);
                     if ($res) {
                         $res = json_decode($res, true);
                         file_put_contents(PUBLIC_PATH . '/' . $cp . '/css/temp.zip', urldecode($res['data']));
                         require 'Zkernel/Other/Lib/ekernel/lib/Unzip.php';
                         $zip = new Unzip();
                         $zip->extract(PUBLIC_PATH . '/' . $cp . '/css/temp.zip', PUBLIC_PATH . '/' . $cp . '/css');
                         unlink(PUBLIC_PATH . '/' . $cp . '/css/temp.zip');
                         $nfn = str_replace('.scss', '.css', basename($file));
                         $content = @file_get_contents(PUBLIC_PATH . '/' . $cp . '/css/' . $nfn);
                         unlink(PUBLIC_PATH . '/' . $cp . '/css/' . $nfn);
                     }
                 }
             }
         }
     }
     return $content;
 }
Esempio n. 19
0
 /**
  * @return array
  */
 public function AjaxMessageAttachmentsZip()
 {
     $aHashes = $this->getParamValue('Hashes', null);
     if (!is_array($aHashes) || 0 === count($aHashes) || !class_exists('ZipArchive')) {
         throw new \ProjectCore\Exceptions\ClientException(\ProjectCore\Notifications::InvalidInputParameter);
     }
     $mResult = false;
     $oAccount = $this->getAccountFromParam();
     $self = $this;
     $aAdd = array();
     foreach ($aHashes as $sHash) {
         $this->rawCallback($sHash, function ($oAccount, $sContentType, $sFileName, $rResource) use($self, $sHash, &$aAdd) {
             $sHash = md5($sHash . rand(1000, 9999));
             if ($self->ApiFileCache()->putFile($oAccount, $sHash, $rResource)) {
                 $sFullFilePath = $self->ApiFileCache()->generateFullFilePath($oAccount, $sHash);
                 $aAdd[] = array($sFullFilePath, $sFileName, $sContentType);
             }
         }, false, $oAccount);
     }
     if (0 < count($aAdd)) {
         include_once PSEVEN_APP_ROOT_PATH . 'libraries/other/Zip.php';
         $oZip = new \Zip();
         $sZipHash = md5(implode(',', $aHashes) . rand(1000, 9999));
         foreach ($aAdd as $aItem) {
             $oZip->addFile(fopen($aItem[0], 'r'), $aItem[1]);
         }
         $self->ApiFileCache()->putFile($oAccount, $sZipHash, $oZip->getZipFile());
         $mResult = \CApi::EncodeKeyValues(array('TempFile' => true, 'AccountID' => $oAccount->IdAccount, 'Name' => 'attachments.zip', 'TempName' => $sZipHash));
     }
     return $this->DefaultResponse($oAccount, __FUNCTION__, $mResult);
 }
Esempio n. 20
0
<?php
// Example. Zip all .html files in the current directory and send the file for Download.
$fileDir = './';

include_once("Zip.php");
$fileTime = date("D, d M Y H:i:s T");

$zip = new Zip();
$zip->setComment("Example Zip file.\nCreated on " . date('l jS \of F Y h:i:s A'));
$zip->addFile("Hello World!", "hello.txt");

if ($handle = opendir($fileDir)) {
	/* This is the correct way to loop over the directory. */
	while (false !== ($file = readdir($handle))) {
		if (strpos($file, ".html") !== false) {
			$pathData = pathinfo($fileDir . $file);
			$fileName = $pathData['filename'];

			$zip->addFile(file_get_contents($fileDir . $file), $file, filectime($fileDir . $file));
		}
	}
}

$zip->sendZip("ZipExample1a.zip");
?>
 function export_and_download_layouts()
 {
     if (isset($_POST['export_and_download'])) {
         $nonce = $_POST["wp_nonce_export_layouts"];
         if (WPDD_Utils::user_not_admin()) {
             die(__("You don't have permission to perform this action!", 'ddl-layouts'));
         }
         if (wp_verify_nonce($nonce, 'wp_nonce_export_layouts')) {
             $results = $this->export_for_download();
             $sitename = sanitize_key(get_bloginfo('name'));
             if (!empty($sitename)) {
                 $sitename .= '.';
             }
             require_once WPDDL_TOOLSET_COMMON_ABSPATH . '/Zip.php';
             if (class_exists('Zip')) {
                 $dirname = $sitename . 'dd-layouts.' . date('Y-m-d');
                 $zipName = $dirname . '.zip';
                 $zip = new Zip();
                 $zip->addDirectory($dirname);
                 foreach ($results as $file_data) {
                     $zip->addFile($file_data['file_data'], $dirname . '/' . $file_data['file_name']);
                 }
                 $zip->sendZip($zipName);
             }
         }
         die;
     }
 }
Esempio n. 22
0
 public function preprocess_scss($content, $file, $options = array())
 {
     $opt = $this->_scss;
     if ($options && !is_array($options)) {
         $options = array();
     }
     if ($options) {
         $this->_check_options($options);
         $opt = array_merge($opt, $options);
     }
     // process scss file content
     $res = $this->_preprocess_scss_content($content, $file);
     // find all images from images_dir
     $images = array();
     $images_dir = trim(dirname($file) . '/' . rtrim($opt['images_dir'], './'), '/');
     $this->_preprocess_scss_image($images_dir, '', $images);
     // zip scss file and all images
     $zip = new Zip();
     $zip->addFile($res, 'sass/style.scss');
     if ($images) {
         foreach ($images as $el) {
             $zip->addFile($this->_read_file(ltrim($images_dir . '/', '/') . $el), 'images/' . $el);
         }
     }
     // preparing options for remote call
     $opt['file'] = basename($file);
     $opt['images_dir'] = '__cache_dir__';
     // cleaning gen images cache
     $this->_cache_purge('images/' . $opt['file']);
     // call api
     $result = $this->scss($zip->getZipData(), $opt);
     $content = $result['content'];
     // unzip images and replace their names in content
     if ($result['images']) {
         $dir = $this->_path_root . '/' . $this->_cache_dir . '/images/' . $opt['file'];
         $this->_cache_save('images/' . $opt['file'], 'temp', $result['images'], 'zip');
         try {
             $zip = new Unzip();
             $zip->extract($dir . '/temp.zip', $dir);
             $zip->close();
             unlink($dir . '/temp.zip');
         } catch (\Exception $ex) {
         }
         $content = str_replace('__cache_dir__', '/' . $this->_cache_dir . '/images/' . $opt['file'], $content);
     }
     return $content;
 }