function upload($pdo)
{
    $error = true;
    if (validRequest()) {
        if (isset($_GET['token'], $_SESSION['token']) && $_GET['token'] == $_SESSION['token']) {
            if (isset($_FILES["file"]) && isset($_POST['title']) && !empty($_POST['title'])) {
                $upload_dir = "files/";
                $target_file = $upload_dir . basename($_FILES["file"]["name"]);
                $fileType = pathinfo($target_file, PATHINFO_EXTENSION);
                $file_name = rand(1, 9) . rand(1, 9) . rand(1, 9) . rand(1, 9) . rand(1, 9) . rand(1, 9);
                $target_file = $upload_dir . $file_name . '.' . $fileType;
                if ($_FILES["file"]["size"] <= 4000000) {
                    if (in_array($fileType, array('pdf', 'jpg', 'gif', 'png', 'bmp', 'doc', 'docx', 'ppt', 'mp3', 'mp4', 'xls', 'xlsx', 'zip', 'rar', 'gz', 'txt'))) {
                        if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
                            $file = array('name' => $target_file, 'size' => formatbytes($target_file, "KB"), 'type' => strtoupper($fileType));
                            $sql = "insert into cmsfiles(`uId`,`file`,`title`,`size`,`type`) value(:uId,:file,:title,:size,:type)";
                            $stmt = $pdo->prepare($sql);
                            $stmt->bindValue(':uId', $_SESSION['userId'], PDO::PARAM_INT);
                            $stmt->bindValue(':file', $file['name'], PDO::PARAM_STR);
                            $stmt->bindValue(':size', $file['size'], PDO::PARAM_STR);
                            $stmt->bindValue(':type', $file['type'], PDO::PARAM_STR);
                            $stmt->bindValue(':title', filter_var($_POST['title'], FILTER_SANITIZE_STRING), PDO::PARAM_STR);
                            $stmt->execute();
                            $stmt = $pdo->query("SELECT LAST_INSERT_ID()");
                            $last_id = $stmt->fetchColumn(0);
                            $error = false;
                        }
                    }
                }
            }
        }
    }
    if ($error) {
        _log('error_upload', 'Avoid incorrect information', 'user id=' . isset($_SESSION['userId']) ? $_SESSION['userId'] : 'null');
        echo 'Error';
        exit;
    } else {
        _log('info_upload', '1 file(s) successfully added to the cms file manager');
        if (ajax()) {
            echo json_encode(array("error" => "0", "title" => $_POST['title'], "size" => $file['size'], "type" => $file['type'], "name" => $file['name'], "id" => $last_id));
            exit;
        } else {
            redirect(BASE_PATH . '/filemanage/', 1);
        }
    }
}
 function upload($pdo)
 {
     $error = true;
     if (validRequest()) {
         if (isset($_GET['token'], $_SESSION['token']) && $_GET['token'] == $_SESSION['token']) {
             if (isset($_FILES["file"]) && isset($_POST['title']) && !empty($_POST['title'])) {
                 $upload_dir = "assets/d/" . $_SESSION['username'] . "/";
                 $target_file = $upload_dir . basename($_FILES["file"]["name"]);
                 $fileType = pathinfo($target_file, PATHINFO_EXTENSION);
                 $file_name = rand(1, 9) . rand(1, 9) . rand(1, 9) . rand(1, 9) . rand(1, 9) . rand(1, 9);
                 $target_file = $upload_dir . $file_name . ".pdf";
                 if ($_FILES["file"]["size"] <= 4000000) {
                     if ($fileType == "pdf") {
                         if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
                             $file = array('name' => $_SESSION['username'] . '_' . $file_name, 'size' => formatbytes($target_file, "KB"));
                             $sql = "insert into `files`(`uId`,`file`,`title`,`size`,`quantity`) values(:uId,:file,:title,'" . $file['size'] . "',0)";
                             $stmt = $pdo->prepare($sql);
                             $stmt->bindValue(':uId', $_SESSION['userId'], PDO::PARAM_INT);
                             $stmt->bindValue(':file', $file['name'], PDO::PARAM_STR);
                             $stmt->bindValue(':title', filter_var($_POST['title'], FILTER_SANITIZE_STRING), PDO::PARAM_STR);
                             $stmt->execute();
                             $stmt = $pdo->query("SELECT LAST_INSERT_ID()");
                             $last_id = $stmt->fetchColumn(0);
                             $error = false;
                         }
                     }
                 }
             }
         }
     }
     if ($error) {
         _log('error_upload', 'Avoid incorrect information', 'user id=' . isset($_SESSION['userId']) ? $_SESSION['userId'] : 'null');
         echo 'Error';
     } else {
         _log('info_upload', '1 file(s) successfully added to the file manager');
         if (ajax()) {
             echo json_encode(array('error' => 0, 'title' => $_POST['title'], 'size' => $file['size'], "id" => $last_id));
             exit;
         } else {
             redirect(BASE_PATH . '/filemanage/', 1);
         }
     }
 }
Example #3
0
    }
    ?>
</a><?php 
}
?>
	<?php 
if ($node->field_raw_images[0]['value']) {
    ?>
<a class="raw-field" href="<?php 
    print $node->field_raw_images[0]['value'];
    ?>
">Raw images<?php 
    if ($node->field_raw_images_filesize[0]['value']) {
        ?>
 (<?php 
        print formatbytes($node->field_raw_images_filesize[0]['value']);
        ?>
)<?php 
    }
    ?>
</a><?php 
}
?>
  </div>
  <div id="embed">
	<?php 
$cen_lon = ($sw[0] + $ne[0]) / 2;
$cen_lat = ($sw[1] + $ne[1]) / 2;
?>
	<p><a class="button" href="http://www.zazzle.com/api/create/at-238652512768069879?rf=238652512768069879&ax=Linkover&pd=228632289886847720&fwd=ProductPage&ed=true&tc=&ic=&title=<?php 
print $title;
Example #4
0
function backup($pdo)
{
    global $today;
    $path = 'dbbackup' . DS;
    $backup = backup_tables(HOST, LOGIN, PASSWORD, DATABASE);
    $filesize = formatbytes($path . $backup, 'KB');
    $sql = "insert into backup.backup(`file`,`backupdate`,`size`) values(:b,:bd,:fs)";
    $stmt = $pdo->prepare($sql);
    $stmt->bindvalue(':b', $backup, PDO::PARAM_STR);
    $stmt->bindvalue(':bd', $today, PDO::PARAM_STR);
    $stmt->bindvalue(':fs', $filesize, PDO::PARAM_STR);
    $stmt->execute();
    if (is_connected()) {
        dropboxBackup($path . $backup, $backup);
    }
    redirect(BASE_PATH . '/backup/?token=' . $_SESSION['token'], 1);
}
Example #5
0
function image_upload_process_handler()
{
    global $db, $smarty, $main_smarty, $linkres;
    include_once 'image_upload_settings.php';
    $module_error = false;
    // Debug Info
    image_upload_printdebug("START: image_upload_process_handler.");
    // Get the image real name, temp name, submission ID
    $imageFilename = $_FILES[module_imageupload_filename_field]['name'];
    $sourceFile = $_FILES[module_imageupload_filename_field]['tmp_name'];
    if ($sourceFile != "") {
        if (isset($_POST['id'])) {
            $linkID = strip_tags($_POST['id']);
        } else {
            $module_error = true;
            $module_errors[] = "- Submission entry id not found.";
        }
        // Get new names
        $destFile = module_imageupload_fullsize_prefix . $linkID;
        $destPath = module_imageupload_basedir . module_imageupload_imagedir;
        // Get image dimensions
        $thisImage = getimagesize($sourceFile);
        $thisImageFileSize = filesize($sourceFile);
        $thisImageWidth = $thisImage[0];
        $thisImageHeight = $thisImage[1];
        $thisImageMimeType = $thisImage['mime'];
        // Debug Info
        image_upload_printdebug("Original image filename = " . $imageFilename);
        image_upload_printdebug("Temp image filename = " . $sourceFile);
        image_upload_printdebug("Link ID = " . $linkID);
        image_upload_printdebug("Raw File size = " . $thisImageFileSize);
        image_upload_printdebug("Formatted File size = " . formatbytes($thisImageFileSize));
        image_upload_printdebug("Max allowed file size = " . module_imageupload_upload_maxsize * 1000 * 1000);
        image_upload_printdebug("Max allowed image x height = " . module_imageupload_upload_maxwidth . "x" . module_imageupload_upload_maxheight);
        image_upload_printdebug("Destination file = " . $destFile);
        image_upload_printdebug("Destination path = " . $destPath);
        image_upload_printdebug("Image data = " . $thisImageWidth . "x" . $thisImageHeight . " (" . $thisImageMimeType . ")");
        // Test image against max width / height constraints
        if ($thisImageWidth > module_imageupload_upload_maxwidth || $thisImageHeight > module_imageupload_upload_maxheight) {
            $module_error = true;
            $module_errors[] = "- This image exceeds the " . module_imageupload_upload_maxwidth . "x" . module_imageupload_upload_maxheight . " (width x height) maximum.";
        }
        // Test image against max file size constraints
        if ($thisImageFileSize > module_imageupload_upload_maxsize * 1000 * 1000) {
            $module_error = true;
            $module_errors[] = "- This image exceeds the allowed file size of " . module_imageupload_upload_maxsize . "MB";
        }
        // Determine Mime Type
        if (!$module_error) {
            switch ($thisImageMimeType) {
                case "image/jpeg":
                    $module_error = false;
                    $tempExt = ".jpg";
                    break;
                case "image/gif":
                    $module_error = false;
                    $tempExt = ".gif";
                    break;
                case "image/png":
                    $module_error = false;
                    $tempExt = ".png";
                    break;
                case "image/wbmp":
                    $module_error = false;
                    $tempExt = ".wbmp";
                    break;
                default:
                    if ($imageAttached) {
                        $module_error = true;
                        $module_errors[] = "- Unknown image type.  Only JPG, PNG, GIF and WMBP allowed.";
                    }
            }
        }
        // Process file, remove re-posts, and convert if necessary
        if (!$module_error) {
            if (file_exists($destPath . $destFile . $tempExt)) {
                @unlink($destPath . $destFile . $tempExt);
            }
            // Convert image if not JPG
            switch ($thisImageMimeType) {
                case "image/jpeg":
                    // No conversion needed
                    // Debug Info
                    image_upload_printdebug("No image conversion necessary.");
                    if (!move_uploaded_file($sourceFile, $destPath . $destFile . $tempExt)) {
                        $module_error = true;
                        $module_errors[] = "- Error processing image.";
                        // Delete original
                        @unlink($destPath . $destFile . $tempExt);
                    }
                    break;
                case "image/gif":
                case "image/png":
                case "image/wbmp":
                    // Include image converter class
                    @(include_once 'plugins/class.imageconverter.inc.php');
                    // Debug Info
                    image_upload_printdebug("Conversion of image file beginning...");
                    if (move_uploaded_file($sourceFile, $destPath . $destFile . $tempExt)) {
                        $tempDest = $destPath . $destFile . $tempExt;
                        // Convert image to JPG
                        $img = new ImageConverter($tempDest, "jpg", $destPath);
                        @unlink($tempDest);
                        // Get converted image dimensions
                        $destImage = getimagesize($destPath . $destFile . ".jpg");
                        $destImageWidth = $destImage[0];
                        $destImageHeight = $destImage[1];
                        $destImageMimeType = $destImage['mime'];
                        @unlink($tempDest);
                        // Debug Info
                        image_upload_printdebug("Dest Filename = " . $destPath . $destFile . ".jpg");
                        image_upload_printdebug("Dest image width = " . $destImageWidth);
                        image_upload_printdebug("Dest image height = " . $destImageHeight);
                        image_upload_printdebug("Dest image mime type = " . $destImageMimeType);
                    } else {
                        // Debug Info
                        image_upload_printdebug("Unable to move source file to dest for conversion.  Deleting source file.");
                        $module_error = true;
                        $module_error_message = module_imageupload_errorcode_2;
                        // Delete original
                        @unlink($sourceFile);
                    }
                    break;
            }
        }
        // Check if we need to resize image to meet fullsize width or height setting
        if (!$module_error) {
            // Debug Info
            image_upload_printdebug("Checking image dimensions for possible resizing.");
            $destFile .= ".jpg";
            # Check to see if the image needs to be rescaled.
            switch (module_imageupload_fullsize_maxtoggle) {
                case "w":
                    if ($thisImageWidth > module_imageupload_fullsize_width) {
                        // Include image resize functions
                        include_once 'plugins/class.thumbnail.inc.php';
                        // Debug Info
                        image_upload_printdebug("Image is wider than setting, attempting to reduce.");
                        image_upload_printdebug("Dest Path = " . $destPath);
                        image_upload_printdebug("Dest File = " . $destFile);
                        $convertImage = new thumbnail($destPath . $destFile);
                        $convertImage->size_auto(module_imageupload_fullsize_width);
                        $convertImage->jpeg_quality(module_imageupload_jpg_quality);
                        $convertImage->save($destPath . $destFile, module_imageupload_gdversion);
                        $destImage = getimagesize($destPath . $destFile);
                        $destImageWidth = $destImage[0];
                        $destImageHeight = $destImage[1];
                        // Debug Info
                        image_upload_printdebug("Converted image is " . $destImageWidth . "x" . $destImageHeight);
                    }
                    break;
                case "h":
                    if ($thisImageHeight > module_imageupload_fullsize_height) {
                        // Include image resize functions
                        include_once 'plugins/class.thumbnail.inc.php';
                        // Debug Info
                        image_upload_printdebug("Image is taller than setting, attempting to reduce.");
                        image_upload_printdebug("Dest Path = " . $destPath);
                        image_upload_printdebug("Dest File = " . $destFile);
                        $convertImage = new thumbnail($destPath . $destFile);
                        $convertImage->size_auto(module_imageupload_fullsize_height);
                        $convertImage->jpeg_quality(module_imageupload_jpg_quality);
                        $convertImage->save($destPath . $destFile, module_imageupload_gdversion);
                        getimagesize($destPath . $destFile);
                        $destImageWidth = $destImage[0];
                        $destImageHeight = $destImage[1];
                        // Debug Info
                        image_upload_printdebug("Converted image is " . $destImageWidth . "x" . $destImageHeight);
                    }
                    break;
            }
        }
        if (!$module_error) {
            // Debug Info
            image_upload_printdebug("Updating database with image filename.");
            // Update database
            $db->query("UPDATE " . table_links . " set " . module_imageupload_filename_field . "='{$destFile}' WHERE link_id='{$linkID}'");
            if (module_imageupload_customcaptions) {
                // Debug Info
                image_upload_printdebug("Using custom image caption.");
                $imageCaption = $_POST[module_imageupload_caption_field];
                if ($imageCaption != "") {
                    // Debug Info
                    image_upload_printdebug("Custom image caption: " . $imageCaption);
                    $imageCaption = strip_tags($imageCaption);
                    $imageCaption = addslashes($imageCaption);
                    // Debug Info
                    image_upload_printdebug('Updating database with custom image caption');
                    // Update database
                    $db->query("UPDATE " . table_links . " set " . module_imageupload_caption_field . "='" . $imageCaption . "' WHERE link_id='{$linkID}'");
                }
            }
            // Debug Info
            image_upload_printdebug("Database updated.");
        } else {
            @unlink($sourceFile);
            @unlink($destPath . $destFile . ".jpg");
            // Output error messages
            image_upload_printerrors($module_errors);
        }
    }
    // Debug Info
    image_upload_printdebug("END: image_upload_process_handler.");
}
function job_shutdown($signal = '')
{
    global $WORKING, $STATIC;
    if (empty($STATIC['LOGFILE'])) {
        //nothing on empty
        return;
    }
    //Put last error to log if one
    $lasterror = error_get_last();
    if (($lasterror['type'] == E_ERROR or $lasterror['type'] == E_PARSE or $lasterror['type'] == E_CORE_ERROR or $lasterror['type'] == E_COMPILE_ERROR or !empty($signal)) and is_writable($STATIC['LOGFILE'])) {
        if (!empty($signal)) {
            file_put_contents($STATIC['LOGFILE'], "<span class=\"timestamp\" title=\"[Line: " . __LINE__ . "|File: " . basename(__FILE__) . "|Mem: " . formatbytes(@memory_get_usage(true)) . "|Mem Max: " . formatbytes(@memory_get_peak_usage(true)) . "|Mem Limit: " . ini_get('memory_limit') . "|PID: " . getmypid() . "]\">" . date('Y/m/d H:i.s', time() + $STATIC['WP']['TIMEDIFF']) . ":</span> <span class=\"error\">[ERROR]" . sprintf(__('Signal %d send to script!', 'backwpup'), $signal) . "</span><br />\n", FILE_APPEND);
        }
        file_put_contents($STATIC['LOGFILE'], "<span class=\"timestamp\" title=\"[Line: " . $lasterror['line'] . "|File: " . basename($lasterror['file']) . "|Mem: " . formatbytes(@memory_get_usage(true)) . "|Mem Max: " . formatbytes(@memory_get_peak_usage(true)) . "|Mem Limit: " . ini_get('memory_limit') . "|PID: " . getmypid() . "]\">" . date('Y/m/d H:i.s', time() + $STATIC['WP']['TIMEDIFF']) . ":</span> <span class=\"error\">[ERROR]" . $lasterror['message'] . "</span><br />\n", FILE_APPEND);
        //write new log header
        $WORKING['ERROR']++;
        $fd = fopen($STATIC['LOGFILE'], 'r+');
        while (!feof($fd)) {
            $line = fgets($fd);
            if (stripos($line, "<meta name=\"backwpup_errors\"") !== false) {
                fseek($fd, $filepos);
                fwrite($fd, str_pad("<meta name=\"backwpup_errors\" content=\"" . $WORKING['ERROR'] . "\" />", 100) . "\n");
                break;
            }
            $filepos = ftell($fd);
        }
        fclose($fd);
    }
    //no more restarts
    $WORKING['RESTART']++;
    if ((!empty($STATIC['WP']['ALTERNATE_CRON']) or $WORKING['RESTART'] >= $STATIC['CFG']['jobscriptretry']) and is_file($STATIC['TEMPDIR'] . '.running') and is_writable($STATIC['LOGFILE'])) {
        //only x restarts allowed
        if (!empty($STATIC['WP']['ALTERNATE_CRON'])) {
            file_put_contents($STATIC['LOGFILE'], "<span class=\"timestamp\" title=\"[Line: " . __LINE__ . "|File: " . basename(__FILE__) . "\"|Mem: " . formatbytes(@memory_get_usage(true)) . "|Mem Max: " . formatbytes(@memory_get_peak_usage(true)) . "|Mem Limit: " . ini_get('memory_limit') . "|PID: " . getmypid() . "]>" . date('Y/m/d H:i.s', time() + $STATIC['WP']['TIMEDIFF']) . ":</span> <span class=\"error\">[ERROR]" . __('Can not restart on alternate cron....', 'backwpup') . "</span><br />\n", FILE_APPEND);
        } else {
            file_put_contents($STATIC['LOGFILE'], "<span class=\"timestamp\" title=\"[Line: " . __LINE__ . "|File: " . basename(__FILE__) . "\"|Mem: " . formatbytes(@memory_get_usage(true)) . "|Mem Max: " . formatbytes(@memory_get_peak_usage(true)) . "|Mem Limit: " . ini_get('memory_limit') . "|PID: " . getmypid() . "]>" . date('Y/m/d H:i.s', time() + $STATIC['WP']['TIMEDIFF']) . ":</span> <span class=\"error\">[ERROR]" . __('To many restarts....', 'backwpup') . "</span><br />\n", FILE_APPEND);
        }
        $WORKING['ERROR']++;
        $fd = fopen($STATIC['LOGFILE'], 'r+');
        while (!feof($fd)) {
            $line = fgets($fd);
            if (stripos($line, "<meta name=\"backwpup_errors\"") !== false) {
                fseek($fd, $filepos);
                fwrite($fd, str_pad("<meta name=\"backwpup_errors\" content=\"" . $WORKING['ERROR'] . "\" />", 100) . "\n");
                break;
            }
            $filepos = ftell($fd);
        }
        fclose($fd);
        job_end();
    }
    //set PID to 0
    $WORKING['PID'] = 0;
    //Excute jobrun again
    if (!is_file($STATIC['TEMPDIR'] . '.running')) {
        exit;
    }
    if (is_writable($STATIC['LOGFILE'])) {
        file_put_contents($STATIC['LOGFILE'], "<span class=\"timestamp\" title=\"[Line: " . __LINE__ . "|File: " . basename(__FILE__) . "|Mem: " . formatbytes(@memory_get_usage(true)) . "|Mem Max: " . formatbytes(@memory_get_peak_usage(true)) . "|Mem Limit: " . ini_get('memory_limit') . "|PID: " . getmypid() . "]\">" . date('Y/m/d H:i.s', time() + $STATIC['WP']['TIMEDIFF']) . ":</span> <span>" . $WORKING['RESTART'] . '. ' . __('Script stop! Will started again now!', 'backwpup') . "</span><br />\n", FILE_APPEND);
    }
    update_working_file(true);
    if (!empty($STATIC['JOBRUNURL'])) {
        if (function_exists('curl_exec')) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $STATIC['JOBRUNURL']);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, array('BackWPupJobTemp' => $STATIC['TEMPDIR'], 'nonce' => $WORKING['NONCE'], 'type' => 'restart'));
            curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_USERAGENT, 'BackWPup');
            if (!empty($STATIC['CFG']['httpauthuser']) and !empty($STATIC['CFG']['httpauthpassword'])) {
                curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
                curl_setopt($ch, CURLOPT_USERPWD, $STATIC['CFG']['httpauthuser'] . ':' . base64_decode($STATIC['CFG']['httpauthpassword']));
            }
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
            curl_exec($ch);
        } else {
            //use fopen if no curl
            $urlParsed = parse_url($STATIC['JOBRUNURL']);
            if ($urlParsed['scheme'] == 'https') {
                $host = 'ssl://' . $urlParsed['host'];
                $port = !empty($urlParsed['port']) ? $urlParsed['port'] : 443;
            } else {
                $host = $urlParsed['host'];
                $port = !empty($urlParsed['port']) ? $urlParsed['port'] : 80;
            }
            $query = http_build_query(array('BackWPupJobTemp' => $STATIC['TEMPDIR'], 'nonce' => $WORKING['NONCE'], 'type' => 'restart'));
            $path = (isset($urlParsed['path']) ? $urlParsed['path'] : '/') . (isset($urlParsed['query']) ? '?' . $urlParsed['query'] : '');
            $header = "POST " . $path . " HTTP/1.1\r\n";
            $header .= "Host: " . $urlParsed['host'] . "\r\n";
            $header .= "User-Agent: BackWPup\r\n";
            $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
            $header .= "Content-Length: " . strlen($query) . "\r\n";
            if (!empty($STATIC['CFG']['httpauthuser']) and !empty($STATIC['CFG']['httpauthpassword'])) {
                $header .= "Authorization: Basic " . base64_encode($STATIC['CFG']['httpauthuser'] . ':' . base64_decode($STATIC['CFG']['httpauthpassword'])) . "\r\n";
            }
            $header .= "Connection: Close\r\n\r\n";
            $header .= $query;
            $fp = fsockopen($host, $port, $errno, $errstr, 3);
            fwrite($fp, $header);
            fclose($fp);
        }
    }
    exit;
}
Example #7
0
function db_dump()
{
    global $WORKING, $STATIC;
    trigger_error(sprintf(__('%d. try for database dump...', 'backwpup'), $WORKING['DB_DUMP']['STEP_TRY']), E_USER_NOTICE);
    if (!isset($WORKING['DB_DUMP']['DONETABLE']) or !is_array($WORKING['DB_DUMP']['DONETABLE'])) {
        $WORKING['DB_DUMP']['DONETABLE'] = array();
    }
    mysql_update();
    //to backup
    $tabelstobackup = array();
    $result = mysql_query("SHOW TABLES FROM `" . $STATIC['WP']['DB_NAME'] . "`");
    //get table status
    if (!$result) {
        trigger_error(sprintf(__('Database error %1$s for query %2$s', 'backwpup'), mysql_error(), "SHOW TABLE STATUS FROM `" . $STATIC['WP']['DB_NAME'] . "`;"), E_USER_ERROR);
    }
    while ($data = mysql_fetch_row($result)) {
        if (!in_array($data[0], $STATIC['JOB']['dbexclude'])) {
            $tabelstobackup[] = $data[0];
        }
    }
    $WORKING['STEPTODO'] = count($tabelstobackup);
    //Set maintenance
    maintenance_mode(true);
    if (count($tabelstobackup) > 0) {
        $result = mysql_query("SHOW TABLE STATUS FROM `" . $STATIC['WP']['DB_NAME'] . "`");
        //get table status
        if (!$result) {
            trigger_error(sprintf(__('Database error %1$s for query %2$s', 'backwpup'), mysql_error(), "SHOW TABLE STATUS FROM `" . $STATIC['WP']['DB_NAME'] . "`;"), E_USER_ERROR);
        }
        while ($data = mysql_fetch_assoc($result)) {
            $status[$data['Name']] = $data;
        }
        if ($file = fopen($STATIC['TEMPDIR'] . $STATIC['WP']['DB_NAME'] . '.sql', 'wb')) {
            fwrite($file, "-- ---------------------------------------------------------\n");
            fwrite($file, "-- Dump with BackWPup ver.: " . $STATIC['BACKWPUP']['VERSION'] . "\n");
            fwrite($file, "-- Plugin for WordPress " . $STATIC['WP']['VERSION'] . " by Daniel Huesken\n");
            fwrite($file, "-- http://backwpup.com/\n");
            fwrite($file, "-- Blog Name: " . $STATIC['WP']['BLOGNAME'] . "\n");
            fwrite($file, "-- Blog URL: " . $STATIC['WP']['SITEURL'] . "\n");
            fwrite($file, "-- Blog ABSPATH: " . $STATIC['WP']['ABSPATH'] . "\n");
            fwrite($file, "-- Table Prefix: " . $STATIC['WP']['TABLE_PREFIX'] . "\n");
            fwrite($file, "-- Database Name: " . $STATIC['WP']['DB_NAME'] . "\n");
            fwrite($file, "-- Dump on: " . date('Y-m-d H:i.s', time() + $STATIC['WP']['TIMEDIFF']) . "\n");
            fwrite($file, "-- ---------------------------------------------------------\n\n");
            //for better import with mysql client
            fwrite($file, "/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\n");
            fwrite($file, "/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\n");
            fwrite($file, "/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\n");
            fwrite($file, "/*!40101 SET NAMES '" . mysql_client_encoding() . "' */;\n");
            fwrite($file, "/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;\n");
            fwrite($file, "/*!40103 SET TIME_ZONE='" . mysql_result(mysql_query("SELECT @@time_zone"), 0) . "' */;\n");
            fwrite($file, "/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;\n");
            fwrite($file, "/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;\n");
            fwrite($file, "/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;\n");
            fwrite($file, "/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;\n\n");
            //make table dumps
            foreach ($tabelstobackup as $table) {
                if (in_array($table, $WORKING['DB_DUMP']['DONETABLE'])) {
                    continue;
                }
                _db_dump_table($table, $status[$table], $file);
                $WORKING['DB_DUMP']['DONETABLE'][] = $table;
                $WORKING['STEPDONE'] = count($WORKING['DB_DUMP']['DONETABLE']);
            }
            //for better import with mysql client
            fwrite($file, "\n");
            fwrite($file, "/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;\n");
            fwrite($file, "/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;\n");
            fwrite($file, "/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;\n");
            fwrite($file, "/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;\n");
            fwrite($file, "/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\n");
            fwrite($file, "/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\n");
            fwrite($file, "/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;\n");
            fwrite($file, "/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;\n");
            fclose($file);
            trigger_error(__('Database dump done!', 'backwpup'), E_USER_NOTICE);
        } else {
            trigger_error(__('Can not create database dump!', 'backwpup'), E_USER_ERROR);
        }
    } else {
        trigger_error(__('No tables to dump', 'backwpup'), E_USER_WARNING);
    }
    //add database file to backupfiles
    if (is_readable($STATIC['TEMPDIR'] . $STATIC['WP']['DB_NAME'] . '.sql')) {
        $filestat = stat($STATIC['TEMPDIR'] . $STATIC['WP']['DB_NAME'] . '.sql');
        trigger_error(sprintf(__('Add database dump "%1$s" with %2$s to backup file list', 'backwpup'), $STATIC['WP']['DB_NAME'] . '.sql', formatbytes($filestat['size'])), E_USER_NOTICE);
        $WORKING['ALLFILESIZE'] += $filestat['size'];
        add_file(array(array('FILE' => $STATIC['TEMPDIR'] . $STATIC['WP']['DB_NAME'] . '.sql', 'OUTFILE' => $STATIC['WP']['DB_NAME'] . '.sql', 'SIZE' => $filestat['size'], 'ATIME' => $filestat['atime'], 'MTIME' => $filestat['mtime'], 'CTIME' => $filestat['ctime'], 'UID' => $filestat['uid'], 'GID' => $filestat['gid'], 'MODE' => $filestat['mode'])));
    }
    //Back from maintenance
    maintenance_mode(false);
    $WORKING['STEPSDONE'][] = 'DB_DUMP';
    //set done
}
        $folders = glob($datadir . '/pb*', GLOB_ONLYDIR);
        foreach ($folders as $folder) {
            $info = new stdClass();
            $info->path = $folder;
            $info->folder = substr($folder, strrpos($folder, '/') + 1);
            $info->size = 0;
            $info->size = @exec("du -b {$folder} | awk '{print \$1}'");
            $info->date = str_replace('pb', '', $info->folder);
            $info->ok = file_exists($folder . '/success.txt') ? 'OK' : 'Failed';
            $attemps[] = $info;
        }
    }
    // Now show.
    print '<div id="existing"><p>Previous backups:</p>';
    foreach ($attemps as $attempt) {
        print '<p>' . userdate($attempt->date) . ' : ' . formatbytes($attempt->size) . ' (' . $attempt->ok . ') ';
        // Delete.
        print '<a href="' . $CFG->wwwroot . '/mod/oublog/migratepersonal.php?action=DELETE&name=' . $attempt->folder . '&sesskey=' . sesskey() . '">';
        print $OUTPUT->pix_icon('t/delete', 'Delete') . '</a> ';
        // Zip.
        print '<a href="' . $CFG->wwwroot . '/mod/oublog/migratepersonal.php?action=GO&name=' . $attempt->folder . '&sesskey=' . sesskey() . '">';
        print $OUTPUT->pix_icon('i/restore', 'Import data') . '</a>';
        print '</p>';
    }
    print '</div>';
}
print $OUTPUT->footer();
exit;
/**
 * Start the import of personal blog data
 * @param string $dir path of directory containing backup data
Example #9
0
function wp_export()
{
    global $WORKING, $STATIC;
    $WORKING['STEPTODO'] = 1;
    trigger_error(sprintf(__('%d. try for wordpress export to XML file...', 'backwpup'), $WORKING['WP_EXPORT']['STEP_TRY']), E_USER_NOTICE);
    need_free_memory(10485760);
    //10MB free memory
    if (function_exists('curl_exec')) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, substr($STATIC['JOBRUNURL'], 0, -11) . 'wp_export_generate.php');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, array('nonce' => $WORKING['NONCE'], 'type' => 'getxmlexport'));
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
        curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_USERAGENT, 'BackWPup');
        if (defined('CURLOPT_PROGRESSFUNCTION')) {
            curl_setopt($ch, CURLOPT_NOPROGRESS, false);
            curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'curl_progresscallback');
            curl_setopt($ch, CURLOPT_BUFFERSIZE, 1048576);
        }
        if (!empty($STATIC['CFG']['httpauthuser']) and !empty($STATIC['CFG']['httpauthpassword'])) {
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
            curl_setopt($ch, CURLOPT_USERPWD, $STATIC['CFG']['httpauthuser'] . ':' . backwpup_base64($STATIC['CFG']['httpauthpassword']));
        }
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
        $return = curl_exec($ch);
        $status = curl_getinfo($ch);
        if ($status['http_code'] >= 300 or $status['http_code'] < 200 or curl_errno($ch) > 0) {
            if (0 != curl_errno($ch)) {
                trigger_error(__('cURL:', 'backwpup') . ' (' . curl_errno($ch) . ') ' . curl_error($ch), E_USER_ERROR);
            } else {
                trigger_error(__('cURL:', 'backwpup') . ' (' . $status['http_code'] . ')  Invalid response.', E_USER_ERROR);
            }
        } else {
            file_put_contents($STATIC['TEMPDIR'] . preg_replace('/[^a-z0-9_\\-]/', '', strtolower($STATIC['WP']['BLOGNAME'])) . '.wordpress.' . date('Y-m-d') . '.xml', $return);
        }
        curl_close($ch);
    } else {
        //use fopen if no curl
        $urlParsed = parse_url(substr($STATIC['JOBRUNURL'], 0, -11) . 'wp_export_generate.php');
        if ($urlParsed['scheme'] == 'https') {
            $host = 'ssl://' . $urlParsed['host'];
            $port = !empty($urlParsed['port']) ? $urlParsed['port'] : 443;
        } else {
            $host = $urlParsed['host'];
            $port = !empty($urlParsed['port']) ? $urlParsed['port'] : 80;
        }
        $query = http_build_query(array('nonce' => $WORKING['NONCE'], 'type' => 'getxmlexport'));
        $path = (isset($urlParsed['path']) ? $urlParsed['path'] : '/') . (isset($urlParsed['query']) ? '?' . $urlParsed['query'] : '');
        $header = "POST " . $path . " HTTP/1.1\r\n";
        $header .= "Host: " . $urlParsed['host'] . "\r\n";
        $header .= "User-Agent: BackWPup\r\n";
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: " . strlen($query) . "\r\n";
        if (!empty($STATIC['CFG']['httpauthuser']) and !empty($STATIC['CFG']['httpauthpassword'])) {
            $header .= "Authorization: Basic " . base64_encode($STATIC['CFG']['httpauthuser'] . ':' . backwpup_base64($STATIC['CFG']['httpauthpassword'])) . "\r\n";
        }
        $header .= "Connection: Close\r\n\r\n";
        $header .= $query;
        $fp = fsockopen($host, $port, $errno, $errstr, 300);
        fwrite($fp, $header);
        $responseHeader = '';
        do {
            $responseHeader .= fread($fp, 1);
        } while (!preg_match('/\\r\\n\\r\\n$/', $responseHeader));
        while (!feof($fp)) {
            update_working_file();
            file_put_contents($STATIC['TEMPDIR'] . preg_replace('/[^a-z0-9_\\-]/', '', strtolower($STATIC['WP']['BLOGNAME'])) . '.wordpress.' . date('Y-m-d') . '.xml', fgets($fp, 256), FILE_APPEND);
        }
        fclose($fp);
    }
    //add XML file to backupfiles
    if (is_readable($STATIC['TEMPDIR'] . preg_replace('/[^a-z0-9_\\-]/', '', strtolower($STATIC['WP']['BLOGNAME'])) . '.wordpress.' . date('Y-m-d') . '.xml')) {
        $filestat = stat($STATIC['TEMPDIR'] . preg_replace('/[^a-z0-9_\\-]/', '', strtolower($STATIC['WP']['BLOGNAME'])) . '.wordpress.' . date('Y-m-d') . '.xml');
        trigger_error(sprintf(__('Add XML export "%1$s" to backup list with %2$s', 'backwpup'), preg_replace('/[^a-z0-9_\\-]/', '', strtolower($STATIC['WP']['BLOGNAME'])) . '.wordpress.' . date('Y-m-d') . '.xml', formatbytes($filestat['size'])), E_USER_NOTICE);
        $WORKING['ALLFILESIZE'] += $filestat['size'];
        add_file(array(array('FILE' => $STATIC['TEMPDIR'] . preg_replace('/[^a-z0-9_\\-]/', '', strtolower($STATIC['WP']['BLOGNAME'])) . '.wordpress.' . date('Y-m-d') . '.xml', 'OUTFILE' => preg_replace('/[^a-z0-9_\\-]/', '', strtolower($STATIC['WP']['BLOGNAME'])) . '.wordpress.' . date('Y-m-d') . '.xml', 'SIZE' => $filestat['size'], 'ATIME' => $filestat['atime'], 'MTIME' => $filestat['mtime'], 'CTIME' => $filestat['ctime'], 'UID' => $filestat['uid'], 'GID' => $filestat['gid'], 'MODE' => $filestat['mode'])));
    }
    $WORKING['STEPDONE'] = 1;
    $WORKING['STEPSDONE'][] = 'WP_EXPORT';
    //set done
}