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

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

use new trigger functions

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