source: extensions/UserCollections/include/UserCollection.class.php @ 23551

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

many corrections & optimizations + remove useless code + clean

File size: 13.2 KB
Line 
1<?php
2defined('USER_COLLEC_PATH') or die('Hacking attempt!');
3
4class UserCollection
5{
6  private $data;
7  private $images;
8 
9  /**
10   * __construct
11   * @param: mixed col id (##|'new')
12   * @param: array images
13   */
14  function __construct($col_id, $name=null, $comment=null, $public=false, $user_id=null)
15  {
16    global $user;
17   
18    if (empty($user_id)) {
19      $user_id = $user['id'];
20    }
21   
22    $this->data = array(
23      'id' => 0,
24      'user_id' => $user_id,
25      'name' => null,
26      'date_creation' => '0000-00-00 00:00:00',
27      'domment' => null,
28      'nb_images' => 0,
29      'public' => 0,
30      'public_id' => null,
31      );
32    $this->images = array();
33   
34    // access from public id (access permission is checked line 66)
35    if ( strlen($col_id) == 10 and strpos($col_id, 'uc') === 0 )
36    {
37      $query = '
38SELECT id
39  FROM '.COLLECTIONS_TABLE.'
40  WHERE public_id = "'.$col_id.'"
41;';
42      $result = pwg_query($query);
43     
44      if (!pwg_db_num_rows($result))
45      {
46        $col_id = 0;
47      }
48      else
49      {
50        list($col_id) = pwg_db_fetch_row($result);
51      }
52    }
53   
54    // load specific collection
55    if (preg_match('#^[0-9]+$#', $col_id))
56    {
57      $query = '
58SELECT *
59  FROM '.COLLECTIONS_TABLE.'
60  WHERE
61    id = '.$col_id.'
62    '.(!is_admin() ? 'AND (user_id = '.$this->data['user_id'].' OR public = 1)' : null).'
63;';
64      $result = pwg_query($query);
65     
66      if (pwg_db_num_rows($result))
67      {
68        $this->data = array_merge(
69          $this->data,
70          pwg_db_fetch_assoc($result)
71          );
72       
73        // make sure all pictures of the collection exist
74        $query = '
75DELETE FROM '.COLLECTION_IMAGES_TABLE.'
76  WHERE image_id NOT IN (
77    SELECT id FROM '.IMAGES_TABLE.'
78    )
79;';
80        pwg_query($query);
81     
82        // select images of the collection
83        $query = '
84SELECT image_id
85  FROM '.COLLECTION_IMAGES_TABLE.'
86  WHERE col_id = '.$this->data['id'].'
87;';
88        $this->images = array_from_query($query, 'image_id');
89       
90        $this->updateParam('nb_images', count($this->images));
91      }
92      else
93      {
94        throw new Exception(l10n('Invalid collection'));
95      }
96    }
97    // create a new collection
98    else if ($col_id == 'new')
99    {
100      $this->data['name'] = $name;
101      $this->data['comment'] = $comment;
102      $this->data['public'] = (int)$public;
103      $this->data['public_id'] = 'uc'.hash('crc32', uniqid(serialize($this->data), true));
104     
105      $query = '
106INSERT INTO '.COLLECTIONS_TABLE.'(
107    user_id,
108    name,
109    date_creation,
110    comment,
111    public,
112    public_id
113  )
114  VALUES(
115    '.$this->data['user_id'].',
116    "'.$this->data['name'].'",
117    NOW(),
118    "'.$this->data['comment'].'",
119    '.(int)$this->data['public'].',
120    "'.$this->data['public_id'].'"
121  )
122;';
123      pwg_query($query);
124      $this->data['id'] = pwg_db_insert_id();
125     
126      $date = pwg_query('SELECT NOW();');
127      list($this->data['date_creation']) = pwg_db_fetch_row($date);
128    }
129    else
130    {
131      trigger_error('UserCollection::__construct, invalid input parameter', E_USER_ERROR);
132    }
133  }
134 
135  /**
136   * updateParam
137   * @param: string param name
138   * @param: mixed param value
139   */
140  function updateParam($name, $value)
141  {
142    if ($value != $this->data[$name])
143    {
144      $this->data[$name] = $value;
145      pwg_query('UPDATE '.COLLECTIONS_TABLE.' SET '.$name.' = "'.pwg_db_real_escape_string($value).'" WHERE id = '.$this->data['id'].';');
146    }
147  }
148 
149  /**
150   * getParam
151   * @param: string param name
152   * @return: mixed param value
153   */
154  function getParam($name)
155  {
156    return $this->data[$name];
157  }
158 
159  /**
160   * getImages
161   * @return: array
162   */
163  function getImages()
164  {
165    return $this->images;
166  }
167 
168  /**
169   * isInSet
170   * @param: int image id
171   * @return: bool
172   */
173  function isInSet($image_id)
174  {
175    return in_array($image_id, $this->images);
176  }
177 
178  /**
179   * removeImages
180   * @param: array image ids
181   */
182  function removeImages($image_ids)
183  {
184    if (empty($image_ids) or !is_array($image_ids)) return;
185   
186    $this->images = array_diff($this->images, $image_ids);
187   
188    $query = '
189DELETE FROM '.COLLECTION_IMAGES_TABLE.'
190  WHERE
191    col_id = '.$this->data['id'].'
192    AND image_id IN('.implode(',', $image_ids).')
193;';
194    pwg_query($query);
195   
196    $this->updateParam('nb_images', count($this->images));
197  }
198 
199  /**
200   * addImages
201   * @param: array image ids
202   */
203  function addImages($image_ids)
204  {
205    if (empty($image_ids) or !is_array($image_ids)) return;
206   
207    $image_ids = array_unique($image_ids);
208    $inserts = array();
209   
210    foreach ($image_ids as $image_id)
211    {
212      if ($this->isInSet($image_id)) continue;
213     
214      $this->images[] = $image_id;
215      $inserts[] = array(
216        'col_id' => $this->data['id'],
217        'image_id' => $image_id,
218        );
219    }
220   
221    mass_inserts(
222      COLLECTION_IMAGES_TABLE,
223      array('col_id', 'image_id'),
224      $inserts
225      );
226     
227    $query = '
228UPDATE '.COLLECTION_IMAGES_TABLE.'
229  SET add_date = NOW()
230  WHERE
231    col_id = '.$this->data['id'].'
232    AND image_id IN ('.implode(',', $image_ids).')
233    AND add_date IS NULL
234';
235    pwg_query($query);
236     
237    $this->updateParam('nb_images', count($this->images));
238  }
239 
240  /**
241   * toggleImage
242   * @param: int image id
243   */
244  function toggleImage($image_id)
245  {
246    if ($this->isInSet($image_id))
247    {
248      $this->removeImages(array($image_id));
249    }
250    else
251    {
252      $this->addImages(array($image_id));
253    }
254  }
255 
256  /**
257   * clearImages
258   */
259  function clearImages()
260  {
261    $this->images = array();
262    $this->updateParam('nb_images', 0);
263   
264    $query = '
265DELETE FROM '.COLLECTION_IMAGES_TABLE.'
266  WHERE col_id = '.$this->data['id'].'
267;';
268    pwg_query($query);
269  }
270 
271  /**
272   * getCollectionInfo
273   * @return: array
274   */
275  function getCollectionInfo()
276  {
277    $set = array(
278      'ID' => $this->data['id'],
279      'NAME' => $this->data['name'],
280      'COMMENT' => $this->data['comment'],
281      'NB_IMAGES' => $this->data['nb_images'],
282      'PUBLIC' => (bool)$this->data['public'],
283      'DATE_CREATION' => $this->data['date_creation'],
284      'U_PUBLIC' => USER_COLLEC_PUBLIC . 'view/'.$this->data['public_id'],
285      );
286   
287    return $set;
288  }
289 
290  /**
291   * Send the collection by email
292   * @param: array
293   *          - sender_name
294   *          - sender_email
295   *          - recipient_email
296   *          - recipient_name
297   *          - nb_images
298   *          - message
299   * @return: array errors
300   */
301  function sendEmail($comm, $key)
302  {
303    global $conf, $page, $template;
304   
305    $errors = array();
306   
307    $comm = array_map('stripslashes', $comm);
308
309    $comment_action='validate';
310   
311    // check key
312    if (!verify_ephemeral_key(@$key))
313    {
314      array_push($errors, l10n('Invalid key'));
315      $comment_action='reject';
316    }
317
318    // check author
319    if (empty($comm['sender_name']))
320    {
321      array_push($errors, l10n('Please enter your name'));
322      $comment_action='reject';
323    }     
324    if (empty($comm['recipient_name']))
325    {
326      array_push($errors, l10n('Please enter the recipient name'));
327      $comment_action='reject';
328    }
329   
330    // check email
331    if (empty($comm['sender_email']))
332    {
333      array_push($errors, l10n('Please enter your e-mail'));
334      $comment_action='reject';
335    }
336    else if ( !empty($comm['sender_email']) and !uc_check_email_validity($comm['sender_email']) )
337    {
338      array_push($errors, l10n('mail address must be like xxx@yyy.eee (example : jack@altern.org)'));
339      $comment_action='reject';
340    }
341    if (empty($comm['recipient_email']))
342    {
343      array_push($errors, l10n('Please enter the recipient e-mail'));
344      $comment_action='reject';
345    }
346    else if ( !empty($comm['recipient_email']) and !uc_check_email_validity($comm['recipient_email']) )
347    {
348      array_push($errors, l10n('mail address must be like xxx@yyy.eee (example : jack@altern.org)'));
349      $comment_action='reject';
350    }
351     
352    // check content
353    if (!empty($comm['message']))
354    {
355      $comm['message'] = nl2br($comm['message']);
356    }
357   
358    include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
359   
360    if ($comment_action == 'validate')
361    {
362      // format subject
363      $subject = '['.$conf['gallery_title'].'] '.sprintf(l10n('A photo collection by %s'), $comm['sender_name']);
364      $subject = encode_mime_header($subject);
365           
366      // format expeditor
367      $args['from'] = format_email($comm['sender_name'], $comm['sender_email']);
368      $args['to'] = format_email($comm['recipient_name'], $comm['recipient_email']);
369     
370      // hearders
371      $headers = 'From: '.$args['from']."\n"; 
372      $headers.= 'MIME-Version: 1.0'."\n";
373      $headers.= 'X-Mailer: Piwigo Mailer'."\n";
374      $headers.= 'Content-Transfer-Encoding: 8bit'."\n";
375      $headers.= 'Content-Type: text/html; charset="'.get_pwg_charset().'";'."\n";
376           
377      // mail content
378      $content = $this->getMailContent($comm);
379      $content = wordwrap($content, 70, "\n", true);
380     
381      // send mail
382      $result =
383        trigger_event('send_mail',
384          false, /* Result */
385          trigger_event('send_mail_to', $args['to']),
386          trigger_event('send_mail_subject', $subject),
387          trigger_event('send_mail_content', $content),
388          trigger_event('send_mail_headers', $headers),
389          $args
390        );
391     
392      if ($result == false)
393      {
394        array_push($errors, l10n('Error while sending e-mail'));
395      }
396    }
397   
398    return $errors;
399  }
400 
401  /**
402   * get mail content for sendMail()
403   */
404  function getMailContent($params)
405  {
406    global $user, $conf, $template;
407   
408    // switch to guest user
409    $user_save = $user;
410    $user = build_user($conf['guest_id'], true);
411   
412    // get pictures
413    $query = '
414SELECT
415    id,
416    file,
417    name,
418    path
419  FROM '.IMAGES_TABLE.' AS i
420    JOIN '.IMAGE_CATEGORY_TABLE.' AS ci ON ci.image_id = i.id
421  WHERE id IN ('.implode(',', $this->images).')
422    '.get_sql_condition_FandF(array(
423                'forbidden_categories' => 'category_id',
424                'forbidden_images' => 'id'
425                ),
426              'AND'
427              ).'
428  GROUP BY i.id
429  ORDER BY '.DB_RANDOM_FUNCTION.'()
430  LIMIT '.$params['nb_images'].'
431;';
432    $pictures = hash_from_query($query, 'id');
433   
434    // switch back to current user
435    $user = $user_save;
436    unset($user_save);
437 
438    // picture sinfos
439    set_make_full_url();
440    $tpl_vars = array();
441    foreach ($pictures as $row)
442    {
443      $name = render_element_name($row);
444     
445      $tpl_vars[] = array(
446        'TN_ALT' => htmlspecialchars(strip_tags($name)),
447        'NAME' => $name,
448        'URL' => make_picture_url(array('image_id' => $row['id'])),
449        'THUMB' => DerivativeImage::url(IMG_SQUARE, $row),
450        );
451    }
452   
453    // template
454    $mail_css = file_get_contents(dirname(__FILE__).'/../template/mail.css');
455   
456    $template->assign(array(
457      'GALLERY_URL' => get_gallery_home_url(),
458      'PHPWG_URL' => PHPWG_URL,
459      'UC_MAIL_CSS' => str_replace("\n", null, $mail_css),
460      'MAIL_TITLE' => $this->getParam('name').' ('.sprintf(l10n('by %s'), $params['sender_name']).')',
461      'COL_URL' => USER_COLLEC_PUBLIC . 'view/'.$this->data['public_id'],
462      'PARAMS' => $params,
463      'derivative_params' => ImageStdParams::get_by_type(IMG_SQUARE),
464      'thumbnails' => $tpl_vars,
465      ));
466     
467    $template->set_filename('uc_mail', dirname(__FILE__).'/../template/mail.tpl');
468    $content = $template->parse('uc_mail', true);
469 
470    unset_make_full_url();
471   
472    return $content;
473  }
474
475  /**
476   * generate a listing of the collection
477   */
478  function serialize($params)
479  {
480    $params = array_intersect($params, array('id','file','name','url','path','date_creation','collection_add_date','filesize','width','height'));
481   
482    $content = null;
483     
484    // get images infos
485    $query = '
486SELECT
487    id,
488    file,
489    name,
490    path,
491    date_creation,
492    filesize,
493    width,
494    height,
495    add_date AS collection_add_date
496  FROM '.IMAGES_TABLE.'
497    JOIN '.COLLECTION_IMAGES_TABLE.' ON id = image_id
498  WHERE col_id = '.$this->data['id'].'
499  ORDER BY id
500;';
501    $pictures = hash_from_query($query, 'id');
502   
503    if (count($pictures))
504    {
505      // generate csv
506      set_make_full_url();
507      $root_url = get_root_url();
508     
509      $fp = fopen('php://temp', 'r+');
510      fputcsv($fp, $params);
511       
512      foreach ($pictures as $row)
513      {
514        $element = array();
515        foreach ($params as $field)
516        {
517          switch ($field)
518          {
519          case 'name':
520            $element[] = render_element_name($row); break;
521          case 'url':
522            $element[] = make_picture_url(array('image_id'=>$row['id'], 'image_file'=>$row['file'])); break;
523          case 'path':
524            $element[] = $root_url.ltrim($row['path'], './'); break;
525          default:
526            $element[] = $row[$field]; break;
527          }
528        }
529        if (!empty($element))
530        {
531          fputcsv($fp, $element);
532        }
533      }
534     
535      rewind($fp);
536      $content = stream_get_contents($fp);
537      fclose($fp);
538     
539      unset_make_full_url();
540    }
541   
542    return $content;
543  }
544 
545  /**
546   * delete
547   */
548  function delete()
549  {
550    $this->clearImages();
551    pwg_query('DELETE FROM '.COLLECTIONS_TABLE.' WHERE id = '.$this->data['id'].';');
552  }
553}
554
555?>
Note: See TracBrowser for help on using the repository browser.