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

Last change on this file since 20090 was 20090, checked in by mistic100, 11 years ago
  • add webservices
  • add mail function
  • add admin list
  • add admin export function
  • try to deal with Gthumb+
  • activate multisize dropdown menu of collection page

TODO : use webservices instead of toggle_image.php

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