source: extensions/BatchDownloader/include/BatchDownloader.class.php @ 23290

Last change on this file since 23290 was 23290, checked in by mistic100, 11 years ago

WORK IN PROGRESS: allow to download derivatives
TODO: only working with images files, finish download page

File size: 24.3 KB
Line 
1<?php
2defined('BATCH_DOWNLOAD_PATH') or die('Hacking attempt!');
3
4class BatchDownloader
5{
6  private $conf;
7  private $data;
8  private $images;
9 
10  /**
11   * __construct
12   * @param: mixed set id (##|'new')
13   * @param: array images
14   * @param: string set type ('album'|'tag'|'selection')
15   * @param: int set type id (for retrieving album infos for instance)
16   * @param: string size to download
17   */
18  function __construct($set_id, $images=array(), $type=null, $type_id=null, $size='original')
19  {
20    global $user, $conf;
21   
22    $this->conf = $conf['batch_download'];
23    $this->data = array(
24      'id' => 0,
25      'user_id' => $user['id'],
26      'date_creation' => '0000-00-00 00:00:00',
27      'type' => null,
28      'type_id' => null,
29      'size' => 'original',
30      'nb_zip' => 0,
31      'last_zip' => 0,
32      'nb_images' => 0,
33      'total_size' => 0,
34      'estimated_total_size' => 0,
35      'status' => 'new',
36      );
37    $this->images = array();
38   
39    // load specific set
40    if (preg_match('#^[0-9]+$#', $set_id))
41    {
42      $query = '
43SELECT *
44  FROM '.BATCH_DOWNLOAD_TSETS.'
45  WHERE
46    id = '.$set_id.'
47    '.(!is_admin() ? 'AND user_id = '.$this->data['user_id'] : null).'
48;';
49      $result = pwg_query($query);
50     
51      if (pwg_db_num_rows($result))
52      {
53        $this->data = array_merge(
54          $this->data,
55          pwg_db_fetch_assoc($result)
56          );
57       
58        // make sur all pictures of the set exist
59        $query = '
60DELETE FROM '.BATCH_DOWNLOAD_TIMAGES.'
61  WHERE image_id NOT IN (
62    SELECT id FROM '.IMAGES_TABLE.'
63    )
64;';
65        pwg_query($query);
66     
67        $query = '
68SELECT
69    image_id,
70    zip
71  FROM '.BATCH_DOWNLOAD_TIMAGES.'
72  WHERE set_id = '.$this->data['id'].'
73;';
74        $this->images = simple_hash_from_query($query, 'image_id', 'zip');
75       
76        if ( $this->data['status'] != 'done' and count($this->images) != $this->data['nb_images'] )
77        {
78          $this->updateParam('nb_images', count($this->images));
79        }
80      }
81      else
82      {
83        throw new Exception(l10n('Invalid dowload set'));
84      }
85    }
86    // create a new set
87    else if ($set_id == 'new')
88    {
89      if ($size != 'original')
90      {
91        $type_map = array_keys(ImageStdParams::get_defined_type_map());
92        if (!in_array($size, $type_map))
93        {
94          throw new Exception(sprintf(l10n('Invalid size %s'), $size));
95        }
96      }
97 
98      $this->data['type'] = $type;
99      $this->data['type_id'] = $type_id;
100      $this->data['size'] = $size;
101     
102      $query = '
103INSERT INTO '.BATCH_DOWNLOAD_TSETS.'(
104    user_id,
105    date_creation,
106    type,
107    type_id,
108    size,
109    nb_zip,
110    last_zip,
111    nb_images,
112    total_size,
113    status
114  )
115  VALUES(
116    '.$this->data['user_id'].',
117    NOW(),
118    "'.$this->data['type'].'",
119    "'.$this->data['type_id'].'",
120    "'.$this->data['size'].'",
121    0,
122    0,
123    0,
124    0,
125    "new"
126  )
127;';
128      pwg_query($query);
129      $this->data['id'] = pwg_db_insert_id();
130     
131      $date = pwg_query('SELECT FROM_UNIXTIME(NOW());');
132      list($this->data['date_creation']) = pwg_db_fetch_row($date);
133     
134      if (!empty($images))
135      {
136        $this->addImages($images);
137      }
138    }
139    else
140    {
141      trigger_error('BatchDownloader::__construct, invalid input parameter', E_USER_ERROR);
142    }
143  }
144 
145  /**
146   * updateParam
147   * @param: string param name
148   * @param: mixed param value
149   */
150  function updateParam($name, $value)
151  {
152    $this->data[$name] = $value;
153    pwg_query('UPDATE '.BATCH_DOWNLOAD_TSETS.' SET '.$name.' = "'.$value.'" WHERE id = '.$this->data['id'].';');
154  }
155 
156  /**
157   * getParam
158   * @param: string param name
159   * @return: mixed param value
160   */
161  function getParam($name)
162  {
163    return $this->data[$name];
164  }
165 
166  /**
167   * getImages
168   * @return: array
169   */
170  function getImages()
171  {
172    return $this->images;
173  }
174 
175  /**
176   * isInSet
177   * @param: int image id
178   * @return: bool
179   */
180  function isInSet($image_id)
181  {
182    return array_key_exists($image_id, $this->images);
183  }
184 
185  /**
186   * removeImages
187   * @param: array image ids
188   */
189  function removeImages($image_ids)
190  {
191    if (empty($image_ids) or !is_array($image_ids)) return;
192   
193    foreach ($image_ids as $image_id)
194    {
195      unset($this->images[ $image_id ]);
196    }
197   
198    $query = '
199DELETE FROM '.BATCH_DOWNLOAD_TIMAGES.'
200  WHERE
201    set_id = '.$this->data['id'].'
202    AND image_id IN('.implode(',', $image_ids).')
203;';
204    pwg_query($query);
205   
206    $this->updateParam('nb_images', count($this->images));
207  }
208 
209  /**
210   * addImages
211   * @param: array image ids
212   */
213  function addImages($image_ids)
214  {
215    global $conf;
216   
217    if (empty($image_ids) or !is_array($image_ids)) return;
218   
219    $query = '
220SELECT id, file
221  FROM '.IMAGES_TABLE.'
222  WHERE id IN('.implode(',', array_unique($image_ids)).')
223;';
224    $images = simple_hash_from_query($query, 'id', 'file');
225   
226    $inserts = array();
227   
228    foreach ($images as $image_id => $file)
229    {
230      if ($this->isInSet($image_id)) continue;
231      if (!in_array(get_extension($file), $conf['batch_download']['allowed_ext'])) continue;
232     
233      $this->images[ $image_id ] = 0;
234      array_push($inserts, array('set_id'=>$this->data['id'], 'image_id'=>$image_id, 'zip'=>0));
235    }
236   
237    mass_inserts(
238      BATCH_DOWNLOAD_TIMAGES,
239      array('set_id', 'image_id', 'zip'),
240      $inserts
241      );
242     
243    $this->updateParam('nb_images', count($this->images));
244  }
245 
246  /**
247   * clearImages
248   */
249  function clearImages()
250  {
251    $this->images = array();
252   
253    $query = '
254DELETE FROM '.BATCH_DOWNLOAD_TIMAGES.'
255  WHERE set_id = '.$this->data['id'].'
256;';
257    pwg_query($query);
258  }
259 
260  /**
261   * get missing derivatives files
262   * @return: array of i.php urls
263   */
264  function getMissingDerivatives($update=false)
265  {
266    if ($this->data['size'] == 'original')
267    {
268      return array();
269    }
270   
271    global $conf;
272   
273    $root_url = get_root_url();
274    $uid = '&b='.time();
275   
276    $params = ImageStdParams::get_by_type($this->data['size']);
277    $last_mod_time = $params->last_mod_time;
278   
279    $image_ids = array_keys($this->images);
280    $to_update = $urls = $inserts = array();
281   
282    $conf['question_mark_in_urls'] = $conf['php_extension_in_urls'] = true;
283    $conf['derivative_url_style'] = 2; //script
284   
285    // images which we need to update stats
286    if ($update)
287    {
288      $query = '
289SELECT image_id, filemtime FROM '.IMAGE_SIZES_TABLE.'
290  WHERE image_id IN('.implode(',', $image_ids).')
291    AND type = "'.$this->data['size'].'"
292;';
293      $registered = array_from_query($query, 'image_id', 'filemtime');
294     
295      $to_update = array_filter($registered, create_function('$t', 'return $t<'.$last_mod_time.';'));
296      $to_update = array_merge($to_update, array_diff($image_ids, $registered));
297    }
298   
299    $query = '
300SELECT id, path, representative_ext, width, height, rotation
301  FROM '.IMAGES_TABLE.'
302  WHERE id IN('.implode(',', $image_ids).')
303  ORDER BY id DESC
304;';
305
306    $result = pwg_query($query);
307    while ($row = pwg_db_fetch_assoc($result))
308    {
309      $src_image = new SrcImage($row);
310      if ($src_image->is_mimetype()) continue;
311     
312      $derivative = new DerivativeImage($this->data['size'], $src_image);
313      // if ($this->data['size'] != $derivative->get_type()) continue;
314     
315      $filemtime = @filemtime($derivative->get_path());
316     
317      if ($filemtime===false || $filemtime<$last_mod_time)
318      {
319        $urls[] = $root_url.$derivative->get_url().$uid;
320      }
321      else if ($update && in_array($row['id'], $to_update))
322      {
323        $imagesize = getimagesize($derivative->get_path());
324       
325        $inserts[ $row['id'] ] = array(
326          'image_id' => $row['id'],
327          'type' => $this->data['size'],
328          'width' => $imagesize[0],
329          'height' => $imagesize[1],
330          'filesize' => filesize($derivative->get_path())/1024,
331          'filemtime' => $filemtime,
332          );
333      }
334    }
335   
336    if (!empty($inserts))
337    {
338      $query = '
339DELETE FROM '.IMAGE_SIZES_TABLE.'
340  WHERE image_id IN('.implode(',', array_keys($inserts)).')
341;';
342      pwg_query($query);
343     
344      mass_inserts(
345        IMAGE_SIZES_TABLE,
346        array('image_id','type','width','height','filesize'),
347        $inserts
348        );
349    }
350   
351    return $urls;
352  }
353 
354  /**
355   * deleteLastArchive
356   */
357  function deleteLastArchive()
358  {
359    $zip_path = $this->getArchivePath();
360    if (file_exists($zip_path))
361    {
362      unlink($zip_path);
363    }
364  }
365 
366  /**
367   * createNextArchive
368   * @param: bool force all elements in one archive
369   * @return: string zip path or false
370   */
371  function createNextArchive($force_one_archive=false)
372  {
373    // set already downloaded (we should never be there !)
374    if ( $this->data['status'] == 'done' or $this->data['nb_images'] == 0 )
375    {
376      trigger_error('BatchDownloader::createNextArchive, the set is empty', E_USER_ERROR);
377    }
378   
379    global $conf;
380   
381    // first zip
382    if ($this->data['last_zip'] == 0)
383    {
384      $this->updateParam('status', 'download');
385     
386      // limit number of elements
387      if ($this->data['nb_images'] > $this->conf['max_elements'])
388      {
389        $images_ids = array_slice(array_keys($this->images), 0, $this->conf['max_elements']);
390        $this->clearImages();
391        $this->addImages($images_ids);
392      }
393     
394      $this->getEstimatedArchiveNumber();
395     
396      $this->updateParam('date_creation', date('Y-m-d H:i:s'));
397    }
398   
399    // get next images of the set
400    $images_to_add = array();
401    foreach ($this->images as $image_id => $zip_id)
402    {
403      if ($zip_id != 0) continue; // here are already added images
404      array_push($images_to_add, $image_id);
405    }
406   
407    if (count($images_to_add))
408    {
409      $query = '
410SELECT
411    id, name, file, path,
412    representative_ext, rotation,
413    filesize, width, height
414  FROM '.IMAGES_TABLE.'
415  WHERE id IN ('.implode(',', $images_to_add).')
416;';
417      $images_to_add = hash_from_query($query, 'id');
418     
419      if ($this->data['size'] != 'original')
420      {
421        $query = '
422SELECT image_id, filesize
423  FROM '.IMAGE_SIZES_TABLE.'
424  WHERE image_id IN ('.implode(',', array_keys($images_to_add)).')
425    AND type = "'.$this->data['size'].'"
426;';
427        $filesizes = simple_hash_from_query($query, 'image_id', 'filesize');
428      }
429     
430      // open zip
431      $this->updateParam('last_zip', $this->data['last_zip']+1);
432      $zip_path = $this->getArchivePath();
433      $zip = new myZip($zip_path, isset($conf['batch_download_force_pclzip']));
434     
435      // add images until size limit is reach, or all images are added
436      $images_added = array();
437      $total_size = 0;
438      foreach ($images_to_add as $row)
439      {
440        if ($this->data['size'] == 'original')
441        {
442          $zip->addFile(PHPWG_ROOT_PATH . $row['path'], $row['id'].'_'.stripslashes(get_filename_wo_extension($row['file'])).'.'.get_extension($row['path']));
443          $total_size+= $row['filesize'];
444        }
445        else
446        {
447          $src_image = new SrcImage($row);
448          $derivative = new DerivativeImage($this->data['size'], $src_image);
449          $path = $derivative->get_path();
450     
451          $zip->addFile($path, $row['id'].'_'.stripslashes(get_filename_wo_extension(basename($path))).'.'.get_extension($path));
452          $total_size+= $filesizes[ $row['id'] ];
453        }
454       
455        array_push($images_added, $row['id']);
456        $this->images[ $row['id'] ] = $this->data['last_zip'];
457       
458        if ($total_size >= $this->conf['max_size']*1024 and !$force_one_archive) break;
459      }
460     
461      $this->updateParam('total_size', $this->data['total_size'] + $total_size);
462     
463      // archive comment
464      $comment = 'Generated on '.date('r').' with PHP '.PHP_VERSION.' by Piwigo Batch Downloader.';
465      $comment.= "\n".$conf['gallery_title'].' - '.get_absolute_root_url();
466      if (!empty($conf['batch_download_comment']))
467      {
468        $comment.= "\n\n".wordwrap(remove_accents($conf['batch_download_comment']), 60);
469      }
470      $zip->setArchiveComment($comment);
471     
472      $zip->close();
473     
474      // update database
475      $query = '
476UPDATE '.BATCH_DOWNLOAD_TIMAGES.'
477  SET zip = '.$this->data['last_zip'].'
478  WHERE
479    set_id = '.$this->data['id'].'
480    AND image_id IN('.implode(',', $images_added).')
481;';
482      pwg_query($query);
483     
484      // all images added ?
485      if (count($images_to_add) == count($images_added))
486      {
487        $this->updateParam('status', 'done');
488      }
489     
490      // over estimed
491      if ($this->data['status'] == 'done')
492      {
493        $this->updateParam('nb_zip', $this->data['last_zip']);
494      }
495      // under estimed
496      else if ($this->data['last_zip'] == $this->data['nb_zip'])
497      {
498        $this->updateParam('nb_zip', $this->data['last_zip']+1);
499      }
500     
501      return $zip_path;
502    }
503    else
504    {
505      return false;
506    }
507  }
508 
509  /**
510   * getEstimatedTotalSize
511   * @return: int
512   */
513  function getEstimatedTotalSize($force=false)
514  {
515    if ($this->data['status'] == 'done') return $this->data['total_size'];
516    if ($this->data['nb_images'] == 0) return 0;
517    if ( !empty($this->data['estimated_total_size']) and !$force ) return $this->data['estimated_total_size'];
518   
519    $image_ids = array_slice(array_keys($this->images), 0, $this->conf['max_elements']);
520   
521    if ($this->data['size'] == 'original')
522    {
523      $query = '
524SELECT SUM(filesize) AS total
525  FROM '.IMAGES_TABLE.'
526  WHERE id IN ('.implode(',', $image_ids).')
527;';
528    }
529    else
530    {
531      $query = '
532SELECT SUM(filesize) AS total
533  FROM '.IMAGE_SIZES_TABLE.'
534  WHERE image_id IN ('.implode(',', $image_ids).')
535;';
536    }
537   
538    list($total) = pwg_db_fetch_row(pwg_query($query));
539    $this->data['estimated_total_size'] = $total;
540    return $total;
541  }
542 
543  /**
544   * getEstimatedArchiveNumber
545   * @return: int
546   */
547  function getEstimatedArchiveNumber()
548  {
549    if ($this->data['status'] == 'done') return $this->data['nb_zip'];
550   
551    return ceil( $this->getEstimatedTotalSize() / ($this->conf['max_size']*1024) );
552  }
553 
554  /**
555   * getDownloadList
556   * @return: string html
557   */
558  function getDownloadList($url='')
559  {
560    if ($this->data['nb_images'] == 0)
561    {
562      return '<b>'.l10n('No archive').'</b>';
563    }
564   
565    $root_url = get_root_url();
566   
567    $out = '';
568    for ($i=1; $i<=$this->getEstimatedArchiveNumber(); $i++)
569    {
570      $out.= '<li id="zip-'.$i.'">';
571     
572      if ($this->data['status'] == 'done' or $i < $this->data['last_zip']+1)
573      {
574        $out.= '<img src="'.$root_url.BATCH_DOWNLOAD_PATH.'template/drive.png"> Archive #'.$i.' (already downloaded)';
575      }
576      else if ($i == $this->data['last_zip']+1)
577      {
578          $out.= '<a href="'.add_url_params($url, array('set_id'=>$this->data['id'],'zip'=>$i)).'" rel="nofollow" style="font-weight:bold;"' 
579            .($i!=1 ? ' onClick="return confirm(\''.addslashes(sprintf(l10n('Starting download Archive #%d will destroy Archive #%d, be sure you finish the download. Continue ?'), $i, $i-1)).'\');"' : null).
580            '><img src="'.$root_url.BATCH_DOWNLOAD_PATH.'template/drive_go.png"> Archive #'.$i.' (ready)</a>';
581      }
582      else
583      {
584        $out.= '<img src="'.$root_url.BATCH_DOWNLOAD_PATH.'template/drive.png"> Archive #'.$i.' (pending)';
585      }
586     
587      $out.= '</li>';
588    }
589   
590    return $out;
591  }
592 
593  /**
594   * getArchivePath
595   * @param: int archive number
596   * @return: string
597   */
598  function getArchivePath($i=null)
599  {
600    if (!file_exists(BATCH_DOWNLOAD_LOCAL . 'u-' .$this->data['user_id']. '/'))
601    {
602      mkgetdir(BATCH_DOWNLOAD_LOCAL . 'u-' .$this->data['user_id']. '/');
603    }
604   
605    if ($i === null) $i = $this->data['last_zip'];
606    $set = $this->getNames();
607   
608    include_once(PHPWG_ROOT_PATH . 'admin/include/functions.php');
609   
610    $path = BATCH_DOWNLOAD_LOCAL . 'u-'. $this->data['user_id'] . '/';
611    $path.= !empty($this->conf['archive_prefix']) ? $this->conf['archive_prefix'] . '_' : null;
612    $path.= get_username($this->data['user_id']) . '_';
613    $path.= $set['BASENAME'] . '_';
614    $path.= $this->data['user_id'] . $this->data['id'];
615    $path.= $this->getEstimatedArchiveNumber()!=1 ? '_part' . $i : null;
616    $path.= '.zip';
617   
618    return $path;
619  }
620 
621  /**
622   * getNames
623   * @return: array
624   */
625  function getNames()
626  {   
627    switch ($this->data['type'])
628    {
629      // calendar
630      case 'calendar':
631      {
632        global $conf, $page;
633        $old_page = $page;
634       
635        $fields = array(
636          'created' => l10n('Creation date'),
637          'posted' => l10n('Post date'),
638          );
639       
640        $chronology = explode('-', $this->data['type_id']);
641        $page['chronology_field'] = $chronology[0];
642        $page['chronology_style'] = $chronology[1];
643        $page['chronology_view'] = $chronology[2];
644        $page['chronology_date'] = array_splice($chronology, 3);
645       
646        if (!class_exists('Calendar'))
647        {
648          include_once(PHPWG_ROOT_PATH.'include/calendar_'. $page['chronology_style'] .'.class.php');
649        }
650        $calendar = new Calendar();
651        $calendar->initialize('');
652        $display_name = strip_tags($calendar->get_display_name());
653       
654        $set['NAME'] = l10n('Calendar').': '.$fields[$page['chronology_field']].$display_name;
655        $set['sNAME'] = l10n('Calendar').': '.ltrim($display_name, $conf['level_separator']);
656        $set['BASENAME'] = 'calendar-'.$page['chronology_field'].'-'.implode('-',$page['chronology_date']);
657       
658        $page = $old_page;
659        break;
660      }
661     
662      // category
663      case 'category':
664      {
665        $category = get_cat_info($this->data['type_id']);
666        if ($category == null)
667        {
668          $set['NAME'] = l10n('Album').': #'.$this->data['type_id'].' (deleted)';
669          $set['BASENAME'] = 'album'.$this->data['type_id'];
670        }
671        else
672        {
673          $set['NAME'] = l10n('Album').': '.get_cat_display_name($category['upper_names']);
674          $set['sNAME'] = l10n('Album').': '.trigger_event('render_category_name', $category['name']);
675          $set['COMMENT'] = trigger_event('render_category_description', $category['comment']);
676         
677          if (!empty($category['permalink']))
678          {
679            $set['BASENAME'] = 'album-'.$category['permalink'];
680          }
681          else if ( ($name = str2url($category['name'])) != null )
682          {
683            $set['BASENAME'] = 'album-'.$name;
684          }
685          else
686          {
687            $set['BASENAME'] = 'album'.$this->data['type_id'];
688          }
689        }
690        break;
691      }
692     
693      // flat
694      case 'flat':
695      {
696        $set['NAME'] = l10n('Whole gallery');
697        $set['BASENAME'] = 'all-gallery';
698        break;
699      }
700     
701      // tags
702      case 'tags':
703      {
704        $tags = find_tags(explode(',', $this->data['type_id']));
705        $set['NAME'] = l10n('Tags').': ';
706        $set['BASENAME'] = 'tags';
707       
708        $first = true;
709        foreach ($tags as $tag)
710        {
711          if ($first) $first = false;
712          else $set['NAME'].= ', ';
713          $set['NAME'].=
714            '<a href="' . make_index_url(array('tags'=>array($tag))) . '">'
715            .trigger_event('render_tag_name', $tag['name'])
716            .'</a>';
717          $set['BASENAME'].= '-'.$tag['url_name'];
718        }
719        break;
720      }
721     
722      // search
723      case 'search':
724      {
725        $set['NAME'] = '<a href="'.make_index_url(array('section'=>'search', 'search'=>$this->data['type_id'])).'">'.l10n('Search').'</a>';
726        $set['BASENAME'] = 'search'.$this->data['type_id'];
727        break;
728      }
729     
730      // favorites
731      case 'favorites':
732      {
733        $set['NAME'] = '<a href="'.make_index_url(array('section'=>'favorites')).'">'.l10n('Your favorites').'</a>';
734        $set['BASENAME'] = 'favorites';
735        break;
736      }
737     
738      // most_visited
739      case 'most_visited':
740      {
741        $set['NAME'] = '<a href="'.make_index_url(array('section'=>'most_visited')).'">'.l10n('Most visited').'</a>';
742        $set['BASENAME'] = 'most-visited';
743        break;
744      }
745     
746      // best_rated
747      case 'best_rated':
748      {
749        $set['NAME'] = '<a href="'.make_index_url(array('section'=>'best_rated')).'">'.l10n('Best rated').'</a>';
750        $set['BASENAME'] = 'best-rated';
751        break;
752      }
753     
754      // list
755      case 'list':
756      {
757        $set['NAME'] = l10n('Random');
758        $set['BASENAME'] = 'random';
759        break;
760      }
761     
762      // recent_pics
763      case 'recent_pics':
764      {
765        $set['NAME'] = '<a href="'.make_index_url(array('section'=>'recent_pics')).'">'.l10n('Recent photos').'</a>';
766        $set['BASENAME'] = 'recent-pics';
767        break;
768      }
769     
770      // collection
771      case 'collection':
772      {
773        try
774        {
775          if (!class_exists('UserCollection')) throw new Exception();
776          $UserCollection = new UserCollection($this->data['type_id']);
777          $infos = $UserCollection->getCollectionInfo();
778          $set['NAME'] = l10n('Collection').': <a href="'.$infos['U_PUBLIC'].'">'.$UserCollection->getParam('name').'</a>';
779         
780          if ( ($name = str2url($UserCollection->getParam('name'))) != null)
781          {
782            $set['BASENAME'] = 'collection-'.$name;
783          }
784          else
785          {
786            $set['BASENAME'] = 'collection'.$this->data['type_id'];
787          }
788        }
789        catch (Exception $e)
790        {
791          $set['NAME'] = l10n('Collection').': #'.$this->data['type_id'].' (deleted)';
792          $set['BASENAME'] = 'collection'.$this->data['type_id'];
793        }
794        break;
795      }
796    }
797   
798    if (!isset($set['sNAME']))    $set['sNAME'] = strip_tags($set['NAME']);
799    if (!isset($set['COMMENT']))  $set['COMMENT'] = null;
800    if (!isset($set['BASENAME'])) $set['BASENAME'] = $this->data['type'] . $this->data['type_id'];
801   
802    return $set;
803  }
804 
805  /**
806   * getSetInfo
807   * @return: array
808   */
809  function getSetInfo()
810  {   
811    $set = array(
812      'NB_IMAGES' =>     $this->data['nb_images'],
813      'NB_ARCHIVES' =>   $this->data['status']=='new' ? l10n('unknown') : $this->getEstimatedArchiveNumber(),
814      'STATUS' =>        $this->data['status'],
815      'LAST_ZIP' =>      $this->data['last_zip'],
816      'TOTAL_SIZE' =>    $this->data['status']=='new' ? l10n('unknown') : ceil($this->getEstimatedTotalSize()/1024),
817      // 'LINKS' =>         $this->getDownloadList(BATCH_DOWNLOAD_PUBLIC . 'init_zip'),
818      'DATE_CREATION' => format_date($this->data['date_creation'], true),
819      'SIZE_ID' =>       $this->data['size'],
820      'SIZE' =>          l10n($this->data['size']),
821      );
822     
823    if ($this->data['size'] != 'original')
824    {
825      $params = ImageStdParams::get_by_type($this->data['size']);
826      $set['SIZE_INFO'] = $params->sizing->ideal_size[0].' x '.$params->sizing->ideal_size[1];
827    }
828   
829    return array_merge($set, $this->getNames());
830  }
831 
832  /**
833   * delete
834   */
835  function delete()
836  {
837    $this->deleteLastArchive();
838    $this->clearImages();
839    pwg_query('DELETE FROM '.BATCH_DOWNLOAD_TSETS.' WHERE id = '.$this->data['id'].';');
840  }
841}
842
843
844/**
845 * small class implementing basic ZIP creation
846 * with ZipArchive or PclZip
847 */
848class myZip
849{
850  private $lib;
851  private $zip;
852 
853  function __construct($zip_path, $pclzip=false)
854  {
855    if ( class_exists('ZipArchive') and !$pclzip )
856    {
857      $this->lib = 'zipa';
858     
859      $this->zip = new ZipArchive;
860      if ($this->zip->open($zip_path, ZipArchive::CREATE) !== true)
861      {
862        trigger_error('BatchDownloader::createNextArchive, unable to open ZIP archive (ZipArchive)', E_USER_ERROR);
863      }
864    }
865    else
866    {
867      $this->lib = 'pcl';
868     
869      require_once(PHPWG_ROOT_PATH.'admin/include/pclzip.lib.php');
870      $this->zip = new PclZip($zip_path);
871     
872      // create a temporary file for archive creation
873      touch(BATCH_DOWNLOAD_LOCAL.'temp.txt');
874     
875      if ($this->zip->create(BATCH_DOWNLOAD_LOCAL.'temp.txt', PCLZIP_OPT_REMOVE_ALL_PATH) == 0)
876      {
877        trigger_error('BatchDownloader::createNextArchive, unable to open ZIP archive (PclZip)', E_USER_ERROR);
878      }
879     
880      unlink(BATCH_DOWNLOAD_LOCAL.'temp.txt');
881      $this->zip->delete(PCLZIP_OPT_BY_NAME, 'temp.txt');
882    }
883  }
884 
885  function addFile($path, $filename)
886  {
887    if ($this->lib == 'zipa')
888    {
889      $this->zip->addFile($path, $filename);
890    }
891    else
892    {
893      $this->zip->add($path, PCLZIP_OPT_REMOVE_ALL_PATH);
894    }
895  }
896 
897  function setArchiveComment($comment)
898  {
899    if ($this->lib == 'zipa')
900    {
901      $this->zip->setArchiveComment($comment);
902    }
903  }
904 
905  function close()
906  {
907    if ($this->lib == 'zipa')
908    {
909      $this->zip->close();
910    }
911  }
912}
913
914?>
Note: See TracBrowser for help on using the repository browser.