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

Last change on this file since 28834 was 28834, checked in by mistic100, 10 years ago

use new maintain class

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