<?php
# ***** BEGIN LICENSE BLOCK *****
# This file is a simple tool for DotClear2.
# Copyright (c) 2007 julien mudry and contributors. All rights
# GNU/GPL
#
# DotClear2 is a simple and powerful opensource blogware.
# Copyright (c) 2004-2005 Olivier Meunier and contributors. All rights
# reserved.
#
# DotClear is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# DotClear is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with DotClear; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Contributors include (but is not limited to): 
#   Pep (original tool code for DotClear1.2)
#   k-net (author of an automatic backup plugin for DotClear2)
# ***** END LICENSE BLOCK *****
header('Content-Type: text/plain');

// Choix du blog a sauvegarder selon son identifiant
define('DC_BLOG_ID''default');

// Adapter le chemin pour trouver le fichier prepend.php de DotClear2
// en fonction de l'endroit ou se trouve ce script.
require_once(dirname(__FILE__).'/../inc/prepend.php');

global 
$core;
$core->setBlog(DC_BLOG_ID);
if (
$core->blog->id == null) {
    echo 
'Blog is not defined';
    exit;
}

// Ajuster les parametres suivants a ses propres besoins.
$mail_to "Moi <moi@moi.com>";
$mail_from $core->blog->name " <no-reply@monjoliblog.com>";
$mail_subject "[DB DUMP - ".DC_BLOG_ID."] "date('d/m/Y');
$mail_body "Servi tout chaud, votre dump de base de données pour " $core->blog->name " ! \\o/";

/**
    PAS BESOIN DE TOUCHER A CE QUI SUIT.
**/

/**
@function require_importExport

Recherche le plugin importExport dans les differents path
de DC_PLUGINS_ROOT et fait un require_once sur la classe d'export.

 */
function require_importExport() {
    
$found_importExport false;
    
$plugin_paths explode(PATH_SEPARATORDC_PLUGINS_ROOT);
    foreach (
$plugin_paths as $root) {
        if (!
is_dir($root) || !is_readable($root)) {
            continue;
        }
        if (
substr($root, -1) != '/') {
            
$root .= '/';
        }
        if (
file_exists($root.'importExport/class.db.export.php')) {
            require_once(
$root.'importExport/class.db.export.php');
            
$found_importExport true;
            break;
        }
    }
    if (!
$found_importExport) {
        echo 
'Could not found importExport plugin, exiting.';
        exit;
    }
}

/**
@function mail_attached

Un pompage éhonté de la fonction de J. Coggeshall.
Pourquoi ré-inventer la roue ?

Par flemme, je ne détaille pas les arguments.
Leurs noms sont suffisamment parlant à mon goût...

Comme rien ne vaut l'original :
    * Homepage de John : http://www.coggeshall.org/
    * Url de l'article : http://www.theukwebdesigncompany.com/articles/php-file-attachments.php

*/
function mail_attached($to$from$subject$message$filename$headers '')
{
    
$unique_sep md5(uniqid(time()));

    
$headers .=
        
"From: $from\n".
        
"MIME-Version: 1.0\nContent-Type: multipart/mixed;boundary=\"$unique_sep\";\n".
        
"charset=\"iso-8859-1\"\nContent-Transfer-Encoding:7bit";
    
$mime =
        
"--$unique_sep\n".
         
"Content-Type: text/plain; charset=\"iso-8859-1\"\n".
        
"Content-Transfer-Encoding: 7bit\n\n".
        
$message."\n\n";

    if (
is_array($filename)) {
        foreach (
$filename as $val) {
            if(
file_exists($val['file'])) {
                
$mime .=
                    
"--$unique_sep\n".
                    
"Content-Type: {$val['mimetype']}; ".
                    
"name=\"{$val['filename']}\"\n".
                    
"Content-Transfer-Encoding: base64\n".
                    
"Content-Disposition: attachment\n\n";
                
$filedata file_get_contents($val['file']);
                
$mime .= chunk_split(base64_encode($filedata));
            } else {
                print(
"probleme fichier : ".$val['file']." inexistant");
                return(
false);
            }
        }
    } else {
        print(
"probleme : pas de fichiers transmis ou variable erronee");
        return(
false);
    }
    
$mime .= "--$unique_sep--\n";

    return(
mail($to$subject$mime."\n".$message$headers));
}

function 
backup_blog($file$blog_id) {
    
    global 
$core;
    
    
// Preparation de l'environnement necessaire pour charger l'admin des plugins
    
global $_menu;
    
$_menu['System'] = new dcMenu('system-menu','System');
    
$_menu['Blog'] = new dcMenu('blog-menu','Blog');
    
$_menu['Plugins'] = new dcMenu('plugins-menu','Plugins');

    
// Chargement de l'admin des plugins (notamment pour qu'ils "activent" leur eventuel callback d'export)
    
$core->auth->sudo(array($core->plugins'loadModules'), DC_PLUGINS_ROOT,'admin',$_lang);

    if (((
is_file($file) && is_writable($file)) || (!file_exists($file) && is_writable(dirname($file))))) {
        
        
$exp = new dbExport($core->con,$file,$core->prefix);
        
        
fwrite($exp->fp,'///DOTCLEAR|'.DC_VERSION."|single\n");
        
$exp->export('category',
            
'SELECT * FROM '.$core->prefix.'category '.
            
"WHERE blog_id = '".$blog_id."'"
        
);
        
$exp->export('link',
            
'SELECT * FROM '.$core->prefix.'link '.
            
"WHERE blog_id = '".$blog_id."'"
        
);
        
$exp->export('setting',
            
'SELECT * FROM '.$core->prefix.'setting '.
            
"WHERE blog_id = '".$blog_id."'"
        
);
        
$exp->export('post',
            
'SELECT * FROM '.$core->prefix.'post '.
            
"WHERE blog_id = '".$blog_id."'"
        
);
        
$exp->export('media',
            
'SELECT * FROM '.$core->prefix."media WHERE media_path = '".
            
$core->con->escape($core->blog->settings->public_path)."'"
        
);
        
$exp->export('post_media',
            
'SELECT media_id, M.post_id '.
            
'FROM '.$core->prefix.'post_media M, '.$core->prefix.'post P '.
            
'WHERE P.post_id = M.post_id '.
            
"AND P.blog_id = '".$blog_id."'"
        
);
        
$exp->export('ping',
            
'SELECT ping.post_id, ping_url, ping_dt '.
            
'FROM '.$core->prefix.'ping ping, '.$core->prefix.'post P '.
            
'WHERE P.post_id = ping.post_id '.
            
"AND P.blog_id = '".$blog_id."'"
        
);
        
$exp->export('comment',
            
'SELECT C.* '.
            
'FROM '.$core->prefix.'comment C, '.$core->prefix.'post P '.
            
'WHERE P.post_id = C.post_id '.
            
"AND P.blog_id = '".$blog_id."'"
        
);
        
        
# --BEHAVIOR-- exportSingle
        
$core->callBehavior('exportSingle',$core,$exp,$blog_id);
        
        return 
true;
    }
    
    return 
false;
}

/**
    C'est ici que ça se passe...
*/

if (!is_writable(DC_TPL_CACHE)) {
    echo 
'Impossible d\'ecrire dans le dossier de cache pour le fichier temporaire. On arrete la.';
    exit;
}

require_importExport();

$file DC_TPL_CACHE.'/tmp_'.DC_BLOG_ID.'.txt.gz';
backup_blog($fileDC_BLOG_ID);
$backup_content file_get_contents($file);
$backup_content gzencode($backup_content9);
file_put_contents($file$backup_content);
$files[0]['file'] = $file;
$files[0]['mimetype'] = 'application/x-gzip';
$files[0]['filename'] = 'dbdump_'.DC_BLOG_ID.'_'.date('Y-m-d').".txt.gz";

if (
mail_attached($mail_to$mail_from$mail_subject$mail_body$files))
{
    print(
"Fichier de dump envoye");
    
unlink($files[0]['file']);
}
else
{
    print(
"Erreur avec le fichier de dump");
}
?>