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

Last change on this file since 23291 was 23291, checked in by mistic100, 12 years ago

fininalize download page
handle no-image files
correct link error when zips number changes

File size: 25.5 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, 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); // don't give representive_ext
310     
311      // no-image files
312      if ($src_image->is_mimetype())
313      {
314        if ($update && in_array($row['id'], $to_update))
315        {         
316          $inserts[ $row['id'] ] = array(
317            'image_id' => $row['id'],
318            'type' => $this->data['size'],
319            'width' => 0,
320            'height' => 0,
321            'filesize' => filesize(PHPWG_ROOT_PATH.$row['path'])/1024,
322            'filemtime' => filemtime(PHPWG_ROOT_PATH.$row['path']),
323            );
324        }
325      }
326      // images files
327      else
328      {
329        $derivative = new DerivativeImage($this->data['size'], $src_image);
330        // if ($this->data['size'] != $derivative->get_type()) continue;
331       
332        $filemtime = @filemtime($derivative->get_path());
333        $src_mtime = @filemtime(PHPWG_ROOT_PATH.$row['path']);
334        if ($src_mtime===false) continue;
335       
336        if ($filemtime===false || $filemtime<$last_mod_time || $filemtime<$src_mtime)
337        {
338          $urls[] = $root_url.$derivative->get_url().$uid;
339        }
340        else if ($update && in_array($row['id'], $to_update))
341        {
342          $imagesize = getimagesize($derivative->get_path());
343         
344          $inserts[ $row['id'] ] = array(
345            'image_id' => $row['id'],
346            'type' => $this->data['size'],
347            'width' => $imagesize[0],
348            'height' => $imagesize[1],
349            'filesize' => filesize($derivative->get_path())/1024,
350            'filemtime' => $filemtime,
351            );
352        }
353      }
354    }
355   
356    if (!empty($inserts))
357    {
358      $query = '
359DELETE FROM '.IMAGE_SIZES_TABLE.'
360  WHERE image_id IN('.implode(',', array_keys($inserts)).')
361;';
362      pwg_query($query);
363     
364      mass_inserts(
365        IMAGE_SIZES_TABLE,
366        array('image_id','type','width','height','filesize','filemtime'),
367        $inserts
368        );
369    }
370   
371    return $urls;
372  }
373 
374  /**
375   * deleteLastArchive
376   */
377  function deleteLastArchive()
378  {
379    $zip_path = $this->getArchivePath();
380    if (file_exists($zip_path))
381    {
382      unlink($zip_path);
383    }
384  }
385 
386  /**
387   * createNextArchive
388   * @param: bool force all elements in one archive
389   * @return: string zip path or false
390   */
391  function createNextArchive($force_one_archive=false)
392  {
393    // set already downloaded (we should never be there !)
394    if ( $this->data['status'] == 'done' or $this->data['nb_images'] == 0 )
395    {
396      trigger_error('BatchDownloader::createNextArchive, the set is empty', E_USER_ERROR);
397    }
398   
399    global $conf;
400   
401    // first zip
402    if ($this->data['last_zip'] == 0)
403    {
404      $this->updateParam('status', 'download');
405     
406      // limit number of elements
407      if ($this->data['nb_images'] > $this->conf['max_elements'])
408      {
409        $images_ids = array_slice(array_keys($this->images), 0, $this->conf['max_elements']);
410        $this->clearImages();
411        $this->addImages($images_ids);
412      }
413     
414      $this->getEstimatedArchiveNumber();
415     
416      $this->updateParam('date_creation', date('Y-m-d H:i:s'));
417    }
418   
419    // get next images of the set
420    $images_to_add = array();
421    foreach ($this->images as $image_id => $zip_id)
422    {
423      if ($zip_id != 0) continue; // here are already added images
424      array_push($images_to_add, $image_id);
425    }
426   
427    if (count($images_to_add))
428    {
429      $query = '
430SELECT
431    id, name, file, path,
432    rotation, filesize, width, height
433  FROM '.IMAGES_TABLE.'
434  WHERE id IN ('.implode(',', $images_to_add).')
435;';
436      $images_to_add = hash_from_query($query, 'id');
437     
438      if ($this->data['size'] != 'original')
439      {
440        $query = '
441SELECT image_id, filesize
442  FROM '.IMAGE_SIZES_TABLE.'
443  WHERE image_id IN ('.implode(',', array_keys($images_to_add)).')
444    AND type = "'.$this->data['size'].'"
445;';
446        $filesizes = simple_hash_from_query($query, 'image_id', 'filesize');
447      }
448     
449      // open zip
450      $this->updateParam('last_zip', $this->data['last_zip']+1);
451      $zip_path = $this->getArchivePath();
452      $zip = new myZip($zip_path, isset($conf['batch_download_force_pclzip']));
453     
454      // add images until size limit is reach, or all images are added
455      $images_added = array();
456      $total_size = 0;
457      foreach ($images_to_add as $row)
458      {
459        if (!file_exists(PHPWG_ROOT_PATH.$row['path']))
460        {
461          $this->removeImages(array($row['id']));
462          continue;
463        }
464       
465        if ($this->data['size'] == 'original')
466        {
467          $zip->addFile(PHPWG_ROOT_PATH.$row['path'], $row['id'].'_'.stripslashes(get_filename_wo_extension($row['file'])).'.'.get_extension($row['path']));
468          $total_size+= $row['filesize'];
469        }
470        else
471        {
472          $src_image = new SrcImage($row); // don't give representive_ext
473         
474          // no-image files
475          if ($src_image->is_mimetype())
476          {
477            $zip->addFile(PHPWG_ROOT_PATH.$row['path'], $row['id'].'_'.stripslashes(get_filename_wo_extension($row['file'])).'.'.get_extension($row['path']));
478            $total_size+= $row['filesize'];
479          }
480          // images files
481          else
482          {
483            $derivative = new DerivativeImage($this->data['size'], $src_image);
484            $path = $derivative->get_path();
485       
486            $zip->addFile($path, $row['id'].'_'.stripslashes(get_filename_wo_extension(basename($path))).'.'.get_extension($path));
487            $total_size+= $filesizes[ $row['id'] ];
488          }
489        }
490       
491        array_push($images_added, $row['id']);
492        $this->images[ $row['id'] ] = $this->data['last_zip'];
493       
494        if ($total_size >= $this->conf['max_size']*1024 and !$force_one_archive) break;
495      }
496     
497      $this->updateParam('total_size', $this->data['total_size'] + $total_size);
498     
499      // archive comment
500      $comment = 'Generated on '.date('r').' with PHP '.PHP_VERSION.' by Piwigo Batch Downloader.';
501      $comment.= "\n".$conf['gallery_title'].' - '.get_absolute_root_url();
502      if (!empty($conf['batch_download_comment']))
503      {
504        $comment.= "\n\n".wordwrap(remove_accents($conf['batch_download_comment']), 60);
505      }
506      $zip->setArchiveComment($comment);
507     
508      $zip->close();
509     
510      // update database
511      $query = '
512UPDATE '.BATCH_DOWNLOAD_TIMAGES.'
513  SET zip = '.$this->data['last_zip'].'
514  WHERE
515    set_id = '.$this->data['id'].'
516    AND image_id IN('.implode(',', $images_added).')
517;';
518      pwg_query($query);
519     
520      // all images added ?
521      if (count($images_to_add) == count($images_added))
522      {
523        $this->updateParam('status', 'done');
524      }
525     
526      // over estimed
527      if ($this->data['status'] == 'done')
528      {
529        $this->updateParam('nb_zip', $this->data['last_zip']);
530      }
531      // under estimed
532      else if ($this->data['last_zip'] == $this->data['nb_zip'])
533      {
534        $this->updateParam('nb_zip', $this->data['last_zip']+1);
535      }
536     
537      return $zip_path;
538    }
539    else
540    {
541      return false;
542    }
543  }
544 
545  /**
546   * getEstimatedTotalSize
547   * @return: int
548   */
549  function getEstimatedTotalSize($force=false)
550  {
551    if ($this->data['status'] == 'done') return $this->data['total_size'];
552    if ($this->data['nb_images'] == 0) return 0;
553    if ( !empty($this->data['estimated_total_size']) and !$force ) return $this->data['estimated_total_size'];
554   
555    $image_ids = array_slice(array_keys($this->images), 0, $this->conf['max_elements']);
556   
557    if ($this->data['size'] == 'original')
558    {
559      $query = '
560SELECT SUM(filesize) AS total
561  FROM '.IMAGES_TABLE.'
562  WHERE id IN ('.implode(',', $image_ids).')
563;';
564    }
565    else
566    {
567      $query = '
568SELECT SUM(filesize) AS total
569  FROM '.IMAGE_SIZES_TABLE.'
570  WHERE image_id IN ('.implode(',', $image_ids).')
571;';
572    }
573   
574    list($total) = pwg_db_fetch_row(pwg_query($query));
575    $this->data['estimated_total_size'] = $total;
576    return $total;
577  }
578 
579  /**
580   * getEstimatedArchiveNumber
581   * @return: int
582   */
583  function getEstimatedArchiveNumber()
584  {
585    if ($this->data['status'] == 'done') return $this->data['nb_zip'];
586   
587    return ceil( $this->getEstimatedTotalSize() / ($this->conf['max_size']*1024) );
588  }
589 
590  /**
591   * getDownloadList
592   * @return: string html
593   */
594  function getDownloadList($url='')
595  {
596    if ($this->data['nb_images'] == 0)
597    {
598      return '<b>'.l10n('No archive').'</b>';
599    }
600   
601    $root_url = get_root_url();
602   
603    $out = '';
604    for ($i=1; $i<=$this->getEstimatedArchiveNumber(); $i++)
605    {
606      $out.= '<li id="zip-'.$i.'">';
607     
608      if ($this->data['status'] == 'done' or $i < $this->data['last_zip']+1)
609      {
610        $out.= '<img src="'.$root_url.BATCH_DOWNLOAD_PATH.'template/images/drive_error.png"> Archive #'.$i.' (already downloaded)';
611      }
612      else if ($i == $this->data['last_zip']+1)
613      {
614          $out.= '<a href="'.add_url_params($url, array('set_id'=>$this->data['id'],'zip'=>$i)).'" rel="nofollow" style="font-weight:bold;"' 
615            .($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).
616            '><img src="'.$root_url.BATCH_DOWNLOAD_PATH.'template/images/drive_go.png"> Archive #'.$i.' (ready)</a>';
617      }
618      else
619      {
620        $out.= '<img src="'.$root_url.BATCH_DOWNLOAD_PATH.'template/images/drive.png"> Archive #'.$i.' (pending)';
621      }
622     
623      $out.= '</li>';
624    }
625   
626    return $out;
627  }
628 
629  /**
630   * getArchivePath
631   * @param: int archive number
632   * @return: string
633   */
634  function getArchivePath($i=null)
635  {
636    if (!file_exists(BATCH_DOWNLOAD_LOCAL . 'u-' .$this->data['user_id']. '/'))
637    {
638      mkgetdir(BATCH_DOWNLOAD_LOCAL . 'u-' .$this->data['user_id']. '/');
639    }
640   
641    if ($i === null) $i = $this->data['last_zip'];
642    $set = $this->getNames();
643   
644    include_once(PHPWG_ROOT_PATH . 'admin/include/functions.php');
645   
646    $path = BATCH_DOWNLOAD_LOCAL . 'u-'. $this->data['user_id'] . '/';
647    $path.= !empty($this->conf['archive_prefix']) ? $this->conf['archive_prefix'] . '_' : null;
648    $path.= get_username($this->data['user_id']) . '_';
649    $path.= $set['BASENAME'] . '_';
650    $path.= $this->data['user_id'] . $this->data['id'];
651    $path.= '_part' . $i;
652    $path.= '.zip';
653   
654    return $path;
655  }
656 
657  /**
658   * getNames
659   * @return: array
660   */
661  function getNames()
662  {   
663    switch ($this->data['type'])
664    {
665      // calendar
666      case 'calendar':
667      {
668        global $conf, $page;
669        $old_page = $page;
670       
671        $fields = array(
672          'created' => l10n('Creation date'),
673          'posted' => l10n('Post date'),
674          );
675       
676        $chronology = explode('-', $this->data['type_id']);
677        $page['chronology_field'] = $chronology[0];
678        $page['chronology_style'] = $chronology[1];
679        $page['chronology_view'] = $chronology[2];
680        $page['chronology_date'] = array_splice($chronology, 3);
681       
682        if (!class_exists('Calendar'))
683        {
684          include_once(PHPWG_ROOT_PATH.'include/calendar_'. $page['chronology_style'] .'.class.php');
685        }
686        $calendar = new Calendar();
687        $calendar->initialize('');
688        $display_name = strip_tags($calendar->get_display_name());
689       
690        $set['NAME'] = l10n('Calendar').': '.$fields[$page['chronology_field']].$display_name;
691        $set['sNAME'] = l10n('Calendar').': '.ltrim($display_name, $conf['level_separator']);
692        $set['BASENAME'] = 'calendar-'.$page['chronology_field'].'-'.implode('-',$page['chronology_date']);
693       
694        $page = $old_page;
695        break;
696      }
697     
698      // category
699      case 'category':
700      {
701        $category = get_cat_info($this->data['type_id']);
702        if ($category == null)
703        {
704          $set['NAME'] = l10n('Album').': #'.$this->data['type_id'].' (deleted)';
705          $set['BASENAME'] = 'album'.$this->data['type_id'];
706        }
707        else
708        {
709          $set['NAME'] = l10n('Album').': '.get_cat_display_name($category['upper_names']);
710          $set['sNAME'] = l10n('Album').': '.trigger_event('render_category_name', $category['name']);
711          $set['COMMENT'] = trigger_event('render_category_description', $category['comment']);
712         
713          if (!empty($category['permalink']))
714          {
715            $set['BASENAME'] = 'album-'.$category['permalink'];
716          }
717          else if ( ($name = str2url($category['name'])) != null )
718          {
719            $set['BASENAME'] = 'album-'.$name;
720          }
721          else
722          {
723            $set['BASENAME'] = 'album'.$this->data['type_id'];
724          }
725        }
726        break;
727      }
728     
729      // flat
730      case 'flat':
731      {
732        $set['NAME'] = l10n('Whole gallery');
733        $set['BASENAME'] = 'all-gallery';
734        break;
735      }
736     
737      // tags
738      case 'tags':
739      {
740        $tags = find_tags(explode(',', $this->data['type_id']));
741        $set['NAME'] = l10n('Tags').': ';
742        $set['BASENAME'] = 'tags';
743       
744        $first = true;
745        foreach ($tags as $tag)
746        {
747          if ($first) $first = false;
748          else $set['NAME'].= ', ';
749          $set['NAME'].=
750            '<a href="' . make_index_url(array('tags'=>array($tag))) . '">'
751            .trigger_event('render_tag_name', $tag['name'])
752            .'</a>';
753          $set['BASENAME'].= '-'.$tag['url_name'];
754        }
755        break;
756      }
757     
758      // search
759      case 'search':
760      {
761        $set['NAME'] = '<a href="'.make_index_url(array('section'=>'search', 'search'=>$this->data['type_id'])).'">'.l10n('Search').'</a>';
762        $set['BASENAME'] = 'search'.$this->data['type_id'];
763        break;
764      }
765     
766      // favorites
767      case 'favorites':
768      {
769        $set['NAME'] = '<a href="'.make_index_url(array('section'=>'favorites')).'">'.l10n('Your favorites').'</a>';
770        $set['BASENAME'] = 'favorites';
771        break;
772      }
773     
774      // most_visited
775      case 'most_visited':
776      {
777        $set['NAME'] = '<a href="'.make_index_url(array('section'=>'most_visited')).'">'.l10n('Most visited').'</a>';
778        $set['BASENAME'] = 'most-visited';
779        break;
780      }
781     
782      // best_rated
783      case 'best_rated':
784      {
785        $set['NAME'] = '<a href="'.make_index_url(array('section'=>'best_rated')).'">'.l10n('Best rated').'</a>';
786        $set['BASENAME'] = 'best-rated';
787        break;
788      }
789     
790      // list
791      case 'list':
792      {
793        $set['NAME'] = l10n('Random');
794        $set['BASENAME'] = 'random';
795        break;
796      }
797     
798      // recent_pics
799      case 'recent_pics':
800      {
801        $set['NAME'] = '<a href="'.make_index_url(array('section'=>'recent_pics')).'">'.l10n('Recent photos').'</a>';
802        $set['BASENAME'] = 'recent-pics';
803        break;
804      }
805     
806      // collection
807      case 'collection':
808      {
809        try
810        {
811          if (!class_exists('UserCollection')) throw new Exception();
812          $UserCollection = new UserCollection($this->data['type_id']);
813          $infos = $UserCollection->getCollectionInfo();
814          $set['NAME'] = l10n('Collection').': <a href="'.$infos['U_PUBLIC'].'">'.$UserCollection->getParam('name').'</a>';
815         
816          if ( ($name = str2url($UserCollection->getParam('name'))) != null)
817          {
818            $set['BASENAME'] = 'collection-'.$name;
819          }
820          else
821          {
822            $set['BASENAME'] = 'collection'.$this->data['type_id'];
823          }
824        }
825        catch (Exception $e)
826        {
827          $set['NAME'] = l10n('Collection').': #'.$this->data['type_id'].' (deleted)';
828          $set['BASENAME'] = 'collection'.$this->data['type_id'];
829        }
830        break;
831      }
832    }
833   
834    if (!isset($set['sNAME']))    $set['sNAME'] = strip_tags($set['NAME']);
835    if (!isset($set['COMMENT']))  $set['COMMENT'] = null;
836    if (!isset($set['BASENAME'])) $set['BASENAME'] = $this->data['type'] . $this->data['type_id'];
837   
838    return $set;
839  }
840 
841  /**
842   * getSetInfo
843   * @return: array
844   */
845  function getSetInfo()
846  {   
847    $set = array(
848      'NB_IMAGES' =>     $this->data['nb_images'],
849      'NB_ARCHIVES' =>   $this->data['status']=='new' ? l10n('Unknown') : $this->getEstimatedArchiveNumber(),
850      'STATUS' =>        $this->data['status'],
851      'LAST_ZIP' =>      $this->data['last_zip'],
852      'TOTAL_SIZE' =>    $this->data['status']=='new' ? l10n('Unknown') : sprintf(l10n('%d MB'), ceil($this->getEstimatedTotalSize()/1024)),
853      'DATE_CREATION' => format_date($this->data['date_creation'], true),
854      'SIZE_ID' =>       $this->data['size'],
855      'SIZE' =>          $this->data['size']=='original' ? l10n('Original') : l10n($this->data['size']),
856      );
857     
858    if ($this->data['size'] != 'original')
859    {
860      $params = ImageStdParams::get_by_type($this->data['size']);
861      $set['SIZE_INFO'] = $params->sizing->ideal_size[0].' x '.$params->sizing->ideal_size[1];
862    }
863   
864    return array_merge($set, $this->getNames());
865  }
866 
867  /**
868   * delete
869   */
870  function delete()
871  {
872    $this->deleteLastArchive();
873    $this->clearImages();
874    pwg_query('DELETE FROM '.BATCH_DOWNLOAD_TSETS.' WHERE id = '.$this->data['id'].';');
875  }
876}
877
878
879/**
880 * small class implementing basic ZIP creation
881 * with ZipArchive or PclZip
882 */
883class myZip
884{
885  private $lib;
886  private $zip;
887 
888  function __construct($zip_path, $pclzip=false)
889  {
890    if ( class_exists('ZipArchive') and !$pclzip )
891    {
892      $this->lib = 'zipa';
893     
894      $this->zip = new ZipArchive;
895      if ($this->zip->open($zip_path, ZipArchive::CREATE) !== true)
896      {
897        trigger_error('BatchDownloader::createNextArchive, unable to open ZIP archive (ZipArchive)', E_USER_ERROR);
898      }
899    }
900    else
901    {
902      $this->lib = 'pcl';
903     
904      require_once(PHPWG_ROOT_PATH.'admin/include/pclzip.lib.php');
905      $this->zip = new PclZip($zip_path);
906     
907      // create a temporary file for archive creation
908      touch(BATCH_DOWNLOAD_LOCAL.'temp.txt');
909     
910      if ($this->zip->create(BATCH_DOWNLOAD_LOCAL.'temp.txt', PCLZIP_OPT_REMOVE_ALL_PATH) == 0)
911      {
912        trigger_error('BatchDownloader::createNextArchive, unable to open ZIP archive (PclZip)', E_USER_ERROR);
913      }
914     
915      unlink(BATCH_DOWNLOAD_LOCAL.'temp.txt');
916      $this->zip->delete(PCLZIP_OPT_BY_NAME, 'temp.txt');
917    }
918  }
919 
920  function addFile($path, $filename)
921  {
922    if ($this->lib == 'zipa')
923    {
924      $this->zip->addFile($path, $filename);
925    }
926    else
927    {
928      $this->zip->add($path, PCLZIP_OPT_REMOVE_ALL_PATH);
929    }
930  }
931 
932  function setArchiveComment($comment)
933  {
934    if ($this->lib == 'zipa')
935    {
936      $this->zip->setArchiveComment($comment);
937    }
938  }
939 
940  function close()
941  {
942    if ($this->lib == 'zipa')
943    {
944      $this->zip->close();
945    }
946  }
947}
948
949?>
Note: See TracBrowser for help on using the repository browser.