source: extensions/Download_Multi/include/class.inc.php @ 3986

Last change on this file since 3986 was 3986, checked in by flipflip, 15 years ago

Initial Import

File size: 35.7 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Mod Name : Download_multi                                             |
4// | Mod Version : 0.9-1                                                   |
5// | Mod Orignal author: Tboris                                            |
6// | Mod Second author : Cestlodovic                                       |
7// | Mod Version author : FlipFlip <flipflip@free.fr>                      |
8// | Mod description :                                                     |
9// | Ce module est base sur le module existant pour le telechargement,     |
10// | cette version permet le telechargement sur plusieurs pages.           |
11// +-----------------------------------------------------------------------+
12// | This program is free software; you can redistribute it and/or modify  |
13// | it under the terms of the GNU General Public License as published by  |
14// | the Free Software Foundation                                          |
15// |                                                                       |
16// | This program is distributed in the hope that it will be useful, but   |
17// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
18// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
19// | General Public License for more details.                              |
20// |                                                                       |
21// | You should have received a copy of the GNU General Public License     |
22// | along with this program; if not, write to the Free Software           |
23// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
24// | USA.               '                                                  |
25// +-----------------------------------------------------------------------+
26
27class DownloadMulti {
28  var $plugin_name, $plugin_path, $plugin_url;
29  var $my_config;
30
31  function DownloadMulti($plugin_name, $plugin_path, $plugin_url) {
32    // Args
33    $this->plugin_name = $plugin_name;
34    $this->plugin_path = $plugin_path;
35    $this->plugin_url = $plugin_url;
36    // handler
37    $this->initialize_event_handler($plugin_name, $plugin_path, $plugin_url);
38  }
39
40  function initialize_event_handler() {
41    global $user;
42    $this->load_config(); // Chargement de la configuration
43    $this->load_lang(); // Chargement des langues
44
45    if ($user['status'] != 'guest' AND !empty($this->my_config['group_id'])) {
46      // Récupération du groupe utilisateur autorisé à télécharger les images
47      $query = '
48        SELECT group_id
49        FROM '.USER_GROUP_TABLE.'
50        WHERE user_id = '.$user['id'].'
51      ;';
52      $result = pwg_query($query);
53
54      // Parcours la requête SQL
55      while($row = mysql_fetch_array($result)) {
56        if(in_array($row['group_id'], $this->my_config['group_id'])) {
57          // Mise à jour du panier
58          add_event_handler('loc_begin_index', array(&$this, 'DmCart'));
59
60          // Ajout d'élements dans le header
61          // Ne pas inclure dans les pages d'administration
62          add_event_handler('loc_end_page_header', array(&$this, 'DmHeader'));
63
64          // Ajout une entrée dans le menubar
65          add_event_handler('blockmanager_apply', array(&$this, 'DmMenubar'));
66          add_event_handler('blockmanager_register_blocks', array(&$this, 'register_dm_menubar_blocks'));
67
68          // ---- Thumbnail
69          // Entrée HTML du formulaire pour la sélection des images
70          add_event_handler('loc_begin_index_thumbnails', array(&$this, 'DmFormThumbnail'));
71
72          // Affichage des cases à cocher sous les vignettes
73          add_event_handler('loc_end_index_thumbnails', array($this, 'DmCategoryThumbnail'), 50, 2);
74
75          // Affichage du cadre en bas de thumbnail.tpl
76          add_event_handler('loc_begin_index_thumbnails', array(&$this, 'DmCategoryDefault'));
77
78          if (script_basename() == 'popuphelp') {
79            // ---- Aide
80            add_event_handler('get_popup_help_content', array(&$this, 'get_popup_help_content'), EVENT_HANDLER_PRIORITY_NEUTRAL, 2);
81          }
82        }
83      }
84    }
85
86    if (is_admin()) {
87      // ---- Administration
88      add_event_handler('get_admin_plugin_menu_links', array(&$this, 'plugin_admin_menu')); // Menu d'administration
89    }
90  }
91
92  /* this function initialize var $my_config with default values */
93  function init_config() {
94    $this->my_config = array();
95  }
96
97  //Chargement de la configuration
98  function load_config() {
99    $this->init_config();
100
101    $query = '
102      SELECT value
103      FROM '.CONFIG_TABLE.'
104      WHERE param = \'downloadmulti_config\'
105    ;';
106
107    $result = pwg_query($query);
108
109    if($result) {
110      $row = mysql_fetch_row($result);
111      if(is_string($row[0])) {
112        $config = unserialize($row[0]);
113        reset($config);
114        while (list($key, $val) = each($config)) {
115          $this->my_config[$key] = $val;
116        }
117      }
118    }
119  }
120
121  // Sauvegarde de la configuration
122  function save_config() {
123    $query = '
124      REPLACE INTO '.CONFIG_TABLE.'
125      VALUES(
126        \'downloadmulti_config\',
127        \''.serialize($this->my_config).'\',
128        \'Configuration de Download Multi\')
129    ;';
130
131    $result = pwg_query($query);
132
133    if($result) {
134      return true;
135    } else {
136      return false;
137    }
138  }
139
140  // Affichage du lien dans la barre
141  // menu administrateur
142  function plugin_admin_menu($menu) {
143    array_push($menu,
144      array(
145        'NAME' => 'Download Multi',
146        'URL' => get_admin_plugin_menu_link($this->plugin_path.'admin/admin.php')
147      )
148    );
149    return $menu;
150  }
151
152  // Chargement des fichiers langues
153  function load_lang() {
154    load_language('plugin.lang', $this->plugin_path);
155  }
156
157  // Gestion de l'aide pour le plugin
158  function get_popup_help_content($popup_help_content, $page) {
159    if (in_array($page, array($this->plugin_name, 'DownloadMulti'))) {
160      $help_content =
161        load_language('help/'.$page.'.html', $this->plugin_path, array('return'=>true));
162    } else {
163      $help_content = false;
164    }
165
166    if ($help_content == false) {
167      return $popup_help_content;
168    } else {
169      return $popup_help_content.$help_content;
170    }
171  }
172
173  // Enregistrement du menu pour la gestion dans l'administration
174  function register_dm_menubar_blocks($menu_ref_arr) {
175    $menu = & $menu_ref_arr[0];
176    if ($menu->get_id() != 'menubar')
177      return;
178    $menu->register_block(new RegisteredBlock('mbDownloadMulti', 'Download Multi', 'DM'));
179  }
180
181  // Chargement de fichier dans l'entête du template
182  function DmHeader() {
183    global $template;
184
185    $DmUrlJs = get_root_url().'plugins/'.$this->plugin_name.'/include/DownloadMulti.js';
186    $DmUrlCss = get_root_url().'plugins/'.$this->plugin_name.'/include/DownloadMulti.css';
187    $template->append(
188        'head_elements',
189        '<script type="text/javascript" src="'.$DmUrlJs.'"></script>'."\n".
190        '<link rel="stylesheet" type="text/css" href="'.$DmUrlCss.'">'."\n"
191    );
192  }
193
194  // Gestion de l'affichage dans le menubar
195  function DmMenuBar($menu_ref_arr) {
196        global $template;
197
198    $menu = & $menu_ref_arr[0];
199
200    $template->assign('NBIMAGES', $this->DmCountCart());
201
202    if (($block = $menu->get_block( 'mbDownloadMulti' )) != null) {
203      $block->set_title('Download Multi');
204      $block->template = $this->plugin_path.'template/DmMenu.tpl';
205    }
206  }
207
208  // Compte le nombre d'images selectionné
209  // dans le panier du visiteur
210  function DmCountCart() {
211        global $prefixeTable, $user, $lang;
212
213    $query = '
214      SELECT COUNT(*) AS nb_line
215      FROM '.$prefixeTable.'download_multi
216      WHERE id_user = '.$user['id'].'
217    ;';
218    $row = mysql_fetch_array(pwg_query($query));
219
220    // Si le nombre de lignes est supérieur à 0
221    // alors on affiche le message d'avertissement
222    // utilisateur
223        if ($row['nb_line'] > 0) {
224      $nbImages = sprintf($lang['dl_message_cart'], $row['nb_line']);
225    } else {
226      $nbImages = $lang['dl_empty_cart'];
227        }
228
229        return $nbImages;       
230  }
231
232  // Mise à jour du panier
233  function DmCart() {
234    if (isset($_POST['action'])) {
235      $this->DmControle();
236    }
237  }
238
239  // Affiche l'entrée HTML du formulaire
240  function DmFormThumbnail() {
241    global $template;
242    $template->concat('PLUGIN_INDEX_CONTENT_BEGIN', '<form id="dl" class="dl" action="'.duplicate_index_url().'" name="dl" method="post">');
243   
244  }
245
246  // Affiche les cases à cocher derrière le nom de l'image
247  function DmCategoryThumbnail($tpl_var) {
248    foreach($tpl_var as $cle=>$valeur) {
249      $tpl_var[$cle]['NAME'] = $tpl_var[$cle]['NAME'].'&nbsp;<input type="checkbox" id="id_images" name="id_images[]" value="'.$tpl_var[$cle]['ID'].'">';
250    }
251
252    return $tpl_var;
253  }
254
255  // Affichage du formulaire sous les vignettes
256  function DmCategoryDefault() {
257    global $user, $template, $lang;
258
259    // Intégration du formulaire sous les images
260    $template->set_filenames(
261      array('DownloadMulti_category' => $this->plugin_path.'template/DmCategory.tpl')
262    );
263
264        $list_dl = array('thumbnail' => $lang['dl_thumbnail'], 'normal' => $lang['dl_normal']);                                 
265
266    // Si l'utilisateur n'a pas le droit aux hautes définitions
267    // alors la ligne de téléchargement des hautes définitions
268    // ne s'affiche pas.
269    if($user['enabled_high'] == 1) {
270      $list_dl['high'] = $lang['dl_high'];
271    }
272
273        $template->assign('type', $list_dl);
274        $template->assign('select', $this->my_config['select_dl']);
275       
276    // Gestion du template
277    $dm_html = $template->parse('DownloadMulti_category', true);
278    $template->concat('PLUGIN_INDEX_CONTENT_END', $dm_html);
279  }
280
281  // Controle les valeurs envoyés par le formulaire
282  // Crée les répertoires zip_archive et celui de l'utilisateur
283  // si ils n'existent pas
284  function DmControle() {
285    global $template, $lang, $user, $errors;
286    $errors = array();
287
288    if(isset($_POST['id_images'])) {
289      $id_images = $_POST['id_images'];
290    }
291
292    if(isset($_POST['mode'])) {
293      $mode = $_POST['mode'];
294    }
295
296    // Test si au moins une image à été
297    // sélectionné
298    if(count($id_images) == 1) {
299      array_push($errors, $lang['dl_choice_image']);
300    }
301
302    // Test le répertoire zip_archive
303    // Si il n'existe pas le script le créé
304    // Action nécessaire pour résoudre le problème de droit chez certains hébergeurs
305    $dir = $this->plugin_path;
306    if(!is_dir($dir.'zip_archive/')) {
307      umask(0000);
308      if(!mkdir($dir.'zip_archive/', 0755)) {
309        array_push($errors, $lang['dl_dir_zip']);
310      }
311    }
312
313    // Création du répertoire de l'utilisateur avec sont id user
314    if(!is_dir($dir.'zip_archive/'.$user['id'])) {
315      umask(0000);
316      if(!mkdir($dir.'zip_archive/'.$user['id'], 0755)) {
317        array_push($errors, $lang['dl_dir_zip']);
318      }
319    }
320    clearstatcache();
321
322    // Si il n'y a aucunes erreurs
323    // on continue l'ajout dans la panier
324    if(count($errors) == 0) {
325      $this->DmAddPicture($id_images, $mode);
326      $this->DmCountCart();
327    }
328  }
329
330  /* Ajoute les images dans le panier
331  *  $id_images --> Liste des images sélectionnés
332  *  $mode      --> Type d'images ajouter (thumbnail, normal, high) */
333  function DmAddPicture($id_images, $mode) {
334    global $user, $prefixeTable, $template, $lang, $errors;
335
336    switch($mode) {
337      case 'thumbnail':
338        // Insertion des vignettes dans la base de données
339        for($i=0;$i<count($id_images);$i++) {
340          if(!empty($id_images[$i])) {
341            // Sélection des informations sur l'image
342            $query = '
343              SELECT id, name, file, path, tn_ext
344              FROM '.IMAGES_TABLE.'
345              WHERE id = \''.$id_images[$i].'\'
346            ;';
347            $row = mysql_fetch_array(pwg_query($query));
348
349            $file = get_thumbnail_path($row);
350
351            // Contrôle si l'image est un fichier distant
352            // Si c'est le cas alors un message
353            // d'erreur est généré
354            if(url_is_remote($file)) {
355              if($row['name'] == '') {
356                array_push($errors, $row['file'].$lang['dl_no_download_http']);
357              } else {
358                array_push($errors, $row['name'].$lang['dl_no_download_http']);
359              }
360            } else {
361              // Poids de l'image
362              $fic_size = filesize($file);
363
364              $query = '
365                INSERT INTO '.$prefixeTable.'download_multi (id_image, id_user, filesize, type)
366                VALUES (\''.$id_images[$i].'\', \''.$user['id'].'\', \''.$fic_size.'\', \'t\')
367                ON DUPLICATE KEY UPDATE
368                  id_user = \''.$user['id'].'\'
369                  AND id_image = \''.$id_images[$i].'\'
370                  AND type = \'t\'
371                ;';
372              $result = pwg_query($query);
373            }
374          }
375        }
376
377        if(count($errors) != 0) {
378          $template->assign('errors', $errors);
379        }
380      break;
381
382      case 'normal':
383        // Pas propre mais nécessaire pour get_image_path
384        include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
385
386        // Insertion des photos normal dans la base de données
387        for($i=0;$i<count($id_images);$i++) {
388          // Sélection des informations sur l'image
389          $query = '
390            SELECT id, file, path
391            FROM '.IMAGES_TABLE.'
392            WHERE id = \''.$id_images[$i].'\'
393          ;';
394          $row = mysql_fetch_array(pwg_query($query));
395
396          $file = get_image_path($row);
397
398          // Contrôle si l'image est un fichier distant
399          // Si c'est le cas alors un message
400          // d'erreur est généré
401          if (url_is_remote($file)) {
402            if($row['name'] == '') {
403              array_push($errors, $row['file'].$lang['dl_no_download_http']);
404            } else {
405              array_push($errors, $row['name'].$lang['dl_no_download_http']);
406            }
407          } else {
408            // Taille de l'image
409            $fic_size = filesize($file);
410
411            $query = '
412              INSERT INTO '.$prefixeTable.'download_multi (id_image, id_user, filesize, type)
413              VALUES (\''.$id_images[$i].'\', \''.$user['id'].'\', \''.$fic_size.'\', \'n\')
414              ON DUPLICATE KEY UPDATE
415                id_user = \''.$user['id'].'\'
416                AND id_image = \''.$id_images[$i].'\'
417                AND type = \'n\'
418            ;';
419            $result = pwg_query($query);
420          }
421        }
422
423        if(count($errors) != 0) {
424          $template->assign('errors', $errors);
425        }
426      break;
427
428      case 'high':
429        // Pas propre mais nécessaire pour get_image_path
430        include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
431
432        // Insertion des hautes définitions dans la base de données
433        for($i=0;$i<count($id_images);$i++) {
434          // Sélection des informations sur l'image
435          $query = '
436            SELECT id, name, file, path, has_high
437            FROM '.IMAGES_TABLE.'
438            WHERE id = \''.$id_images[$i].'\'
439          ;';
440          $row = mysql_fetch_array(pwg_query($query));
441
442          $file = get_high_path($row);
443
444          // Si une image sélectionné ne possède pas
445          // de version haute définition alors
446          // on renseigne le tableau qui
447          // contient la liste des images
448          if($row['has_high'] == false) {
449                if($row['name'] == '') {
450                  array_push($errors, $row['file'].$lang['dl_no_download_high']);
451            } else {
452                  array_push($errors, $row['name'].$lang['dl_no_download_high']);
453            }
454          } else if (url_is_remote($file)) {
455            // Contrôle si l'image est un fichier distant
456            // Si c'est le cas alors un message
457            // d'erreur est généré
458            if($row['name'] == '') {
459              array_push($errors, $row['file'].$lang['dl_no_download_http']);
460            } else {
461              array_push($errors, $row['name'].$lang['dl_no_download_http']);
462            }
463          } else {
464            // contrôle si le fichier existe, dans le cas contraire
465            // rien n'est inséré et le traitement continue sur les images suivantes.
466            if(file_exists($file)) {
467              // Taille de l'image
468              $fic_size = filesize($file);
469
470              $query = '
471                INSERT INTO '.$prefixeTable.'download_multi (id_image, id_user, filesize, type)
472                VALUES (\''.$id_images[$i].'\', \''.$user['id'].'\', \''.$fic_size.'\', \'h\')
473                ON DUPLICATE KEY UPDATE
474                  id_user = \''.$user['id'].'\'
475                  AND id_image = \''.$id_images[$i].'\'
476                AND type = \'h\'
477              ;';
478              $result = pwg_query($query);
479            }
480          }
481        }
482      break;
483    }
484  }
485
486  /* Préfix des fichiers zip générés
487  * Si l'utilisateur vient de la page thumbnail
488  * il lui est demander de saisir un nom pour
489  * la génération des fichiers zip */
490  function DmPanierPrefixZip() {
491    global $template;
492
493    $template->assign('prefix',
494      array(
495        'VALUE' => $this->my_config['prefix'],
496        'F_ACTION' => 'DmPanier.php?DmAction=genfic',
497      )
498    );
499  }
500
501  /* Si la page est rechargé par le bouton "Supprimer"
502  * du formulaire il ne faut pas recréer les fichiers */
503  function DmPanierGenZip($prefix) {
504    global $prefixeTable, $user, $template, $lang, $counter, $conf;
505
506    $errors = array();
507
508    if(preg_match('/[^a-z0-9\-_]/', $prefix)) {
509      array_push($errors, $lang['dl_no_prefix']);
510    } else {
511      if($this->my_config['create_category']) {
512        // Sélection des photos par rapport à l'id utilisateur
513        // Récupération de la structure des catégories
514        $query = '
515            SELECT '.$prefixeTable.'download_multi.id_image, '.$prefixeTable.'download_multi.filesize, '.$prefixeTable.'download_multi.type,
516            t_images.file, t_images.path, t_images.tn_ext, t_images.has_high, t_images.id, t_images.name,
517            t_category.category_id
518            FROM '.$prefixeTable.'download_multi
519            INNER JOIN '.IMAGES_TABLE.' t_images
520              ON t_images.id = '.$prefixeTable.'download_multi.id_image
521            INNER JOIN '.IMAGE_CATEGORY_TABLE.' t_category
522                ON t_images.id = t_category.image_id
523            WHERE id_user = '.$user['id'].'
524        ;';
525
526      } else {
527        $query = '
528            SELECT '.$prefixeTable.'download_multi.id_image, '.$prefixeTable.'download_multi.filesize, '.$prefixeTable.'download_multi.type,
529            '.IMAGES_TABLE.'.file, '.IMAGES_TABLE.'.path, '.IMAGES_TABLE.'.tn_ext, '.IMAGES_TABLE.'.has_high, '.IMAGES_TABLE.'.id
530            FROM '.$prefixeTable.'download_multi
531            INNER JOIN '.IMAGES_TABLE.'
532            ON '.IMAGES_TABLE.'.id = '.$prefixeTable.'download_multi.id_image
533            WHERE id_user = '.$user['id'].'
534        ;';
535      }
536     
537      $result = pwg_query($query);
538      $nbresult = mysql_num_rows($result);
539
540      // Si le nombre d'enregistrement est inférieur à
541      // alors il n'y a pas de fichier proposé au téléchargement
542      if ($nbresult == 0) {
543        array_push($errors, $lang['dl_no_file']);
544      } else {
545        // Découpage pour la création
546        // de la barre de progression
547        $indice = floor(100 / $nbresult);
548        $indices = 0;
549
550        $template->set_filenames(
551          array('DownloadMulti_waiting' => $this->plugin_path.'/template/DmWaiting.tpl')
552        );
553
554        $template->assign('waiting', $indices);
555       
556        $i = 0;             
557        $fichiers = array();
558        $counter = 0;
559       
560        while ($row = mysql_fetch_array($result)) {
561          $cat_info = '';
562          $cat_name = '';         
563          $c = 0;
564
565          if ($row['type'] == 't') {
566            $fichiers[$i]['path'] = get_thumbnail_path($row);
567            $fichiers[$i]['poids'] = $row['filesize'];
568           
569            // Récupération du fichier originel ou alors du nom
570            // de fichier créé par pLoader
571            // ToDo : A MODIFIER LORSQUE LE NOM DU VRAI FICHIER SERA STOCKE PAR Piwigo   
572            if (empty($row['name'])) {
573              $fichiers[$i]['name'] = $conf['prefix_thumbnail'].$row['file'];
574            } else {
575              $fichiers[$i]['name'] = $conf['prefix_thumbnail'].$row['name'];
576            }
577           
578            if($this->my_config['create_category']) {
579              // Recréation de la structure des catégories     
580              $cat_info = get_cat_info($row['category_id']);
581              if (!empty($cat_info['uppercats'])) {
582                        $nb_cat = count(explode(',', $cat_info['uppercats']));
583                        while ($c < $nb_cat) {
584                      $cat_name = $cat_name.$cat_info['upper_names'][$c]['name'].'/';             
585                      $c++;             
586                }
587                $fichiers[$i]['cat_name'] = $cat_name.'thumbnails/';
588              }                         
589            } else {
590              $fichiers[$i]['cat_name'] = $fichiers[$i]['path'];
591            }
592            $i++;
593          }
594
595          if ($row['type'] == 'n') {
596                include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
597                $fichiers[$i]['path'] = get_image_path($row);
598            $fichiers[$i]['poids'] = $row['filesize'];
599           
600            // Récupération du fichier original ou alors du nom
601            // de fichier créé par pLoader
602            // ToDo : A MODIFIER LORSQUE LE NOM DU VRAI FICHIER SERA STOCKE PAR Piwigo           
603            if (empty($row['name'])) {
604              $fichiers[$i]['name'] = $row['file'];
605            } else {
606              $fichiers[$i]['name'] = $row['name'];
607            }
608           
609            if($this->my_config['create_category']) {
610              // Recréation de la structure des catégories 
611              $cat_info = get_cat_info($row['category_id']);
612              if (!empty($cat_info['uppercats'])) {
613                        $nb_cat = count(explode(',', $cat_info['uppercats']));
614                        while ($c < $nb_cat) {
615                      $cat_name = $cat_name.$cat_info['upper_names'][$c]['name'].'/';             
616                      $c++;             
617                }
618                $fichiers[$i]['cat_name'] = $cat_name;
619              }
620            } else {
621              $fichiers[$i]['cat_name'] = $fichiers[$i]['path'];
622            }             
623            $i++;
624          }
625
626          if ($row['type'] == 'h') {
627                include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
628                $fichiers[$i]['path'] = get_high_path($row);
629            $fichiers[$i]['poids'] = $row['filesize'];
630           
631            // Récupération du fichier originel ou alors du nom
632            // de fichier créé par pLoader 
633            // ToDo : A MODIFIER LORSQUE LE NOM DU VRAI FICHIER SERA STOCKE PAR Piwigo             
634            if (empty($row['name'])) {
635              $fichiers[$i]['name'] = $row['file'];
636            } else {
637              $fichiers[$i]['name'] = $row['name'];
638            }
639
640            if($this->my_config['create_category']) {
641              // Recréation de la structure des catégories
642              $cat_info = get_cat_info($row['category_id']);
643              if (!empty($cat_info['uppercats'])) {
644                        $nb_cat = count(explode(',', $cat_info['uppercats']));
645                        while ($c < $nb_cat) {
646                      $cat_name = $cat_name.$cat_info['upper_names'][$c]['name'].'/';             
647                      $c++;             
648                }
649                $fichiers[$i]['cat_name'] = $cat_name.'pwg_high/';
650              }
651            } else {
652              $fichiers[$i]['cat_name'] = $fichiers[$i]['path'];
653            }             
654            $i++;
655          }
656        }
657
658        $fic_size = 0;
659
660        if(class_exists('zipArchive')) {         
661          // Création de la 1ere archive
662          $this->DmCreateZip($prefix);
663
664          foreach($fichiers as $cle => $file) {
665                $indices = $indice + $indices;
666
667            // Contrôle la taille de l'archive
668            // si elle est inférieur à la configuration
669            // la boucle continue d'ajouter des fichiers
670            if ($file['poids'] >= $this->my_config['archive_size']) {
671              $this->DmAddZip($file['path'], $file['cat_name'].$file['name']);
672              $this->DmCloseZip();
673
674              $counter = $counter + 1;
675              $this->DmCreateZip($prefix);
676              $fic_size = 0;
677            } else if($fic_size <= $this->my_config['archive_size']) {
678              $this->DmAddZip($file['path'], $file['cat_name'].$file['name']);
679            } else {
680              // si la taille est supérieur à la configuration
681              // alors l'archive précédente est fermé
682              // et une nouvelle est créé
683              $this->DmCloseZip();
684             
685              $this->DmCreateZip($prefix);
686              $this->DmAddZip($file['path'], $file['cat_name'].$file['name']);
687              $fic_size = 0;
688            }
689
690            $fic_size = $file['poids'] + $fic_size;
691
692            // Force l'affichage de la barre de progression
693            if(function_exists('ob_flush')) {
694              $template->assign('waiting', $indices);
695              $dm_html = $template->pparse('DownloadMulti_waiting');
696              $template->concat('PLUGIN_INDEX_PANIER_BEFORE', $dm_html);
697              echo '&nbsp;';
698              @ob_flush();
699              flush();
700              @ob_flush();
701              flush();             
702            }
703          }
704
705          $this->DmCloseZip();
706        } 
707          // ANNULE : http://fr.piwigo.org/forum/viewtopic.php?pid=118210#p118210
708          /*else {
709          require_once $this->plugin_path.'include/pclzip.lib.php';
710
711          $fic_size = 0;
712          $create_zip_archive = 1;
713          $i = 0;
714          foreach($fichiers as $cle => $file) {
715                $indices = $indice + $indices;
716            if ($file['poids'] >= $this->my_config['archive_size']) {
717              $this->DmPclZipCreateZip($prefix, $file['path']);
718            } else if ($fic_size <= $this->my_config['archive_size']) {
719              $this->DmPclZipAddZip($prefix, $file['path'], $create_zip_archive);
720              $fic_size = $file['poids'] + $fic_size;
721            } /*else {
722              $create_zip_archive = 1;
723              $this->DmPclZipAddZip($prefix, $file['path'], $create_zip_archive);
724              $fic_size = 0;   
725            }                           
726
727            // Force l'affichage de la barre de progression
728            if(function_exists('ob_flush')) {
729              $template->assign('waiting', $indices);
730              $dm_html = $template->pparse('DownloadMulti_waiting');
731              $template->concat('PLUGIN_INDEX_PANIER_BEFORE', $dm_html);
732              echo '&nbsp;';
733              @ob_flush();
734              flush();
735              @ob_flush();
736              flush();
737            }
738          }
739        }*/
740      }
741    }
742    // Liste le répertoire de l'utlilisateur
743    $this->DmPanierListeDir();
744
745    if(count($errors) != 0) {
746      $template->assign('errors', $errors);
747      $this->DmPanierPrefixZip();
748    }
749  }
750
751  // Créé l'archive avec son nom
752  // avec la lib PclZip
753  // ANNULE : http://fr.piwigo.org/forum/viewtopic.php?pid=118210#p118210
754  /*function DmPclZipCreateZip($prefix, $path) {
755    global $template, $lang, $errors;
756
757    $fichier_zip = $this->DmCreateNameZip($prefix);
758    $archive = new PclZip($fichier_zip);
759
760    if ($this->my_config['active_comment']) {
761      $action = $archive->create($path,
762        PCLZIP_OPT_REMOVE_PATH, PHPWG_ROOT_PATH.'upload',
763        PCLZIP_OPT_ADD_PATH, $this->my_config['prefix_dir'],
764        PCLZIP_OPT_COMMENT, $this->my_config['comment'],
765        PCLZIP_OPT_NO_COMPRESSION
766      );
767    } else {
768      $action = $archive->create($path,
769        PCLZIP_OPT_REMOVE_PATH, PHPWG_ROOT_PATH.'upload',
770        PCLZIP_OPT_ADD_PATH, $this->my_config['prefix_dir'],
771        PCLZIP_OPT_NO_COMPRESSION
772      );
773    }
774
775    if ($action == 0) {
776      array_push($errors, $lang['dl_no_file']);
777      $template->assign('errors', $errors);
778    }   
779  }*/
780
781  // ANNULE : http://fr.piwigo.org/forum/viewtopic.php?pid=118210#p118210
782  // Ajout des fichiers dans l'archive
783  // avec la lib PclZip
784  /*function DmPclZipAddZip($prefix, $path, $create_zip_archive) {
785    global $errors, $template, $lang, $create_zip_archive, $user;
786   
787    if ($create_zip_archive == 1) {
788      $fichier_zip = $this->DmCreateNameZip($prefix);   
789      $create_zip_archive = 0;
790    } else {
791      $fichier_zip = get_class_vars(get_class($action));
792      $fichier_zip = $fichier_zip['zipname'];
793    }
794   
795    $archive = new PclZip($fichier_zip);
796   
797    if ($this->my_config['active_comment']) {
798      $action = $archive->add($path,
799        PCLZIP_OPT_REMOVE_PATH, PHPWG_ROOT_PATH.'upload',
800        PCLZIP_OPT_ADD_PATH, $this->my_config['prefix_dir'],
801        PCLZIP_OPT_COMMENT, $this->my_config['comment'],
802        PCLZIP_OPT_NO_COMPRESSION
803      );
804    } else {
805      $action = $archive->add($path,
806        PCLZIP_OPT_REMOVE_PATH, PHPWG_ROOT_PATH.'upload',
807        PCLZIP_OPT_ADD_PATH, $this->my_config['prefix_dir'],
808        PCLZIP_OPT_NO_COMPRESSION
809      );         
810      var_dump($action);
811    }   
812
813    if ($action == 0) {
814      array_push($errors, $lang['dl_no_file'].'<br />'.$archive->errorInfo(true));
815      $template->assign('errors', $errors);
816    }
817  }*/
818
819  // Génération du nom de fichier zip
820  function DmCreateNameZip($prefix) {
821    global $user, $counter;
822    $dir_zip = $this->plugin_path.'zip_archive/'.$user['id'].'/';
823       
824        // nom du fichier zip
825        $nom_fichier = str_replace('[date]', date('Ymd'), $this->my_config['pattern_name']);
826        $nom_fichier = str_replace('[rand]', rand(1, 2000), $nom_fichier);
827        $nom_fichier = $prefix.$nom_fichier.'_'.$counter;
828       
829    $fichier_zip = $dir_zip.$nom_fichier.'.zip'; // chemin d'accès au fichier zip
830   
831    return $fichier_zip;
832  }
833
834  // Création de l'instance zip
835  // et création de l'archive avec la class zipArchive
836  function DmCreateZip($prefix) {
837    global $zip;
838
839    $fichier_zip = $this->DmCreateNameZip($prefix);
840    $zip = new ZipArchive();
841    $zip->open($fichier_zip, ZIPARCHIVE::CREATE);
842  }
843
844  // Ajout des fichiers dans l'archive
845  // avec la class zipArchive
846  function DmAddZip($path, $file_name) {       
847    global $zip;
848
849    if(!$this->my_config['create_category']) {
850      $file_name = str_replace(PHPWG_ROOT_PATH.'./galleries/', '', $file_name);
851      $file_name = str_replace(PHPWG_ROOT_PATH.'./upload/', '', $file_name);
852    }
853       
854    $zip->addFile($path, $this->my_config['prefix_dir'].'/'.$file_name);
855
856    if($this->my_config['active_comment']) {
857      $zip->setArchiveComment($this->my_config['comment']);
858    }
859  }
860
861  // Fermeture de l'archive
862  // avec la class zipArchive
863  function DmCloseZip() {
864    global $zip;
865    $zip->close();
866  }
867
868  /* Liste le répertoire utilisateur */
869  function DmPanierListeDir() {
870    global $user, $template, $lang, $errors;
871    $dir_zip = $this->plugin_path.'zip_archive/'.$user['id'].'/';
872
873    $errors = array();
874
875    $dir = opendir($dir_zip);
876    while($file = readdir($dir)) {
877      if(!is_file($file) && $file != '.' && $file != '..')  {
878        $tab_file[] = array('file' => $file, 'date' => filemtime($dir_zip.$file));
879      }
880    }
881
882    closedir($dir);
883    clearstatcache();
884
885    if (isset($tab_file)) {
886      $template->assign(
887        array(
888          'F_ACTION' => 'DmPanier.php?DmAction=del'
889        )
890      );
891
892      // Obtient une liste de colonnes
893      foreach ($tab_file as $key => $row) {
894        $file[$key]  = $row['file'];
895        $date[$key] = $row['date'];
896      }
897
898      // Tri les données par volume décroissant, edition croissant
899      // Ajoute $data en tant que dernier paramêtre, pour trier par la clé commune
900      array_multisort($file, SORT_ASC, $date, SORT_DESC, $tab_file);
901
902      foreach($tab_file as $elem) {
903        $tpl_var =
904          array(
905            'FIC_CHEMIN' => $this->plugin_url.'plugins/'.$this->plugin_name.'/zip_archive/'.$user['id'].'/',
906            'FIC_NAME' => $elem['file'],
907            'FIC_DATE' => $this->DmPanierDd($elem['date'])
908        );
909
910        $template->append('telechargements', $tpl_var);
911      }
912    } else {
913      array_push($errors, $lang['dl_no_file']);
914      $template->assign('errors', $errors);
915    }
916  }
917
918  // Vide le panier en cours
919  function DmPanierDelete() {
920    global $user, $prefixeTable;
921    // Suppression des images sélectionné dans une précédente session
922    $query = '
923      DELETE FROM '.$prefixeTable.'download_multi
924      WHERE id_user = \''.$user['id'].'\'
925    ;';
926    $result = pwg_query($query);
927
928    // Optimisation de la table pour éviter la fragmentation
929    // après suppression d'enregistrements
930    $query = '
931      OPTIMIZE TABLE '.$prefixeTable.'download_multi
932    ;';
933    $result = pwg_query($query);
934
935    redirect(duplicate_index_url());
936  }
937
938  /* Suppression des fichiers dans le
939  *  répertoire utilisateur
940  *  $fic --> liste des fichiers  */
941  function DmPanierDelUserDir($fic) {
942    global $user, $prefixeTable;
943    if (isset($fic)) {
944      $dir_zip = $this->plugin_path.'zip_archive/'.$user['id'].'/';
945      foreach($fic as $file) {
946        unlink($dir_zip.$file);
947      }
948      clearstatcache();
949    }
950  }
951
952  /* Renvoie la date */
953  function DmPanierDd($date) {
954    return date("d/m/Y H:i:s", $date);
955  }
956/* ------- Fin de la page DmPanier.php ------ */
957
958/* ------- Section pour le fichier DmPreview.php ------ */
959  /* Affiche la liste des images */
960  function DmPreviewList() {
961    global $prefixeTable, $user, $template, $lang, $errors;
962
963    $errors = array();
964
965    $query = '
966      SELECT *
967      FROM '.$prefixeTable.'download_multi
968      INNER JOIN '.IMAGES_TABLE.'
969      ON '.IMAGES_TABLE.'.id = '.$prefixeTable.'download_multi.id_image
970      WHERE id_user = '.$user['id'].'
971      ORDER BY file
972    ;';
973    $result = pwg_query($query);
974
975    // Si il n'y a pas d'enregistrement
976    // Affiche le message 'panier vide'
977    if (mysql_num_rows($result) == 0) {
978      array_push($errors, $lang['dl_empty_cart']);
979      $template->assign('errors', $errors);
980    } else {
981      while ($row = mysql_fetch_array($result)) {
982
983        $type = $row['type'];
984        switch ($type) {
985          case 't':
986            $txt_type = $lang['dl_type_thumbnail'];
987            $img_type = 'page_white_world.png';
988          break;
989          case 'n':
990            $txt_type = $lang['dl_type_normal'];
991            $img_type = 'page_white_picture.png';
992          break;
993          case 'h':
994            $txt_type = $lang['dl_type_high'];
995            $img_type = 'page_white_camera.png';
996          break;
997        }
998
999        $url = duplicate_picture_url(
1000          array(
1001            'image_id' => $row['id'],
1002            'image_file' => $row['file']
1003          ),
1004          array('start')
1005        );
1006
1007        $thumbnail_url = get_thumbnail_url($row);
1008
1009        $tpl_var =
1010          array(
1011            'F_ID_IMAGE' => $row['id_image'],
1012            'F_TYPE' => $type,
1013            'NAME' => get_thumbnail_title($row),
1014            'TYPE' => $txt_type,
1015            'IMG' => $img_type,
1016            'URL' => $url,
1017            'TN_SRC' => $thumbnail_url
1018          );
1019        $template->append('thumbnails', $tpl_var);
1020      }
1021    }
1022  }
1023
1024  /* Supprime une image
1025  * id_image -> identifiant de l'image
1026  * type -> type de l'image */
1027  function DmPreviewDel($id_image, $type) {
1028    global $prefixeTable;
1029    // Suppression d'une image par rapport à sont id
1030    $query = '
1031      DELETE FROM '.$prefixeTable.'download_multi
1032      WHERE id_image = \''.$id_image.'\'
1033      AND type = \''.$type.'\'
1034    ;';
1035    $result = pwg_query($query);
1036
1037    // Optimisation de la table pour éviter la fragmentation
1038    // après suppression d'enregistrements
1039    $query = '
1040      OPTIMIZE TABLE '.$prefixeTable.'download_multi
1041    ;';
1042
1043    $result = pwg_query($query);
1044  }
1045/* ------- Fin de la page DmPreview.php ------ */
1046
1047/* ------- Administration ------- */
1048  function DmServeurConfiguration() {
1049    global $template;
1050
1051    if(class_exists('zipArchive')) {
1052      $template->assign(
1053          'DmServeurConfiguration',
1054            array(
1055              'ZIP' => 'zipArchive',
1056              'PHP_VERSION' => PHP_VERSION,
1057            )
1058          );
1059    } else {
1060      $template->assign(
1061          'DmServeurConfiguration',
1062            array(
1063              'ZIP' => 'PclZip',
1064              'PHP_VERSION' => PHP_VERSION,
1065            )
1066          );
1067    }
1068  }
1069}
1070?>
Note: See TracBrowser for help on using the repository browser.