· 6 years ago · May 18, 2019, 03:30 AM
1<?php
2/**
3 * @package JDBautoBackup
4 *
5 * @author Robert Gastaud - Marc Studer
6 *
7 * @see
8 * &licence GNU/GPL
9 * Fork of LazyBackup from Stefan Granholm
10 * Portage Joomla 2.5 & internationalisation
11 * 2015/03/08 : replace "media" folder with "/plugins/system/lazydbbackup/dumps"
12 */
13defined('_JEXEC') or die('Restricted access');
14
15jimport('joomla.filesystem.folder'); // september 07 2012
16jimport('joomla.filesystem.file'); // september 07 2012
17
18$today1 = date('Y-m-dTH-i-s', time()); // RRG 2019/04/02
19
20// detect if plugin settings are applied
21//$pJform = JRequest::getVar('jform'); //RRG 06/04/2017
22$input = JFactory::getApplication()->input;
23$pJform = $input->get('jform', '', 'array');
24
25if (isset($pJform['params']['backupfreq'])) {
26 //$fname=array_pop(JFolder::files(JPATH_SITE.'/plugins/system/lazydbbackup/dumps','lazydbbackup_checkfile.*'));
27 $fnames = (JFolder::files(JPATH_SITE . '/plugins/system/lazydbbackup/dumps', 'lazydbbackup_checkfile.*'));
28 $fname = array_pop($fnames);
29 if ($fname) {
30 unlink(JPATH_SITE . '/plugins/system/lazydbbackup/dumps/' . $fname);
31 }
32 $dayssecs = $pJform['params']['backuptime'];
33 $dayssecs = strtotime(date('Y-m-d') . ' ' . $dayssecs);
34 if (!$dayssecs) {
35 $dayssecs = 0;
36 } else {
37 $dayssecs -= strtotime(date('Y-m-d'));
38 }
39 $time = time();
40 $round = strtotime(date('Y-m-d', $time));
41 $backuptime = $round + $dayssecs;
42 $xdays = (int)$pJform['params']['xdays'];
43 if (0 == $xdays) {
44 $xdays = 1;
45 }
46 if (1 == $xdays) {
47 $interval = (int)$pJform['params']['backupfreq'];
48 if (0 == $interval) {
49 $interval = 86400;
50 } else {
51 $interval = (int)(86400 / $interval);
52 }
53 while ($backuptime < $time) {
54 $backuptime += $interval;
55 }
56 } else {
57 $interval = $xdays * 86400;
58 if ($backuptime < $time) {
59 $backuptime += 86400;
60 }
61 }
62 $fname = JPATH_SITE . '/plugins/system/lazydbbackup/dumps/lazydbbackup_checkfile.' . $backuptime;
63 if (!touch($fname)) {
64 return;
65 }
66 $f = fopen($fname, 'w');
67 fputs($f, 'w' . $interval);
68 fclose($f);
69}
70
71function suppr_accents($str, $encoding = 'utf-8')
72{
73 // transformer les caractères accentués en entités HTML
74 $str = htmlentities($str, ENT_NOQUOTES, $encoding);
75
76 // remplacer les entités HTML pour avoir juste le premier caractères non accentués
77 // Exemple : "&ecute;" => "e", "&Ecute;" => "E", "Ã " => "a" ...
78 $str = preg_replace('#&([A-za-z])(?:acute|grave|cedil|circ|orn|ring|slash|th|tilde|uml);#', '\1', $str);
79
80 // Remplacer les ligatures tel que : Œ, Æ ...
81 // Exemple "Å“" => "oe"
82 $str = preg_replace('#&([A-za-z]{2})(?:lig);#', '\1', $str);
83 // Supprimer tout le reste
84 $str = preg_replace('#&[^;]+;#', '', $str);
85
86 return $str;
87}
88
89function teste($s)
90{
91 echo print_r($s, true) . ' - ';
92 // echo $s.' - ';
93 // echo '<pre><span style="background-color:white;color:black">'.$s.'</span></pre>';
94}
95
96// Import library dependencies
97jimport('joomla.event.plugin');
98jimport('joomla.registry.registry');
99
100class plgSystemLazyDbBackup extends JPlugin
101{
102 public function onAfterInitialise()
103 {
104 JPlugin::loadLanguage('plg_system_lazydbbackup', JPATH_ADMINISTRATOR);
105
106 jimport('joomla.filesystem.folder'); // ???
107 //$plugin =& JPluginHelper::getPlugin( 'system', 'lazydbbackup' );
108 $plugin = JPluginHelper::getPlugin('system', 'lazydbbackup');
109 //$pluginParams = new JParameter( $plugin->params );
110 $pluginParams = new JRegistry($plugin->params);
111 $create = false;
112 $fnames = JFolder::files(JPATH_SITE . '/plugins/system/lazydbbackup/dumps', 'lazydbbackup_checkfile.*');
113 $fname = array_pop($fnames);
114 //$fname=array_pop(JFolder::files(JPATH_SITE.'/plugins/system/lazydbbackup/dumps','lazydbbackup_checkfile.*'));
115 if (!$fname) {
116 return;
117 }
118 $backuptime = substr($fname, -10, 10);
119 $interval = file_get_contents(JPATH_SITE . '/plugins/system/lazydbbackup/dumps/' . $fname);
120 //test("$interval");
121 if ('w' == $interval[0]) {
122 $interval = (int)substr($interval, 1);
123 $create = true;
124 }
125
126 // RRG 27/06/2018 email d'alerte de mise à jour
127 //if (!empty($pluginParams->get('updates_email'))) { /// is_ull 23/04/2019
128 if (!is_null($pluginParams->get('updates_email'))) {
129 $mail_update = $pluginParams->get('updates_email');
130 } else {
131 $mail_update = 1;
132 }
133 if (1 == $mail_update) { // seulement si la case est cochée ou si le plungin n'a pas été enregistré avec le choix
134 // on lit le fichier repère pour savoir si on doit vérifier ou pas
135 $fupdname = JPATH_SITE . '/plugins/system/lazydbbackup/dumps/lazydbbackup.upd';
136 if (!file_exists($fupdname)) { // pas de fichier repère, on crée nouveau fichier
137 $updtime = strtotime('now') - 86400;
138 } else {
139 $updtime = file_get_contents(JPATH_SITE . '/plugins/system/lazydbbackup/dumps/lazydbbackup.upd');
140 }
141 if ($updtime + 86400 <= strtotime('now')) { // si intervalle de 24 h atteint ou dépassé depuis la précédente recherche, on en lance une nouvelle
142 // RRG 25/03/2018 recherche version actuelle du plugin pour comparaison avec version de mise à jour
143 $url = JPATH_SITE . '/plugins/system/lazydbbackup/lazydbbackup.xml';
144 $xml = simplexml_load_file($url);
145 $version = intval(str_replace('.', '', $xml->version)); // on transforme la version en nombre
146 $server_url = $xml->updateservers->server; // on récupère aussi l'URL du serveur de mise à jour
147
148 // on récupère la version de Joomla! sous forme 3.8.6 pour vérifier dasns le fichier d'update si ça correspond à la "targetplatform"
149 $versionJ = new JVersion();
150 list($majorV, $minorV, $currentV) = explode('.', $versionJ->getShortVersion());
151
152 $xml = simplexml_load_file($server_url);
153 if (false == !$xml) { /// 11/04/2018 seulement si on peut récupérer le contenu du fichier
154 foreach ($xml->children() as $update) {
155 // on vérifie dans le champ targetplatform si la version de Joomla! est visée
156 $targetP = $update->targetplatform;
157 //echo ($targetP['version']);
158 list($majorVu, $minorVu) = explode('.', $targetP['version']); // valeur sous forme version=3[0123456789]
159 if ($majorVu == $majorV) {
160 if (strpos($minorVu, $minorV)) {
161 $nv_version = $update->version; // dernière version de l'extension
162 break; // à la première occurrence, on a un "update" correspondant, donc on sort
163 }
164 }
165 }
166 $new_version = intval(str_replace('.', '', $nv_version)); // on transforme la version en nombre
167
168 if ($new_version > $version) { // si une version plus récente existe, on informe l'utilisateur
169 $config = JFactory::getConfig();
170 $lbupd_mailfrom = $config->get('mailfrom');
171 $lbupd_fromname = $config->get('fromname');
172 if ($updemailresult = $this->LazyDbBackupUpdEmail($pluginParams, $lbupd_mailfrom, $lbupd_fromname, $nv_version)) {
173 } else {
174 //return false; mail non envoyé
175 }
176 }
177 }
178 $fupd = fopen($fupdname, 'w');
179 fputs($fupd, strtotime('now'));
180 fclose($fupd); // on met à jour le fichier d'horodatage
181 }
182 }
183
184 //test(date('Y-m-d H:i:s',$time));
185 //test(date('Y-m-d H:i:s',$backuptime));
186 // RRG 30/03/2013 added params for admin refresh backups
187 $admin_bkp = false;
188 if (((1 == $pluginParams->def('config_bkp', 0)) && (false !== strpos(strtolower($_SERVER['REQUEST_URI']), 'option=com_config'))) || ((1 == $pluginParams->def('user_bkp', 0)) && (false !== strpos(strtolower($_SERVER['REQUEST_URI']), 'option=com_users'))) || ((1 == $pluginParams->def('menu_bkp', 0)) && (false !== strpos(strtolower($_SERVER['REQUEST_URI']), 'option=com_menus'))) || ((1 == $pluginParams->def('content_bkp', 0)) && (false !== strpos(strtolower($_SERVER['REQUEST_URI']), 'option=com_content'))) || ((1 == $pluginParams->def('category_bkp', 0)) && (false !== strpos(strtolower($_SERVER['REQUEST_URI']), 'option=com_categories'))) || ((1 == $pluginParams->def('installer_bkp', 0)) && (false !== strpos(strtolower($_SERVER['REQUEST_URI']), 'option=com_installer'))) || ((1 == $pluginParams->def('module_bkp', 0)) && (false !== strpos(strtolower($_SERVER['REQUEST_URI']), 'option=com_modules'))) || ((1 == $pluginParams->def('plugin_bkp', 0)) && (false !== strpos(strtolower($_SERVER['REQUEST_URI']), 'option=com_plugins'))) || ((1 == $pluginParams->def('template_bkp', 0)) && (false !== strpos(strtolower($_SERVER['REQUEST_URI']), 'option=com_templates'))) || ((1 == $pluginParams->def('language_bkp', 0)) && (false !== strpos(strtolower($_SERVER['REQUEST_URI']), 'option=com_languages')))) {
189 $admin_bkp = true;
190 }
191 //if((strpos(strtolower($_SERVER['REQUEST_URI']),'administrator')!==false)&&(strpos(strtolower($_SERVER['REQUEST_URI']),'option=com_plugins')!==false)){ // RRG 19/01/2012 backup not only for plugins
192 // RRG 30/03/2013 added params for admin refresh backups
193 //if((strpos(strtolower($_SERVER['REQUEST_URI']),'administrator')!==false) {
194 if ((false !== strpos(strtolower($_SERVER['REQUEST_URI']), 'administrator')) && (true == $admin_bkp)) {
195 //if($pluginParams->def('test',0)==1){
196 $testsave = $pluginParams->def('test', 0);
197 if (1 == ($testsave)) {
198 $create = true;
199 }
200 }
201 $time = time();
202 if (($time > $backuptime) || $create) {
203 unlink(JPATH_SITE . '/plugins/system/lazydbbackup/dumps/' . $fname);
204 while ($backuptime < $time) {
205 $backuptime += $interval;
206 }
207 $fname = JPATH_SITE . '/plugins/system/lazydbbackup/dumps/lazydbbackup_checkfile.' . $backuptime;
208 if (!touch($fname)) {
209 return;
210 }
211 $f = fopen($fname, 'w');
212 fputs($f, $interval);
213 fclose($f);
214
215 $db = JFactory::getDBO();
216 $config = JFactory::getConfig();
217 $lb_abspath = JPATH_SITE;
218 $lb_host = $config->get('host');
219 $lb_user = $config->get('user');
220 $lb_password = $config->get('password');
221 $lb_db = $config->get('db');
222 $lb_mailfrom = $config->get('mailfrom');
223 $lb_fromname = $config->get('fromname');
224 //$lb_livesite = JURI::root(); // 17/05/2013
225 $mediapath = $lb_abspath . '/plugins/system/lazydbbackup/dumps';
226 $checkfilename = 'lazydbbackup_checkfile';
227 //$today = date("Y-m-d_H-i-s"); // RRG 2014/06/11 time added
228 setlocale(LC_ALL, 0); /// RRG 2019/04/01
229 //$today = date("Y-m-dTH-i-s"); // RRG 2018/12/01 replace "_" by "T"
230 $today = JHtml::_('date', $today1, JText::_('Y-m-dTH-i-s')); /// RRG 2019/04/02
231 // create file name
232 // RRG 16/01/2014 replace / and \ in site name
233 $sitename = suppr_accents($config->get('sitename'));
234 $sitename = str_replace(DIRECTORY_SEPARATOR, '_', $sitename);
235 $sitename = str_replace(' ', '-', $sitename);
236
237 if (!$pluginParams->def('name_format', 0)) {
238 //$filename=$config->get('sitename').'.'.$today;
239 $filename = $sitename . '.' . $today;
240 } else {
241 //$filename=$today.'.'.$config->get('sitename');
242 $filename = $today . '.' . $sitename;
243 }
244
245 $filename .= '.' . str_pad(rand(0, 999), 3, '0', STR_PAD_LEFT);
246 $filename .= ($pluginParams->def('compress', 0) ? '.sql.gz' : '.sql');
247 //teste("$filename");
248 // No need to do the require beforehand if not ok to continue, so we'll do it here to save an eeny weeny amount of time
249 require_once $lb_abspath . '/plugins/system/lazydbbackup/lazydbbackup/mysql_db_backup.class.php';
250 // Alternative location for Bot query
251 $deletefile = $pluginParams->def('deletefile', 1);
252 $compress = $pluginParams->def('compress', 0);
253 $backuppath = $pluginParams->def('backuppath', 0);
254 $sendmail = $pluginParams->def('sendmail', 1);
255
256 // Now we need to create the backup
257 $backup_obj = new LazyDbBackup_MySQL_DB_Backup();
258 $result = $this->LazyDbBackupBackup($backup_obj, $lb_host, $lb_user, $lb_password, $lb_db, $pluginParams, $mediapath, $lb_fromname, $compress, $backuppath, $filename);
259 $backupfile = $backup_obj->lazydbbackup_file_name;
260 //test("$backupFile");
261 if ($pluginParams->def('encrypt', 0)) {
262 $password = $pluginParams->def('password', 0);
263 if (!empty($password)) {
264 if ('WIN' === strtoupper(substr(PHP_OS, 0, 3))) {
265 $zipcmd = $lb_abspath . '/plugins/system/lazydbbackup/lazydbbackup/zip.exe';
266 exec("$zipcmd -j -P $password \"$backupfile.zip\" \"$backupfile\"");
267 } else {
268 $zipcmd = 'zip';
269 exec("$zipcmd -j -P $password \"$backupfile.zip\" \"$backupfile\"");
270 }
271 unlink($backupfile);
272 $backupfile .= '.zip';
273 }
274 }
275
276 if ($sendmail) {
277 // and email it to wherever
278 //if(!$emailresult=$this->LazyDbBackupEmail($pluginParams,$lb_mailfrom,$lb_fromname,$backupfile,$result['output'],$lb_livesite)) { // 09/12/2014
279 if (!$emailresult = $this->LazyDbBackupEmail($pluginParams, $lb_mailfrom, $lb_fromname, $backupfile, $result['output'])) {
280 return false;
281 }
282 if ('1' == $deletefile && !empty($backupfile) && (false == !$emailresult)) {
283 unlink($backupfile);
284 }
285 }
286 // Job done
287 return true;
288 }
289 }
290
291 //function LazyDbBackupEmail($pluginParams,$lb_mailfrom,$lb_fromname,$attachment,$Body,$lb_livesite) { 17/05/2013
292 public function LazyDbBackupEmail($pluginParams, $lb_mailfrom, $lb_fromname, $attachment, $body)
293 {
294 $mail = JFactory::getMailer();
295 $toemail = $pluginParams->def('recipient', '');
296 $subject = $pluginParams->def('subject', 'Mysql backup');
297 //$fromname = $pluginParams->def( 'fromname', $lb_fromname ); /// 28/06/2013 not used
298
299 if (empty($toemail)) {
300 $toemail = $lb_mailfrom;
301 }
302 // Thanks to Gerald Berger for correction on multiple email addresses
303 if (strpos($toemail, ',')) {
304 //$ToEmail2 = split(",",$ToEmail ); // 19/04/2013 replace split
305 $toemail2 = explode(',', $toemail);
306 } else {
307 $toemail2 = $toemail;
308 }
309
310 $mail->addAttachment($attachment);
311 //$mail->addRecipient($ToEmail);
312 // Thanks to Gerald Berger for correction on multiple email addresses
313 $mail->addRecipient($toemail2);
314 //$mail->setSubject($subject.' '.$lb_livesite); // 17/05/2013
315 // 16/05/2013
316 $lb_addurl = $pluginParams->def('addurl', 1);
317 if ($lb_addurl) {
318 $mail->setSubject($subject . ' ' . JURI::root());
319 } else {
320 $mail->setSubject($subject);
321 }
322 $mail->setBody($body);
323 if (!$mail->Send()) {
324 return false;
325 } else {
326 return true;
327 }
328 }
329
330 // RRG 26/03/2018 envoi mail signalant une nouvelle version
331 public function LazyDbBackupUpdEmail($pluginParams, $lb_mailfrom, $lb_fromname, $nv_version)
332 {
333 $updmail = JFactory::getMailer();
334 $updtoemail = $pluginParams->def('update_recipient', '');
335 if (empty($updtoemail)) {
336 $updtoemail = $pluginParams->def('recipient', '');
337 }
338 $updsubject = JText::_('PLG_LAZYDBBKP_UPDATE_SUBJECT') . $nv_version;
339 $urlmaj = JUri::root() . 'administrator/index.php?option=com_installer&view=update';
340 $updbody = JText::_('PLG_LAZYDBBKP_UPDATE_BODY') . $urlmaj;
341
342 if (empty($updtoemail)) {
343 $updtoemail = $lb_mailfrom;
344 }
345 if (strpos($updtoemail, ',')) {
346 $updtoemail2 = explode(',', $updtoemail);
347 } else {
348 $updtoemail2 = $updtoemail;
349 }
350
351 $updmail->addRecipient($updtoemail2);
352 $lb_updaddurl = $pluginParams->def('addurl', 1);
353 if ($lb_updaddurl) {
354 $updmail->setSubject($updsubject . ' ' . JURI::root());
355 } else {
356 $updmail->setSubject($updsubject);
357 }
358 $updmail->setBody($updbody);
359 if (!$updmail->Send()) {
360 return false;
361 } else {
362 return true;
363 }
364 }
365
366 public function LazyDbBackupBackup(&$backup_obj, $lb_host, $lb_user, $lb_password, $lb_db, $pluginParams, $mediapath, $lb_fromname, $compress, $backuppath, $filename = '')
367 {
368 $body = $pluginParams->def('body', 'Mysql backup from ' . $lb_fromname);
369 $drop_tables = $pluginParams->def('drop_tables', 1);
370 $create_tables = $pluginParams->def('create_tables', 1);
371 $struct_only = $pluginParams->def('struct_only', 1);
372 $site_only = $pluginParams->def('site_only', 1);
373 $foreign_key = $pluginParams->def('foreign_key', 1);
374 $locks = $pluginParams->def('locks', 1);
375 $comments = $pluginParams->def('comments', 1);
376 if (!empty($backuppath) && is_dir($backuppath) && @is_writable($backuppath)) {
377 $backup_dir = $backuppath;
378 } else {
379 $backup_dir = $mediapath;
380 }
381
382 // START - REQUIRED SETUP VARIABLES
383 $backup_obj->server = $lb_host;
384 $backup_obj->port = 3306;
385 $backup_obj->username = $lb_user;
386 $backup_obj->password = $lb_password;
387 $backup_obj->database = $lb_db;
388 // Tables you wish to backup. All tables in the database will be backed up if this array is null.
389 $backup_obj->tables = [];
390 // END - REQUIRED SETUP VARIABLES
391
392 // START - OPTIONAL PREFERENCE VARIABLES
393 // Add DROP TABLE IF EXISTS queries before CREATE TABLE in backup file.
394 $backup_obj->drop_tables = $drop_tables;
395 // No table structure will be backed up if false
396 $backup_obj->create_tables = $create_tables;
397 // Only site's tables will be backed up if true.
398 $backup_obj->site_only = $site_only;
399 // disable foreign key checks if true.
400 $backup_obj->foreign_key = $foreign_key;
401 // Add LOCK TABLES before data backup and UNLOCK TABLES after
402 $backup_obj->struct_only = $struct_only;
403 // Add LOCK TABLES before data backup and UNLOCK TABLES after
404 $backup_obj->locks = $locks;
405 // Include comments in backup file if true.
406 $backup_obj->comments = $comments;
407 // Directory on the server where the backup file will be placed. Used only if task parameter equals MSX_SAVE.
408 $backup_obj->backup_dir = $backup_dir . '/';
409 // Default file name format.
410 $backup_obj->fname_format = 'd_m_Y';
411 // Values you want to be intrerpreted as NULL
412 $backup_obj->null_values = [];
413
414 $savetask = MSX_SAVE;
415 // Optional name of backup file if using 'MSX_APPEND', 'MSX_SAVE' or 'MSX_DOWNLOAD'. If nothing is passed, the default file name format will be used.
416 // $filename = '';
417 // END - REQUIRED EXECUTE VARIABLES
418 $result_bk = $backup_obj->Execute($savetask, $filename, $compress);
419 if (!$result_bk) {
420 $output = $backup_obj->error;
421 } else {
422 //$output = $body.': ' . strftime('%A %d %B %Y - %T ') . ' '; // RRG 24/0/2018
423 //setlocale (LC_ALL,0);
424 //$today = date("Y-m-dTH:i:s");
425 //$output = $body.': ' . JHtml::_('date', now, JText::_('DATE_FORMAT_LDB'));
426 //$output = $body.': ' . JHtml::_('date', $today, JText::_('DATE_FORMAT_LDB')); /// RRG 11/08/2018
427 $output = $body . ': ' . JHtml::_('date', $today1, JText::_('DATE_FORMAT_LDB')); /// RRG 2019/04/02
428 }
429
430 return ['result' => $result_bk, 'output' => $output];
431 }
432}